puppet Evaluation Error: Cannot reassign variable - puppet

We are trying to override the the value assigned to the variable in the puppet manifest. Below is the piece of the line from puppet manifest :
39 $java_opts_nodeconfig_extra = '-XX:+ScavengeBeforeFullGC -verbose:gc'
40
41 if $jdk_version =~ /^1.8\.\d+\_/ {
42 $java_opts_nodeconfig_extra = "-XX:+PrintGCTimeStamps -XX:+PrintGCDateStamps -XX:+PrintGCDetails ${java_opts_nodeconfig_extra}"
43 }
And puppet script fails with below error, my use case is if the JDK version is 1.8.x, then override the value and assign to the same variable otherwise the original value assigned to the variable.
Error: Evaluation Error: Error while evaluating a Resource Statement, Evaluation Error: Cannot reassign variable '$java_opts_snippet_nodeconfig_extra' (file:/puppet/modules/acme/manifests/acme_manager.pp, line: 42, column: 41)
How do we solve this ?

Never mind, based on this https://codeburst.io/puppet-code-by-example-part-2-b1099b4ff9a1, looks like we cannot reassign. So , we used other way by means of using "Case" statement.

Related

Expected string literal in condition express in Jenkins pipeline

I am using ?: to determine the build agent of Jenkins shared library groovy script like this:
def call(String type, Map map) {
if (type == "gradle") {
pipeline {
agent "${map.agent == null}" ? "any" : "${map.agent}"
}
}
}
but it gives me the following error:
org.jenkinsci.plugins.workflow.cps.CpsCompilationErrorsException: startup failed:
/Users/dabaidabai/.jenkins/jobs/soa-robot/builds/154/libs/pipeline-shared-library/vars/ci.groovy: 6: Expected string literal # line 6, column 42.
agent "${map.agent == null}" ? "any" :
^
/Users/dabaidabai/.jenkins/jobs/soa-robot/builds/154/libs/pipeline-shared-library/vars/ci.groovy: 6: Only "agent none", "agent any" or "agent {...}" are allowed. # line 6, column 13.
agent "${map.agent == null}" ? "any" : "${map.agent}"
^
/Users/dabaidabai/.jenkins/jobs/soa-robot/builds/154/libs/pipeline-shared-library/vars/ci.groovy: 6: No agent type specified. Must be one of [any, docker, dockerfile, label, none] # line 6, column 13.
agent "${map.agent == null}" ? "any" : "${map.agent}"
What am I doing wrong?
This error is thrown by the pipeline syntax validator that runs before your pipeline code gets executed. The reason you see this error is the following:
Only "agent none", "agent any" or "agent {...}" are allowed. # line 6, column 13.
This is the constraint for the label section. It means that the following values are valid:
agent any
agent none
agent "constant string value here"
agent { ... }
When you pass something like:
agent "${map.agent ?: 'any'}
agent(map.agent ?: 'any')
you are getting Expected string literal because any form of an expression is not allowed in this place, including interpolated GStrings of any form.
Solution
There is a way to define pipeline agent dynamically however. All you have to do is to use a closure block with the label set to either expression or empty string (an equivalent of agent any in this case.)
pipeline {
agent {
label map.agent ?: ''
}
stages {
...
}
}
The label section allows you to use any expression, so map.agent is a valid construction here. Just remember to use an empty string instead of "any" - otherwise Jenkins will search for a node labeled as "any".
Don't use string replacments everyhwhere:
agent(map.agent==null ? "any" : map.agent)
Or get groovy:
agent(map.agent?:"any")
The actual problem is most likely the "ternary operator" battling against the "parens are maybe optional"-rule.
It seems to me that agent is a method taking a string argument and the way your code is written is ambiguous. Try surrounding the argument expression with parens:
agent(map.agent == null ? "any" : "${map.agent}")
I removed the quotes around map.agent == null as they seemed extraneous.
Also this could probably be rewritten using the groovy "elvis operator" (:?) as:
agent(map.agent ?: "any")
Which essentially means "use map.agent if it has a value, otherwise use 'any'". "If it has a value" is in this context being defined using groovy truth where both empty string and null represent "no value".

