Ansible主机组和IP过滤问题

时间:2019-10-24 11:18:53

标签: ansible vagrant

我在遍历Ansible组中的主机列表时遇到问题,我得到了想要的值,但得到了虚假的错误,我无法弄清。本来以为如果有错误,它应该根本不打印值:

fatal: [worker01]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'ansible.vars.hostvars.HostVarsVars object' has no attribute 'ansible_eth1'\n\nThe error appears to be in 'roles/vagrant/tasks/main.yml': line 15, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- debug:\n  ^ here\n"}

从流浪文件中提取

ansible.groups = {
            "workers" => ["worker01", "worker02", "worker03"],
            "controllers" => ["controller01", "controller02"],
            "kubernetes" => ["kubernetes"],
            "all_groups:children" => ["workers", "controllers", "kubernetes"]
        }

流浪者使用的示例主机定义

{
  "name": "worker03",
  "alias": "worker03",
  "box": "bento/ubuntu-18.04",
  "memory": 2048,
  "vcpu": 2,
  "provider": "virtualbox",
  "autostart": "false",
  "cpus": 2,
  "cpu_percentage": 100,
  "Controller": "SATA Controller",
  "lv_disks": 4,
  "pv_size": 5,
  "infra_ip_addr": "10.2.15.60",
  "service_ip_addr": "10.96.0.60",
  "pod_ip_addr": "192.168.0.60",
  "port_forwards": {},
  "project": "wks",
  "tags": "all",
  "group": "workers",
  "extra_vars": {}
}

以下代码:

- debug:
    msg: "External: {{ hostvars[item]['ansible_eth1']['ipv4']['address'] }} ; Service: {{ hostvars[inventory_hostname]['ansible_eth3']['ipv4']['address'] }} "
  with_items:
    - "{{ groups['workers'] }}"

产生输出-注意错误“ ansible.vars.hostvars.HostVarsVars对象”没有属性“ ansible_eth1”

ok: [worker01] => (item=worker01) => {
    "msg": "External: 10.2.15.40 ; Service: 192.168.0.40 "
}
fatal: [worker01]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'ansible.vars.hostvars.HostVarsVars object' has no attribute 'ansible_eth1'\n\nThe error appears to be in 'roles/vagrant/tasks/main.yml': line 15, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- debug:\n  ^ here\n"}

PLAY RECAP ****************************************************************************************************************************************************************************************************************************
worker01                   : ok=3    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0   

1 个答案:

答案 0 :(得分:0)

在现代Ubuntu映像上,接口名称是愚蠢的(例如enp0s31f6wlp0s20f3);您想要的是使用ansible_default_ipv4而不是命名一个特定的接口(或者,当然,您可以进一步遍历所有发现的接口,但是对于您正在做的事情,这似乎并不是您想要的)

- debug:
    msg: "External: {{ hostvars[item]['ansible_default_ipv4']['address'] }} ; Service: {{ hostvars[inventory_hostname]['ansible_eth3']['ipv4']['address'] }} "
  with_items:
    - "{{ groups['workers'] }}"

虽然可以解决您的特定问题,但对于您将来的调试帮助,更一般的建议是使用debug: var=hostvars,以查看是什么可用,因为错误 'ansible.vars.hostvars.HostVarsVars object' has no attribute 'ansible_eth1'不可能更清楚地指出问题所在。