Proper way to concatenate variable strings

北城余情 提交于 2019-12-20 10:22:48

问题


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?


回答1:


Good question. But I think there is no good answer which fits your criteria. The best I can think of is to use an extra vars file.

A task like this:

- include_vars: concat.yml

And in concat.yml you have your definition:

newvar: "{{ var1 }}-{{ var2 }}-{{ var3 }}"



回答2:


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.




回答3:


As simple as joining lists in python itself.

ansible -m debug -a msg="{{ '-'.join(('list', 'joined', 'together')) }}" localhost

localhost | SUCCESS => {
  "msg": "list-joined-together" }

Works the same way using variables:

ansible -m debug -a msg="{{ '-'.join((var1, var2, var3)) }}" localhost


来源:https://stackoverflow.com/questions/31186874/proper-way-to-concatenate-variable-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!