Configuring the Backend for Automated Deployment

Configure the backend and the EC2 instance to automate deployment on AWS.

Let’s write the GitHub Action file and configure the backend for automatic deployment.

At the root of the project, we’ll create a directory called .github, and inside this directory, we’ll create another directory called workflows. Inside the workflows directory, we’ll create a file called ci-cd.yml. This file will contain the YAML configuration for the GitHub Action. Let’s start by defining the name and the events that will trigger the running of the workflow:

Press + to interact
name: Build, Test and Deploy Postagram
on:
push:
branches: [ main ]

The workflow will run every time there is a push on the main branch. Let’s go on to write a build-test job. For this job, we will follow three steps:

  1. Inject environment variables into a file. Docker will need a .env file to build the images and start the containers. We’ll inject dummy environment variables into the Ubuntu environment.

  2. After that, we will build the containers.

  3. Finally, we run the tests on the API container.

Let’s get started with the steps:

Step 1

Let’s start by writing the job and injecting the environment variables:

Press + to interact
build-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Injecting environment vars
run: |
echo "SECRET_KEY=test_foo
DATABASE_NAME=test_coredb
DATABASE_USER=test_core
DATABASE_PASSWORD=12345678
DATABASE_HOST=test_postagram_db
DATABASE_PORT=5432
POSTGRES_USER=test_core
POSTGRES_PASSWORD=12345678
POSTGRES_DB=test_coredb
ENV=TESTING
DJANGO_ALLOWED_HOSTS=127.0.0.1, localhost
" >> .env

The tests will probably fail because we haven’t defined the GitHub Secret called TEST_SECRETS.

Press + to interact
Testing GitHub secrets
Testing GitHub secrets

Step 2

Next, let’s add the command to build the containers:

Press + to interact
- name: Building Docker containers
run: |
docker-compose up -d --build

Step 3

And, finally, let’s run the pytest command in the api container:

Press + to interact
- name: Running Tests
run: |
docker-compose exec -T api pytest

Great! We have the first job of the workflow fully written.

Step 4

Let’s push the code by running the following command and see how it runs on the GitHub side:

Press + to interact
git push -u origin main -f
...

Get hands-on with 1400+ tech skills courses.