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

Accessing hostvars for a host group in Ansible

· 52CE 我爱测

I am trying to use Ansible to add entries in the server hosts file. I have a group of servers that I need to talk to each other over a private LAN. My inventory file: [server_list] server1 server2 The task I am trying to get work…

问题原文

原帖链接 · melsayed · CC BY-SA 3.0

I am trying to use Ansible to add entries in the server hosts file. I have a group of servers that I need to talk to each other over a private LAN.

My inventory file:

[server_list]
server1
server2

The task I am trying to get working:

- lineinfile: dest=/etc/hosts line="{{ hostvars[" {{ item }} "]['ansible_eth1']['ipv4']['address'] }}   {{ hostvars[" {{ item }} "]['ansible_hostname'] }}"
  with_items: groups['server_list']

It's not doing the trick, I get this:

fatal: [server1] => host not found:  {{item}} 
fatal: [server2] => host not found:  {{item}} 

This is basically the same as this, but in the new Ansible variable access format {{ }}.

Any ideas how to get this done?

社区高分解答

原帖链接 · melsayed · CC BY-SA 3.0

OK. I had tried this before and it didn't really work. So I must have done something wrong back there.

This works:

- lineinfile: dest=/etc/hosts line="{{ hostvars[item]['ansible_eth1']['ipv4']['address'] }}   {{ hostvars[item]['ansible_hostname'] }}"
  with_items: groups['server_list']

or for 1.9 or later:

- lineinfile: dest=/etc/hosts line="{{ hostvars[item]['ansible_eth1']['ipv4']['address'] }}   {{ hostvars[item]['ansible_hostname'] }}"
  with_items: "{{ groups['server_list'] }}"

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

资料来源与适用范围

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

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

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