Search code examples
continuous-integrationgithub-actions

What is the correct way of using secrets in strategy-matrix pattern in GitHub Actions?


I am using GitHub Actions for one of the projects. I have a use case when I need to deploy to 2 different environments. As the number of domains may grow, I want to deploy to all of them at once parametrically.

Part of my job that fails:

jobs:
  build:
    strategy:
      matrix:
        domain: [['main', 'books-v1'], ['old-main', 'books-v2']]

The above part works perfectly but if I need to add new variants from the secrets, the workflow doesn't work. See the snippet below:

jobs:
  build:
    strategy:
      matrix:
        domain: [['main', 'books-v1', ${{ secrets.URL_V1 }}], ['old-main', 'books-v2', ${{ secrets.URL_V2 }}]]

I checked GitHub Actions docs. I also searched available examples on GitHub to see existing solutions. So far, I didn't find a similar use case.

Is there a way to make it work like that? What are alternatives to my approach that will work?

GitHub Actions failure message:

You have an error in your yaml syntax on line XYZ


Solution

  • At the YAML level, single quotes around ${{ secrets... }} should fix the syntax error.

    But, according to the Context availability, the secrets context is not allowed under stratey. The allowed contexts are:

    jobs.<job_id>.strategy      github, needs, vars, inputs
    

    You can make use of the vars context for your use case.

    Apart from that, linting your workflow with https://rhysd.github.io/actionlint/ would be much faster to identify potential issues.


    UPDATE (by Dmytro Chasovskyi)

    Here is an example with the vars context:

    With a variable DOMAINS having this config:

    {
       "v1": {
         "url": "http://localhost:80/api/v1"
       },
       "v2": {
         "url": "http://localhost:80/api/v2"
       }
    }
    

    the workflow will be:

    jobs:
      build:
        strategy:
          matrix:
            domain: [['main', 'books-v1', '${{ vars.DOMAINS.v1.url }}'], ['old-main', 'books-v2', '${{ vars.DOMAINS.v2.url }}']]