首页 > 解决方案 > 使用 ansible 在循环中将主机变量写入文件

问题描述

我正在尝试建立一个配置文件,其中包含我的库存主机服务器列表及其字段,例如。IP、FQDN 等

这是我的库存文件的一部分:

ocp_cluster:
   hosts:
     anbootstrap.ocp.hattusas.tst:
         fqdn: anbootstrap.ocp.hattusas.tst
         ip: 10.72.217.92
     anmaster1.ocp.hattusas.tst:
         fqdn: anmaster1.ocp.hattusas.tst
         ip: 10.72.217.93
     anmaster2.ocp.hattusas.tst:
         fqdn: anmaster2.ocp.hattusas.tst
         ip: 10.72.217.94
     anmaster3.ocp.hattusas.tst:

这是我的剧本:

  - name: Adding OCP Clusters to DHCP configuration
    debug:
      "{{ hostvars[item][fqdn] }}"
    loop: "{{ groups['ocp_cluster'] }}"

(我将很快使用blockinfile)

当我运行我的剧本时,我收到未定义的错误 fqdn。我尝试使用 for 循环,但没有帮助。有什么建议么?非常感谢。

标签: ansibleansible-inventory

解决方案


固定任务如下

- debug:
    msg: "{{ hostvars[item]['fqdn'] }}"
  loop: "{{ groups['ocp_cluster'] }}"
  • msg缺少调试参数
  • fqdn是字典的一个属性。必须用括号括起来。类似于ocp_cluster
  • 可以使用点符号并简化对字典属性的引用
- debug:
    msg: "{{ hostvars[item].fqdn }}"
  loop: "{{ groups.ocp_cluster }}"

推荐阅读