Bootstrap FreeKB - GitHub Actions - Always run task even after error
GitHub Actions - Always run task even after error

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.

Let's say you have the following GitHub Action, which first appends the GitHub Actions Runner IPv4 address to your Amazon Web Services (AWS) Security Group using the aws ec2 authorize-security-group-ingress command, then attempts to copy a file onto one of your AWS EC2 instances using appleboy/scp-action, and finally removes the GitHub Actions Runner IPv4 address from your AWS Security Group using the aws ec2 revoke-security-group-ingress command.

But what if the SCP task fails with an error? Then the task to remove the GitHub Actions Runner IPv4 address from your AWS Security Group will not be run. 

Enter if: always()

if: always() tells a task to always run, even if a prior task fails with an error.

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

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

      - name: Add Github Actions IP to Security group
        run: |
          aws ec2 authorize-security-group-ingress --group-id sg-1234jfhn9282jfmf --ip-permissions IpProtocol=tcp,FromPort=22,ToPort=22,IpRanges='[{CidrIp=${{ steps.ip.outputs.ipv4 }}/32,Description='github-actions-runner'}]' 
      
      - name: copy foo.jpg to /tmp
        uses: appleboy/scp-action@master
        with:
          host: ec2-10-11-12-13.compute-1.amazonaws.com
          username: ec2-user
          password: ${{ secrets.PASSWORD }}
          port: 22
          source: "foo.jpg"
          target: "/tmp" 

      - name: Remove Github Actions IP from Security group
        if: always()
        run: |
          aws ec2 revoke-security-group-ingress --group-id sg-1234jfhn9282jfmf --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 3971b7 in the box below so that we can be sure you are a human.