Ansible

Ansible:將清單中的 IP 添加到所有節點的 /etc/hosts

  • January 26, 2022

我正在部署一個小型 3 節點集群,我想將清單中定義的公共 IP 地址添加到所有節點的 /etc/hosts 文件中。

我正在嘗試使用以下內容,但它給了我一個錯誤:

- 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']

錯誤是:

致命的:

$$ app1.domain.com $$: 失敗的!=> {“failed”: true, “msg”: “欄位 ‘args’ 的值無效,似乎包含一個未定義的變數。錯誤是:‘ansible.vars.hostvars.HostVars object’ 沒有屬性 u” 組$$ ‘all’ $$"\n\n錯誤似乎出現在 ‘/Users/k/Projects/Ansible/roles/common/tasks/main.yml’: 第 29 行第 3 列中,但可能\n在文件中的其他位置,具體取決於確切的語法問題。\n\n違規行似乎是:\n\n\n- name: Add all hosts of all hosts to all hosts\n ^ here\n"}

關於我所缺少的任何想法?

上一個答案根本不起作用,因為它為同一主機添加了一個新行,而不是在主機的 IP 地址更改時修改現有行。

以下解決方案考慮到特定伺服器的 ip 地址發生更改時,並通過僅修改行而不是添加重複條目來很好地處理它。

---
- 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 }}"

引用自:https://serverfault.com/questions/832799