How to Use an IAM Role Assigned to an EC2 Instance in AWS with Hybrid Deployment
Question
How do I use an IAM role assigned to an EC2 instance in AWS with Hybrid Deployment?
Environment
Container platform: Docker and Podman
Answer
To use an IAM role assigned to an EC2 instance in AWS with Hybrid Deployment, follow the steps below. For more information, see the AWS documentation for IAM roles for Amazon EC2.
Create IAM policy
Depending on which AWS services you need to access, create one or more IAM policies that define the necessary permissions. Multiple IAM policies can be attached to a single IAM role.
For example, to access an S3 bucket:
Create an S3 bucket.
Define an IAM policy
s3-policy.jsonthat grants access to the bucket:{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:DeleteObjectTagging", "s3:ReplicateObject", "s3:PutObject", "s3:GetObjectAcl", "s3:GetObject", "s3:DeleteObjectVersion", "s3:ListBucket", "s3:PutObjectTagging", "s3:DeleteObject", "s3:PutObjectAcl" ], "Resource": [ "arn:aws:s3:::BUCKET_NAME", "arn:aws:s3:::BUCKET_NAME/*" ] } ] }Create the policy using the AWS CLI:
aws iam create-policy --policy-name <your-policy> --policy-document file://s3-policy.json
Create IAM role
Define a trust policy
trust-policy.jsonthat allows EC2 to assume the role:{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "ec2.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }Create the IAM role and attach each IAM policy:
aws iam create-role --role-name <your-role-name> --assume-role-policy-document file://trust-policy.json aws iam attach-role-policy --role-name <your-role-name> --policy-arn arn:aws:iam::<account-id>:policy/<your-policy>
Create instance profile
An instance profile is required to attach an IAM role to an EC2 instance.
Create an instance profile:
aws iam create-instance-profile --instance-profile-name <your-instance-profile-name>Attach the IAM role to the instance profile:
aws iam add-role-to-instance-profile --role-name <your-role-name> --instance-profile-name <your-instance-profile-name>
Attach instance profile to EC2 instance
Associate the instance profile with your EC2 instance:
aws ec2 associate-iam-instance-profile --instance-id <your-instance-id> --iam-instance-profile Name=<your-instance-profile-name>
Hybrid Deployment jobs running on the EC2 instance will automatically use the assigned IAM role credentials when accessing AWS services such as S3, without requiring manual credential configuration.