如何在Ansible中创建/加入vars >>

问题描述 投票:0回答:1

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

必须采用这种格式:

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

我本来是通过读取主机中特定组的主机来尝试执行此操作的,但是我决定使用vars文件会更好。

在我的vars文件中]

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

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

- name: Update cluster nodes
  lineinfile:
    path: /etc/nodes.txt
    regexp: '^#nodes:'
    line: "nodes: ["node1","node2","node3"]"

任何人都可以帮助我,因为我真的很努力在遍历节点列表后创建字符串。

我需要为配置文件创建一个字符串。它必须采用这种格式:nodes = [“ node1”,“ node2”,“ node3”]我最初试图通过从...

ansible
1个回答
0
投票

您想通过使用"whitespace control" feature{%-引导和尾随模板来利用jinja2的-%},以确保存在的任何空白都不会被剧本阅读器带到该行。然后,您可能会发现将行组成移到局部vars:只是为了便于阅读:

- 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:

© www.soinside.com 2019 - 2024. All rights reserved.