我如何使用 Ansible 将 IP 添加到从 10.x.x.66..10.x.x.83 迭代的 18 个虚拟机上的 Linux 主机文件

How do I use Ansible to add an IP to a Linux hosts file on 18 VMs that iterates from 10.x.x.66..10.x.x.83

所以,我有一个使用主机文件模板更新或恢复 18 个特定 Linux VM 上的主机文件的剧本。文件末尾的条目如下所示:

10.x.x.66 fooconnect

上面的示例将在 18 个 VM 中的第 1 个上,第 18 个 VM 如下所示:

10.x.x.83 fooconnect

通常,该主机名解析为 VIP。然而,我们在一些负载测试中发现,将每个前端 VM 直接指向后端 VM 可能是有益的。所以,我的目标是拥有一个可以更新主机名解析为上述范围的剧本,或者将其恢复为 VIP(恢复仅使用模板完成——这部分工作正常)。

我不确定的是如何在 Ansible 中实现它。有没有一种方法可以使用 jinja2 模板“for loops”来遍历 IP?或者也许使用 lineinfile 和一些循环魔法?

这是我的 Ansible 角色示例。目前我正在使用肮脏的 shell 命令来创建我的 IP 列表...欢迎提出更好的实现方法的建议。

- name: Add a line to a hosts file using a template
  template:
    src: "{{ srcfile }}"
    dest: "{{ destfile }}"
    owner: "{{ own_var }}"
    group: "{{ grp_var }}"
    mode: "{{ mode_var }}"
    backup: yes

- name: Get the IPs
  shell: "COUNTER=66;for i in {66..83};do echo 10.x.x.$i;((COUNTER++));done"
  register: pobs_ip

- name: Add a line
  lineinfile:
    path: /etc/hosts
    line: "{{item}}    fooconnect"  #Ideally would want "item" to just be one IP and not 
    insertafter: EOF                #the entire list as it would be like this.
  loop: "{{pobsips}}"

VAR 文件:

pobsips:
  - "{{pobs_ip.stdout}}"

我们可以即兴创作并使用 set_factrange 创建 IP 地址范围,而不是使用 shell 任务。一旦我们在“列表”中有了 IP 地址范围,我们就可以用它循环 lineinfile 并实现这一点。

示例:

    - name: create a range of IP addresses in a variable my_range
      set_fact:
        my_range: "{{ my_range|default([]) + [ '10.1.1.' ~ item ] }}"
      loop: "{{ range(66, 84)|list }}"
    - name: Add a line to /etc/hosts
      lineinfile:
        path: /etc/hosts
        line: "{{ item }} fooconnect"
        insertafter: EOF
      loop: "{{ my_range }}"

更新的答案:

如果我们想将 仅 1 行附加到具有递增 IP 地址的每个主机的 /etc/hosts 文件中,还有另一种方法。

  • 为此,我们可以使用 ipaddr filteripmath 来获取给定 IP 地址的下一个 IP 地址。
  • 使用 ansible_play_hosts 获取正在播放 运行ning
  • 的主机列表
  • 设置索引变量index_varwhen条件,仅当ansible_hostnameinventory_hostname匹配时更新文件。
  • 运行 playbook 连续运行,并且每个 运行 使用 serialrun_once 标志仅在主机上运行一次。

让我们考虑一个示例清单文件,例如:

[group_1]
host1
host2
host3
host4
...

然后在剧本中:

- hosts: group_1
  serial: 1

  vars:
    start_ip: 10.1.1.66

  tasks:
    - name: Add a line to /etc/hosts
      lineinfile:
        path: "/tmp/hosts"
        line: "{{ start_ip|ipmath(my_idx) }} fooserver"
        insertafter: EOF
      loop: "{{ ansible_play_hosts }}"
      loop_control:
        index_var: my_idx
      run_once: true
      when: item == inventory_hostname