Set up a CI/CD pipeline to run lambda tests using AWS cloud service emulator named LocalStack

Recently, I have explored LocalStack AWS local stack to test cloud application locally. You can test the lambda in the AWS lambda console or Moto i.e. mocking. However running tests against LocalStack, would be good as this would not incur any cost of using AWS Services. LocalStack can be used for running any AWS service locally as well as on the CI/CD environment as well.

I was looking to develop CI/CD flow for tests, I could not locate much samples on the internet. In this blog, I have recorded the flow I have written running ci-cd against LocalStack.


Steps to write ci-cd flow:

This can be achieved using following steps:

1. First start localstack services, this can be done using following step, you can mention required services under SERVICES mentioned in env

jobs:
  localstack:
    runs-on: ubuntu-latest
    services:
      localstack:
        image: localstack/localstack:latest
        env:
          SERVICES: lambda
          DEFAULT_REGION: eu-west-1
          AWS_ACCESS_KEY_ID: localkey
          AWS_SECRET_ACCESS_KEY: localsecret
        ports:
          - 4566:4566
          - 4571:4571

2. Install python dependencies and run tests

steps:
      - uses: actions/checkout@v2
      - name: Install Python 3.8
        uses: actions/setup-python@v1
        with:
          python-version: 3.8
      - name: Install dependencies
        run: |
          pip3 install --upgrade pip==20.0.1
          pip3 install -r requirements.txt
      # Execute Tests lambda
      - name: Run test for sample lambda
        run: |
          cd lambda
          pytest -sv

Note: I have used one sample lambda as an application under test. The test case written to test the sample code as well as ci-cd yml file. I have kept all these in the Repo


ci-cd workflow file after including all above steps:

 
"""
AWS CI-CD Flow using LocalStack
"""
name: Aws Localstack CI
on: push
jobs:
  localstack:
    runs-on: ubuntu-latest
    services:
      localstack:
        image: localstack/localstack:latest
        env:
          SERVICES: lambda
          DEFAULT_REGION: eu-west-1
          AWS_ACCESS_KEY_ID: localkey
          AWS_SECRET_ACCESS_KEY: localsecret
        ports:
          - 4566:4566
          - 4571:4571
    steps:
      - uses: actions/checkout@v2
 
      - name: Install Python 3.8
        uses: actions/setup-python@v1
        with:
          python-version: 3.8
      - name: Install dependencies
        run: |
          pip3 install --upgrade pip==20.0.1
          pip3 install -r requirements.txt
      # Execute Tests lambda
      - name: Run test for sample lambda
        run: |
          pytest -sv

After running test following output will be shown:


I hope this blog helped you to get acquainted and use this library quickly. Thanks for reading!


Leave a Reply

Your email address will not be published. Required fields are marked *