Variable Interpolation in Terraform

I am having trouble in variable interpolation in terraform. Here is what my terraform configuration looks like. i.e variable inside builtin function
variable "key" {}
ssh_keys {
path = "/home/${var.provider["user"]}/.ssh/authorized_keys"
key_data = "${file(${var.key})}"
}
Command: terraform apply -var 'key=~/.ssh/id_rsa.pub'
It's not reading the value of "key" from command line argument or from env variable. However when i hardcore the value in .tf file, it works. Like below.
key_data = "${file("~/.ssh/id_rsa.pub")}"
The ${ ... } syntax is only used when embedding an expression into a quoted string. In this case, where your var.key variable is just being passed as an argument to a function already within a ${ ... } sequence, you can just reference the variable name directly like this:
key_data = "${file(var.key)}"
Nested ${ ... } sequences are sometimes used to pass an interpolated string to a function. In that case there would first be a nested set of quotes to return to string context. For example:
key_data = "${file("${path.module}/${var.key_filename}")}"
In this more complicated case, the innermost string expression is first evaluated to join together the two variables with a /, then that whole string is passed to the file function, with the result finally returned as the value of key_data.
It doesn't work because you were using the wrong flag for the scenario you described above.
If you want to specify a path to a file use the "-var-file" flag as follow:
terraform apply -var-file=~/.ssh/id_rsa.pub
If you must use the "-var" flag then you must specify the content of the file as follow:
terraform apply -var 'key=contenctOFPublicKey'
ssh_keys - (Optional) Specifies a collection of path and key_data to be placed on the virtual machine.
Note: Please note that the only allowed path is /home/<username>/.ssh/authorized_keys due to a limitation of Azure.
refer: AZURERM_VIRTUAL_MACHINE

Evaluate variable value from string dynamically

We need to get the value of dynamically constructed variables.
What I mean is we have a variable loaded from a property file called data8967677878788node. So when we run echo $data8967677878788node we get the output test.
Now in data8967677878788node the number part 8967677878788 needs to be dynamic. That means there could be variables like
data1234node
data346346367node
and such.
The number is an input argument to the script. So we need something like this to work
TESTVAR="data`echo $DATANUMBER`node"
echo $$TESTVAR #This line gives the value "test"
Any idea on how this can be accomplished
You can use BASH's indirect variable expansion:
data346346367node='test'
myfunc() {
datanumber="$1"
var1="data${datanumber}node"
echo "${!var1}"
}
And call it as:
myfunc 346346367
Output:
test
Your code is actually already pretty close to working, it just needs to be modified slightly:
TESTVAR="data`echo $DATANUMBER`node"
echo ${!TESTVAR}
If $DATANUMBER has the value 12345 and $data12345node has the value test then the above snippet will output test.
Source: http://wiki.bash-hackers.org/syntax/pe#indirection

Dynamic value for an element using property expansion

