如何在Ansible中创建/加入vars [英] How to create/join vars in Ansible

查看:61
本文介绍了如何在Ansible中创建/加入vars的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为配置文件创建一个字符串.

I need to create a string for a configuration file.

必须采用以下格式:

nodes = ["node1","node2","node3"]

最初,我试图通过读取主机中特定组中的主机来做到这一点,但是我决定使用vars文件会更好.

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.

我的vars文件中有

---
nodes:
  - node: node1
  - node: node2
  - node: node3

然后我想使用lineinfile函数更新配置:

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.

推荐答案

您想利用为使剧本阅读器清晰易读而存在的任何空白都不会传递到该行中.然后,您可能会发现将行组成移至本地 vars:只是为了便于阅读:

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 -%}

根据您的特定需求,您可能还只想使用 to_json 过滤器,然后告诉它使用不带空格的分隔符,因为您的示例非常类似于JSON:

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=(",", ":")) }}'

这篇关于如何在Ansible中创建/加入vars的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