本文介绍了迭代存储在 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

我有一个 ansible playbook,它基本上在 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 中的主机名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 18:36