使用--limit标志运行playbook时,我可以获取库存文件中所有主机的ips吗?

问题描述 投票:0回答:1

我正在尝试将iptable规则应用于一组主机,我希望所有端口都可以为特定组中的主机打开。但我无法在生产环境中为所有主机运行此配方。所以我使用--limit标志来运行剧本。但它失败了,给出了以下错误:

fatal: [test-vm1]: FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'ansible.vars.hostvars.HostVarsVars object' has no attribute 'ansible_default_ipv4'"}

库存文件

[all]

test-vm1  ansible_ssh_host=10.x.x.x
test-vm2  ansible_ssh_host=10.x.x.x
test-vm3  ansible_ssh_host=10.x.x.x

M-playbook.yml

- hosts: all
  become: yes
  gather_facts: yes
  roles:
    - iptables

规则list.j2

#Allow communication within hosts in a group
{% for host in groups['all'] %}
iptables -A INPUT -s {{ hostvars[host]['ansible_default_ipv4']['address'] }} -j ACCEPT
{% endfor %}

角色/ iptables的/任务/ main.yml

- name: Prepare iptables rules
  template: dest='/etc/sysconfig/iptable-config' src=rules-list.j2 owner=root group=root mode=0744
  notify: save iptables rules

我试图运行的命令是 -

ansible-playbook -i inventory-file my-playbook.yml --limit test-vm1

如果我运行上面的命令没有限制标志,它运行良好而不会失败,即

ansible-playbook -i inventory-file my-playbook.yml
ansible iptables ansible-inventory
1个回答
1
投票

我认为你的模板在groups[all]主机上循环,包括所有主机,而不仅仅是有限主机。而且因为你限制某些主机,ansible不会收集其余的事实,你的模板无法找到其他主机的ipv4。

你试过ansible_play_batchansible_play_hosts吗? https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html

© www.soinside.com 2019 - 2024. All rights reserved.