CloudFormation 模板 - 将现有 IAM 角色用于 Lambda 函数

nev*_*ial 17 amazon-web-services aws-cloudformation aws-lambda

我正在尝试使用 cloudformation 模板中的现有角色(存在于 AWS 帐户中)来设置 lambda 函数,我计划在多个 AWS 帐户中使用它。

在 CF 模板中,我使用参数来设置角色的名称,然后在 Lambda 函数的角色属性中使用 Ref。这就是我的模板的样子,

"Parameters" : {
  "ExistingRoleName" : {
    "Type" : "String",
    "Default" : "MyCustomRole"
  }
"Resources" : {
  "CustomLambdaFunction" : {
    "Type" : "AWS::Lambda::Function",
     "Properties" : {
      "MemorySize" : "128",
      "Role" : { "Ref" : "ExistingRoleName" },
    }
  },
  ...
Run Code Online (Sandbox Code Playgroud)

但是,CF 模板失败并出现以下错误:

Properties validation failed for resource CustomLambdaFunction with message: #/Role: failed validation constraint for keyword [pattern]
Run Code Online (Sandbox Code Playgroud)

这是因为 Cloudformation 中的 Lambda 资源需要角色 arn 而不是 RoleName,正如我在此文档aws-resource-lambda-function中看到的那样

基于此我像这样更新了CF,

"Resources" : {
  "CustomLambdaFunction" : {
    "Type" : "AWS::Lambda::Function",
     "Properties" : {
      "MemorySize" : "128",
      "Role" : "arn:aws:iam::AccountID:role/MyCustomRole",
    }
  },
Run Code Online (Sandbox Code Playgroud)

但是,我仍然看到同样的错误。

Properties validation failed for resource CustomLambdaFunction with message: #/Role: failed validation constraint for keyword [pattern]
Run Code Online (Sandbox Code Playgroud)

我想知道我是否在这里遗漏了一些东西?

scy*_*scy 31

IAM角色Ref\xe2\x80\x9c 返回资源名称\xe2\x80\x9d,而不是其 ARN。但您可以改为使用角色的属性GetAttArn

\n

在 JSON 中:

\n
{"Fn::GetAtt": ["MyRole", "Arn"]}\n
Run Code Online (Sandbox Code Playgroud)\n

在 YAML 中:

\n
!GetAtt MyRole.Arn\n
Run Code Online (Sandbox Code Playgroud)\n

  • 这方面的文档分散在所有单独的资源页面中。我发现[这个大列表](https://theburningmonk.com/cloudformation-ref-and-getatt-cheatsheet/)作为快速参考很有用。 (2认同)

小智 4

引用 iam 角色的格式 arn
"Role" : { "Fn::Sub" : "arn:aws:iam::${AWS::AccountId}:role/MyCustomRole" }