How do I create Amazon EC2 instances through AWS CloudFormation when the IAM policy for RunInstances has tag-based restrictions?
Last updated: 2020-10-15
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.
You can use a launch template to create EC2 instances through AWS CloudFormation.
When you create an EC2 instance with AWS CloudFormation using the resource AWS::EC2::Instance, AWS CloudFormation makes two API calls: RunInstances and CreateTags. RunInstances creates the instance and CreateTags applies the necessary tags after the instance is created. The RunInstances request made by AWS CloudFormation doesn't support the tags, but the API does support the tags. Because tags aren't included in the RunInstances request, the IAM tag-based restriction isn't satisfied and you receive an error message. The error message is “You are not authorized to perform this operation.”
Note: AWS CloudFormation doesn't support instance creation with tags in a solitary request (that is, for a RunInstances API call).
To pass the tags to ec2:RunInstances through AWS CloudFormation, you must define your tags in the AWS::EC2::LaunchTemplate resource in your AWS CloudFormation template. Avoid defining your tags in the AWS::EC2::Instance resource.
1. Define a launch template in the stack with the necessary tags as required by the IAM policy. For example:
RequiredTagsLaunchTemplate: Type: 'AWS::EC2::LaunchTemplate' Properties: LaunchTemplateData: TagSpecifications: - ResourceType: instance 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: instance Tags: - Key: Env Value: Dev
3. Confirm that your launch template has all the necessary tags required by your IAM policy.
If your IAM policy has restrictions on volume tags, include the restrictions in the Type: AWS::EC2::LaunchTemplate section of your launch template. Then, set ResourceType to volume. For example:
TagSpecifications: - ResourceType: volume Tags: - Key: Env Value: Dev
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 API calls made by AWS CloudFormation from tagging requirements.