How can I set an expression as an environment variable at workflow level?

I am trying to create an environment variable at workflow level with its value being an expression but keep running into syntax errors. I need this env var available to several jobs.

env:
  TIMESTAMP: ${{ date +%s }}

Can this be done?

2 Likes

I’m trying to do something similar to get a timestamp without any colons but not having any luck.

env:
  TIMESTAMP: ${{ date "+%Y-%m-%d-%H:%M" }}

Your workflow file was invalid: The pipeline is not valid. .github/workflows/prod.yml (Line: 47, Col: 20): Unrecognized named-value: 'date'. Located at position 1 within expression: date "+%Y-%m-%d-%H:%M"

@gplayersv I ended up using https://github.com/marketplace/actions/current-time to get the current ISO timestamp, then https://github.com/marketplace/actions/replace-string to regex it to the exact format we needed.

It was a lot of hoops to jump through but it worked for us in the end. Hopefully this helps you!

4 Likes

@dalezak - Any chance you can paste the solutions you ended up with please?

1 Like

Hi @srfrnk, this is what I ended up doing:

- name: Get timestamp
      uses: gerred/actions/current-time@master
      id: current-time

    - name: Run string replace
      uses: frabert/replace-string-action@master
      id: format-time
      with:
        pattern: '[:\.]+'
        string: "${{ steps.current-time.outputs.time }}"
        replace-with: '-'
        flags: 'g'

And then you can use ${{ steps.format-time.outputs.replaced }}.

3 Likes

This way is working for me. Without additional actions:

jobs:
build:
runs-on: ubuntu-latest
steps:
-name: Get current date
id: date
run: echo "::set-output name=date::$(date +'%Y-%m-%d')"

After you can use ${{steps.date.outputs.date}} to use a value.

Not sure if you can put it to env var and use across several jobs.

19 Likes

BTW @dalezak maybe this can help you - having seen your solution I went and upgraded https://github.com/marketplace/actions/current-time so that it could have custom formatting and you can avoid using two components for that.

You can find it here:

https://github.com/marketplace/actions/current-time-2

4 Likes

Thanks @vstelmakh, your suggestion worked for me! 👍

Along a similar train of thought, here’s how to set an environment variable. In my case, I wanted to generate a single name for an output folder but you could modify the variable to be just the date.

- run: |
          echo "OUTPUT=output-$(date "+%Y.%m.%d-%H.%M.%S")" >> $GITHUB_ENV
- uses: actions/upload-artifact@v2
        with:
          name: ${{ env.OUTPUT }}
          path: .......
1 Like

This worked for me, thanks!