GitHub Actions Day 16: Conditionals with Shared Data
This is day 16 of my GitHub Actions Advent Calendar. If you want to see the whole list of tips as they're published, see the index.
Yesterday we looked at how we can set custom
data
in one of our workflow steps that we could use in subsequent
steps. We did that by adding data to the env
context, which
is a property bag that you can read and write.
But you don't have to limit yourself to using the env
context
only in your steps. You can also use the env
context within your
workflow itself, setting up conditionals
based on data that you set in earlier steps.
For example, you might have a workflow that you want to run every
day, and you want to make a minor modification to how this workflow
runs on Mondays. You can use a schedule
trigger
to run a workflow every day. And you could duplicate that workflow
and add in the special changes that you want to run only on Mondays.
But, ugh, maintaining two similar but only slightly different workflows
is a serious pain.
Instead, you can look at the day of the week and set up an environment
variable based on that -- here, I'll use bash syntax to run the date
command to print the abbreviated day-of-week, and put that inside my
echo
statement that will set up the DAY_OF_WEEK
variable in our
env
context.
Then I'll use that env.DAY_OF_WEEK
as a conditional for a subsequent
step.
With this configuration, I'll run the workflow every day at 05:00 UTC. On a Monday, like today, the Monday-only step will be run.
But for the rest of the week, that step will be skipped.
This is another great example of how GitHub Actions gives you simple primitives that you can combine together to create powerful workflows.