You can use “on” in your GitHub workflow file to automatically trigger GitHub workflow actions on changes to specific files.
Step 1: Create a personal access token in GitHub.
Step 2: Create a GitHub repository using REST API.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
## Declare some Variables GITHUB_PAT_TOKEN=' GITHUB_REPO_NAME=' GITHUB_USER_NAME=' ## Create a new GitHub repository curl \ --silent \ --header "Authorization: token $GITHUB_PAT_TOKEN" \ --data '{ "name": "'"$GITHUB_REPO_NAME"'", "description": "GitHub repo created through API", "auto_init": true, "private": true, "gitignore_template": "nanoc" }' \ https://api.github.com/user/repos |
Step 3: Create a workflow definition for GitHub actions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
## Create your workflow file cat << EOF > myworkflow.yaml name: GitHub Actions Demo on: push: branches: - 'main' paths: - '**.yaml' jobs: job1: name: job1 runs-on: ubuntu-latest steps: - name: step1 run: echo "hello world!" EOF |
Note: We have used “on” with “push” and “paths” events to make GitHub automatically trigger GitHub workflow actions on changes to certain files.
Step 4: Upload the workflow file and perform git push operations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
## Create base64 version of workflow CONTENT=$(cat myworkflow.yaml | base64 -w 0) && cat << EOF > content.json { "message":"file myworkflow.yaml added", "content":"$CONTENT" } EOF ## Upload the workflow file in GitHub curl \ --silent \ --request PUT \ --header "Authorization: token $GITHUB_PAT_TOKEN" \ --data @content.json \ https://api.github.com/repos/$GITHUB_USER_NAME/$GITHUB_REPO_NAME/contents/.github/workflows/myworkflow.yaml ## Clone the repository and push a change to specific branch git clone git@github.com:$GITHUB_USER_NAME/$GITHUB_REPO_NAME.git cd $GITHUB_REPO_NAME echo "dummy file added" > file1.txt git add . git commit -m "dummy file added" git push ## action not getting triggered as no yaml file present echo "--" > file2.yaml git add . git commit -m "yaml file added" git push ## action will get triggered this time as we have added a yaml file |
Observe: During the first push to the master/main branch, no GitHub action was triggered as there was no “yaml” file in the repository. In the second push, we have added a “yaml” file hence the action gets triggered.
Step 5: Clean up.
1 2 3 4 5 6 7 8 9 |
## Delete the GitHub repository curl \ --silent \ --request DELETE \ --header "Authorization: token $GITHUB_PAT_TOKEN" \ https://api.github.com/repos/$GITHUB_USER_NAME/$GITHUB_REPO_NAME ## Delete the local repository cd .. && rm -rf $GITHUB_REPO_NAME |