dan1st
dan1st

Reputation: 16477

switch environment variable in github actions

I use github actions for integration tests.

The problem is, that the tests should not run on multiple instances with the same configuration in parallel (the test would fail).

But, it can be run once with let's say configuration 1 and once with configuration 2 in parallel.

As this blog post describes, it is not possible to secure that a workflow does not run in parallel.

Is there any way to switch configurations, that configuration 1 and configuration 2 alternately?

In that case, it would not be that likely that the workflow workflows with the same configuration runs in parallel (I could add more configurations if needed).

For example, this could be done by a global and writable (for the workflow) variable that is alternately 1 or 2 and the workflow picks that configuration.

Example workflow(the secret confToSwitch should be switched):

name: test
on: [push]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v1
    - name: Set up JDK 1.8
      uses: actions/setup-java@v1
      with:
        java-version: 1.8
    - name: "load configuration"
      run: echo "configuration=$conf" >> ./conf
      env:
        conf: ${{ secrets.confToSwitch }}
    - name: "integration tests"
      run: "mvn -B integration-test"

Upvotes: 8

Views: 11495

Answers (1)

smac89
smac89

Reputation: 43224

You can try a matrix configuration with:

name: test
on: [push]
jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        token: [token1, token2, etc...]
    steps:
    - uses: actions/checkout@v1
    - name: Set up JDK 1.8
      uses: actions/setup-java@v1
      with:
        java-version: 1.8
    - name: "load configuration"
      run: echo "configuration=$conf" >> ./conf
      env:
        conf: ${{ matrix.token }}
    - name: "integration tests"
      run: "mvn -B integration-test"

This will create N jobs where N is the number of tokens in the list and each job with conf: ${{ matrix.token }} will resolve to a token in the list for the current job.


I think it may also be possible to store your tokens as secrets and setup the matrix like:

strategy:
  matrix:
    token: ["${{secrets.token1}}", "${{secrets.token2}}", etc...]

However, I haven't tested this.

EDIT

I found a trick to make the secrets tokens work:

  1. Create your secrets and call them token1, token2, etc
  2. Create your matrix configuration using the tokens i.e. the names of the secrets:
strategy:
  matrix:
    token: [token1, token2]
  1. In your job's env, create the following environment variable:
env:
  token: ${{secrets[matrix.token]}}
  1. Now the actual value for the token for each build matrix is stored inside the environment variable ${{env.token}} (when operating within an expression context) or $token (in bash).

The environment variable will still remain a secret, so you don't loose anything.

Upvotes: 15

Related Questions