AWS access keys deployed directly to an EC2 instance

Use temporary IAM role credentials instead of placing long-lived keys on EC2.

Description

Putting AWS access keys and secret keys directly in EC2 user_data, scripts, files, or environment variables can expose them through repositories, logs, or images. An IAM role attached through an instance profile provides AWS permissions without distributing long-lived keys directly.

Potential impact

  • Exposed long-lived keys can be reused from other environments.
  • Keys copied to multiple instances can be difficult to replace and inventory.

Remediation

Attach a least-privilege IAM role through iam_instance_profile and configure the application to use its temporary credentials. Identify consumers of deployed long-lived keys, replace them, and deactivate or delete exposed keys. Removing a key from source code does not revoke the issued credential.

Examples

These excerpts compare credential sources only. The key strings in the first example are placeholders, not actual keys. Choose an AMI suitable for the Region and operating system, and configure the instance profile, role trust, and permissions separately.

Before

hcl
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

hcl
resource "aws_instance" "example" {
  ami                  = "ami-005e54dee72cc1d00"
  instance_type        = "t2.micro"
  iam_instance_profile = aws_iam_instance_profile.test_profile.name
}

The revision attaches an instance profile instead of placing long-lived keys in user data. Effective permissions still depend on the role policy and other access controls.

References