Over 10 years we help companies reach their financial and branding goals. Engitech is a values-driven technology agency dedicated.

Gallery

Contacts

Bhubaneswar, India

info@krescitus.com

+1 -800-456-478-23

Imagine you’re about to launch a web application. You need servers, databases, storage, security configurations, and perhaps a content delivery network. You could go into AWS, manually create each resource, configure them, and wire everything together. But there’s a catch: what if you need to repeat this process multiple times for different environments like development, testing, and production? And what happens if you need to modify something later on or deploy the same infrastructure for another project? Manually managing cloud resources can become tedious, error-prone, and inconsistent.

       This is where AWS CloudFormation comes into play—offering a way to automate and manage your entire infrastructure as code, effortlessly. But how does it actually work, and why should you use it? Let’s dive into the story of how CloudFormation can transform your cloud deployments from a manual slog into a streamlined, repeatable process.

What is CloudFormation, and What is a Stack?

At its core, AWS CloudFormation is a service that allows you to define your entire cloud infrastructure using code—either in JSON or YAML format. This definition is called a CloudFormation template. Think of it like a blueprint or an instruction manual for AWS, detailing exactly which resources you need and how they should be configured.

Now, let’s say you’ve finished writing your CloudFormation template for a typical web application. You’ve defined your EC2 instances for your servers, an S3 bucket to store user-uploaded files, an RDS database for storing user data, and an IAM role to control access to these resources. Once your template is ready, you simply upload it to AWS CloudFormation, and—here’s where the magic happens—CloudFormation will automatically create all the resources defined in the template. It’s like clicking a button and watching your infrastructure spring into existence, all at once.

This collection of resources that CloudFormation creates is what we call a CloudFormation Stack. A stack is like a neatly packaged bundle of all the AWS services your application depends on. You can manage this entire group of resources as a single unit—creating, updating, or deleting them all at once.

How Does CloudFormation Work?

Let’s break down how CloudFormation works using a real-world scenario.

Imagine you’re deploying a multi-tier web application that consists of a frontend hosted on EC2 instances, a backend API running on Lambda, and a database on Amazon Aurora. You start by writing a CloudFormation template that defines these components. This template is written in a structured way, specifying resources like EC2 instances, Aurora database clusters, security groups, and API Gateway configurations. Each resource is described with its necessary settings: for example, the size of the EC2 instance, the security group rules, and the subnet it should belong to.

Once the template is ready, you go to the CloudFormation console or use the AWS CLI to deploy it. AWS then interprets the template, figures out what needs to be created first (like creating a security group before launching EC2 instances), and provisions everything in the correct order. This process ensures that the infrastructure is built in a reliable, automated manner, avoiding common pitfalls like missing dependencies or misconfigured settings.

After the resources are deployed, CloudFormation keeps track of everything within the stack. If you ever need to update your infrastructure—say, increase the size of your EC2 instances or add a new Lambda function—you can simply modify the template and apply the update. CloudFormation will carefully compare the changes and make sure to only update the necessary parts of your infrastructure, leaving everything else untouched. This way, you can modify large deployments with minimal risk.

Why Should You Use CloudFormation?

So why go through the effort of learning CloudFormation? The short answer: automation, consistency, and control. But let’s put it into perspective with a few examples.

Infrastructure as Code: Consistency and Reusability

Consider a situation where you need to replicate your cloud environment for three different stages: development, staging, and production. Manually setting up resources three times isn’t just time-consuming—it’s also error-prone. You might accidentally configure something slightly different between environments, which could lead to unpredictable bugs or security vulnerabilities.

With CloudFormation, you write your template once, and you can deploy it as many times as you need. You can even parameterize parts of the template to change things like the instance size or database settings based on the environment. The result is consistent, reusable infrastructure, where each environment is a carbon copy of the other, ensuring that what works in staging will work in production.

Automated Updates and Rollbacks

Picture this: you’ve deployed your application, but now your business needs are changing. You want to scale your application by adding more EC2 instances or switching from a single Aurora instance to a multi-AZ setup. Normally, this would involve logging into AWS, manually tweaking settings, and hoping that nothing breaks.

With CloudFormation, you simply modify the template and update the stack. CloudFormation will automatically apply the necessary changes, whether it’s launching additional instances or modifying a database configuration. If anything goes wrong during the update (perhaps the new instance type isn’t available in your region), CloudFormation has your back. It will automatically roll back the changes, ensuring your infrastructure remains in a stable state. This ability to roll back in case of failure makes updates far less risky.

 

Simplified Resource Management

Let’s say you’re working on a temporary project that requires a dozen AWS resources—EC2 instances, S3 buckets, Lambda functions, and so on. Once the project is complete, manually tearing down each resource one by one can be a hassle, and missing even one resource could leave you with unexpected charges.

With CloudFormation, deleting a stack is as simple as a single click or command. Deleting the stack will automatically clean up every resource that was created as part of the deployment. No more hunting down stray resources. Everything is managed in a clean, predictable way.

 

STEP BY STEP PROCESS:

    “well, i have a angular project built to change the background image of any picture. so for this functionality i am using aws api gateway, lambda function, s3 and amazon bedrock , now i want to create cloud formation stack for the solution, so that user can deploy everything in one click “

 

         To create a CloudFormation stack for your solution (which uses AWS API Gateway, Lambda, S3, and Amazon Bedrock), you’ll need to design a CloudFormation template that provisions all of these resources. This will enable one-click deployment for users. Here’s a high-level approach and a YAML-based template structure you can use.

