【问题标题】:Get list of ip adresses in playbook获取剧本中的IP地址列表
【发布时间】:2021-04-20 08:05:14
【问题描述】:

我是 Ansible 的新手,无法从文档中弄清楚如何实现这一点: 我有一个这样的库存文件:

example_site:
  children:
    ...
    example_hosts:
      hosts:
        h1:
          ansible_host: "192.168.0.1"
        h2:
          ansible_host: "192.168.0.2"

现在我想在 playbook 中启动一个 Gluster 集群:

  tasks:
    - name: Create a trusted storage pool
      become: yes
      gluster.gluster.gluster_peer:
        state: present
        nodes:
          - "192.168.0.1"
          - "192.168.0.2"

有没有办法不对这个 IP 地址列表进行硬编码?我试过node: groups['example_hosts'],但没用。

如何从库存中获取 IP 地址列表?

【问题讨论】:

  • 谢谢参考,不过我不想把所有的ip地址都写第二遍在变量里,而是直接用库存的hosts部分定义的ip地址

标签: ansible yaml jinja2 glusterfs


【解决方案1】:

可以使用ansible_host 变量访问清单中定义的主机的 IP 地址,即hostvars['h1']['ansible_host'] => "192.168.0.1"。由于您需要该组中主机的 IP 地址作为数组,我们可以遍历 group['example_hosts'] 中的主机,这也是一个列表 ["h1", "h2"]

在下面的示例中,我们使用example_hosts 组中主机的 IP 地址列表创建另一个变量:

    - set_fact:
        cluster_hosts: "{{ cluster_hosts|default([]) + [ hostvars[item]['ansible_host'] ] }}"
      loop: "{{ groups['example_hosts'] }}"
      run_once: true
    - debug:
        var: cluster_hosts

这给出了cluster_hosts 中的 IP 地址列表:

    "cluster_hosts": [
        "192.168.0.1",
        "192.168.0.2"
    ]

这个变量可以传递给gluster_peer模块的nodes参数:

        nodes: "{{ cluster_hosts }}"

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 2012-09-17
    • 2011-10-11
    • 1970-01-01
    • 2012-11-29
    • 2011-04-08
    • 1970-01-01
    • 2018-04-10
    相关资源
    最近更新 更多