Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to concatenate variable strings

I need to create new variable from contents of other variables. Currently I'm using something like this:

- command: echo "{{ var1 }}-{{ var2 }}-{{ var3 }}"   register: newvar 

The problem is:

  • Usage of {{ var1 }}...{{ varN }} brings too long strings and very ugly code.
  • Usage of {{ newvar.stdout }} a bit better but confusing.
  • Usage of set_fact module caches fact between runs. It isn't appropriate for me.

Is there any other solution?

like image 720
Timofey Stolbov Avatar asked Jul 02 '15 14:07

Timofey Stolbov


People also ask

What is the most efficient way to concatenate many strings together?

When concatenating three dynamic string values or less, use traditional string concatenation. When concatenating more than three dynamic string values, use StringBuilder . When building a big string from several string literals, use either the @ string literal or the inline + operator.

Can variables be combined with strings?

To combine the values of two or more variables or text strings into a single text value, you use the string concatenation function.

What are the 2 methods used for string concatenation?

There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.


1 Answers

Since strings are lists of characters in Python, we can concatenate strings the same way we concatenate lists (with the + sign):

{{ var1 + '-' + var2 + '-' + var3 }} 

If you want to pipe the resulting string to some filter, make sure you enclose the bits in parentheses:

e.g. To concatenate our 3 vars, and get a sha512 hash:

{{ (var1 + var2 + var3) | hash('sha512') }} 

Note: this works on Ansible 2.3. I haven't tested it on earlier versions.

like image 170
user187557 Avatar answered Oct 02 '22 07:10

user187557