Home > Enterprise >  Instance profile not being added to EC2 instance
Instance profile not being added to EC2 instance

Time:11-08

I am creating a EC2 instnace through a script such like:

  const instanceParams: EC2.Types.RunInstancesRequest = {
      ImageId: AWSImageIDs.AmazonLinux_arm64,
      InstanceType: 't4g.nano',
      MinCount: 1,
      MaxCount: 1,
      UserData: userData,
      SubnetId: SubnetIds.QA1,
      IamInstanceProfile: {Arn: INSTANCE_PROFILE_ARN},
      SecurityGroupIds: [SecurityGroupIds.QA_AllowTraffic],
    };
  const instance = await new EC2({apiVersion: '2016-11-15'})
    .runInstances(instanceParams)
    .promise()

It creates the instance just fine. When I got to EC2 through the AWS Console, I see the instance, and I see the role for the instance profile attached to the instance. The role has the S3FullAccessPolicy attached.

However when I run aws configure list it returns:

profile                <not set>             None    None

Expectedly aws s3 commands fail with unable to locate credentials. I'm not sure why the instance doesn't believe the profile is attached, when the AWS Console does?

CodePudding user response:

The Trust Policy is incorrect.

The policy needs to grant permission to the Amazon EC2 server to assume the role.

For example:

{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "ec2.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}

This is saying that the EC2 service can call AssumeRole on this instance. The EC2 service does this to obtain credentials to pass to the instance via metadata.

Since your current Trust Policy only allows the Amazon S3 service to assume the role, the EC2 service cannot generate credentials.

Note that the actual IAM Role might be granting permission to access S3, but if the IAM Role is being assigned to an EC2 instance, the Trust Policy must allow the EC2 service to use it.

  • Related