Laravel 10 Eloquent whereBetween() Query: A Powerful Filtering Query
Read More
Deploying a Python application to an AWS EC2 instance can be streamlined using GitHub Actions. This guide will walk you through setting up a GitHub Actions workflow to automate the deployment process. The workflow will handle copying your application code to the EC2 instance, installing dependencies, and starting the application.
Before setting up the GitHub Actions workflow, ensure you have the following:
name: Deploy Python App to EC2
on:
push:
branches:
- main # Trigger the workflow on pushes to the main branch
jobs:
deploy:
runs-on: ubuntu-latest # Use the latest Ubuntu runner
steps:
- name: Checkout the repository
uses: actions/checkout@v3 # Check out the repository code
- name: Set up SSH Agent
uses: webfactory/[email protected] # Set up SSH agent for authentication
with:
ssh-private-key: ${{ secrets.EC2_SSH_PRIVATE_KEY }} # Use the private key stored in GitHub Secrets
- name: Add EC2 instance to known_hosts
run: |
mkdir -p ~/.ssh
ssh-keyscan -H ec2-12-34-56-78.compute-1.amazonaws.com >> ~/.ssh/known_hosts # Replace with your EC2 instance's public DNS
- name: Install rsync
run: sudo apt-get install -y rsync # Install rsync for file transfer
- name: Copy files to EC2 using rsync (exclude .git)
run: |
rsync -avz --exclude='.git' ./ [email protected]:/home/ec2-user/app # Replace with your EC2 instance's public DNS
- name: SSH into EC2 and Deploy
run: |
ssh -o StrictHostKeyChecking=no [email protected] << 'EOF' # Replace with your EC2 instance's public DNS
# Navigate to the app directory
cd /home/ec2-user/app
# Ensure Python3 and pip3 are installed
sudo yum install -y python3 python3-pip # For Amazon Linux 2
# sudo apt-get install -y python3 python3-pip # For Ubuntu
# Install dependencies
pip3 install --user -r requirements.txt
# Create and enable the systemd service (if not already done)
echo "[Unit]
Description=Python Application
After=network.target
[Service]
User=ec2-user
WorkingDirectory=/home/ec2-user/app
ExecStart=/usr/bin/python3 /home/ec2-user/app/app.py
Restart=always
[Install]
WantedBy=multi-user.target" | sudo tee /etc/systemd/system/python_app.service
# Reload systemd, start the service, and enable it to run on boot
sudo systemctl daemon-reload
sudo systemctl start python_app
sudo systemctl enable python_app
EOF
ssh -i "example-key.pem" [email protected]
Check the status of the systemd service:
sudo systemctl status python_app
By following this guide, you’ve set up a GitHub Actions workflow to automate the deployment of your Python application to an AWS EC2 instance. This workflow ensures that your application is deployed consistently and efficiently whenever changes are pushed to the main branch. You can further customize the workflow to suit your specific needs, such as adding environment variables or running tests before deployment. Happy deploying! 🚀
Recent posts form our Blog
0 Comments
Like 0