Provider Authentication
Providers need credentials; for AWS, prefer environment variables or IAM roles over hard-coded keys.
Providers must authenticate to their platform. For AWS, Terraform looks for credentials in a standard order.
Where AWS credentials come from
- Environment variables (
AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY). - A shared credentials file (
~/.aws/credentials), selected byAWS_PROFILE. - An IAM role attached to the EC2 instance or CI runner.
Never hard-code secrets
Do not put access keys directly in .tf files — they end up in Git. Use environment variables or IAM roles instead.
Example
# Preferred: set credentials as environment variables
export AWS_ACCESS_KEY_ID="AKIAIOSFODNN7EXAMPLE"
export AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
export AWS_REGION="us-east-1"
# Or select a named profile from ~/.aws/credentials
export AWS_PROFILE="soundscode-dev"
terraform planWhen to use it
- A CI pipeline exports AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY as masked environment variables so Terraform never stores credentials in code.
- An EC2 instance running Terraform uses an attached IAM role, so no credentials are stored anywhere β Terraform picks them up from the instance metadata.
- A developer uses AWS SSO with aws configure sso and sets AWS_PROFILE so Terraform authenticates without any long-lived access keys on the machine.
More examples
Authenticate via environment variables
Passes AWS credentials through environment variables so Terraform reads them without any credential block in .tf files.
# Set credentials in the shell session (never commit these)
export AWS_ACCESS_KEY_ID="AKIAIOSFODNN7EXAMPLE"
export AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
export AWS_DEFAULT_REGION="us-east-1"
terraform planNamed AWS profile authentication
Selects a named AWS CLI profile so Terraform uses preconfigured credentials without embedding secrets in code.
# Use a named profile from ~/.aws/credentials
export AWS_PROFILE=my-prod-profile
terraform apply
# Or set it inside the provider block (non-sensitive)
# provider "aws" {
# profile = "my-prod-profile"
# }IAM role assumption in provider
Configures the provider to assume a specific IAM role, enabling cross-account deployments with least-privilege access.
provider "aws" {
region = "us-east-1"
assume_role {
role_arn = "arn:aws:iam::123456789012:role/TerraformDeployRole"
session_name = "terraform-session"
}
}
Discussion