Substitute values from property file in Jenkinsfile for dynamically set variables - groovy

I have a Jenkinsfile with multiple parameters that are environment-specific.
The values for those parameters are stored in a property file. I am trying to set the variables based upon the selected environment and then replace their values from the property files.
Jenkinsfile
ENVIRONMENT is a choice parameter having 2 values: ft, perf and pm as below in my Jenkinsfile
choice (
name: 'ENVIRONMENT',
choices: ['ft', 'perf','pm'],
description: 'please select the environment'
)
PROPERTY_FILE is another choice parameter as below
choice (
name: 'PROPERTY_FILE',
choices: ['jenkins/app.groovy'],
description: 'please select the property file'
)
app.groovy looks like:
Test_perf="Hello"
Test_ft="World"
Test_pm="Welcome"
Stages
stage('Load Environment Property File') {
steps {
script {
//sourcing user selected property file
load "${PROPERTY_FILE}"
def envName = "${PROPERTY_FILE}".tokenize(".")[0]
//it will set build description as description in Jenkins build history
env.envName=envName
currentBuild.description = "Env:${envName}"
}
}
}
//STAGE FOR WHICH I NEED HELP
stage('Set Variables Based upon environment name') {
steps {
script{
if ("${ENVIRONMENT}" == "perf" ){
var="\${Test_"+"${DEPLOYMENT_ENVIRONMENT}"+"}"
echo "${var}" //output is ${Test_pm} and is correct as the substitution happens.
//NOW, I AM TRYING TO echo "HELLO", i.e.; replacing the variable "${Test_perf}" stuffed inside "var" from the property file. However, since the property file is already loaded, it will not replace the key by its value from the property file.
} else if ("${ENVIRONMENT}" == "ft" ){
var="\${Test_"+"${DEPLOYMENT_ENVIRONMENT}"+"}"
echo "${var}" //output is ${Test_ft} and is correct as the substitution happens.
//NOW, I AM TRYING TO echo "World"
} else {
var="\${Test_"+"${DEPLOYMENT_ENVIRONMENT}"+"}"
echo "${var}" //output is ${Test_pm} and is correct as the substitution happens.
//NOW, I AM TRYING TO echo "Welcome"
}
}
}
}
Is there a way to further substitute the value from the property file. For e.g.; "${var}" expands to "${Test_pm}" and then "${Test_pm}" gets the value "Welcome" from the property file.
Please help.

Related

Retrieve with groovy an Attribute value

