github-actionscredentialsgithub-secret

How to set an "environment" in a non-trivial way using expression?


I have a GitHub Actions workflow which deploys some things to an environment. The workflow needs to log in to access the environment, so we use GitHub environment secrets to store credentials.

My workflow contains this:

on:
  workflow_dispatch:
    inputs:
      deployment_target:
        type: choice
        description: Choose an environment to deploy to
        options:
          - dev
          - staging
          - production
          - benchmarks
...
jobs:
  deploy-to-persistent-environment:
    environment: ${{ github.event.inputs.deployment_target}}
    steps: 
      - name: Login # Pseudocode
        run: login -password "${{ secrets.PASSWORD }}"
      - name: Deploy # Pseudocode
        run: DeploymentTool.exe -environment "${{ github.event.inputs.deployment_target}}"

The "benchmarks" environment uses the same credentials as the "development" environment. So I would like to re-use the same GitHub environment secrets rather than have two sets of duplicate environment secrets in GitHub.

I.e., I would like to do something like this pseudocode:

jobs:
  deploy-to-persistent-environment: # Pseudocode
    environment: ${{ if github.event.inputs.deployment_target == 'benchmarks' then 'development' else github.event.inputs.deployment_target }}
    steps: 
      - name: Login
        run: login -password "${{ secrets.PASSWORD }}"
      - name: Deploy
        run: DeploymentTool.exe -environment "${{ github.event.inputs.deployment_target}}"

Is there any way to achieve this with GitHub Actions?


Solution

  • There is a way to do it directly in the expression, according to this reference on the Github Community, by using the syntax ${{ x && 'ifTrue' || 'ifFalse' }}

    In that case:

    In our case here, it would look like this:

    environment: ${{ github.event.inputs.deployment_target == 'benchmarks' && 'development' ||  github.event.inputs.deployment_target }}
    

    Where:

    Updating the pseudocode:

    jobs:
      deploy-to-persistent-environment: # Pseudocode
        environment: ${{ github.event.inputs.deployment_target == 'benchmarks' && 'development' ||  github.event.inputs.deployment_target }}   
        steps: 
          - name: Login
            run: login -password "${{ secrets.PASSWORD }}"
          - name: Deploy
            run: DeploymentTool.exe -environment "${{ github.event.inputs.deployment_target}}"
    

    EDIT: This is now available on the GitHub official doc as well (Thanks Benjamin W for reporting)