问题
I need to create a string for a configuration file.
It needs to be in this format:
nodes = ["node1","node2","node3"]
I was originally trying to do this by reading the hosts from a specific group in hosts, but decided it would be better to use a vars file.
in my vars file I have
---
nodes:
- node: node1
- node: node2
- node: node3
I then want to use the lineinfile function to update the config:
- name: Update cluster nodes
lineinfile:
path: /etc/nodes.txt
regexp: '^#nodes:'
line: "nodes: ["node1","node2","node3"]"
Can anyone help me as I am really struggling to get the string created after looping through the node list.
回答1:
You want to take advantage of the "whitespace control" feature of jinja2 by leading and trailing the template with {%-
and -%}
to ensure any whitespace that is present for legibility to the playbook reader isn't carried through to the line. Then, you may find it convenient to move the line composition into a local vars:
just for legibility:
- name: Update cluster nodes
lineinfile:
# ...as before
line: 'nodes: [{{ nodes_csv }}]'
vars:
nodes_csv: >-
{%- for n in nodes -%}
{{ "" if loop.first else "," }}"{{ n }}"
{%- endfor -%}
Depending on your specific needs, you may also just want to use the to_json filter and then tell it to use separators without whitespace, since your example looks very much like JSON:
lineinfile:
line: 'nodes: {{ nodes | to_json(separators=(",", ":")) }}'
来源:https://stackoverflow.com/questions/59142633/how-to-create-join-vars-in-ansible