Lambda function cannot set the IAM Role on a new EC2 instance

0

I have created a SAM application to assign an IAM to new EC2 instances that are created. I cannot set the Role on creation, for various reasons. The event is coming through EventBridge, and it is being received by the Lambda function. The logs in CloudWatch are receiving the debug output. In the docker image, a python script is using the boto3 library. It first accesses describe_instances like this:

ec2_client = boto3.client("ec2") ... reservations = ec2_client.describe_instances( InstanceIds=[ instance_id ])

This succeeds. Then a later call:

iip = {
    "Arn": "the_correct_arn",
    "Name": "the_correct_name"
}
ii = instances[0].get("InstanceId")
logger.debug("Request: %s, %s" % (iip, ii))
response = ec2_client.associate_iam_instance_profile(
    IamInstanceProfile=iip,
    InstanceId=ii
)

This does not succeed. The CloudWatch log says:

[ERROR] ClientError: An error occurred (UnauthorizedOperation) when calling the AssociateIamInstanceProfile operation: You are not authorized to perform this operation.

The Role assigned to the Lambda function has the following AWS-managed policies:

AmazonEC2FullAccess AmazonEC2ReadOnlyAccess AWSLambdaBasicExecutionRole

I'm not happy about "AmazonEC2FullAccess", but it was all the permissions I could give it and know it should have the permissions it needs. I've tried it with only specifying Arn, and only Name, and neither was better. I confirmed the instance ID was correct. Is there some other set of permissions that could be blocking me? Like a restriction on the EC2 instance? Or is security stuff like IAM Roles need special permission? Is "IAM Instance Profile" not the same as a Role? I thought they were the same. I've redeployed a few times to ensure there wasn't a caching problem. I should get ec2:AssociateIamInstanceProfile from AmazonEC2FullAccess. Any thoughts?

1 Answer
0

Is your account running as part of a larger organization/account structure? If so, it's possible that there are some permissions (including AssociateIamInstanceProfile) that are being blocked.

profile pictureAWS
EXPERT
answered a year ago
  • That's a great idea. I'll check on that.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions