使用CloudFormation创建资源受AWS IAM策略限制的问题排查
问题描述
作为SSO用户,我所扮演的AWS IAM角色已附加以下IAM强制策略:
{ "Effect": "Allow", "Action": "ec2:CreateSecurityGroup", "Resource": "arn:aws:ec2:*:*:security-group/*", "Condition": { "StringLike": { "aws:RequestTag/Name": "*UserDefined*" } } }
使用AWS CLI脚本可成功创建符合标签要求的安全组:
VPC_ID='vpc-12345678901234567' AWS_PROFILE='my-aws-profile' AWS_REGION='eu-west-1' aws ec2 create-security-group \ --profile ${AWS_PROFILE} \ --region ${AWS_REGION} \ --description "For Testing" \ --group-name "my-test-security-group" \ --vpc-id ${VPC_ID} \ --tag-specifications 'ResourceType=security-group,Tags=[{Key=Name,Value=UserDefined-my-test-sg}]'
但使用相同AWS Profile通过CloudFormation模板创建同配置安全组时失败:
AWSTemplateFormatVersion: '2010-09-09' Parameters: VPC: Type: AWS::EC2::VPC::Id Default: vpc-12345678901234567 Resources: MySecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupName: my-test-security-group GroupDescription: For Testing VpcId: !Ref VPC Tags: - Key: Name Value: UserDefined-my-test-sg
报错信息:
You are not authorized to perform this operation. User: arn:aws:sts:::assumed-role/AWSRstrictedSSO_Ops_7f991be0d78c1285/user@company.com is not authorized to perform: ec2:CreateSecurityGroup on resource: arn:aws:ec2:eu-west-1:12345678012:security-group/* because no identity-based policy allows the ec2:CreateSecurityGroup action.
原因与解决方案
问题核心是CloudFormation与CLI的安全组创建流程不同:
- CLI调用
create-security-group时,标签随创建请求一同发送,IAM策略的aws:RequestTag条件能直接识别标签,权限校验通过。 - CloudFormation会分两步操作:先创建不带标签的安全组,再单独调用
CreateTags接口添加标签。第一步创建请求中没有Name标签,不符合IAM策略的aws:RequestTag/Name条件,导致权限校验失败。
解决方法是修改IAM策略,适配CloudFormation的两步流程:
调整后的IAM策略方案一
允许创建不带标签的安全组,同时授权后续添加符合要求标签的操作:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "ec2:CreateSecurityGroup", "Resource": "arn:aws:ec2:*:*:security-group/*", "Condition": { "Null": { "aws:RequestTag/Name": "true" } } }, { "Effect": "Allow", "Action": "ec2:CreateTags", "Resource": "arn:aws:ec2:*:*:security-group/*", "Condition": { "StringLike": { "aws:RequestTag/Name": "*UserDefined*" } } } ] }
调整后的IAM策略方案二
改用aws:ResourceTag条件,确保最终资源的标签符合要求,同时覆盖创建和打标签操作:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ec2:CreateSecurityGroup", "ec2:CreateTags" ], "Resource": "arn:aws:ec2:*:*:security-group/*", "Condition": { "StringLike": { "aws:ResourceTag/Name": "*UserDefined*" } } } ] }
修改完成后,重新执行CloudFormation模板即可成功创建安全组。
内容的提问来源于stack exchange,提问作者Rafiq
相关产品推荐
相关产品推荐

