Associate existing IAM role with EC2 instance in CloudFormation

后端 未结 3 1407
忘了有多久
忘了有多久 2020-12-14 09:21

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 Con

3条回答
  •  星月不相逢
    2020-12-14 09:34

    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",
          ...
        }
      }
    }
    

提交回复
热议问题