我有一个 yaml Ansible 库存,其结构如下
rpi_wifi:
children:
_wifi:
hosts:
10.74.47.49 :
10.74.47.218:
10.74.47.70 :
我的目标是拥有一个剧本,它将从每个主机收集 ansible_hostname var 并将其添加到清单文件中每个主机的新行中 所以我创造了这样的东西
- name: Add ansible_hostname to hosts
hosts: rpi_wifi
gather_facts: true
tasks:
- name: Update inventory file with ansible_hostname_var
lineinfile:
path: hosts0.yml
regexp: "{{ inventory_hostname }}"
line: "{{ ansible_hostname }} \n {{ ansible_hostname }}"
delegate_to: localhost
所以最终结果应该如下所示
rpi_wifi:
children:
_wifi:
hosts:
10.74.47.49 :
ansible_hostname: foo
10.74.47.218:
ansible_hostname: bar
10.74.47.70 :
ansible_hostname: foo-bar
目前,我的主要问题是,由于某种原因,Ansible 没有为每个主机添加主机名。它可以跳过其中一个或多个,并且每次运行时都会随机发生。我不明白为什么,尽管如此,当我使用 -vvv 选项运行它时,它显示它已正确收集主机名
第二个问题是YAML格式的表格。我的库存采用 yaml 格式,因此我需要为我的主机组提供不同数量的空间,是否有其他方法来处理它?
它适用于此代码
- name: Update inventory file with ansible_hostname_var
throttle: 1
lineinfile:
backrefs: true
path: hosts0.yml
regexp: '^(\s*)({{ inventory_hostname }}:)'
line: '\1\2\n\1 hostname: "{{ ansible_hostname }}"'
delegate_to: localhost