Referring property expansion from here
One of the element of the soap request is defined as follows.
<ns:PRODUCTID>${=def list = [12, 13,12];list.join(',')}</ns:PRODUCTID>
And when the request is submitted, it evaluates correctly and sends out the request as below(from the raw request):
<ns:PRODUCTID>12,13,12</ns:PRODUCTID>
However, could not get it working a dynamic value as shown below, i mean it is leading below error
<ns:PRODUCTID>${=def a = (int)(Math.random()*5);def list = [];a.times {list.add((int)(Math.random()*1000))};list.join(',')}</ns:PRODUCTID>
But the same script runs perfectly fine when it is run separately.
Error below:
startup failed:
Script16.groovy: 1: expecting '}', found '' # line 1, column 94.
add((int)(Math.random()*1000))
^
org.codehaus.groovy.syntax.SyntaxException: expecting '}', found '' # line 1, column 94.
at org.codehaus.groovy.antlr.AntlrParserPlugin.transformCSTIntoAST(AntlrParserPlugin.java:139)
at org.codehaus.groovy.antlr.AntlrParserPlugin.parseCST(AntlrParserPlugin.java:107)
at org.codehaus.groovy.control.SourceUnit.parse(SourceUnit.java:236)
at org.codehaus.groovy.control.CompilationUnit$1.call(CompilationUnit.java:163)
at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:839)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:544)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:520)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:497)
at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:306)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:287)
at groovy.lang.GroovyShell.parseClass(GroovyShell.java:731)
at groovy.lang.GroovyShell.parse(GroovyShell.java:743)
at groovy.lang.GroovyShell.parse(GroovyShell.java:770)
at groovy.lang.GroovyShell.parse(GroovyShell.java:761)
at com.eviware.soapui.support.scripting.groovy.SoapUIGroovyScriptEngine.compile(SoapUIGroovyScriptEngine.java:148)
at com.eviware.soapui.support.scripting.groovy.SoapUIGroovyScriptEngine.run(SoapUIGroovyScriptEngine.java:93)
at com.eviware.soapui.model.propertyexpansion.resolvers.EvalPropertyResolver.doEval(EvalPropertyResolver.java:191)
at com.eviware.soapui.model.propertyexpansion.resolvers.EvalPropertyResolver.resolveProperty(EvalPropertyResolver.java:170)
at com.eviware.soapui.model.propertyexpansion.PropertyExpander.expand(PropertyExpander.java:180)
at com.eviware.soapui.model.propertyexpansion.PropertyExpander.expandProperties(PropertyExpander.java:113)
at com.eviware.soapui.impl.wsdl.submit.filters.PropertyExpansionRequestFilter.filterWsdlRequest(PropertyExpansionRequestFilter.java:45)
at com.eviware.soapui.impl.wsdl.submit.filters.AbstractRequestFilter.filterAbstractHttpRequest(AbstractRequestFilter.java:37)
at com.eviware.soapui.impl.wsdl.submit.filters.AbstractRequestFilter.filterRequest(AbstractRequestFilter.java:31)
at com.eviware.soapui.impl.wsdl.submit.transports.http.HttpClientRequestTransport.sendRequest(HttpClientRequestTransport.java:184)
at com.eviware.soapui.impl.wsdl.WsdlSubmit.run(WsdlSubmit.java:123)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
Caused by: Script16.groovy:1:94: expecting '}', found ''
at groovyjarjarantlr.Parser.match(Parser.java:211)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.closableBlock(GroovyRecognizer.java:8620)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.appendedBlock(GroovyRecognizer.java:11397)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.pathElement(GroovyRecognizer.java:11349)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.pathExpression(GroovyRecognizer.java:11464)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.postfixExpression(GroovyRecognizer.java:13175)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.unaryExpressionNotPlusMinus(GroovyRecognizer.java:13144)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.powerExpressionNotPlusMinus(GroovyRecognizer.java:12848)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.multiplicativeExpression(GroovyRecognizer.java:12780)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.additiveExpression(GroovyRecognizer.java:12450)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.shiftExpression(GroovyRecognizer.java:9664)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.relationalExpression(GroovyRecognizer.java:12355)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.equalityExpression(GroovyRecognizer.java:12279)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.regexExpression(GroovyRecognizer.java:12227)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.andExpression(GroovyRecognizer.java:12195)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.exclusiveOrExpression(GroovyRecognizer.java:12163)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.inclusiveOrExpression(GroovyRecognizer.java:12131)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.logicalAndExpression(GroovyRecognizer.java:12099)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.logicalOrExpression(GroovyRecognizer.java:12067)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.conditionalExpression(GroovyRecognizer.java:4842)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.assignmentExpression(GroovyRecognizer.java:7988)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.expression(GroovyRecognizer.java:9841)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.expressionStatementNoCheck(GroovyRecognizer.java:8314)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.expressionStatement(GroovyRecognizer.java:8739)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.statement(GroovyRecognizer.java:1274)
at org.codehaus.groovy.antlr.parser.GroovyRecognizer.compilationUnit(GroovyRecognizer.java:757)
at org.codehaus.groovy.antlr.AntlrParserPlugin.transformCSTIntoAST(AntlrParserPlugin.java:130)
... 30 more
1 error
;list.join(',')}
Seems that in property expansion the curly braces {} are not allowed inside ${= ... } because ${= close with any } character from any closure, loop, method.. you try to add it.
Also trying to escape the close \} inside ${= ... } does not help.
You can not even use } in a String, the follow code throws the same exception in SOAPUI:
<ns:PRODUCTID>${=return '}'}</ns:PRODUCTID>
The only way that you can use } here seems that is nesting expression like ${= ... ${= ... } }. For example the follow nested exceptions works:
<ns:PRODUCTID>${= 5 + ${= 3+4 } }</ns:PRODUCTID>
// in raw View you will see <ns:PRODUCTID>12</ns:PRODUCTID>
However they also can not help because individually each one has the same problem with } from closures, loops, methods.
Seems that the parser for property expansion which implements SOAPUI can not deal with this. Good catch, maybe you can request a new feature.
I don't add a workaround using groovy script to save the result in a property, and then use it in your request since I'm totally sure that you know how to do it :)
I don't see where the syntax error is either. But try this:
(0..(Math.random() * 5 as Integer)).collect { Math.random() * 1000 as Integer }.join(',')

