Welcome to this comprehensive guide on CI/CD (Continuous Integration and Continuous Deployment) with Python! This tutorial is designed for both beginners and intermediates, so let's dive right in. 🎯
CI/CD is a modern approach to software development that focuses on automating the entire software release process. The main goals are to catch errors early, reduce the time to market, and improve the quality of software releases.
CI is the practice of frequently merging all developer working copies into a shared repository, where automated builds and tests are run. The main goal is to detect integration issues early, making it easier to resolve them.
CD is an extension of CI that automatically deploys the tested and approved code to the production environment. This ensures that the most recent version of the software is always available to users.
We'll use a popular Python CI/CD tool called GitHub Actions for this tutorial.
First, create a new repository on GitHub for your Python project.
In the repository, create a new file in the .github/workflows directory called python-ci-cd.yml.
Open the python-ci-cd.yml file and write the following content:
name: Python CI/CD
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0 📝 Fetching the entire commit history will make the build faster.
- name: Set up Python 3.x
uses: actions/setup-python@v2
with:
python-version: 3.x 💡 Python version can be updated as needed.
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Run tests
run: python test.py
- name: Lint the code
run: flake8 .
- name: Format the code
run: black .
- name: Check for lint errors
run: |
export FLake8_MAX_LINE_LENGTH=120 💡 Linter configuration can be adjusted as needed.
flake8 . || true
- name: Check for formatting errors
run: black --check . || true
- name: Deploy to production
uses: JamesIves/github-actions-ssh@master
with:
host: your-server-ip
username: your-server-username
key: ${{ secrets.SSH_PRIVATE_KEY }}
script: |
cd path/to/your/project
git pull
python manage.py deployrequirements.txt and test.pyCreate a requirements.txt file that lists all the Python dependencies of your project. Also, create a test.py file that contains unit tests for your project.
In your GitHub repository settings, create a new secret called SSH_PRIVATE_KEY and paste your SSH private key. This will be used to deploy the code to the production environment.
Commit and push the changes to the main branch to trigger the CI/CD pipeline. You can check the status of the workflow in the GitHub Actions tab.
What is the main goal of Continuous Integration?
With this, you now have a basic understanding of CI/CD and how to set up a Python CI/CD pipeline using GitHub Actions. Happy coding! 💡📝✅