Bootstrap FreeKB - GitHub Actions - Restart remote Docker containers
GitHub Actions - Restart remote Docker containers

Updated:   |  GitHub Actions articles

GitHub Actions can be used to do something whenever something happens in one of your GitHub repositories. If you are not familiar with GitHub Actions, check out my article Getting Started with GitHub Actions.

Following are ways to run a command on a target server.

This example uses the built-in run command.

name: GitHub Action
run-name: ${{ github.workflow }} run by ${{ github.actor }}
on:
  push:
    branches:
      - main
jobs:
  restart-docker-container:
    runs-on: ubuntu-latest
    steps:      
      - name: Checking out the repository code
        uses: actions/checkout@v4
      
      - name: restart docker container on EC2 instance ec2-10-11-12-13.compute-1.amazonaws.com
        run: |
          sudo docker restart my-container

 

If you want to SCP a file to an Amazon Web Services (AWS) EC2 Instance and you are using appleboy ssh-action, the Security Group will need to allow connections from GitHub on port 22 since appleboy ssh-action makes an SSH connection on port 22 to the target system. Here is how you can get the GitHub Actions Runner IP address and update the Security Group.

Check out my article FreeKB - GitHub Actions - Get runner IP using curl for more details on getting the GitHub Actions Runner IPv4 address using curl.

name: GitHub Action
run-name: ${{ github.workflow }} run by ${{ github.actor }}
on:
  push:
    branches:
      - main
jobs:
  restart-docker-container:
    runs-on: ubuntu-latest
    steps:      
      - name: Checking out the repository code
        uses: actions/checkout@v4

      - name: runner IPv4
        id: ip
        run: ipv4=$(curl --silent --url https://api.ipify.org); echo "ipv4=$ipv4" >> $GITHUB_OUTPUT

      - name: Update EC2 Security Group to allow connections on port 22 from GitHub
        run: |
          aws ec2 authorize-security-group-ingress --group-id sg-abcdefg123456789 --ip-permissions IpProtocol=tcp,FromPort=22,ToPort=22,IpRanges='[{CidrIp=${{ steps.ip.outputs.ipv4 }}/32,Description='github actions runner'}]' 

      - name: restart docker container
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.HOST }}
          username: ${{ secrets.USERNAME }}
          key: ${{ secrets.RSA_PRIVATE_KEY }}
          port: ${{ secrets.PORT }}
          script: sudo docker restart my-container

      - name: Remove Github Actions IP from Security group
        run: |
          aws ec2 revoke-security-group-ingress --group-id sg-0778124087b3d14d4 --protocol tcp --port 22 --cidr ${{ steps.ip.outputs.ipv4 }}/32

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 479c2e in the box below so that we can be sure you are a human.