简体   繁体   中英

CloudFormation template - Using existing IAM role in for Lambda functions

I'm trying to use an existing role (present in the AWS account) in a cloudformation template to setup a lambda function, i plan to be use this across multiple AWS accounts.

In the CF template, I'm using Parameters to set the name of the Role and then using Ref in the Role property for the Lambda function. This is what my template looks like,

"Parameters" : {
  "ExistingRoleName" : {
    "Type" : "String",
    "Default" : "MyCustomRole"
  }
"Resources" : {
  "CustomLambdaFunction" : {
    "Type" : "AWS::Lambda::Function",
     "Properties" : {
      "MemorySize" : "128",
      "Role" : { "Ref" : "ExistingRoleName" },
    }
  },
  ...

However, the CF template fails with the following error:

Properties validation failed for resource CustomLambdaFunction with message: #/Role: failed validation constraint for keyword [pattern]

Is this because Lambda resource in Cloudformation needs the role arn instead of RoleName as i seen in this doc aws-resource-lambda-function

Based on which i updated the CF like so,

"Resources" : {
  "CustomLambdaFunction" : {
    "Type" : "AWS::Lambda::Function",
     "Properties" : {
      "MemorySize" : "128",
      "Role" : "arn:aws:iam::AccountID:role/MyCustomRole",
    }
  },

However, i still see the same error.

Properties validation failed for resource CustomLambdaFunction with message: #/Role: failed validation constraint for keyword [pattern]

I was wondering if i'm missing something here?

The Ref of an IAM Role “returns the resource name” , not its ARN. But you can use GetAtt on the Arn attribute of the role instead.

In JSON:

{"Fn::GetAtt": ["MyRole", "Arn"]}

In YAML:

!GetAtt MyRole.Arn

Format to reference the iam role arn
"Role" : { "Fn::Sub" : "arn:aws:iam::${AWS::AccountId}:role/MyCustomRole" }

This is what worked for me,

"Role": { "Fn::Join" : [ "", [ "arn:aws:iam::", { "Ref" : "AWS::AccountId" }, ":role/MyCustomRole" ] ] }

In yaml if you are pointing to an already existing role the syntax is:

function:
  ...
  role: !Sub arn:aws:iam::${AWS::AccountId}:role/MyRoleName

Somehow I have forgotten the !Sub in the beginning

I was getting the same problem with below syntax -

"Resources" : {
  "CustomLambdaFunction" : {
    "Type" : "AWS::Lambda::Function",
     "Properties" : {
      "Role" : "arn:aws:iam::<account-id>:role/MyCustomRole",
    }
  },

I solved it like this - The issue was that when inserting my AWS account ID in place of "account-id", I was keeping it in the same format as is given on the AWS console ie xxxx-xxxx-xxxx. However, the "account-id" space expects "\d{12}" format, ie 12 digits only. Removing the '-' in between digits solved the problem for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM