Search code examples
environment-variablesgithub-actionsdynamic-programmingworkflowloadvars

How to load variable file dynamically in github actions workflow


i have a set of 20 variables for each of the 5 environments viz dev, qa, uat, prod, dr like below var_dev.yml:

hostname: "mydevhost"
port: "1885"
mount: "D:\"
...
...

In ansible I could save the variable in variable files that have environment names like var_dev.yml, var_qa.yml etc and load one file based on user input choice like whichever environment they select.

- hosts: localhost
  vars_files:
    - "vars/var_{{ myenv }}.yml"
  tasks:
    - debug: var={{ port }}

ansible-playbook test.yml -e "myenv=dev"

How is it possible to achieve the same in Github Actions workflow?

Below approach I took does not look clean.

name: example-workflow
env:
  hostname_dev: "mydevhost"
  hostname_qa: "myqahost"
  port_dev: "1885"
  port_qa: "1881"
on: 
  push:
  workflow_dispatch:
    inputs:
      myenv:
        type: choice
        options:
          - dev
          - qa
          - perf
          - dr
          - prod

jobs:

  deploy:
    runs-on: ubuntu-latest
    steps:
      - run: echo env[env.hostname_${myen}]

Solution

  • I would suggest you to use the action-dotenv-to-setenv GitHub Action, as example you could have one env files for each environment and use like:

    - name: Configure ${{ inputs.myenv }} environment
      uses: c-py/action-dotenv-to-setenv@v2
      with:
        env-file: ./env/env.${{ inputs.myenv }}
    

    with the following files

    ./env/env.dev

    hostname: "mydevhost"
    port: "1885"
    

    ./env/env.qa

    hostname: "myqahost"
    port: "1881"