我想要透過 AWS CloudFormation 建立 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體。但我的 RunInstances 的 AWS Identity and Access Management (IAM) 政策具有標籤型限制。
簡短說明
您可以使用啟動範本透過 CloudFormation 建立 Amazon EC2 執行個體。
AWS::EC2::Instance 資源的「標籤」內容不會延伸至透過 CloudFormation 建立的磁碟區。如果與使用者或角色相關聯的 IAM 政策具有對磁碟區標籤的限制,則您會收到下列錯誤:
「您無權執行此作業。」
若要將標籤透過 CloudFormation 傳遞至 ec2:CreateVolume,您必須在 CloudFormation 範本的 AWS::EC2::LaunchTemplate 資源中定義標籤。
解決方案
1. 使用 IAM 政策需要的標籤在堆疊中定義啟動範本。例如:
RequiredTagsLaunchTemplate:
Type: 'AWS::EC2::LaunchTemplate'
Properties:
LaunchTemplateData:
TagSpecifications:
- ResourceType: volume
Tags:
- Key: Env
Value: Dev
2. 將啟動範本連接至 EC2 執行個體資源。例如:
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. 確認您的啟動範本具有所有必要的標籤。
**重要事項:**您必須確認建立堆疊的角色或使用者具有建立和使用啟動範本的許可,而無需標記限制。您可以使用 aws:CalledVia 條件金鑰來建立新的陳述式,以免除 CloudFormation API 呼叫的標記需求。