Posted on Leave a comment

Providing AWS credentials to Terraform

When creating AWS infrastructure with Terraform, the AWS provider needs to be configured with the necessary credentials to authorize access to your Amazon Web Services account.

There are several ways to provide these credentials to Terraform:

  1. Environment variables:
    You can set the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables with your AWS credentials. Terraform will automatically detect these variables when running any command. You can also set the AWS_SESSION_TOKEN environment variable if you’re using temporary security credentials.
export AWS_ACCESS_KEY_ID="your_access_key"
export AWS_SECRET_ACCESS_KEY="your_secret_key"
  1. Shared credentials file:
    The AWS CLI and SDKs use a shared credentials file, usually located at ~/.aws/credentials (Linux/macOS) or %UserProfile%\.aws\credentials (Windows). You can configure multiple named profiles with different AWS credentials in this file. By default, Terraform uses the “default” profile, but you can specify a different profile using the profile attribute in the AWS provider configuration block.

Example of a shared credentials file:

aws_access_key_id = your_access_key
aws_secret_access_key = your_secret_key


aws_access_key_id = your_other_access_key aws_secret_access_key = your_other_secret_key

  1. AWS provider configuration block:
    You can directly provide the access and secret keys in the AWS provider configuration block in your Terraform configuration files. However, this method is not recommended, as it may expose your credentials if the file is accidentally shared or committed to a version control system.
provider "aws" {
  access_key = "your_access_key"
  secret_key = "your_secret_key"
  region     = "us-west-2"

It’s generally recommended to use environment variables or a shared credentials file to provide AWS credentials to Terraform. This way, you can keep your credentials secure and separate from your Terraform configuration files.

Leave a Reply

Your email address will not be published. Required fields are marked *