Vizneo Academy
Published in

Vizneo Academy

How to deploy a Django project to AWS EB with Github actions

AWS Elastic Beanstalk

For this quick guide, we will prepare the AWS setup.

  1. Setup your AWS account, if you do not have one yet. — Do note that for new signup, you will have a 12-month free tier on certain services.
  2. Create the basic Django app — We will run through the basic steps here.
  3. Prepare the Elastic Beanstalk environment
  4. Setup Github actions for your repository.

Note: This article does not describe the deployment of a Docker image. — I might post a separate article for that later.

(1) Setting up AWS

After you set up your AWS account, you will need to create an IAM role for this project.

Here is a suggested set of steps to create an IAM role and store the IAM keys.

IAM dashboard

Go to the IAM dashboard on your AWS console. IAM stands for Identity Access Management.

You can now create a new user, I have named my user “eb-deployuser”.

Check the Access key — Programmatic access, and click next. The next screen

Create IAM user

is where you give access to resources.

I have created a group called DevOps, from where Administrative access is enabled. This gives access to ALL AWS resources, so be careful how you use it. — When you move to production, you should limit the access to just the services your solution is using.

Enable permission to user.

Click next and add key values (optional) then next and click “create user”.

Created IAM user

Once you have created the user, you must note down the Access Key ID and the Secret access key.

You can copy them out or download them as a CSV file. (You will be using the keys when deploying your app to AWS).

Create a database instance

You will also want to create an RDS database. Follow the steps to set up a free tier MySql database on AWS.

We will connect the app to the database in the next post.

(2) Create the basic Django app

There are so many tutorials for creating Django apps, so I will be very brief here. Clone this Django example:

$ git clone git@github.com:motethansen/django-example.git

create your python environment

$ python3 -m venv venv
$ source venv/bin/activate
$ make install

The make install will load the packages from the requrements.txt.

follow the steps from the example Readme file to explore more.

(3) Prepare the Elastic Beanstalk environment

Here is where you will use the IAM user we create ed earlier. Follow this guide to install the EB CLI on your computer. I am using Mac while typing this, so I will be installing the command-line tool on macOS.

Now I will use the command-line tool to create the Elastic Beanstalk environment. I will also show some screenshots from the console.

inside the project folder, initialize the EB environment

/Users/michael/Projects/django-example
$ eb init

This will give you some prompts for configuration

eb init prompt

Choose your region. For me, I choose (7) for ap-southeast-1 (Singapore).

You will be prompted to enter the Access Key. The following example is from the AWS guide.

You have not yet set up your credentials or your credentials are incorrect You must provide your credentials. 
(aws-access-id): AKIAJOUAASEXAMPLE
(aws-secret-key): 5ZRIrtTM4ciIAvd4EXAMPLEDtm+PiPSzpoK

You must copy and paste the keys you downloaded previously when you created the IAM user.

After you have entered the keys, you should respond to the following prompts similar to this image.

eb application example

Before creating the application, we need to set some elastic beanstalk configurations.

create a folder and a file ``` .ebextensions ``` in the project root:

django-example/.ebextensions/eb.config

option_settings:
aws:elasticbeanstalk:container:python:
WSGIPath: djangoexample.wsgi:application

Let's try to deploy the application.

$ eb create
eb create

The environment will be created, and the application will be deployed. Make sure to select the default load balancer. You can use spot instances for your application, as it can save you some money.

Now run the deploy command:

$ eb deploy

and

$ eb status
eb deploy and status commands

You will then see the application deployed. follow with the status command.

you can open the app in your browser with:

eb open

REMEMBER: on was elastic beanstalk, your code MUST be committed to GitHub before you create the application with

eb create

(4) Setup Github actions

You can monitor your Github Actions on the project repository on Github, under click Actions.

Actions screen on Github

To create a workflow, you want to create a new folder named ``` .github/workflows``` in your project root

mkdir .github/workflows

Now create a .yml file ``` ebdeploy.yml ```

.github
│ └── workflows
│ └── ebdeploy.yml

and fill the code below, which defines a test process on the code

name: ebdeploy

on:
push:
branches: [main]
pull_request:
branches: [main]

jobs:
test:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Set up Python Environment
uses: actions/setup-python@v2
with:
python-version: '3.x'
- name: Install Dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt

- name: Run Tests
run: |
python manage.py test

After committing the code to GitHub, you will see an update in the Actions window.

after committing with Github Actions

You will notice the test failed. Let's see that the test will succeed.

Create a tests.py file in the app folder djangoexample/tests.py

Add some test scripts to this file

from django.test import TestCase  class ViewsTestCase(TestCase):    
def test_home_page_loads(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)

In the same folder, add a views.py

from django.http import HttpResponse def home(request):   
text = """<h1>Django Example</h1>"""
return HttpResponse(text)

in ``` urls.py ``` and add the path to the view. The urlpatterns will look something like this

from djangoexample.views import homeurlpatterns = [    
path('admin/', admin.site.urls),
path('', home, name='home'),
]

Now, commit and check the Github Actions.

Success testing view from test script in Github Actions workflow

Adding beanstalk deploy

The first step will be to update your Github with the AWS secret keys you created earlier.

Go to the settings page of the repository to add the keys. Click Secrets->Actions

Then click New repository secret

Paste the Access key in Value and repeat with the Secret key
The keys are defined by the environment names.

Next we update the workflow yml file, by adding the following code

deploy:
needs: [test]
runs-on: ubuntu-latest

steps:
- name: Checkout source code
uses: actions/checkout@v2

- name: Generate deployment package
run: zip -r deploy.zip . -x '*.git*'

- name: Deploy to EB
uses: einaregilsson/beanstalk-deploy@v20
with:

// Remember the secrets we embedded? this is how we access them
aws_access_key: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws_secret_key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}

// Replace the values here with your names you submitted in one of
// The previous sections
application_name: djangoexample
environment_name: djangoexample-dev

// The version number could be anything. You can find a dynamic way
// Of doing this.
version_label: 1
region: "ap-southeast-1"
deployment_package: deploy.zip

the line

uses: einaregilsson/beanstalk-deploy@v20

Is a package from the Github Actions marketplace by@einaregilsson

This should process the “eb” deployment process.

After committing, the workflow will run the test and deploy scripts.

Now we have a Github Actions workflow to deploy the code to AWS Elastic Beanstalk.

Github repository for this example.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store