To deploy an AWS instance in a particular region, configure where the AWS provider operates. A `provider "aws"` block can set that region. It is separate from `required_providers`: the requirement tells Terraform which provider to install and can constrain its version; the provider block supplies settings for that provider. section 2.1.3
Listing 2.1 Configuring required providers
terraform { #1
required_providers { #2
aws = { #3
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" { #4
region = "us-east-1" #5
}
Compare the versioned AWS requirement with the separate provider block that sets `region = "us-east-1"`. section 2.1.3
Provider settings commonly handle authentication and scope. The available settings depend on the provider: AWS can use a region, while Google can use a project and region. Credentials may instead come from environment variables or provider-specific files, so check the provider’s documentation. A provider block can be omitted when those other configuration methods supply everything needed. section 2.4.3
Put provider blocks in the root module—the `.tf` files in the directory where Terraform commands run—not in a reusable module. A root module can use an input variable for the region, letting different workspaces supply different values. Choose that value carefully: changing a deployment’s region after resources have launched is not normally intended. section 3.1.3 section 3.8.4
Listing 3.35 Providers for our test workspace
terraform {
required_providers {
aws = { #1
source = "hashicorp/aws"
version = "~> 4.0"
}
}
}
variable "region" { #2
type = string
default = "us-east-1"
description = "The AWS Region to connect and run the tests in."
}
provider "aws" { #3
region = var.region #4
}
See how a test workspace declares its AWS requirement, defines a `region` variable, and passes `var.region` into the provider block. section 3.8.4
For multiple connections of the same provider, define an aliased provider block for each additional set of settings. Resources and data sources use the default configuration unless directed to an alias with their `provider` argument. This supports, for example, lookups in a second AWS region. section 2.4.4
Listing 2.22 Using multiple providers and aliases
provider "aws" { #1
region = "us-east-1"
}
provider "aws" {
alias = "west" #2
region = "us-west-2"
}
# Default Subnet Lookup
data "aws_vpc" "default" { #3
default = true
}
data "aws_subnets" "default" { #3
filter {
name = "vpc-id"
values = [data.aws_vpc.default.id]
}
}
# Secondary Subnet Lookup
data "aws_vpc" "backup" {
provider = aws.west #4
default = true
}
data "aws_subnets" "backup" {
provider = aws.west #4
filter {
name = "vpc-id"
values = [data.aws_vpc.defabackupult.id]
}
}
Follow the default AWS configuration and the `aws.west` alias; the secondary VPC and subnet lookups select the alias explicitly. section 2.4.4
