迭代存储在var_files

时间:2017-03-31 15:24:48

标签: ansible

我在ansible main.yml var文件中添加了两种类型的服务器主机名:

main.yml文件:

foo_server1: 10.10.1.1
foo_server2: 10.10.1.2

bar_server1: 192.168.1.3
bar_server2: 192.168.1.4
bar_server3: 192.168.1.5

我有一个基本上在foo_server1上运行的ansible playbook,并且一次初始化/格式化列表中的所有其他服务器 - 从foo_server2开始,然后是bar_server1,bar_server2等等......

---
- name: Reading variables from var files
  hosts: localhost
  connection: local
  vars_files:
    - main.yml
  tasks:
    - name: Initialize foo server2
      command: initialize --host1 {{foo_server1}} to --host2 {{foo_server2}} 
    - name: Initialize bar server1
      command: initialize --host1 {{foo_server1}} to --host2 {{bar_server1}}
    - name: Initialize bar server2
      command:  initialize --host1 {{foo_server1}} to --host2 {{bar_server2}}
    - name: Initialize bar server3
      command:  initialize --host1 {{foo_server1}} to --host2 {{bar_server3}}

我不想在每个服务器的playbook中添加多行,而是想从变量文件中循环主机名。我不知道我怎么会这样做..我正在尝试循环主机名..尝试下面的东西,但没有运气,因为我得到未定义的变量名称..

---
server_list:
    foo_server1: 10.10.1.1
    foo_server2: 10.10.1.2

    bar_server1: 192.168.1.3
    bar_server2: 192.168.1.4
    bar_server3: 192.168.1.5

Ansible playbook ...

---
- hosts: localhost
  gather_facts: no
  vars_files:
  - input.yml
  tasks:
  - name: Enable replication
    local_action: shell initialize --host1 {{item.foo_server1}} --host2 {{item.foo_server2}}
    with_items:
     - "{{ server_list }}"

有人可以建议我如何在多台服务器上运行相同的命令。非常感谢提供任何帮助..

1 个答案:

答案 0 :(得分:0)

以下是您的示例:

---
- hosts: localhost
  gather_facts: no
  vars:
    servers:
      foo_server1: 10.10.1.1
      foo_server2: 10.10.1.2
      bar_server1: 192.168.1.3
      bar_server2: 192.168.1.4
      bar_server3: 192.168.1.5
  tasks:
    - debug:
        msg: shell initialize --host1 {{ servers.foo_server1 }} --host2 {{ item.value }}
      when: item.key != 'foo_server1'
      with_dict: "{{ servers }}"