如何获取动态创建的 lambda 角色的名称?

How do I get the name of a dynamically created lambda role?

我喜欢部署模板时创建角色 + 内联策略的方式:

资源:

MyFUnction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
        Description: Enter description of what this specific Lambda does
        CodeUri: hello_world/build/
        Handler: app.lambda_handler
        Runtime: python2.7

        Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object
            Variables:
                PARAM1: VALUE

        Policies:
            # Using AWSLambdaExecute automatically creates a role named: <StackName>Role-<UUID>
            - AWSLambdaExecute
            # This policy is assigned as an  Inline policy to the role
            - Version: '2012-10-17' # Policy Document
              Statement:
                  Effect: Allow
                  Action: ......

现在我可以引用动态创建的角色并在 SAM 模板中为它添加一个输出吗?

SAM 为您创建的最终角色只是在您的函数名称末尾添加了 "Role"。您可以使用此信息通过普通的 CloudFormation 函数获取角色或其属性。

例如,如果您想访问 MyFunction 的角色 ARN,您可以在 SAM YAML 模板中使用 !GetAtt MyFunctionRole.Arn。同样的原则应该适用于 !Ref 和其他功能。

我能够测试一个解决方案,在 SAM template.yaml 中,您可以像在 CloudFormation 中一样为逻辑 ID 添加输出,该逻辑 ID 在使用时作为转换的一部分自动为您创建Policies for AWS::Serverless::Function

等属性

生成的 IAM 角色的逻辑 ID 是 <Function Logical ID>Role,我使用了以下内容:

Outputs:
  LambdaRole:
    Value: 
      Fn::GetAtt: 
        - "LambdaFunctionRole"
        - "Arn"
    Description: "Lambda IAM Role"