大网数据广告活动
服务器运维问答

Ansible : host variable reference confusion

· 52CE 我爱测

I'm new to Ansible, and found it a great tool, but I've stumbled upon a problem that I find very confusing. In my inventory, there's just: host1 host2 host3 host1 and host2 both have two network interfaces, one of them connected …

问题原文

原帖链接 · zbro · CC BY-SA 4.0

I'm new to Ansible, and found it a great tool, but I've stumbled upon a problem that I find very confusing.

In my inventory, there's just:

host1 host2 host3

host1 and host2 both have two network interfaces, one of them connected to host3 that is acting as a router. In my playbook, I wanted a task on host3 that would configure routing and test it via ping. In order to do so, I wanted to:

a) get IP addresses of network interfaces connected to host3 for both host1 and host2. Name of the interface connected to host3 is set via host variable 'routed_if' and it's IP via 'routed_ip4'.

b) Use these variables to set up routing and send few pings from host1 to host2 to verify it works.

I decided to debug these variables doing so:

(...)
- debug:
   var: "{{ hostvars['host1']['routed_ip4'] }}"

What I'm getting is:

ok: [host3] => {
"192.168.1.1/24": "VARIABLE IS NOT DEFINED!"
}

Which is very odd. The IP "192.168.1.1" is the correct value (for host1) set via host variable but it is being presented as though it's a key in dictionary. What I was expecting to get is just '192.168.1.1/24' (literally).

I read chapter of ansible manual for variables, but it didn't really help me that much.

已采纳解答

原帖链接 · Vladimir Botka · CC BY-SA 4.0

In debug, either you use parameter msg

    msg: "{{ hostvars['host1']['routed_ip4'] }}"

, or parameter var

    var: hostvars['host1']['routed_ip4']

also, the dot notation should work

    var: hostvars.host1.routed_ip4

The syntax of the examples is self-explaining.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2023-01-23)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。