I have the following data on groovy
Binding Variables: [ timing:After Create,
attributes:[LOCK_OUT:Attribute: { NAME:Attribute:
{Name=NAME, Value=[Bob]}, PASSWORD:Attribute:
{Name=PASSWORD,
Value=[org.identityconnectors.common.security.GuardedString#959e062c]}
]]
And I would like to retrieve the value of the password attribute (the GuardedString ) with groovy but I am stuck in the last part.
Until now I did the following:
if (binding.variables != null) {
System.out.println("Binding Variables: "+ binding.variables );
if(binding.variables.containsKey("attributes")){
System.out.println("Got Password binding variable" );
System.out.println (binding.variables.attributes.get("__PASSWORD__")); //here it prints Attribute: {Name=__PASSWORD__, Value=[org.identityconnectors.common.security.GuardedString#3a6f394]}
System.out.println (binding.variables.attributes.get("__PASSWORD__").getAttribute("__PASSWORD__")); //this is not working..
}
}
Can anyone help me? How can I retrieve this value?
Thanks

Jenkins pipeline convert all parameters to lowercase

How can I convert all the parameters in a Jenkins pipeline to lowercase. Similar to trim, is there an attribute that one could add as part of the parameter declaration,
For trim, I have something like below,
parameters {
string defaultValue: '', description: 'Some dummy parameter', name: 'someparameter', trim: true
}
In my pipeline job, I have more than 10 string parameters and would like to convert them all to lowercase
Here's one approach:
pipeline {
agent any
parameters {
string ( name: 'testName', description: 'name of the test to run')
}
stages {
stage('only') {
environment {
TEST_NAME=params.testName.toLowerCase()
}
steps {
echo "the name of the test to run is: ${params.testName}"
sh 'echo "In Lower Case the test name is: ${TEST_NAME}"'
}
}
}
}
sh """ ${the_parameter.toLowerCase()} """
Need to use double quote so you have a GString
Put the toLowerCase() function call inside the brace for shell to refer back to groovy
Actually one can just do
VAR = "${VAR.toLowerCase()}"
Had to use this for my use case. It will not convert but it will prevent passing wrong value.
validatingString(name: "MYVAR",
defaultValue: "",
regex: /^[a-z0-9]+$/,
failedValidationMessage: "",
description: "")

Correct way to Terraform template_provider data source output

I'm trying to render the output of a map using a template in Terraform:
variable "default_tags" {
type = "map"
default = {
"tag1" ="Tag A",
"tag2" ="Tag B"
}
}
Define a template_file data source to render the map:
```
data "template_file" "test" {
template = "${data}"
vars {
data = "${join(",", formatlist("key: %s, val: %s. ", keys(var.default_tags), values(var.default_tags)))}"
}
}
```
My output bloc should look like this:
```
output "default_tags_rendered" {
value="${data.template_file.test.rendered}"
}
```
However I get this error when planning:
```
Error: data.template_file.test: 1 error(s) occurred:
* data.template_file.test: invalid variable syntax: "data". Did you mean 'var.data'? If this is part of inline `template` parameter
then you must escape the interpolation with two dollar signs. For
example: ${a} becomes $${a}.
```
What would be the correct way to output the rendered template?
This may be better suited to using local values like so
locals {
data = "${join(",", formatlist("key: %s, val: %s. ", keys(var.default_tags), values(var.default_tags)))}"
}
output "default_tags_rendered" {
value="${local.data}"
}
Reasoning is because the template_file provisioner is mainly used for files (or inline templates) that need to be run through the standard interpolation syntax. In this case, you don't have any variables to be interpolated in a template - you have a variable coming in and you need to mutate it's value.

Optional parameter in Groovy Script

I have a script that simply does
// TODO: assign default value if not defined
println optionalParameter
When I invoke it using:
new GroovyShell(new Binding([optionalParameter: 'text'])).evaluate(script)
it works fine. But if I run it without a parameter like below:
new GroovyShell().evaluate(script)
it fails with MissingPropertyException.
How can I assign default value for optionalParameter so that I don't get MissingPropertyException?
Adding this code to script works for me:
String value
if (binding.hasVariable('optionalParameter')) {
value = binding.getVariable('optionalParameter')
} else {
value = 'defaultValue'
}
println value

Using contains key with file_get_contents

So I'm trying to read a JSON file at a seperate url and based off what what is in the JSON file I would like for the program to do something. But the way I'm currently trying to do it is not working.
<?php
$homepage = file_get_contents('http://direct.cyberkitsune.net/canibuycubeworld/status.json');
//echo $homepage;
if($homepage contains 'f'){
echo 'true';
}else{
echo 'Something went terribly wrong!";
}
?>
This is the error that I get
Parse error: syntax error, unexpected T_STRING in /home/a1285224/public_html/cubeworld.php on line 4
When I searched up the "file_get_contents" under the php manual it says that it should read the entire file into a string, so I'm a little confused why I'm getting a string error.
Thanks~
In stead of 'contains', see the strpos function. Also, you must close single quotes with single quotes, and double quotes with double quotes.
i.e.
$homepage = file_get_contents("http://direct.cyberkitsune.net/canibuycubeworld/status.json");
// echo $homepage;
if (strpos($homepage, "f") !== false)
{
echo "true";
}
else
{
echo "Somethingwentterriblywrong!";
}
Based on what you are trying to do, also see PHP's JSON library.
To get the JSON data, you can use json_decode.
To dump all vars:
$json = json_decode($homepage, true);
var_dump($json);
To get all the other data:
printf("Time: %s<br>Site: %s<br>Reg: %s<br>Shop: %s", $json['time'], $json['site'], $json['reg'], $json['shop']);

Resources