Home > Software engineering >  AWS CLI: create EC2 instance and attach instance profile (unauthorized)
AWS CLI: create EC2 instance and attach instance profile (unauthorized)

Time:09-30

From an ec2 instance "A", I'd like to launch another ec2 instance "B" and assign it an instance profile.

I am able to create the new instance "B" without an instance profile:

aws ec2 run-instances --image-id ami-<redacted> --count 1 --instance-type t2.micro --key-name <redacted> --security-group-ids sg-<redacted> --subnet-id subnet-<redacted> 

However, when I add the --iam-instance-profile Name="<redacted>" flag to attach the instance profile, I receive an error:

An error occurred (UnauthorizedOperation) when calling the RunInstances operation:  
You are not authorized to perform this operation. Encoded authorization failure message: <redacted>

It guess the instance profile that is attached to instance "A" (and used to create instance "B") is lacking some resource permissions, but I cannot come up with the solution.

I decoded the failure message (aws sts decode-authorization-message --encoded-message <message>), but I still don't get the point:

{
    "DecodedMessage": 
"{\"allowed\":false,\"explicitDeny\":false,\"matchedStatements\":{\"items\":[]},\"failures\":{\"items\":[]},\"context\":{\"principal\":{\"id\":\"<redacted>\",\"arn\":\"arn:aws:sts::<redacted>:assumed-role/<redacted>/<redacted>\"},\"action\":\"iam:PassRole\",\"resource\":\"arn:aws:iam::<redacted>:role/<redacted>\",\"conditions\":{\"items\":[{\"key\":\"aws:Region\",\"values\":{\"items\":[{\"value\":\"eu-central-1\"}]}},{\"key\":\"aws:Service\",\"values\":{\"items\":[{\"value\":\"ec2\"}]}},{\"key\":\"aws:Resource\",\"values\":{\"items\":[{\"value\":\"role/<redacted>\"}]}},{\"key\":\"iam:RoleName\",\"values\":{\"items\":[{\"value\":\"<redacted>\"}]}},{\"key\":\"aws:Type\",\"values\":{\"items\":[{\"value\":\"role\"}]}},{\"key\":\"aws:Account\",\"values\":{\"items\":[{\"value\":\"<redacted>\"}]}},{\"key\":\"aws:ARN\",\"values\":{\"items\":[{\"value\":\"arn:aws:iam::<redacted>:role/<redacted>\"}]}}]}}}"
}

What am I missing?

CodePudding user response:

The IAM principal (typically an IAM role) associated with instance A needs permission to pass the IAM role associated with your chosen profile to the AWS EC2 service so that instance B can be launched with that chosen profile/role.

The reason that this permission is required is to prevent one role from launching compute with another role that confers elevated permissions (this is called 'privilege escalation').

Add something like the following to the policies associated with the IAM role that instance A was launched with:

{
  "Effect": "Allow",
  "Action": "iam:PassRole",
  "Resource": "arn:aws:::your-account:role/your-role"
}
  • Related