Associate existing IAM role with EC2 instance in CloudFormation

amazon-web-services, aws-cloudformation

Solution

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.

Problem

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.

Original source