我试图获取主机名和IP地址,并将它们保存到一个文件中。
我有这个解决方案起作用;
- name: Create File with hosts and IP address.
when: inventory_hostname in groups['local']
lineinfile:
dest: "{{store_files_path}}/{{ansible_date_time.date}}/{{ansible_date_time.time}}/hosts.txt"
create: yes
line: "{{hostvars[inventory_hostname].ansible_hostname}}:{{hostvars[inventory_hostname].ansible_default_ipv4.address}}"但是问题在我的主机文件中,我有两个组,local和Servers。我只想得到Servers,而不是local组,它仅是localhost。
我试过下面这一行,但它不起作用,它给了我一个错误。
line: "{{ hostvars[ groups['Servers'][0] ].ansible_hostname }} :{{ hostvars[ groups['Servers'][0] ].ansible_default_ipv4.address }}"我到处找过了,这就是我发现的,我该怎么做?
发布于 2020-11-14 15:39:00
你把这件事弄得太复杂了。
hostvars来达到您想要的目的,特殊变量主要是为您提供当前正在运行的主机Ansible的信息。为主人收集的事实也是如此。group_names,它将允许您以列表的形式获得当前正在处理的组。因此,获取作为组一部分的主机就像执行when: "'group_that_interest_you' in group_names"一样简单。因此,考虑到清单:
all:
vars:
ansible_python_interpreter: /usr/bin/python3
children:
local:
hosts:
localhost:
Servers:
hosts:
foo.example.org:
ansible_host: 172.17.0.2还有剧本:
- hosts: all
gather_facts: yes
tasks:
- debug:
msg: "{{ ansible_hostname }}:{{ ansible_default_ipv4.address }}"
when: "'Servers' in group_names"这就产生了重述:
PLAY [all] **********************************************************************************************************
TASK [Gathering Facts] **********************************************************************************************
ok: [localhost]
ok: [foo.example.org]
TASK [debug] ********************************************************************************************************
skipping: [localhost]
ok: [foo.example.org] => {
"msg": "8088bc73d8cf:172.17.0.2"
}
PLAY RECAP **********************************************************************************************************
foo.example.org : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0 现在,如果你在你自己的剧本中修改了这一点,你应该做得很好:
- name: Create File with hosts and IP address.
lineinfile:
dest: "{{ store_files_path }}/{{ ansible_date_time.date }}/{{ ansible_date_time.time }}/hosts.txt"
create: yes
line: "{{ ansible_hostname }}:{{ ansible_default_ipv4.address }}"
when: "'Servers' in group_names"
delegate_to: localhosthttps://stackoverflow.com/questions/64834583
复制相似问题