Jivan
Jivan

Reputation: 23078

Generate unique string in Github Actions

I have the following env definition for a job in Github Actions:

jobs:
  build-test-deploy:
    runs-on: ubuntu-latest
    env:
      FOO : foobar-${{ github.sha }}
      BAR : BAZ

However the github.sha remains identical when the same workflow is re-run without any commit in between. I need the FOO to be unique for every run (even if it's technically a re-run), independently of commits.

Two options I'm thinking of:

I don't know how to get either of these values in the context of the env: directive. There are some actions available to use within steps but how is it possible to get this kind of unique values right from the env directive instead?

Upvotes: 6

Views: 11700

Answers (2)

Possseidon
Possseidon

Reputation: 582

There is a github.run_attempt variable now (not sure since when) that increments on re-runs. So by combing that with e.g. github.run_id you can generate per-run fully unique strings.

jobs:
  build-test-deploy:
    runs-on: ubuntu-latest
    env:
      FOO : foobar-${{ github.run_id }}-${{ github.run_attempt }}
      BAR : BAZ

Make sure to put a delimiter inbetween (- in the example above) as you might get duplicates otherwise. Without it, e.g. 123 could result from both run 12 attempt 3 or run 1 attempt 23.

Quick link to the relevant docs for further reading.

Upvotes: 16

Jivan
Jivan

Reputation: 23078

jobs:
  build-test-deploy:
    runs-on: ubuntu-latest
    env:
      BAR : BAZ

    steps:
      - name: generate FOO unique variable based on timestamp
        run: echo FOO=foobar--$(date +%s) >> $GITHUB_ENV

      - name: other step that needs FOO
        run: echo ${{ env.FOO }}

Upvotes: 4

Related Questions