BudiBadu Logo
Samplebadu

Terraform by Example: Providers

1.x

Learn how to configure Terraform providers to interact with cloud APIs using this sample code. Covers essential best practices like version pinning, secure credential management, and using aliases for multi-region deployments.

Code

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

# Configure the AWS Provider
provider "aws" {
  region = "us-east-1"
  
  # Credentials can be set here, but environment variables are safer
  # access_key = "my-access-key"
  # secret_key = "my-secret-key"

  default_tags {
    tags = {
      Environment = "Dev"
      Project     = "TerraformDemo"
    }
  }
}

# Multiple provider instances (aliasing)
provider "aws" {
  alias  = "west"
  region = "us-west-2"
}

Explanation

Providers are the plugins that enable Terraform to interact with cloud platforms, SaaS providers, and other APIs. To ensure stability and prevent breaking changes, it is a critical best practice to explicitly declare required providers and pin their versions using the required_providers block. This guarantees that your configuration always uses a compatible version of the provider plugin, avoiding unexpected behavior during updates.

Effective provider configuration involves several key practices:

  • Version Pinning: Always use constraints like ~> 5.0 to lock major versions while allowing patch updates
  • Secure Credentials: Never hardcode keys. Use environment variables (e.g., AWS_ACCESS_KEY_ID) or IAM roles
  • Aliasing: Use the alias argument to manage resources across multiple regions or accounts in a single config

The provider block configures specific settings such as the cloud region. By using the alias meta-argument, you can define multiple instances of the same provider, which is essential for architectures that span across different geographic locations.

Code Breakdown

2-7
required_providers block locks the AWS provider to version 5.x.
11
provider "aws" initializes the default provider instance for us-east-1.
18-23
default_tags applies common tags (Env, Project) to all resources.
27-30
alias = "west" defines a secondary provider for the us-west-2 region.