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

Ansible: Add IPs from inventory to /etc/hosts of all nodes

· 52CE 我爱测

I am deploying a small 3 node cluster and I want to add the public IP addresses as defined in my inventory to the /etc/hosts files of all of the nodes. I am trying to use the following, but it is giving me an error: - name: Add I…

问题原文

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

I am deploying a small 3 node cluster and I want to add the public IP addresses as defined in my inventory to the /etc/hosts files of all of the nodes.

I am trying to use the following, but it is giving me an error:

- name: Add IP address of all hosts to all hosts
  lineinfile: 
    dest: /etc/hosts
    line: '{{ hostvars[item]["ansible_host"] }} {{ hostvars[item]["ansible_hostname"] }} {{ hostvars[item]["ansible_nodename"] }}'
    state: present
  with_items: groups['all']

The error is:

fatal: [app1.domain.com]: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'ansible.vars.hostvars.HostVars object' has no attribute u"groups['all']"\n\nThe error appears to have been in '/Users/k/Projects/Ansible/roles/common/tasks/main.yml': line 29, 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- name: Add IP address of all hosts to all hosts\n ^ here\n"}

Any ideas on what I'm missing?

已采纳解答

原帖链接 · Basil A · CC BY-SA 4.0

The previous answer simply does not work because it adds a new line for the same host instead of modifying the existing line when an IP Address for a host changes.

The following solution takes into account when the ip address changes for a specific server and handles it well by only modifying the line instead of adding duplicate entries.

---
- name: Add IP address of all hosts to all hosts
  lineinfile:
    dest: /etc/hosts
    regexp: '.*{{ item }}$'
    line: "{{ hostvars[item].ansible_host }} {{item}}"
    state: present
  when: hostvars[item].ansible_host is defined
  with_items: "{{ groups.all }}"

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

资料来源与适用范围

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

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

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