2
votes

I'm using CloudFormation to create a lambda function. Most of the documentation assumes the role will be created in the template. Is there a way to specify a role that has already been created via say the console? This question tackles a similar question but for EC2 instance creation: Associate existing IAM role with EC2 instance in CloudFormation

I'm looking for something like:

 "LambdaFunction": {
            "Type": "AWS::Lambda::Function",
            "Properties": {
                "FunctionName": "My Function"
                "Runtime": "netcoreapp2.0",
                "Handler": "handler.location",
                "Role": "Existing_Role"
3

3 Answers

4
votes

If you refer to the cloud formation documentation,

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html

you can locate the Role attribute to replace your role.

It needs in arn format, not simply the rolename.

arn:aws:iam::554668579590:role/ProdAdmin

"FunctionName": {
  "Type": "AWS::Lambda::Function",
  "Properties": {
    "Handler": "index.handler",
    "Role": "arn:aws:iam::AccountID:role/RoleName",
    "Code": {
      "S3Bucket": "lambda-functions",
      "S3Key": "amilookup.zip"
    },
    "Runtime": "nodejs4.3",
    "Timeout": 25,
    "TracingConfig": {
      "Mode": "Active"
   }
  }
}
0
votes

To run on multiple accounts with CloudFormation StackSets use Fn::Sub to substitutes variables - in this case, using Account ID:

"FunctionName": {
  "Type": "AWS::Lambda::Function",
  "Properties": {
    "Handler": "index.handler",
    "Role": { "Fn::Sub": "arn:aws:iam::${AWS::AccountId}:role/RoleName" },
    "Code": {
      "S3Bucket": "lambda-functions",
      "S3Key": "amilookup.zip"
    },
    "Runtime": "nodejs4.3",
    "Timeout": 25,
    "TracingConfig": {
      "Mode": "Active"
   }
  }
}
0
votes

This works "Role": { "Fn::Sub": "arn:aws:iam::${AWS::AccountId}:role/RoleName" },