问题描述
如何获取角色当前主机的 IP 地址?
How do you get the current host's IP address in a role?
我知道您可以获得主机所属的组列表和主机的主机名,但我找不到获取 IP 地址的解决方案.
I know you can get the list of groups the host is a member of and the hostname of the host but I am unable to find a solution to getting the IP address.
您可以使用 {{inventory_hostname}}
获取主机名,使用 {{group_names}}
You can get the hostname by using {{inventory_hostname}}
and the group by using {{group_names}}
我尝试过类似 {{ hostvars[{{ inventory_hostname }}]['ansible_ssh_host'] }}
和 ip="{{ hostvars.{{inventory_hostname }}.ansible_ssh_host }}"
推荐答案
所有地址的列表存储在ansible_all_ipv4_addresses
中,默认地址在ansible_default_ipv4.address
.
A list of all addresses is stored in a fact ansible_all_ipv4_addresses
, a default address in ansible_default_ipv4.address
.
---
- hosts: localhost
connection: local
tasks:
- debug: var=ansible_all_ipv4_addresses
- debug: var=ansible_default_ipv4.address
然后分配给每个网络接口的地址...在这种情况下,您可以显示所有事实并找到具有您想要使用的值的那个.
Then there are addresses assigned to each network interface... In such cases you can display all the facts and find the one that has the value you want to use.
这篇关于Ansible:获取当前目标主机的 IP 地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!