Use an instance profile to pass an IAM role to an EC2 instance.It allows EC2 Instances to access AWS services securely and securely without using traditional login credentials such as Access Key ID and Secret Access Key.
When you create an IAM role using the IAM console, the console creates an instance profile automatically and gives it the same name as the role to which it corresponds. If you use the Amazon EC2 console to launch an instance with an IAM role or to attach an IAM role to an instance, you choose the role based on a list of instance profile names.
If you use the AWS CLI, API, or an AWS SDK to create a role, you create the role and instance profile as separate actions, with potentially different names. If you then use the AWS CLI, API, or an AWS SDK to launch an instance with an IAM role or to attach an IAM role to an instance, specify the instance profile name.
Create an IAM role and define which accounts or AWS services can assume the role.
ecs_instance_role_name=$project-ecs-instance-role
# Create EC2 Role
aws iam create-role \
--role-name $ecs_instance_role_name \
--assume-role-policy-document '{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {
"Service": ["ec2.amazonaws.com"]
},
"Action": ["sts:AssumeRole"]
}]
}' \
--tags "$tags"
Define which API actions and resources the application can use after assuming the role (Attach policy to IAM Role).
aws iam attach-role-policy \
--policy-arn arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role \
--role-name $ecs_instance_role_name
aws iam attach-role-policy \
--policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore \
--role-name $ecs_instance_role_name
Create an IAM instance profile
aws iam create-instance-profile \
--instance-profile-name $ecs_instance_role_name
Add the Role just created to the Instance profile
aws iam add-role-to-instance-profile \
--instance-profile-name $ecs_instance_role_name \
--role-name $ecs_instance_role_name
Retrieve Instance Profile information used for instances (EC2)
ecs_instance_profile_arn=$(aws iam get-instance-profile \
--instance-profile-name $ecs_instance_role_name \
--output text \
--query 'InstanceProfile.Arn')
Create an IAM Role
Attach policies to the IAM Role
Create an IAM instance profile
Add the Role to the Instance profile
Access the IAM Role via the AWS Console, and for roles assigned to the instance profile, the Instance profile ARN will be displayed in the upper-right corner under the Summary section
Retrieve the Instance Profile information used for the instance (EC2)
To learn more about Instance Profile and IAM Role for EC2: