Setup environment to use variable context when calling a reusable workflow

757 views Asked by At

I'm trying to make use of variables instead of secrets because some of the secrets are not really secrets so wanted to make it nicer, however, I'm having a bit of a fight here.

The first one runs ok because I'm able to use the environment: name: development. However on the build_deploy job, because I'm using a reusable workflow I'm not able to use the environment: name: development.

How can I fix this, or is this even the correct way to do it?

Thanks in advance! :)

name: Deploy 

on:
  workflow_dispatch:

jobs:

  check-env-vars:
    runs-on: ubuntu-latest
    environment:
      name: development

    steps:
      - name : Output vars
        run: |
          echo "cluster-name ${{vars.CLUSTER_NAME}}"
          echo "region ${{vars.REGION}}"
          echo "projectid ${{vars.PROJECT_ID}}"

  build_deploy:
    uses: owner/repo/.github/workflows/build_deploy.yaml@master
    with:
      project-id: ${{ vars.PROJECT_ID }}
      environment: development
      cluster-name: ${{ vars.CLUSTER_NAME }}
      region: ${{ vars.REGION }}
1

There are 1 answers

2
GuiFalourd On

because I'm using a reusable workflow I'm not able to use the environment: name: development.

In that case, following your main workflow, the reusable workflow should look like this:

on:
  workflow_call:
    # Map the workflow outputs to job outputs
    inputs:
      environment:
        required: true
        type: string

jobs:
  my-dynamic-env-job:
    runs-on: ubuntu-latest
    environment:
      name: ${{ inputs.environment }}
    steps:
      - run: |
          echo "${{ vars.PROJECT_ID }}"
          echo "${{ vars.CLUSTER_NAME }}"
          echo "${{ vars.REGION }}"

Where the environment input is used to fill the environment.name property of the job set in the reusable workflow.

In that case, you wouldn't need to send the PROJECT_ID, CLUSTER_NAME and REGION as inputs, because they would depend on the environment input sent.

Your Deploy workflow would then look like this:

name: Deploy 

on:
  workflow_dispatch:

jobs:
  check-env-vars:
    runs-on: ubuntu-latest
    environment:
      name: development
    steps:
      - name : Output vars
        run: |
          echo "cluster-name ${{vars.CLUSTER_NAME}}"
          echo "region ${{vars.REGION}}"
          echo "projectid ${{vars.PROJECT_ID}}"

  build_deploy:
    uses: owner/repo/.github/workflows/build_deploy.yaml@master
    with:
      environment: development

I made an example if you want to check (my environment name is other):