Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform aws provider - how to use default region from ~/.aws/config

In my main.tf I have an empty aws provider defined

provider aws {}

In the absence of environment variables the aws provider picks the [default] credentials from ~/.aws/credentials. However I still get prompted to enter the region:

>terraform plan
provider.aws.region
  The region where AWS operations will take place. Examples
  are us-east-1, us-west-2, etc.

  Enter a value: 

How can I get the aws provider to automatically pick up the corresponding region to the [default] credentials as defined in ~/.aws/config?

like image 797
Bernie Lenz Avatar asked Feb 25 '20 22:02

Bernie Lenz


People also ask

How do you specify a region in Terraform?

You can get the region that's currently in use by the provider by using the aws_region data source. So in your case you could do something like this: provider "aws" { alias = "region" } data "aws_region" "current" { provider = "aws. region" } resource "aws_vpc" "default" { provider = "aws.

How do I use AWS access key and secret key in Terraform?

So first I install the AWS CLI. Then we run aws configure. [ ] $ aws configure AWS Access Key ID []: ENTER-YOUR-ACCESS-KEY-HERE AWS Secret Access Key []: ENTER-YOUR-SECRET-KEY-HERE Default region name []: us-west-2 Default output format []


2 Answers

AWS provider has profile attribute but it does not pick up the region from .aws/config.

$ cat main.tf
provider aws {
     profile="default"
}

$ terraform plan
provider.aws.region
  The region where AWS operations will take place. Examples
  are us-east-1, us-west-2, etc.
...

The way I can think of now is using the environment variable (I use this way).

$ export AWS_DEFAULT_REGION=$(aws configure get region --profile default)
$ terraform plan
Refreshing Terraform state in-memory prior to plan...
...

------------------------------------------------------------------------

No changes. Infrastructure is up-to-date.
like image 58
mon Avatar answered Oct 16 '22 19:10

mon


If the only reason that you have the provider block is to reference the region in your code then you can simply use the aws_region data source which allows you to reference the current region instead of having the provider block (the region should be picked up from the default profile in this case I believe)


data "aws_region" "current-region" {}

// Then get the region using
data.aws_region.current-region.name 

like image 2
FearlessHyena Avatar answered Oct 16 '22 19:10

FearlessHyena