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

  1. Environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY).
  2. A shared credentials file (~/.aws/credentials), selected by AWS_PROFILE.
  3. 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

Example Β· bash
# 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 plan

When 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.

Example Β· bash
# 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 plan

Named AWS profile authentication

Selects a named AWS CLI profile so Terraform uses preconfigured credentials without embedding secrets in code.

Example Β· bash
# 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.

Example Β· hcl
provider "aws" {
  region = "us-east-1"

  assume_role {
    role_arn     = "arn:aws:iam::123456789012:role/TerraformDeployRole"
    session_name = "terraform-session"
  }
}

Discussion

  • Be the first to comment on this lesson.
Provider Authentication β€” Terraform | SoundsCode