How do I create Amazon EC2 instances through CloudFormation when the IAM policy for RunInstances has tag-based restrictions?

Last updated: 2022-11-01

I want to create Amazon Elastic Compute Cloud (Amazon EC2) instances through AWS CloudFormation. But my AWS Identity and Access Management (IAM) policy for RunInstances has tag-based restrictions.

Short description

You can use a launch template to create Amazon EC2 instances through CloudFormation.

The Tags property of the AWS::EC2::Instance resource doesn't extend to the volumes that are created through CloudFormation. If the IAM policy that's associated with the user or role has restrictions on volume tags, then you receive the following error:

"You are not authorized to perform this operation."

To pass the tags through CloudFormation to ec2:CreateVolume, you must define your tags in the AWS::EC2::LaunchTemplate resource in your CloudFormation template.

Resolution

1.    Define a launch template in the stack with the tags that the IAM policy requires. For example:

RequiredTagsLaunchTemplate:
    Type: 'AWS::EC2::LaunchTemplate'
    Properties:
      LaunchTemplateData:
        TagSpecifications:
          - ResourceType: volume
            Tags:
              - Key: Env
                 Value: Dev

2.    Attach your launch template to your EC2 instance resource. For example:

Instance:
    Type: 'AWS::EC2::Instance'
    Properties:
      LaunchTemplate:
        LaunchTemplateId: !Ref RequiredTagsLaunchTemplate
        Version: 1
      InstanceType: r4.xlarge
      .
      .
  RequiredTagsLaunchTemplate:
    Type: 'AWS::EC2::LaunchTemplate'
    Properties:
      LaunchTemplateData:
        TagSpecifications:
          - ResourceType: volume
            Tags:
              - Key: Env
                Value: Dev

3.    Confirm that your launch template has all the necessary tags.

Important: You must confirm that the role or user that creates the stack has the permissions to create and use a launch template without tagging restrictions. You can use the aws:CalledVia condition key to create a new statement that exempts CloudFormation API calls from tagging requirements.


Did this article help?


Do you need billing or technical support?