how to set a environment variables on some condition in github workflow

Viewed 2980

Below is my workflow in github:

name: Deploy

on:
  push:
    branches:
      - develop
      - master

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v1
      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v1
        with:
          aws-access-key-id: ${{ secrets.AWS_ECR_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_ECR_SECRET_ACCESS_KEY }}
          aws-region: eu-west-2

How can I set variable value as per condition? Something like this

if branch = master then

          aws-access-key-id: ${{ secrets.AWS_ECR_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_ECR_SECRET_ACCESS_KEY }}

else

      aws-access-key-id: ${{ secrets.ACCESS_KEY_ID }}
      aws-secret-access-key: ${{ secrets.SECRET_ACCESS_KEY }}
1 Answers

You can set env variables at the step level jobs.<job_id>.steps[*].env and use conditional at the step level as well jobs.<job_id>.steps[*].if.

You can find some information about the syntax on the official documentation.

Consequently, using the conditional to perform a specific step if the branch is master (or another branch) is possible.

Here is an example:

steps:

  name: Configure AWS credentials (MASTER)
    if: github.ref == 'refs/heads/master'
    uses: aws-actions/configure-aws-credentials@v1
    with:
      aws-access-key-id: ${{ secrets.AWS_ECR_ACCESS_KEY_ID }}
      aws-secret-access-key: ${{ secrets.AWS_ECR_SECRET_ACCESS_KEY }}
      aws-region: eu-west-2

  name: Configure AWS credentials (NOT MASTER)
    if: github.ref != 'refs/heads/master'
    uses: aws-actions/configure-aws-credentials@v1
    with:
      aws-access-key-id: ${{ secrets.ACCESS_KEY_ID }}
      aws-secret-access-key: ${{ secrets.SECRET_ACCESS_KEY }}
      aws-region: eu-west-2

Here, the first step will only be executed if the branch is master, otherwise the second step will be executed.

Another reference can be found on the github community.

Related