CloudFormation: AWS Infrastructure as Code

CloudFormation: AWS Infrastructure as Code

What is CloudFormation

CloudFormation is AWS native Infrastructure as Code (IaC) service. It allows for modelling, provisioning and managing of AWS resources in a structured, repeatable, and automated way. With CloudFormation, you do not need to individually create and configure AWS resources (like Amazon EC2 instances or Amazon RDS DB instances) and rack your brain about what is dependent on what. But you just define your AWS cloud infrastructure using a text-based template written in JSON or YAML format and CloudFormation handles the rest.

Benefits of AWS CloudFormation

Simplify Infrastructure Management

Infrastructure management like provisioning and configuring resources individually can be time consuming and complexity could be introduced at times. By using CloudFormation, you easily manage a collection of resources as a single unit (template). A template describes all your resources and their properties. When you use a template to create a CloudFormation stack, CloudFormation provisions the resources for you. After the stack has been successfully created, your AWS resources are up and running. You can delete the stack just as easily, which deletes all the resources in the stack.

Repeatability

CloudFormation helps in reduction of human error by eliminating manual configuration that can introduce inconsistencies. Enabling quick replication without repetitive tasks help to save time. Repeatable templates improve collaboration as teams can share and use the same standardized configurations. Additionally, it facilitates compliance by enforcing company policies and standards through pre-approved templates.

Simplifies Infrastructure Automation

Infrastructure automation is simplified by defining, provisioning, and managing AWS resources as code. With CloudFormation, you can create reusable templates for infrastructure, seamlessly integrate with CI/CD pipelines, and deploy environments quickly, improving scalability and operational efficiency.

Cost Management

With AWS CloudFormation you ensure that only the necessary infrastructure is deployed. By using templates, you can standardize resource configurations, avoid over-provisioning, and eliminate manual errors that may lead to unexpected costs. Additionally, CloudFormation integrates with AWS billing and monitoring tools, allowing you to track and optimize resource utilization, ensuring cost efficiency across your AWS deployments.

Integration

AWS CloudFormation seamlessly work with other AWS services and third-party tools, enabling streamlined workflows and enhanced automation. By integrating with services like AWS CodePipeline, CloudFormation supports Continuous Integration/Continuous Deployment (CI/CD) pipelines for efficient infrastructure and application delivery. It integrates with AWS CloudWatch for monitoring and automated scaling, AWS Config for compliance and resource tracking, and IAM for secure access control. Additionally, it works well with SDKs, CLI tools, and IDEs like AWS CloudFormation Designer, providing flexibility for developers and DevOps teams to manage resources programmatically or visually.

Declarative Approach

AWS CloudFormation allows users to define the desired state of their infrastructure, focusing on what resources are needed rather than how to provision them. This simplifies the deployment process by removing the need for manual steps and its complexities. Also, since the infrastructure is defined in code, it can be versioned, reused, and shared, making it easier to replicate environments, manage changes, and maintain scalability across different projects and teams.

CloudFormation Deployment Tools

CloudFormation is available through the following

  • AWS Management Console: For visual management.

  • AWS CLI: For automating stack management through scripting.

  • AWS SDKs: For programmatic access in languages like Python, Java, and .NET.

  • AWS CDK: Use high-level programming languages to define infrastructure.

  • AWS CloudFormation Designer: A drag-and-drop tool for visualizing templates.

Use Cases

  • Multi-tier Architectures: Define resources for web, application, and database layers.

  • Serverless Applications: Manage Lambda, DynamoDB, and API Gateway resources.

  • CI/CD Pipelines: Automate infrastructure deployment as part of DevOps processes.

  • Disaster Recovery: Replicate infrastructure across regions for high availability.

Key Concepts

When you use CloudFormation, you work with templates and stacks. You create templates to describe your AWS resources and their properties. Whenever you create a stack, CloudFormation provisions the resources that are described in your template.

Templates

A CloudFormation template is a text file in YAML or JSON format. The files extension could be .yaml, .json, . template, or .txt. CloudFormation uses these templates as blueprints for building your AWS resources. Whatever you described in the template is what CloudFormation uses to build the stack with which it creates the resources.

Examples

  • example.yaml

      AWSTemplateFormatVersion: '2010-09-09'
      Description: An example CloudFormation template to create an EC2 instance with a security group.
    
      Resources:
        # Security Group
        MySecurityGroup:
          Type: AWS::EC2::SecurityGroup
          Properties:
            GroupDescription: Allow SSH and HTTP access
            SecurityGroupIngress:
              - IpProtocol: tcp
                FromPort: 22
                ToPort: 22
                CidrIp: 0.0.0.0/0
              - IpProtocol: tcp
                FromPort: 80
                ToPort: 80
                CidrIp: 0.0.0.0/0
    
        # EC2 Instance
        MyEC2Instance:
          Type: AWS::EC2::Instance
          Properties:
            InstanceType: t2.micro
            KeyName: My-KeyPair # Replace with your key pair name
            SecurityGroups:
              - !Ref MySecurityGroup
            ImageId: ami-0c02fb55956c7d316 # Amazon Linux 2 AMI (replace with your region's AMI ID)
    
      Outputs:
        InstanceID:
          Description: The Instance ID of the created EC2 instance
          Value: !Ref MyEC2Instance
        InstancePublicIP:
          Description: The Public IP of the created EC2 instance
          Value: !GetAtt MyEC2Instance.PublicIp
    
  • example.json

      {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Description": "An example CloudFormation template to create an EC2 instance with a security group.",
        "Resources": {
          "MySecurityGroup": {
            "Type": "AWS::EC2::SecurityGroup",
            "Properties": {
              "GroupDescription": "Allow SSH and HTTP access",
              "SecurityGroupIngress": [
                {
                  "IpProtocol": "tcp",
                  "FromPort": 22,
                  "ToPort": 22,
                  "CidrIp": "0.0.0.0/0"
                },
                {
                  "IpProtocol": "tcp",
                  "FromPort": 80,
                  "ToPort": 80,
                  "CidrIp": "0.0.0.0/0"
                }
              ]
            }
          },
          "MyEC2Instance": {
            "Type": "AWS::EC2::Instance",
            "Properties": {
              "InstanceType": "t2.micro",
              "KeyName": "MyKeyPair", 
              "SecurityGroups": [
                {
                  "Ref": "MySecurityGroup"
                }
              ],
              "ImageId": "ami-0c02fb55956c7d316"
            }
          }
        },
        "Outputs": {
          "InstanceID": {
            "Description": "The Instance ID of the created EC2 instance",
            "Value": {
              "Ref": "MyEC2Instance"
            }
          },
          "InstancePublicIP": {
            "Description": "The Public IP of the created EC2 instance",
            "Value": {
              "Fn::GetAtt": [
                "MyEC2Instance",
                "PublicIp"
              ]
            }
          }
        }
      }
    

Stacks

A stack in CloudFormation comprise of related resources managed as a single unit. You create, update, and delete a collection of resources by creating, updating, and deleting stacks. All the resources in a stack are defined by the stack's CloudFormation template.

Change sets

A change set is a summary of a proposed changes. It allows you to see how the intended update might impact your running resources, especially for critical resources, before implementing them. It is important to use change sets before carrying out update to our environment. With this you can choose your actions wisely and plan accordingly before updating your stack.

How it Works

  • Write a Template: Use JSON or YAML to define resources.

  • Deploy a Stack: Upload the template to CloudFormation.

  • Monitor Resources: Use the CloudFormation dashboard to track progress.

  • Update and Manage: Make changes by updating the template and applying them to the stack.