Build your Serverless Infrastructure as a Code(IaC) using AWS Cloud Formation

AWS Cloud Formation is a service providing Infrastructure as a Code(IaC) feature to AWS users. It is exclusively used for AWS services. It is the easiest way to create multiple services required for an Application on AWS by using simple statements. It reduces the time taken to build the infrastructure using the console, CLI, API or SDK and uses simple declarative languages JSON and YAML. It supports almost all the services except very few and AWS is trying to add others too. It is an easy way to replicate the infrastructure for multiple environments. Before going to the implementation part you must have a look at concepts and terminology used in it.

AWS ClouFromation Image
AWS Cloud Formation

Let us create one RESTful service using a Lambda function, API Gateway and IAM roles. IAM service is required to create roles(permissions) to invoke a lambda function self and from API Gateway. Cloud Formation Templates can be created in multiple ways and it depends on the programmer feasibility. But it is advisable to follow the best practices of AWS. I will use the most simple way to create resources.

Note: This demo is using Cloud Formation, not the SAM.

  1. IAM Roles creation for Lambda Execution and Lambda invocation from API Gateway:

We are only adding lambda basic execution permission for lambda’s role and for API Gateway Lambda invoke only through custom policy. You can find two ways to create the roles, one with the managed policy and another with the custom policy.

2. Lambda function creation:

Let us create a simple lambda function with hello world message. We are using zip file functionality in cloud formation stack to upload the code. Remember we are using AWS_PROXY setup for API Gateway method, so we must need to pass statusCode and the body.

3. API Gateway creation:

We are creating one API Gateway, Resource, GET Method and enabling CORS through this. Remember, after the creation of methods in the resources we must deploy the API to reflect the changes as we do from the console or SDK.

Let us look at the whole template with all the parts. This strategy is a little bit difficult as it is having more code, we can use the SAM template to reduce the code by using Transform feature in cloud formation. We will look into the SAM template later.

Run the stack and test with the endpoint rendered in the Outputs section, yes you did it. That’s it with the cloud formation for the serverless infrastructure.

Thanks for reading the blog. Feel free to comment and let me know your opinion on the blog and content to make changes to increase the readability.

--

--