groovy compile error

class x{
public static void main(String[] args){
String x="<html><head></head></html>";
String arr[]=x.split("<head>");
String script="hi";
x=arr[0]+"<head>"+script+arr[1];
System.out.println(x);
}
}
the above code when compiled as a java file compiles fine but when used a s a groovy file spits the error :
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
D:\Garage\groovy-binary-1.7.1\groovy-1.7.1\bin\x.groovy: 4: Apparent variable 'a
rr' was found in a static scope but doesn't refer to a local variable, static fi
eld or class. Possible causes:
You attempted to reference a variable in the binding or an instance variable fro
m a static context.
You misspelled a classname or statically imported field. Please check the spelli
ng.
You attempted to use a method 'arr' but left out brackets in a place not allowed
by the grammar.
# line 4, column 10.
String arr[]=x.split("");
^
D:\Garage\groovy-binary-1.7.1\groovy-1.7.1\bin\x.groovy: 6: Apparent variable 'a
rr' was found in a static scope but doesn't refer to a local variable, static fi
eld or class. Possible causes:
You attempted to reference a variable in the binding or an instance variable fro
m a static context.
You misspelled a classname or statically imported field. Please check the spelli
ng.
You attempted to use a method 'arr' but left out brackets in a place not allowed
by the grammar.
# line 6, column 5.
x=arr[0]+""+script+arr[1];
^
D:\Garage\groovy-binary-1.7.1\groovy-1.7.1\bin\x.groovy: 6: Apparent variable 'a
rr' was found in a static scope but doesn't refer to a local variable, static fi
eld or class. Possible causes:
You attempted to reference a variable in the binding or an instance variable fro
m a static context.
You misspelled a classname or statically imported field. Please check the spelli
ng.
You attempted to use a method 'arr' but left out brackets in a place not allowed
by the grammar.
# line 6, column 28.
x=arr[0]+""+script+arr[1];
^
3 errors
D:\Garage\groovy-binary-1.7.1\groovy-1.7.1\bin>
It works if you move the [] to the String side like so:
String[] arr = x.split("<head>");

Resources