DevOps: Deploy Flask App Using Git Actions
We will use this Git Action: https://github.com/marketplace/actions/ssh-deploy
- Generate key pair(public and private)
2. Add Secrets to Git Repository Settings
Add local Private key generated earlier to your Git Secrets
Add all 3 secrets that are required for this Git action. We are not using SSH with password.
3. Add Git Action
Go to Actions > New Workflow > Set up a workflow yourself (or use suggested workflows)
name: Deploy Flask App
on:
push:
branches:
- main # Adjust this branch name based on your Git branch
jobs:
deploy:
runs-on: ubuntu-latest # You can choose a different operating system if needed
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.x' # Specify the Python version your Flask app requires
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt # Assuming you have a requirements.txt file
- name: Run tests # Optional: Add test commands here
run: |
echo "Run tests"
#pytest # Example test command, adjust based on your testing setup
- name: Deploy to server
uses: easingthemes/ssh-deploy@main
with:
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }} # Your SSH private key secret
ARGS: "-rlgoDzvc -i" # rsync arguments
SOURCE: "." # Source directory of your Flask app
REMOTE_HOST: ${{ secrets.REMOTE_HOST }} # Remote server hostname or IP
REMOTE_USER: ${{ secrets.REMOTE_USER }} # SSH username
TARGET: "/var/www/html/myapp" # Target directory on the remote server
EXCLUDE: "/.git/, /.github/, /venv/, /__pycache__/" # Exclude specific directories
SCRIPT_BEFORE: |
whoami
echo "Before running the deployment, delete old files"
rm -r /var/www/hmtl/myapp
SCRIPT_AFTER: |
echo "Deployment complete."
ls -al
# Manually deploy a Flask application steps
sudo apt update -y
sudo apt install -y python3 python3-pip
sudo apt install -y python3-venv
cd /var/www/html/myapp
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
echo "Restarting MyApp Service"
sudo systemctl restart myapp && echo "Application is running"
sudo systemctl status myapp
echo "Test the deployment"
curl -i -k https://security.iverique.com # Replace with your server IP and Flask app port
The file can be found here:
More stories: