String elkEndpoint = 'https://elastic.beta.tower.am.health.ge.com/'
I need to use value of elkEndpoint somewhere in code like below:
// Some code
'metrics': [
'elasticEndpoint': elkEndpoint,
'esConnection': ''
],
// Some code
I tried using below, but its not working:
'elasticEndpoint': elkEndpoint,
2 'elasticEndpoint': ${elkEndpoint},
3 'elasticEndpoint': $elkEndpoint,
What is way to use value of a variable?
What is way to use value of a variable?
You can do this:
String elkEndpoint = 'https://elastic.beta.tower.am.health.ge.com/'
Map metrics = [ elasticEndpoint: elkEndpoint, esConnection: '' ]
println metrics
That will output the following:
[elasticEndpoint:https://elastic.beta.tower.am.health.ge.com/, esConnection:]
Related
I'm trying to remove url prefix from urls Array in logstash using ruby:
The url looks like this: urlArray = ['https://www.google.com','https://www.bcc.com']
I tried to use other array and do something like:
urlArray.each{ |url| newUrlArray.push(url.gsub("(https?://)?(www\.)?","")) }
I also tried:
newUrlArray = urlArray.map{ |url| url.gsub("(https?://)?(www\.)?","") }
I think I miss here something with the gsub.
Thanks
I suggest to use slice and then capture the group you're interested in.
urlArray = [
"https://www.google.com",
"https://www.bcc.com",
"http://hello.com",
"www.world.com"
]
newUrlArray = []
pattern = /(https?:\/\/)?(www.)?(.*)/
urlArray.each{ |url| newUrlArray.push(url.slice(pattern, 3)) }
puts newUrlArray
# google.com
# bcc.com
# hello.com
# world.com
I must be being incredibly stupid but I can't figure out how to do simple string concatenation in Terraform.
I have the following data null_data_source:
data "null_data_source" "api_gw_url" {
inputs = {
main_api_gw = "app.api.${var.env_name == "prod" ? "" : var.env_name}mydomain.com"
}
}
So when env_name="prod" I want the output app.api.mydomain.com and for anything else - let's say env_name="staging" I want app.api.staging.mydomain.com.
But the above will output app.api.stagingmydomain.com <-- notice the missing dot after staging.
I tried concating the "." if the env_name was anything but "prod" but Terraform errors:
data "null_data_source" "api_gw_url" {
inputs = {
main_api_gw = "app.api.${var.env_name == "prod" ? "" : var.env_name + "."}mydomain.com"
}
}
The error is __builtin_StringToInt: strconv.ParseInt: parsing ""
The concat() function in TF appears to be for lists not strings.
So as the title says: How do you do simple string concatenation in Terraform?
I can't believe I'm asking how to concat 2 strings together XD
Update:
For anyone that has a similar issue I did this horrific workaround for the time being:
main_api_gw = "app.api.${var.env_name == "prod" ? "" : var.env_name}${var.env_name == "prod" ? "" : "."}mydomain.com"
I know this was already answered, but I wanted to share my favorite:
format("%s/%s",var.string,"string2")
Real world example:
locals {
documents_path = "${var.documents_path == "" ? format("%s/%s",path.module,"documents") : var.documents_path}"
}
More info:
https://www.terraform.io/docs/configuration/functions/format.html
so to add a simple answer to a simple question:
enclose all strings you want to concatenate into one pair of ""
reference variables inside the quotes with ${var.name}
Example: var.foo should be concatenated with bar string and separated by a dash
Solution: "${var.foo}-bar"
Try Below data resource :
data "null_data_source" "api_gw_url" {
inputs = {
main_api_gw = "app.api${var.env_name == "prod" ? "." : ".${var.env_name}."}mydomain.com"
}
}
For Terraform 0.12 and later, you can use join() function:
join(separator, list)
Example:
> join(", ", ["foo", "bar", "baz"])
foo, bar, baz
> join(", ", ["foo"])
foo
If you just want to concatenate without a separator like "foo"+"bar" = "foobar", then:
> join("", ["foo", "bar"])
foobar
Reference: https://www.terraform.io/docs/configuration/functions/join.html
Use the Interpolation Syntax for versions < 0.12
Here is a simple example:
output "s3_static_website_endpoint" {
value = "http://${aws_s3_bucket.bucket_tf.website_endpoint}"
}
Reference the Terraform Interpolation docs:
https://developer.hashicorp.com/terraform/language/expressions/strings#string-templates
after lot of research, It finally worked for me. I was trying to follow https://www.hashicorp.com/blog/terraform-0-12-preview-first-class-expressions/, but it did not work. Seems string can't be handled inside the expressions.
data "aws_vpc" "vpc" {
filter {
name = "tag:Name"
values = ["${var.old_cluster_fqdn == "" ? "${var.cluster_fqdn}" : "${var.old_cluster_fqdn}"}-vpc"]
}
}
I have two functions that only store variables. Example:
Function datanode1(){
homedirectory = "/path/to/file"
ConfigDirectory = "/path/to/file"
user = "john"
max_open_Files = 262114
}
datanode2 is exactly the same, just different path files.
I would like to do something like this:
if [ "$a1" == "all" ]; then
for i in [datanode2, datanode1] do
*execute Script*
done
fi
Is this possible? How are the functions acting as arrays?
If you have functions named datanode2 and datanode1, and you want to execute them in a loop, you could write like this:
for fun in datanode2 datanode1; do
"$fun"
done
Btw the function definition in your example has some syntax error. It should be more like this:
datanode1() {
homedirectory="/path/to/file"
ConfigDirectory="/path/to/file"
user="john"
max_open_Files=262114
}
My requirement is to create a template engine to support a looping in it.
The final template should look something like this:
#cat output.template
env:
- name : param1
value : 1
- name : param2
value : 2
I have pseudo code to explain my requirement
def f = new File('output.template')
def engine = new groovy.text.GStringTemplateEngine()
def mapping = [
[ name : "param1",
value : "1"],
[ name : "param2",
value : "2" ]
] // This mapping can consists of a multiple key value pairs.
def Template = engine.createTemplate(f).make(mapping)
println "${Template}"
Can someone help me how to achieve this requirement of looping inside the templates and how should I modify my template?
*UPDATE : All the solutions provided by tim_yates or by Eduardo Melzer has resulted in following output with extra blank lines at the end of template. What could be the reason for that?* Are the solution providers not able to see this behavior or the issue is my system only?.
# groovy loop_template.groovy
env:
- name: param1
value : 1
- name: param2
value : 2
root#instance-1:
Change your template file to look like this:
#cat output.template
env:<% mapping.eachWithIndex { v, i -> %>
- name : ${v.name}
value : ${v.value}<% } %>
As you can see, your template file expects an input parameter called mapping, so you need change your main code to something like this:
def f = new File('output.template')
def engine = new groovy.text.GStringTemplateEngine()
def mapping = [
[ name : "param1", value : "1"],
[ name : "param2", value : "2"]
] // This mapping can consists of a multiple key value pairs.
def Template = engine.createTemplate(f).make([mapping: mapping])
println "${Template}"
Output:
#cat output.template
env:
- name : param1
value : 1
- name : param2
value : 2
I have input data of type
abc 12d
uy 76d
ce 12a
with the lines being separated by \n and the values by \t.
The data comes from a shell command:
brlist = 'mycommand'.execute().text
Then I want to get this into a map:
brmap = brlist.split("\n").collectEntries {
tkns = it.tokenize("\t")
[ (tkns[0]): tkns[1] ]
}
I also tried
brmap = brlist.split("\n").collectEntries {
it.tokenize("\t").with { [ (it[0]): it[1] ] }
}
Both ways gave the same result, which is a map with a single entry:
brmap.toString()
# prints "[abc:12d]"
Why does only the first line of the input data end up being in the map?
Your code works, which means the input String brlist isn't what you say it is...
Are you sure that's what you have? Try printing brlist, and then it inside collectEntries
As an aside, this does the same thing as your code:
brlist.split('\n')*.split('\t')*.toList().collectEntries()
Or you could try (incase it's spaces not tabs, this will expect both)
brlist.split('\n')*.split(/\s+/)*.toList().collectEntries()
This code works
// I use 4 spaces as tab.
def text = 'sh abc.sh'.execute().text.replaceAll(" " * 4, "\t")
brmap = text.split("\n").collectEntries {
tkns = it.tokenize("\t")
[(tkns[0]) : tkns[1]]
}
assert[abc:"12d", uy:"76d", ce:"12a"] == brmap
abc.sh
#!/bin/sh
echo "abc 12d"
echo "uy 76d"
echo "ce 12a
Also, I think your groovy code is correct. maybe your mycommand has some problem.
Ok, thanks for the hints, it is a bug in Jenkins: https://issues.jenkins-ci.org/browse/JENKINS-26481.
And it has been mentioned here before: Groovy .each only iterates one time