Search code examples
github-actions

When should you use single curly braces vs double curly braces for variable reference in github actions?


I'm starting to learn github actions (converting from jenkins piplines). I am not super familiar with yaml.

I cannot figure out when or why variables should be referenced using double curly braces vs single curly braces. I have a feeling there is an important distinction here.... Can you clue me in?

name: sample
on:
  workflow_dispatch
env:
  MY_VAR: "something"

jobs:
  do_things:
    runs-on: ubuntu-latest
    steps:
      - name: "Step 1"
        run: echo "${MY_VAR}"
      - name: "Step 2"
        run: echo "${{env.MY_VAR}}"

enter image description here


Solution

  • This line:

    run: echo "${MY_VAR}"
    

    is literally running a bash script that says:

    echo "${MY_VAR}"
    

    so in this case, ${MY_VAR} is expanded according to bash's rules; in this case it will just print the environment variable MY_VAR, but you can do all sorts of crazy things with bash's parameter expansion.

    On the other hand, this line:

    run: echo "${{env.MY_VAR}}"
    

    is expression syntax for GitHub Actions and will be expanded by the GitHub Actions runner. In this case, the variable MY_VAR that is in your environment context will be replaced in the shell script.

    The literal shell script that will be executed will have the environment variable value in it. So if MY_VAR=foo, then the literal bash script that will be run is:

    echo "foo"
    

    So although the outcome is similar at the end, the means of getting there is very different, based on when the substitution happens.