Review AWS credentials in EC2 user data

Remove long-term AWS credentials from EC2 user data and use temporary credentials from an instance role.

Description

Remove long-term AWS keys from EC2 user_data and the scripts it runs. Values can be exposed through source repositories, Terraform state, instance metadata, or initialization logs.

Potential impact

A valid access key ID and its secret together can be used with that key’s permissions. Replacing the key affects any startup tasks and applications that still use it.

Remediation

Attach an IAM role through an instance profile and let the AWS SDK use its temporary credentials. Limit the role to required actions and resources. Retrieve external-service secrets from a restricted store such as Secrets Manager. If a real key was exposed, deactivate it promptly, switch its consumers, and verify they work. Investigate AWS activity and restrict access to source, state, and logs.

Examples

Supply the appropriate ami_id and subnet_id and configure the instance profile separately.

Before

hcl
module "ec2_instance" {
  source  = "terraform-aws-modules/ec2-instance/aws"
  version = "~> 3.0"

  name      = "single-instance"
  ami       = var.ami_id
  subnet_id = var.subnet_id
  user_data = "1234567890123456789012345678901234567890$"
}

The string is set directly in user_data. Its appearance alone does not identify an issued credential.

After

hcl
module "ec2_instance" {
  source  = "terraform-aws-modules/ec2-instance/aws"
  version = "~> 3.0"

  name      = "single-instance"
  ami       = var.ami_id
  subnet_id = var.subnet_id
  user_data = file("scripts/first-boot-http.sh")
}

file() sends the contents of scripts/first-boot-http.sh as user data. Keep credentials out of that script too.

References