本文介绍了遍历存储在var_files中的主机名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two type of server host names added in the ansible main.yml var file:

main.yml文件:

main.yml file:

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上运行,并且一次初始化/格式化列表中的所有其他服务器-从foo_server2开始,然后是bar_server1,bar_server2等...

I am having an ansible playbook which essentially runs on foo_server1 and initializes/formats all other servers in the list one at a time - starting with foo_server2 then bar_server1, bar_server2 and so on...

---
- 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}}

我不想在剧本中为每台服务器添加多行,而是想遍历变量文件中的主机名.我不确定如何完成此操作..我正在尝试遍历主机名..尝试了以下操作,但由于我获得了未定义的变量名,所以运气不佳.

I dont want to add multiple lines in the playbook for each server rather wants to loop over the host names from the variable file. I am not sure how i would get this done..i am trying to loop over the hostname.. tried something below but no luck as i am getting undefined variable name..

---
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剧本...

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 }}"

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

Can some one please suggest how can i run the same command on multiple servers. Would appreciate any help offered..

推荐答案

以下是您的示例:

---
- 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 }}"

这篇关于遍历存储在var_files中的主机名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 01:45