Hi readers, in this blog we will discuss about the different ways to add aws credentials (access key and secret key) in a Terraform configuration file. There are many ways to do it. Lets discuss some of them.
Add it to your configuration files while defining your variable
This would be the most naive way to do it. You will add the values in the variables section of your configuration files.
variable “aws_access_key”{
default = “AWSXXXXXX0978”
}variable "aws_secret_key"{
default = "AULP0XXXXXXY7US9XXXXOP56JX"
}
provider “aws” {
access_key=var.aws_access_key
secret_key=var.aws_secret_key
}
By using the above method, make sure that you don’t commit your code to a public repository. This could expose your IAM credentials.
Pass them as environment variables
This is a safer way to add credentials. Pass the values of access key and secret key as environment variables. The only overhead would be of adding them again with a new session/terminal.
export AWS_ACCESS_KEY_ID="anaccesskey"
export AWS_SECRET_ACCESS_KEY="asecretkey"
provider "aws" {}
Using aws profile
This is a better approach in comparison to the above mentioned approaches. We can configure aws credentials in out local.
aws configure
AWS Access Key ID:
AWS Secret Access Key :
Default region name:
Default output format:
The above information will be stored in ~/.aws/credentials file. Add this path to the shared_credentials_file section in your aws provider block.
provider "aws" {
shared_credentials_file = ~/.aws/credentials"
region = var.aws_region
}
If you have multiple profiles of aws, with different accounts and IAM authentication keys, add those entries in the credentials file as follows:
[production]
aws_access_key_id = XXXXXXXXXXXXXXXXXXXX
aws_secret_access_key = XXXXXXXXXXXXXXXXXX
[development]
aws_access_key_id = XXXXXXXXXXXXXXXXXXXX
aws_secret_access_key = XXXXXXXXXXXXXXXXXX
[staging]
aws_access_key_id = XXXXXXXXXXXXXXXXXXXX
aws_secret_access_key = XXXXXXXXXXXXXXXXXX
provider "aws"{
region=var.region
profile=var.profile
}
Check out more blogs on Terraform:
https://blog.knoldus.com/?s=terraform
References:
https://registry.terraform.io/providers/hashicorp/aws/latest/docs#environment-variables