DEV Community

Cover image for Day 48: Automating Infrastructure Deployment with AWS CloudFormation
Thu Kha Kyawe
Thu Kha Kyawe

Posted on

Day 48: Automating Infrastructure Deployment with AWS CloudFormation

Lab Information

The Nautilus DevOps team needs to implement a Lambda function using a CloudFormation stack. Create a CloudFormation template named /root/devops-lambda.yml on the AWS client host and configure it to create the following components. The stack name must be devops-lambda-app.

Create a Lambda function named devops-lambda.
Use the Runtime Python.
The function should print the body Welcome to KKE AWS Labs!.
Ensure the status code is 200.
Create and use the IAM role named lambda_execution_role.
Enter fullscreen mode Exit fullscreen mode

Lab Solutions

πŸ“„ CloudFormation Template

vi devops-lambda.yml
Enter fullscreen mode Exit fullscreen mode
AWSTemplateFormatVersion: '2010-09-09'
Description: DevOps Lambda Application Stack

Resources:

  LambdaExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: lambda_execution_role
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

  DevOpsLambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: devops-lambda
      Runtime: python3.9
      Handler: index.lambda_handler
      Role: !GetAtt LambdaExecutionRole.Arn
      Timeout: 10
      Code:
        ZipFile: |
          def lambda_handler(event, context):
              return {
                  "statusCode": 200,
                  "body": "Welcome to KKE AWS Labs!"
              }
Enter fullscreen mode Exit fullscreen mode

πŸš€ Deploy the Stack

aws cloudformation create-stack \
  --stack-name devops-lambda-app \
  --template-body file:///root/devops-lambda.yml \
  --capabilities CAPABILITY_NAMED_IAM
Enter fullscreen mode Exit fullscreen mode

Wait for completion:

aws cloudformation wait stack-create-complete \
  --stack-name devops-lambda-app
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ (Optional) Test the Lambda

aws lambda invoke \
  --function-name devops-lambda \
  output.json
Enter fullscreen mode Exit fullscreen mode

cat output.json

Expected output:

{
"statusCode": 200,
"body": "Welcome to KKE AWS Labs!"
}


Resources & Next Steps
πŸ“¦ Full Code Repository: KodeKloud Learning Labs
πŸ“– More Deep Dives: Whispering Cloud Insights - Read other technical articles
πŸ’¬ Join Discussion: DEV Community - Share your thoughts and questions
πŸ’Ό Let's Connect: LinkedIn - I'd love to connect with you

Credits
β€’ All labs are from: KodeKloud
β€’ I sincerely appreciate your provision of these valuable resources.

Top comments (0)