CloudFormation template - Using existing IAM role in for Lambda functions

Viewed 7670

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 docaws-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 ?

4 Answers

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

Related