Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrieve the cloudformation stack name from the lambda function

I invoke a lambda function from a custom resource in cloudformation template. This custom resource has a property : the name of the cloudformation stack. I need this property value in the lambda function so that I can get other variables like parameters and outputs of the stack. Here is the custom resource:

"DeployApp": {
  "Type" : "Custom::deployapplication",
  "Properties" : {
    "ServiceToken": { "Fn::GetAtt" :  ["lambda" , "Arn"]  },
    "StackName": { "Ref": "AWS::StackName" }
  }
}

For the moment, I get the stack name in the lambda function this way:

import boto3

def lambda_handler(event, context):

    cf_client = boto3.client('cloudformation')
    # Get the name of the stack
    stack = context.invoked_function_arn.split(':')[6]
    stack = stack.split('-')[:4]
    stack_name = stack[0]+'-'+stack[1]+'-'+stack[2]+'-'+stack[3]
    print('CloudFormation stack name : '+stack_name)

Here I always set the name of the stack to something like this:

stack-cfn-lambda-app : 4 words split by '-' But I want to make it more general so that all names formats are accepted. How to do that and get the exact name of the stack without knowing already how the format is going to be?

In other words, how in python I can get from this string (function lambda ARN):

arn:aws:lambda:eu-west-1:53436693423891:function:stackName-ELATEDLEXZPS

the string between :function: and ELATEDLEXZPS ?

like image 888
Souad Avatar asked Oct 23 '25 03:10

Souad


1 Answers

If you already placed the stack name in the function properties, like you do in your first code sample, you can simply access those properties through the event object.

  StackInfo:
    Type: Custom::StackInfo
    Properties:
      ServiceToken: !GetAtt StackInfoFunction2.Arn
      StackName:
        Ref: "AWS::StackName"

Lambda Code:

import json
import cfnresponse
def handler(event, context):
  print("stack name: " + event['ResourceProperties']['StackName'])
  cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
like image 59
jens walter Avatar answered Oct 25 '25 18:10

jens walter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!