如何通过CloudFormation为AWS IAM Role设置描述?
如何通过CloudFormation为IAM Role设置描述
我完全懂你碰到的这个痛点——AWS控制台明明能轻松给IAM角色加描述,但翻CloudFormation文档却找不到对应的配置方法,试了好几种写法要么不生效要么报错,确实让人头疼。我来帮你拆解一下问题,再给出可行的解决方案:
先分析你试过的几种写法为什么不行:
- 把
Description放在Properties里:CloudFormation的特性是会忽略它不识别的属性,所以不会报错,但也不会把这个值传给IAM服务,自然控制台看不到描述; - 把
Description直接放在资源层级下:CloudFormation要求资源的所有配置属性都必须放在Properties块里,直接放在外面属于不符合规范的结构,所以会报"不支持的属性"错误; - 尝试用
Tags存储描述:早期版本的AWS::IAM::Role确实不支持Tags属性(后来AWS更新后支持了,但你的写法也不对——Tags需要是对象数组格式,比如[{Key: "Description", Value: "My Description"}]),而且就算标签配置成功,它也和IAM角色的原生描述不是一回事,不会显示在控制台的描述字段里。
正确的解决方案
方案1:使用CloudFormation原生支持的Description属性(推荐,若环境支持)
AWS后来已经更新了AWS::IAM::Role资源,现在可以直接在Properties里配置Description属性,写法如下:
Resources: MyRole: Type: "AWS::IAM::Role" Properties: Description: "这是我的IAM角色描述" AssumeRolePolicyDocument: Version: "2012-10-17" Statement: - Effect: Allow Principal: Service: ec2.amazonaws.com Action: sts:AssumeRole # 可以添加其他角色属性,比如ManagedPolicyArns、Path等
如果你的AWS区域和CloudFormation版本支持这个属性,执行栈创建/更新后,控制台就能看到对应的描述了。
方案2:用自定义资源(Custom Resource)调用IAM API(兼容旧环境)
如果你的环境还不支持原生的Description属性,那就需要借助CloudFormation自定义资源,通过Lambda函数调用IAM的UpdateRoleDescription API来设置描述。具体模板示例如下:
1. 定义目标IAM角色
Resources: MyRole: Type: "AWS::IAM::Role" Properties: AssumeRolePolicyDocument: Version: "2012-10-17" Statement: - Effect: Allow Principal: Service: ec2.amazonaws.com Action: sts:AssumeRole
2. 创建Lambda执行角色(赋予更新角色描述的权限)
LambdaExecutionRole: Type: "AWS::IAM::Role" Properties: AssumeRolePolicyDocument: Version: "2012-10-17" Statement: - Effect: Allow Principal: Service: lambda.amazonaws.com Action: sts:AssumeRole ManagedPolicyArns: - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole Policies: - PolicyName: UpdateRoleDescriptionAccess PolicyDocument: Version: "2012-10-17" Statement: - Effect: Allow Action: iam:UpdateRoleDescription Resource: !GetAtt MyRole.Arn
3. 定义处理自定义资源的Lambda函数
SetRoleDescriptionLambda: Type: "AWS::Lambda::Function" Properties: Runtime: python3.9 Handler: index.lambda_handler Role: !GetAtt LambdaExecutionRole.Arn Code: ZipFile: | import boto3 import cfnresponse iam_client = boto3.client('iam') def lambda_handler(event, context): try: role_name = event['ResourceProperties']['RoleName'] target_description = event['ResourceProperties']['Description'] # 创建或更新栈时设置描述 if event['RequestType'] in ['Create', 'Update']: iam_client.update_role_description( RoleName=role_name, Description=target_description ) # 删除栈时可选择清除描述,这里默认不处理 cfnresponse.send(event, context, cfnresponse.SUCCESS, {}) except Exception as e: cfnresponse.send(event, context, cfnresponse.FAILED, {'ErrorDetail': str(e)})
4. 定义自定义资源触发Lambda
MyRoleDescriptionSetter: Type: "AWS::CloudFormation::CustomResource" Properties: ServiceToken: !GetAtt SetRoleDescriptionLambda.Arn RoleName: !Ref MyRole Description: "这是通过自定义资源设置的IAM角色描述" DependsOn: MyRole
当栈创建或更新时,自定义资源会触发Lambda函数,调用IAM API为MyRole设置描述,控制台就能正常显示了。
内容的提问来源于stack exchange,提问作者Sam Anthony
相关产品推荐
相关产品推荐

