EC2 instances should use IAM roles and instance profiles instead of IAM access keys to perform requests

Description

EC2 instances should use IAM roles and instance profiles instead of IAM access keys to perform requests. By passing role information to an EC2 instance at launch, you can limit the risk of access key exposure and help prevent a malicious user from compromising the instance.

Remediation Steps

AWS Console

If you use the AWS Management Console to create a role for Amazon EC2, the console automatically creates an instance profile and gives it the same name as the role. When you then use the Amazon EC2 console to launch an instance with an IAM role, you can select a role to associate with the instance. You cannot associate a role with an instance from the console after it has been launched, so use the CLI for remediation instead.

AWS CLI

  • To associate an instance profile with a stopped or running instance, replace i-123456789abcde123 with your instance ID and MYIAMROLENAME with the name of your role:

    • aws ec2 associate-iam-instance-profile --instance-id i-123456789abcde123 --iam-instance-profile Name=MYIAMROLENAME

CloudFormation

JSON

{
  "Properties" : {
    "IamInstanceProfile" : "arn:aws:iam::1234567890:instance-profile/MyProfile-ASDNSDLKJ"
  }
}
JSON Example Configuration
{
  "Type" : "AWS::EC2::Instance",
  "Properties" : {
    "IamInstanceProfile" : "arn:aws:iam::1234567890:instance-profile/MyProfile-ASDNSDLKJ"
    }
  # other required fields here
}

YAML

Properties:
  IAMInstanceProfile: arn:aws:iam::1234567890:instance-profile/MyProfile-ASDNSDLKJ
YAML Example Configuration
Type: AWS::EC2::Instance
Properties:
  IAMInstanceProfile: arn:aws:iam::1234567890:instance-profile/MyProfile-ASDNSDLKJ
# other required fields here

Terraform

  • Ensure that the aws_instance iam_instance_profile field specifies the name of the instance profile to use.

Example Configuration

resource "aws_instance" "example" {
  iam_instance_profile = "${aws_iam_instance_profile.test_profile.name}"
  # other required fields here
}

resource "aws_iam_instance_profile" "test_profile" {
  name = "test_profile"
  role = "${aws_iam_role.test_role.name}"
}