How to create/join vars in Ansible

懵懂的女人 提交于 2021-01-29 08:48:55

问题


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

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