This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name: Deploy to Amazon EC2 | |
on: | |
push: | |
branches: [ "main" ] | |
env: | |
AWS_REGION: ap-southeast-1 | |
CONTAINER_NAME: darthmalgus1997/basic-go-service | |
permissions: | |
contents: read | |
jobs: | |
deploy: | |
name: Deploy | |
runs-on: ubuntu-latest | |
environment: production | |
steps: | |
- name: Checkout | |
uses: actions/checkout@v4 | |
- name: Log in to Docker Hub | |
uses: docker/login-action@v2 | |
with: | |
username: ${{ secrets.DOCKER_HUB_USERNAME }} | |
password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} | |
- name: Build, tag, and push image to Docker Hub | |
id: build-image | |
env: | |
IMAGE_TAG: ${{ github.sha }} | |
run: | | |
docker build -t $CONTAINER_NAME:$IMAGE_TAG . | |
docker push $CONTAINER_NAME:$IMAGE_TAG | |
echo "image=$CONTAINER_NAME:$IMAGE_TAG" >> $GITHUB_OUTPUT | |
- name: Deploy to EC2 | |
env: | |
PRIVATE_KEY: ${{ secrets.EC2_SSH_PRIVATE_KEY }} | |
HOST: ${{ secrets.EC2_HOST }} | |
USER: ec2-user | |
IMAGE: $CONTAINER_NAME:$IMAGE_TAG | |
run: | | |
echo "$PRIVATE_KEY" > private_key.pem | |
chmod 600 private_key.pem | |
ssh -i private_key.pem -o StrictHostKeyChecking=no ${USER}@${HOST} << EOF | |
CONTAINER_NAME="${CONTAINER_NAME}" | |
IMAGE_TAG="${IMAGE_TAG}" | |
IMAGE="\${CONTAINER_NAME}:\${IMAGE_TAG}" | |
sudo docker images | |
echo $IMAGE | |
EOF | |