How can I use an existing IAM role for an EC2 instance, as opposed to creating a new one in my CloudFormation template?
For example, I have created a role in AWS Console and just want to use that.
To attach an IAM role to an instance Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/ . In the navigation pane, choose Instances. Select the instance, choose Actions, Security, Modify IAM role. Select the IAM role to attach to your instance, and choose Save.
To add an existing or new IAM managed policy to a new IAM role resource, use the ManagedPolicyArns property of resource type AWS::IAM::Role. To add a new IAM managed policy to an existing IAM role resource, use the Roles property of resource type AWS::IAM::ManagedPolicy.
Note that only one role can be assigned to an Amazon EC2 instance at a time, and all applications on the instance share the same role and permissions.
You can use an existing InstanceProfile instead of creating a new one from within the stack. In fact, one might already be created for you - from the docs:
If you use the AWS Management Console to create a role for Amazon EC2, the console automatically creates an instance profile and gives it the same name as the role.
This means that you might not have to create an AWS::IAM::InstanceProfile
resource in the stack. However note that also:
The console does not create an instance profile for a role that is not associated with Amazon EC2.
In this case you can do it manually from AWS CLI using these 2 commands:
aws iam create-instance-profile --instance-profile-name MyExistingRole
aws iam add-role-to-instance-profile --instance-profile-name MyExistingRole --role-name MyExistingRole
Then, provided you've defined a role in the UI named MyExistingRole
, this will be sufficient:
"Resources" : {
"Instance" : {
"Type" : "AWS::EC2::Instance",
...
"Properties" : {
"IamInstanceProfile" : "MyExistingRole",
...
}
}
}
You need an instance profile, a role, and the instance info (or launch configuration) itself.
Your instance profile would look like this:
"Resources" : {
"InstanceProfile" : {
"Type" : "AWS::IAM::InstanceProfile",
"Properties" : {
"Path" : "/",
"Roles" : ["MyExistingRole"]
}
},
"Instance" : {
"Type" : "AWS::EC2::Instance",
"Properties" : {
"IamInstanceProfile" : {"Ref" : "InstanceProfile"}
...
}
}
In particular - note that the reference in the Instance profile is to an existing RoleName
Also - I've written about bootstrapping instances which uses instance profiles and roles to ensure we're not persisting security.
The key thing is rather than using the {"Ref" : RoleName} etc, to use the actual name of the role.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With