We are using github to backup configuration files automatically from our servers.
To check that the cron job is working correctly is there a way to have an action failing if there is a no commit for the last 24 hours ?
You can use action with below structure
Github scheduled action, Uses cron syntax
Step actions/checkout step to checkout code
Custom step to get last commit date time e.q.
git log -1 --format=%cd //Outputs: time of last commit
git log -1 --format=%cr //Output: X days ago
Check this and fail the workflow, if condition met.
Eventually that the action to check we are using
name: CheckBackup
on:
workflow_dispatch:
schedule:
- cron: '0 1 * * *' # every day at 1:00am
jobs:
build:
runs-on: ubuntu-latest
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout#v3
- name: Check dates difference
run: |
echo "Github last update : " + `git log -1 --format=%cd$`
echo "Now : " + `date`
let now=`date +%s`
let backupTime=`git log -1 --format=%cd$ --date=raw | grep -o "^\w*\b"`
deltaHours=$((now-backupTime))
deltaHours=$((deltaHours/3600))
if [ $deltaHours -ge 8 ]; then
echo 'failed : ' + $deltaHours + ' hours'
exit 1
else
echo 'ok : ' + $deltaHours
exit 0
fi
Related
name: Git diff files changed
jobs:
if-file-changed:
name: Check if files changed
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout#v3
with:
fetch-depth: 0 # fetch all history of all branches
- name: Get files changed when pr is created/updated
# compare source branch with target branch in Pull request
if: github.event_name=='pull_request'
id: files_changed_on_pr
run: |
git symbolic-ref refs/remotes/origin/HEAD origin/${{github.base_ref}}
all_changed_files=$(git --no-pager diff --name-only origin/${{github.head_ref}} origin/${{github.base_ref}})
echo "::set-output name=all_changed_files::$all_changed_files"
echo all_changed_files = $all_changed_files
- name: Get output
id: get_output
run: |
all_changed_files=${{ steps.files_changed_on_pr.outputs.all_changed_files }}
echo $all_changed_files
I see 4 files in job id files_changed_on_pr
Output looks like following:
all_changed_files = .github/workflows/files_changed.yaml
.github/workflows/load_seed_data.yaml
.github/workflows/miscellaneous_test.yaml
.github/workflows/on_pr_dev.yaml
I only see 1 file in job id get_output
.github/workflows/files_changed.yaml
Is there some kind of JSON conversion I need to do before sending those files as output?
I have a nightly job running and I would like it to run only if there has been a commit during the past 24 hours
I have seen this question but it is a linux command. I am looking to achieve the same thing on a Windows self-hosted environment so that command does not work.
I tried the solution there but there is not equivalent to the test command and --after doesn't exist
check_date:
runs-on: self-hosted
name: Check latest commit
outputs:
should_run: ${{ steps.should_run.outputs.should_run }}
steps:
- uses: actions/checkout#v3.0.0
- name: Print Latest Commit
run: echo ${{ github.sha }}
- id: should_run
continue-on-error: true
name: Check if latest commit is less than a day
if: ${{ github.event_name == 'schedule' }}
run: test -z $(git rev-list --after="24 hours" ${{ github.sha }}) && echo "::set-output name=should_run::false"
but I get this error message
Run test -z $(git rev-list --after="24 hours" db8f6566733fd7240baaa51607783d54305efa7d)
test : The term 'test' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
the spelling of the name, or if a path was included, verify that the path is correct and try again.
At D:\workspace\_temp\4d4d15eb-e2be-422e-a826-44984f2860dc.ps1:2 char:1
+ test -z $(git rev-list --after="24 hours" db8f6566733fd7240baaa5160 ...
+ ~~~~
+ CategoryInfo : ObjectNotFound: (test:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : CommandNotFoundException
Error: Process completed with exit code 1.
One issue that I had was that my git version was too old (2.33).
--after was introduced from 2.35
The other one, I "hacked" it by using a script. Not a very elegant solution but it works..
I did put this into a batch file and call it.
#echo off
setlocal enabledelayedexpansion
set result=
for /f "tokens=*" %%i in ('git rev-list %~1 --after="24 hours"') do (
set result=%%i
)
if "!result!"=="" (
echo ::set-output name=should_run::false
) else (
echo ::set-output name=should_run::true
)
And use it like this:
check_date:
runs-on: self-hosted
name: Check latest commit
outputs:
should_run: ${{ steps.should_run.outputs.should_run }}
steps:
- uses: actions/checkout#v3.0.0
- name: Print Latest Commit
run: echo ${{ github.sha }}
- id: should_run
continue-on-error: true
name: Check if latest commit is less than a day
shell: cmd
run: ci_check_last_commit.bat ${{ github.sha }}
What is the nicest approach to check if environment variable is empty on Github action as a condition to a step? I've tried the trivial approach but it doesn't seem to work.
For example:
name: SimpleWorkflow
on:
push:
env:
MULTI_LINE_ARG: |
ARG1: value
jobs:
update:
runs-on: ubuntu-latest
steps:
- name: Fetching Local Repository
uses: actions/checkout#master
- name: run step if multiline not null
if: ${{env.MULTI_LINE_ARG}} != ""
run: echo multiline not null
No matter how I've tried this I fail to properly check if env is empty.
Updated to new GitHub syntax (as of 2022-12)
Background: The issue of secrets not available to forks is known to GitHub folks, but no concrete activity announced: https://github.community/t/github-workflow-not-running-from-pull-request-from-forked-repository/16379/41?u=koppor
One can use output variables of steps to determine whether a secret is available.
The name of the secret in GitHub is SECRET.
- name: Check secrets presence
id: checksecrets
shell: bash
run: |
if [ "$SECRET" == "" ]; then
echo "secretspresent=NO" >> $GITHUB_OUTPUT
else
echo "secretspresent=YES" >> $GITHUB_OUTPUT
fi
env:
SECRET: ${{ secrets.SECRET}}
- name: run step if secret is present
if: (steps.checksecrets.outputs.secretspresent == 'YES')
run: echo secret is present
Note: Solution adapted from https://github.community/t/if-expression-with-context-variable/16558/6?u=koppor.
I'm trying to use an environment variable in an if condition in github actions like so:
name: Worfklow
on:
push
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v1
- name: EXIT step
if: $GITHUB_REF == 'specific-branch'
run: exit 1
I want to exit if the current branch is equal to a specific branch.
Unfortunately, the github actions console displays an error:
Unexpected symbol: '$GITHUB_REF'
I can use $GITHUB_REF in a run: (where it contains the current branch), but not in an if:. What am I doing wrong?
Though the original problem had been solved without environment vars, I'd like to share how it can be used with if conditions.
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Set env BRANCH
run: echo "BRANCH=$(echo $GITHUB_REF | cut -d'/' -f 3)" >> $GITHUB_ENV
- name: Set env NEED
run: |
if [[ $BRANCH == 'master' && $GITHUB_EVENT_NAME == 'push' ]]; then
echo "NEED=true" >> "$GITHUB_ENV"
else
echo "NEED=false" >> "$GITHUB_ENV"
fi
- name: Skip Deploy?
if: env.NEED != 'true'
run: echo "Only pushing to 'master' causes automatic deployment"
...
The first two steps set 2 env variables, the third step demonstrates what syntax you need to follow to use these vars in if conditions.
do it like this:
if: github.ref == 'specific-branch'
reference branch conditional
If you want to check an environment variable on job-level (refer to Github context), you can do like this:
env:
MY_VAR: Dummy
jobs:
build:
name: Build
runs-on: ubuntu-latest
outputs:
myVar: ${{ steps.init.outputs.myVar }}
steps:
- name: Environment variables to output
id: init
run: |
echo "myVar=${{ env.MY_VAR }}" >> $GITHUB_OUTPUT
And use it in another job:
second_job:
name: Second Job
needs: build
if: needs.build.outputs.myVar == 'Dummy'
You can use some restrictions on the push section of the action
on:
push:
branches:
- '*' # matches every branch that doesn't contain a '/'
- '*/*' # matches every branch containing a single '/'
- '**' # matches every branch
- '!master' # excludes master
This answer was taken from this stack overflow question
I am running the example of javascript github actions and it works just fine when I have
on: [push]
but not when I have
on:
schedule:
- cron: '*/5 * * * *'
I expect the github action to run every 5 minutes but it doesn't seem to run at all.
Here is the rest of my code for reference
.github/worflows/main.yml
on:
schedule:
- cron: '*/5 * * * *'
jobs:
hello_world_job:
runs-on: ubuntu-latest
name: A job to say hello
steps:
- name: Hello world action step
id: hello
uses: StephenVNelson/website/#3-experiment-with-actions
with:
who-to-greet: 'Mona the Octocat'
# Use the output from the `hello` step
- name: Get the output time
run: echo "The time was ${{ steps.hello.outputs.time }}"
./action.yml
name: 'Hello World'
description: 'Greet someone and record the time'
inputs:
who-to-greet: # id of input
description: 'Who to greet'
required: true
default: 'World'
outputs:
time: # id of output
description: 'The time we greeted you'
runs:
using: 'node12'
main: './github-actions/main.js'
./github-actions/main.js
const core = require('#actions/core');
const github = require('#actions/github');
try {
// `who-to-greet` input defined in action metadata file
const nameToGreet = core.getInput('who-to-greet');
console.log(`Hello ${nameToGreet}!`);
const time = (new Date()).toTimeString();
core.setOutput("time", time);
// Get the JSON webhook payload for the event that triggered the workflow
const payload = JSON.stringify(github.context.payload, undefined, 2)
console.log(`The event payload: ${payload}`);
} catch (error) {
core.setFailed(error.message);
}
You won't be able to schedule it for every 5 minutes as the "shortest interval you can run scheduled workflows is once every 15 minutes":
https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#schedule
Change it to '*/15 * * * *' and you'll be fine.
As mentioned in the GitHub documentation about Scheduled events
The schedule event can be delayed during periods of high loads of GitHub Actions workflow runs. High load times include the start of every hour. To decrease the chance of delay, schedule your workflow to run at a different time of the hour.
Read further : No assurance on scheduled jobs?