【发布时间】:2019-05-20 12:03:50
【问题描述】:
我在我的 Ansible 剧本中有一个任务,我想遍历我拥有的组中的每个主机,并且我想从我在 vars 文件夹中创建的主机名列表中为每个主机分配一个名称.
我已经通过编写 loop:"{{ groups['mygroup'] }}" 来熟悉循环库存,并且我有一个主机名列表,我想在主机文件中的 'mygroup' 中分配每个 IP .
# In tasks file - roles/company/tasks/main.yml
- name: change hostname
win_hostname:
name: "{{ item }}"
loop: "{{ hostname }}"
register: res
# In the Inventory file
[company]
10.0.10.128
10.0.10.166
10.0.10.200
# In vars - roles/company/vars/main.yml
hostname:
- GL-WKS-18
- GL-WKS-19
- GL-WKS-20
# site.yml file located under /etc/ansible
- hosts: company
roles:
- common
- company #This is where the loop exists mentioned above.
# Command to run playbook
ansible-playbook -i hosts company.yml
我似乎已经记录了各个部分或知道它,但是我如何结合对清单组中的主机的迭代并分配我已经在已经创建的列表(在角色 vars 文件夹中)中的名称?
更新 上述任务已更新以反映答案中提到的更改:
- name: change hostname
win_hostname:
name: "{{ item.1 }}"
loop: {{ groups.company|zip(hostname)|list }}"
register: res
但是我得到的输出不正确,这不应该运行 9 次,而应该只运行 3 次,清单中 [company] 组中的每个 IP 一次。此外,列表中只有三个主机名需要分配给清单表中的每个主机。
changed: [10.0.10.128] => (item=[u'10.0.10.128', u'GL-WKS-18'])
changed: [10.0.10.166] => (item=[u'10.0.10.128', u'GL-WKS-18'])
changed: [10.0.10.200] => (item=[u'10.0.10.128', u'GL-WKS-18'])
changed: [10.0.10.128] => (item=[u'10.0.10.166', u'GL-WKS-19'])
changed: [10.0.10.166] => (item=[u'10.0.10.166', u'GL-WKS-19'])
changed: [10.0.10.200] => (item=[u'10.0.10.166', u'GL-WKS-19'])
ok: [10.0.10.128] => (item=[u'10.0.10.200', u'GL-WKS-20'])
ok: [10.0.10.166] => (item=[u'10.0.10.200', u'GL-WKS-20'])
ok: [10.0.10.200] => (item=[u'10.0.10.200', u'GL-WKS-20'])
【问题讨论】:
标签: ansible yaml ansible-inventory