Forums

Articles
Create
cancel
Showing results for 
Search instead for 
Did you mean: 

Using environment variables within strings (interpolation) to output JSON

Skowronek
I'm New Here
I'm New Here
Those new to the Atlassian Community have posted less than three times. Give them a warm welcome!
March 7, 2019 edited

Given a pipeline env variable $MYVAR, how would one write the pipeline script command to interpolate the env var within my pipeline YAML? Here is very basic example:

script:

  - echo '{"myvar":"$MYVAR"}' > ~/file.json

Right now, the $MYVAR is not getting interpolated. have tried ${MYVAR} as well. Haven't found a lot of examples unfortunately.

Thanks.

 

1 answer

1 vote
Graham Gatus
Atlassian Team
Atlassian Team members are employees working across the company in a wide variety of roles.
April 16, 2019 edited

@Skowronek in your example, the MYVAR variable wasn't interpolated due to the single quotes - you need to swap this out for double quotes. Alternatively, you can also use a 'here' document. Below is an example showing the broken approach, and two working approaches; double quoting, and using a here document:

 

image: atlassian/default-image:2

pipelines:
default:
- step:
script:
# Broken due to single quotes, bash wont substitute $MYVAR.
- echo '{"myvar":"$MYVAR"}' > file1.json
- cat file1.json
# Works - escaping with double quotes.
- echo "{\"myvar\":\"$MYVAR\"}" > file2.json
- cat file2.json
# Works - using a here document, see http://tldp.org/LDP/abs/html/here-docs.html
- >
cat <<EOF > file3.json
{"myvar":"${MYVAR}"}
EOF
- cat file3.json

 

Graham Gatus
Atlassian Team
Atlassian Team members are employees working across the company in a wide variety of roles.
April 16, 2019 edited

I'd also recommend using the 'jq' tool (https://stedolan.github.io/jq/) when trying to generate json. You can use it with variable substitution to build up complex json strings, e.g

 

jq -n --arg varname "$MYVAR" '{"myvar": $varname }'

 

Suggest an answer

Log in or Sign up to answer
TAGS
atlassian, jira cloud certification, managing jira projects, jira project administration, jira cloud exam, atlassian certification, agile project management, jira workflows, jira permissions, jira training, jira cloud skills, atlassian learning

Become a Certified Jira Service Project Expert 🦸🏻‍♂️

Validate your expertise in managing Jira Service Projects for Cloud. Master configuration, optimize workflows, and manage users seamlessly. Earn global 🗺️ recognition and advance your career as a trusted Jira Service management expert.

Get Certified! ✍️
AUG Leaders

Atlassian Community Events