Skip to content

Deploy to AWS

Deploy to AWS #2

name: Deploy to AWS
on:
workflow_run:
workflows: ["Build", "Test Docker Image"]
types:
- completed
branches: [main]
workflow_dispatch:
env:
AWS_REGION: us-east-2
TF_WORKING_DIR: terraform
permissions:
id-token: write
contents: read
jobs:
terraform:
name: Deploy Infrastructure
runs-on: ubuntu-latest
if: |
github.event_name == 'workflow_dispatch' ||
(github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success')
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Download build artifacts
uses: actions/download-artifact@v4
with:
name: thales-ubuntu-${{ vars.UBUNTU_VERSION }}-Release
path: build/
- name: Configure AWS Credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
aws-region: ${{ env.AWS_REGION }}
- name: Setup Terraform
uses: hashicorp/setup-terraform@v3
with:
terraform_version: "1.2.0"
- name: Terraform Format Check
working-directory: ${{ env.TF_WORKING_DIR }}
run: terraform fmt -check
- name: Terraform Init
working-directory: ${{ env.TF_WORKING_DIR }}
run: terraform init
env:
AWS_BUCKET_NAME: thales-terraform-state
AWS_DYNAMODB_TABLE: thales-terraform-locks
- name: Terraform Plan
working-directory: ${{ env.TF_WORKING_DIR }}
if: github.event_name == 'pull_request'
run: terraform plan -no-color
env:
TF_VAR_db_password: ${{ secrets.DB_PASSWORD }}
continue-on-error: true
- name: Update Pull Request
uses: actions/github-script@v7
if: github.event_name == 'pull_request'
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const output = `#### Terraform Format and Style 🖌\`${{ steps.fmt.outcome }}\`
#### Terraform Initialization ⚙️\`${{ steps.init.outcome }}\`
#### Terraform Plan 📖\`${{ steps.plan.outcome }}\`
<details><summary>Show Plan</summary>
\`\`\`\n
${process.env.PLAN}
\`\`\`
</details>
*Pushed by: @${{ github.actor }}, Action: \`${{ github.event_name }}\`*`;
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: output
})
- name: Terraform Apply
working-directory: ${{ env.TF_WORKING_DIR }}
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
run: terraform apply -auto-approve
env:
TF_VAR_db_password: ${{ secrets.DB_PASSWORD }}
- name: Deploy Application
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
run: |
# SSH into EC2 instance and update application
echo "${{ secrets.SSH_PRIVATE_KEY }}" > private_key.pem
chmod 600 private_key.pem
# Get EC2 public IP from Terraform output
EC2_IP=$(cd ${{ env.TF_WORKING_DIR }} && terraform output -raw ec2_instance_public_ip)
# Copy files to EC2
scp -i private_key.pem -o StrictHostKeyChecking=no \
-r docker/* ubuntu@${EC2_IP}:/home/ubuntu/docker/
# Start the application
ssh -i private_key.pem -o StrictHostKeyChecking=no ubuntu@${EC2_IP} << 'EOF'
cd /home/ubuntu/docker
docker-compose pull
docker-compose up -d
EOF
rm private_key.pem