首页 > 解决方案 > 使用 ansible_hostnames 的 Ansible 循环

问题描述

我正在尝试更新 NiFi 部署的配置文件,初始部署配置需要包含节点以允许在它们之间建立 HTTPS 连接。

我有一个对配置文件进行所需结构更改的 ansible 任务,但我似乎无法插入正确的细节。

- name: Add each host to the authorizers.xml
  lineinfile:
    path: /opt/nifi/conf/authorizers.xml
    line: "<property name=\"Node Identity {{ item }}\">CN={{ item }}, OU=NiFi</property>"
    insertafter: <!--accessPolicyProvider Node Identities-->
  loop: "{{ query('inventory_hostnames', 'nifi') }}"

这会放置主机的 IP 地址,而我需要获取每个节点的 ansible_hostname。我玩过 ansible_play_batch 和 loop: "{{ groups['nifi'] }}" 但我得到了结果,每次都输出 IP 地址而不是短主机名。

短主机名不会存储在我的任何地方的 ansible 配置中,它们(如果我理解正确的话)是在运行时通过收集事实过程确定的。我真的不想将节点名称放入列表变量中。

标签: loopsansibleapache-nifi

解决方案


问:“获取每个节点的 ansible_hostname”

A:鉴于库存

shell> cat hosts
[nifi]
10.1.0.51
10.1.0.52

下面的剧本

- hosts: nifi
  tasks:
    - debug:
        var: ansible_hostname

给出(删节)

ok: [10.1.0.51] => 
  ansible_hostname: test_01
ok: [10.1.0.52] => 
  ansible_hostname: test_02

可以迭代组中的主机并从主机变量中获取ansible_hostname。例如,delegate_to localhost 和run_once

    - debug:
        msg: "{{ hostvars[item].ansible_hostname }}"
      loop: "{{ groups.nifi }}"
      delegate_to: localhost
      run_once: true

ok: [10.1.0.51 -> localhost] => (item=10.1.0.51) => 
  msg: test_01
ok: [10.1.0.51 -> localhost] => (item=10.1.0.52) => 
  msg: test_02

推荐阅读