Components to Include in the CloudFormation Stack:

  1. S3 Bucket: Store images (input and output) for background removal.
  2. Lambda Function: Process images by calling Amazon Bedrock.
  3. API Gateway: Expose an HTTP endpoint for invoking the Lambda function.
  4. IAM Roles: Define permissions for Lambda, API Gateway, and S3.
  5. Amazon Bedrock: Invoke Bedrock from the Lambda function (if you have a custom API call for that).

STEP-1:

STEP-2: Creating Cloud Formation Stack:

1.First create a .yml file in your local and paste the following yaml code.

CloudFormation Template Structure (YAML):

AWSTemplateFormatVersion: 2010-09-09

Description: CloudFormation template for an Angular project to change the

  background of images using AWS API Gateway, Lambda, S3, and Bedrock.

Resources:

  S3Bucket:

    Type: AWS::S3::Bucket

    Properties:

      BucketName: ${AWS::StackName}-image-storage

      PublicAccessBlockConfiguration:

        BlockPublicAcls: false

        BlockPublicPolicy: false

        IgnorePublicAcls: false

        RestrictPublicBuckets: false

  S3BucketPolicy:

    Type: AWS::S3::BucketPolicy

    Properties:

      Bucket: S3Bucket

      PolicyDocument:

        Version: 2012-10-17

        Statement:

          – Effect: Allow

            Principal: “*”

            Action: s3:GetObject

            Resource: arn:aws:s3:::${S3Bucket}/*

  LambdaExecutionRole:

    Type: AWS::IAM::Role

    Properties:

      AssumeRolePolicyDocument:

        Version: 2012-10-17

        Statement:

          – Effect: Allow

            Principal:

              Service: lambda.amazonaws.com

            Action: sts:AssumeRole

      Policies:

        – PolicyName: LambdaS3AndBedrockAccess

          PolicyDocument:

            Version: 2012-10-17

            Statement:

              – Effect: Allow

                Action:

                  – s3:PutObject

                  – s3:GetObject

                  – s3:DeleteObject

                Resource: arn:aws:s3:::${S3Bucket}/*

              – Effect: Allow

                Action: lambda:InvokeFunction

                Resource: “*”

              – Effect: Allow

                Action:

                  – bedrock:InvokeModel

                  – bedrock:DescribeModel

                Resource: “*”

  ImageProcessingLambda:

    Type: AWS::Lambda::Function

    Properties:

      FunctionName: ${AWS::StackName}-image-processing

      Runtime: python3.9

      Handler: lambda_function.lambda_handler

      Role: LambdaExecutionRole.Arn

      Code:

        S3Bucket: background-change-code-for-stack

        S3Key: image-processing.zip

      Timeout: 600

      Environment:

        Variables:

          OUTPUT_BUCKET: S3Bucket

          BEDROCK_MODEL_NAME: arn:aws:bedrock:ap-south-1::foundation-model/amazon.titan-image-generator-v1

  ApiGateway:

    Type: AWS::ApiGateway::RestApi

    Properties:

      Name: ${AWS::StackName}-api

      Description: API Gateway for image background change

  ApiGatewayResource:

    Type: AWS::ApiGateway::Resource

    Properties:

      ParentId: ApiGateway.RootResourceId

      RestApiId: ApiGateway

      PathPart: process

  ApiGatewayMethod:

    Type: AWS::ApiGateway::Method

    Properties:

      AuthorizationType: NONE

      HttpMethod: POST

      ResourceId: ApiGatewayResource

      RestApiId: ApiGateway

      Integration:

        Type: AWS_PROXY

        IntegrationHttpMethod: POST

        Uri: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${ImageProcessingLambda.Arn}/invocations

  LambdaApiPermission:

    Type: AWS::Lambda::Permission

    Properties:

      FunctionName: ImageProcessingLambda

      Action: lambda:InvokeFunction

      Principal: apigateway.amazonaws.com

      SourceArn: arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${ApiGateway}/*/POST/process

Outputs:

  ApiUrl:

    Description: API Gateway URL for image processing

    Value: https://${ApiGateway}.execute-api.${AWS::Region}.amazonaws.com/prod/process

  S3BucketName:

    Description: S3 Bucket Name where images are stored

    Value: S3Bucket

 

  1. Now open Cloudformation and create a stack.

Upload your .yml file , click Next

Give a name, (give name in lower case only, as it will be used to create s3 bucket dynamically, it will give error.)

Then click Next and and create your stack.

Then it will create all the required resources for you as shown in image below.

After it you can the use the newly created API in your angular application.

 

Conclusion

 AWS CloudFormation is a powerful tool that turns cloud infrastructure management into a streamlined, automated process. Whether you’re deploying a simple web app or managing a complex microservice architecture, CloudFormation enables you to define your resources as code, ensuring consistent, scalable, and easily maintainable infrastructure. It’s more than just a tool—it’s a game-changer for anyone working with cloud technologies, helping to eliminate human error, automate complex setups, and simplify ongoing management. In the end, using CloudFormation means you can focus more on building applications and less on wrangling infrastructure.