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.
@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
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 }'
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Online forums and learning are now in one easy-to-use experience.
By continuing, you accept the updated Community Terms of Use and acknowledge the Privacy Policy. Your public name, photo, and achievements may be publicly visible and available in search engines.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.