Jenkins groovy string interpolation using a combination of secret and non secret values
In Jenkins, groovy string interpolation can be used to dynamically insert values into strings. This is useful for constructing dynamic content, such as log messages, configuration files, or scripts.
When using groovy string interpolation, there are two types of values that can be inserted into strings:
- Secret values: These values are sensitive and should not be exposed in plain text. Examples of secret values include passwords, API keys, and access tokens.
- Non-secret values: These values are not sensitive and can be exposed in plain text. Examples of non-secret values include user names, file paths, and URLs.
To insert a secret value into a string, you must use double quotes and escape the $
sign. For example:
"password is \$PASSWORD"
To insert a non-secret value into a string, you can simply use double quotes. For example:
"username is $USERNAME"
You can also use groovy string interpolation to set environment variables. This is useful for passing values to other scripts or processes.
To set an environment variable, you must use single quotes and escape the $
sign. For example:
'USERNAME=$USERNAME'
This will set the USERNAME
environment variable to the value of the $USERNAME
variable.
Example
The following example shows how to use groovy string interpolation to construct a dynamic log message:
def logMessage = "User $USERNAME logged in at $TIMESTAMP"
println logMessage
This script will print the following message to the console:
User johndoe logged in at 2023-03-08 12:34:56
Conclusion
Groovy string interpolation is a powerful tool that can be used to construct dynamic content in Jenkins. By using a combination of secret and non-secret values, you can create scripts that are both secure and flexible.