Created
December 22, 2022 19:44
-
-
Save dryan/98e535aa962a027ff36639d1ab1d4008 to your computer and use it in GitHub Desktop.
GitHub Actions workflow that queries EC2 for a list of instances with a specified tag name and value, gets those IP addresses, then sends a command via ssh to them
This file contains hidden or 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: CI | |
on: | |
push: | |
branches: | |
- main | |
pull_request: | |
branches: | |
- main | |
jobs: | |
deploy: | |
name: App -> EC2 | |
env: | |
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} | |
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} | |
AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }} | |
DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }} # the contents of a private ssh key authorized to connect to the instances | |
DEPLOY_TAG_NAME: ${{ secrets.DEPLOY_TAG_NAME }} # which tag to use to filter instances | |
DEPLOY_TAG_VALUE: ${{ secrets.DEPLOY_TAG_VALUE }} | |
DEPLOY_USER: ${{ secrets.DEPLOY_USER }} # the ssh user to use (ubuntu, ec2-user, admin, etc) | |
DEPLOY_SCRIPT: | | |
cd /opt/app | |
git reset --hard | |
git pull | |
# add as many commands as needed | |
needs: test # remove this if there's no test step, but also don't not have a test step | |
if: github.ref == 'refs/heads/main' # this makes sure this only runs on merges to main and not on PRs to main | |
runs-on: ubuntu-latest | |
steps: | |
- uses: actions/checkout@v3 | |
- name: Get IP addresses of instances | |
id: ip_addresses | |
run: | | |
sudo apt-get install jq | |
export INSTANCE_IPS=$(aws ec2 describe-instances --output json --filters "Name=tag:$DEPLOY_TAG_NAME,Values=$DEPLOY_TAG_VALUE" | jq ".Reservations[].Instances[].PublicIpAddress" | paste -d, -s - | tr -d '"') | |
[ -z "$INSTANCE_IPS" ] && echo "No IPs found" && exit 1 | |
echo "INSTANCE_IPS=$INSTANCE_IPS" | |
echo "INSTANCE_IPS=$INSTANCE_IPS" >> $GITHUB_OUTPUT | |
- name: Send update command to EC2 instance | |
env: | |
INSTANCE_IPS: ${{ steps.ip_addresses.outputs.INSTANCE_IPS }} | |
run: | | |
echo "$DEPLOY_SSH_KEY" > private_key && chmod 600 private_key | |
for IP in ${INSTANCE_IPS//,/$'\n'} | |
do | |
echo "Sending to ${IP}..." | |
ssh -o StrictHostKeyChecking=no -i private_key $DEPLOY_USER@${IP} "${DEPLOY_SCRIPT}" | |
done | |
rm private_key |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment