githubgithub-actions

How to get an updated value of repository variable in the same workflow?


I have a workflow with a job consisting of two steps. The first one is updating the repo level variable (GitHub documentation). The second outputs this value using the vars. context.

    - name: Set new value
      run: |
        gh api \
          --method PATCH \
          -H "Accept: application/vnd.github+json" \
          -H "X-GitHub-Api-Version: 2022-11-28" \
          /repos/ORG/REPO/actions/variables/MY_VAR \
          -f name='MY_VAR' \
          -f value="1.2.3"
    - name: Echo new value
      run: |
        echo ${{ vars.MY_VAR}}

But I'm still getting the old value in the second step although the value was definitely updated (I can check this using both the UI and API call).

It looks like the vars. are initialized only at the beginning of the execution. Is there any way to 'reload' them during the execution? I definitely can get the updated value using the API, but it looks like an overhead.


Solution

  • I had similar workflow, I was updating my variable on different jobs steps, only one got updated, it seems the value is cached at execution time, I had to pull the current value using gh REST API, and updated it with gh CLI (I prefer the CLI, but listing variables truncates the value) for each of the steps.

    If you want to set, and get the updated value, you could achieve that with the combination of gh CLI (for brevity) and gh REST API:

    - name: Set new value
      run: |
        gh variable set MY_VAR --body "1.2.3"
    
    - name: Get new value, pipe it with jq to print just the value to STDOUT
      run: |
        gh api \
          --method GET \
          -H "Accept: application/vnd.github+json" \
          -H "X-GitHub-Api-Version: 2022-11-28" \
          /repos/ORG/REPO/actions/variables/MY_VAR | jq -r '.value'
    

    (Aug 31, 2024) UPDATE:

    As VonC mentioned from their answer there have been updates to gh CLI, it now have the get command for variables, although getting the variables take a slightly different approach than theirs;

    VonC's:

    - name: Get new value, pipe it with jq to print just the value to STDOUT
      run: |
        gh variable get MY_VAR --json | jq -r '.value'
    

    The CLI spit the below out:

    Specify one or more comma-separated fields for `--json`:
      createdAt
      name
      numSelectedRepos
      selectedReposURL
      updatedAt
      value
      visibility
    

    What worked:

    - name: Get new value, pipe it with jq to print just the value to STDOUT
      run: |
        gh variable get MY_VAR --json value | jq -r '.value'