Description
Long-lived AWS access keys in EC2 user data or Terraform provisioners can leak through scripts, files, or logs. An AWS CLI configuration file may contain only settings such as the Region and output format.
Potential impact
An exposed long-lived key can be used outside the instance with its assigned permissions until the issuing account disables it.
Remediation
Check the referenced script or file for long-lived keys. If it contains any, use iam_instance_profile to attach a role that trusts EC2 and allows only the required operations. Remove the keys from user data, provisioning scripts, and the workload environment. Verify that the application calls AWS with temporary role credentials. Migrate other consumers of the old key, then deactivate and delete it.
Examples
Supply an AMI for the target Region and define aws_iam_instance_profile.test_profile. The keys in the first example are placeholders. The second removes all user data, so install the AWS CLI separately if the workload needs it.
Before
resource "aws_instance" "example" {
ami = "ami-005e54dee72cc1d00"
instance_type = "t2.micro"
user_data = <<EOF
#!/bin/bash
apt-get install -y awscli
export AWS_ACCESS_KEY_ID=your_access_key_id_here
export AWS_SECRET_ACCESS_KEY=your_secret_access_key_here
EOF
}
After
resource "aws_instance" "example" {
ami = "ami-005e54dee72cc1d00"
instance_type = "t2.micro"
iam_instance_profile = aws_iam_instance_profile.test_profile.name
}