【问题标题】:Ansible hosts' inventory yml doesn't support repeated ip with_itemsAnsible 主机的库存 yml 不支持重复 ip with_items
【发布时间】:2017-12-21 06:35:29
【问题描述】:

以下内容:

  store_controller:
    hosts:
      SERVER:
        ansible_host: "{{ STORE_CTL }}"
        mgmt_ip: "{{ ansible_host }}"
  global_mgmt:
    hosts:
      SERVER:
        ansible_host: "{{ NOMAD_SERVER }}"
        mgmt_ip: "{{ ansible_host }}"
  node_exporter: ##if comment the part from here to end, it's ok####
    hosts:
      "{{ item }}":
        ansible_host: "{{ item }}"
        mgmt_ip: "{{ ansible_host }}"
    with_items:
      - "172.7.7.1"
      - "172.7.7.9"
      - "172.7.7.12"

但是 Ansible 不允许我在这里使用 'with_items'。似乎 ansible 不支持主机上的迭代器。

如何在 node_exporter 组中为我的三个 IP 定义 hosts 数组?

【问题讨论】:

  • 我只想在我的 .yml 文件中定义一些类似的主机。他们每个人都有一个 var 'mgmt_ip' 等于 'ansible_host'。
  • 我已经在这个部分之前在同一个 .yml 文件中使用了“ansible_host”,就像这里一样(如果没有这个部分也没关系)。
  • 我发现如果从node_exporter中去掉ansible_host: "{{ item }}" 就可以了....
  • 虽然我还不知道具体原因,但感谢您的帮助。

标签: ansible yaml


【解决方案1】:

所有你需要定义的是:

node_exporter:
  hosts:
    172.7.7.1:
    172.7.7.9:
    172.7.7.12:
  vars: 
    mgmt_ip: "{{ inventory_hostname }}"

解释

mgmt_ip 只定义了一个模板(字符串值),它会在使用时被解析。

对于每个目标机器inventory_hostname(因此mgmt_ip)将解析为当前执行主机的IP地址。

使用ansible_host 分配与清单主机名相同的值是一个空操作,因此您根本不需要。

我认为它不会给代码带来任何价值/清晰性,但既然你评论它对你有用,那就是用多个主机实现它的方法。您所要做的就是创建一个别名 mgmt_ipinventory_hostname


关于问题的前提

with_items: 用于 YAML 是字典键名(字符串值)。 Ansible 可能会也可能不会使用它。

它在任务中指定时使用它(在那里它具有语义含义)。

否则它要么忽略它(从不使用这个键),要么报告错误。

【讨论】:

    【解决方案2】:

    快速查看您的代码,您遇到了缩进问题。 尝试在 "{{item}}:" 之前添加 2 个空格

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-12
      • 2020-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      相关资源
      最近更新 更多