Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • either generate a random string
  • or get the current unix timestamp

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?

like image 943
Jivan Avatar asked Jul 11 '26 23:07

Jivan


1 Answers

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.

like image 80
Possseidon Avatar answered Jul 15 '26 07:07

Possseidon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!