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

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

问题描述

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

I need to create a string for a configuration file.

它需要采用这种格式:

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

我最初尝试通过从 hosts 中的特定组读取主机来实现此目的,但决定使用 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 文件中

in my vars file I have

---
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 filter 然后告诉它使用没有空格的分隔符,因为您的示例看起来非常像 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 中创建/加入变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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