Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access an env var using a dynamic key variable?

Currently we have a requirement to get a value from an environment variable where the value would be determined dynamically.

Normal fixed syntax that works in GitHub Actions Workflow:

P_SCHEMA=${{ vars.DB_APPS_SCHEMA }}

However, if the value of DB_APPS_SCHEMA is dynamic, how do we specify it in the GitHub Actions Workflow?

I derive the value and get it into a variable v_db_schema. Following do not work:

v_db_schema='DB_APPS_SCHEMA'
# Which variable to pick from the Env is dynamic 

P_SCHEMA=${{ vars.$v_db_schema }}
P_SCHEMA=${{ vars.$(v_db_schema) }}
P_SCHEMA=${{ vars.($v_db_schema) }}

Is there any way to get the value populated, where our input variable string has to be dynamic due to some business requirements?

Currently since it is not able to resolve the syntax it throws errors like:

Invalid workflow file: .github/workflows/Argo_Deploy_Line.yml#L239The workflow is not valid. .github/workflows/Argo_Deploy_Line.yml (Line: 239, Col: 18): Unexpected symbol: '('. Located at position 6 within expression: vars.($v_db_schema)

like image 449
ChzDz Avatar asked Oct 15 '25 02:10

ChzDz


1 Answers

Within the Microsoft Github Action Workflow Context Expression, there is no way to do this directly.

However you can import the whole vars context as JSON Text (Cf. toJSON(value) ) and then filter it within a shell pipeline (Cf. jq(1), also supports named parameters).

    run: |      
      v_db_schema='DB_APPS_SCHEMA'
      # Which variable to pick from the Env is dynamic
      P_SCHEMA="$(jq -r --arg v_db_schema "$v_db_schema" '.[$v_db_schema]' <<'JSON'
      ${{ toJSON(vars) }}
      JSON
      )"
      # ...

TLDR: In workflow syntax no, in shell/javascript/... yay!

like image 194
hakre Avatar answered Oct 18 '25 15:10

hakre