Bash – Not able to access groovy variable inside shell script in JenkinsFile

bashhelpdeskJenkinsscriptingshell

def NAMESPACE = "Dev"

def BODY= sh(
script:'''body=$(cat <<-EOF
{
    "name": "${NAMESPACE}",
    "type": "regularwebapp"
}
EOF
)
(echo $body)''',
returnStdout: true
).trim()

The above doesnt work, output is as follows:

{
    "name": "",
    "type": "regularwebapp"
}

Best Answer

Groovy doesn't perform variable substitution inside single-quoted (') strings. Use double-quoted (") strings instead - this will also require escaping non-Groovy variables:

def NAMESPACE = "Dev"

def BODY= sh(
script:"""body=\$(cat <<-EOF
{
    "name": "${NAMESPACE}",
    "type": "regularwebapp"
}
EOF
)
(echo \$body)""",
returnStdout: true
).trim()