CloudFormation – 6 – DependsOn, Lambda

DependsOn

DependsOn is a way to say that some resource can’t be created before other resource is created.  Consider a template::

EC2 instance will not be created until MyDB resource is successfully created.

Let’s run the template:

CloudFormation -> Stacks -> Create stack

Next -> Next -> Create Stack

As we see the MyDB is beeing created as a first resource in the stack:

 

Deploying Lambda Functions

First way of defining a lambda function in CloudFormation is Inline.

Consider such a template:

Let’s run the template:

CloudFormation -> Stacks -> Create stack

Next -> Next -> Create stack -> Requires capabilities : [CAPABILITY_IAM] ->  Review LambdaInline

Create stack ->

As we see the lambda function has been created:

Let’s test the lambda function:

Lambda function simply list all s3 buckets which we have in AWS account.

A second way of defining a lambda function in CloudFormation is to use a zip from S3.

First we need to zip an index.py file:

And then upload the zip file to the S3 service.

Upload->

In CloudFormation template file we need to reference to the uploaded zip file:

Now let’s create a stack:

Next ->

Next -> Next ->

Create stack ->

A new lambda function has been created:

The code of new function is the same as old code because CloudFormation retrieved zip file and unziped it.

What if we want to upload a new version of lambda-function.zip. We can change S3Bucket: !Ref S3BucketParam or S3Key: !Ref S3KeyParam but better way is to use a template with versioning:

Let’s upload the same lambda-function.zip file to the S3 bucket and check the version-id:

Now let’s update the stack:

Next ->

Next ->

Update stack ->

 

Custom Resources

You can define a Custom Resource in CloudFormation to address any of these use cases:

  • An AWS resource is yet not covered (new service for example)
  • An On-Premise resource
  • Emptying an S3 bucket before being deleted
  • Fetch an AMI id
  • Anything you want…!

CloudFormation Custom Resources (Lambda)

  • The Lambda Function will get invoked only if there is a Create, Update or Delete event, not every time you run the template

Consider a yaml tamplate, this is an inline method:

Let’s create a stack:

Next ->

Next ->

Create stack ->

Labda funcion has been created:

Consider a yaml template with custom resource:

Now let’s create a stack with custom recource:

Next ->

Next -> Create stack

After th new stack has been created we can go to the rosurces and see that S3 bucket has been created also:

We can  go to this 33 bucket and upload a random file here:

Upload ->

Now let’s delete the stack.

 

When the stack has been deleted the lambda funcion cleaned up the S3 Bucket.