3

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)

Azeem
  • 11,148
  • 4
  • 27
  • 40
ChzDz
  • 171
  • 1
  • 1
  • 9

1 Answers1

2

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!

hakre
  • 193,403
  • 52
  • 435
  • 836
  • Thanks for your response, I have never used jq binding earlier will have to look it up. Looks like there is some issue with the code you specified. the " seems to be delimited in an incorrect place i.e. the Third occurrence of " Will look it up anyways. – ChzDz May 31 '23 at 02:43
  • In single line with Bash [here strings](https://www.gnu.org/software/bash/manual/bash.html#Here-Strings) `<<<`: `P_SCHEMA="$(jq -r --arg v_db_schema "$v_db_schema" '.[$v_db_schema]' <<< '${{ toJSON(vars) }}')"` – Azeem May 31 '23 at 04:32
  • @ChzDz: Not in my tests, but as the code in my answer depends on the code in the question but it was only a fragment, not the [mre] YMMV and you may need to adopt it to match your specific place of use. The example in the answer should show how it works in general, in a run propery, multiline string default GNU Bash shell. Please also check if the syntax suggested by Azeem does it for you. – hakre May 31 '23 at 05:27