首页 > 解决方案 > 如何在ansible的一场比赛中处理每个任务的不同主机?

问题描述

我是 Ansible(ansible 2.9.6)的新手,最近开始研究项目的设计/目录结构。我的任务是在测试实验室中配置设备(特别是不同的 Cisco 设备)以支持测试用例。

我想要一个包含所有 20 多个测试用例的 site.yml 文件。这个想法是,用户可以根据参数,通过 site.yml 针对特定供应商设备类型(Cisco 4507、Cisco 3850 等)执行所有、多个或单个测试用例。

最初,我将 site.yml 构建为一个包含 20 个任务的游戏,其中包括每个测试用例(ntp、lldp、vlans 等)的角色并适当地标记。但是,我无法为每个需要的任务(测试用例)使用不同的主机。每个测试用例都需要使用自己的设备子集。这是一个例子:

ansible-playbook -i inventory/network_staging site.yml --tags=ntp -e type=C4507

~/site.yml

---
- name: Test Cases
  hosts: all
  gather_facts: false
  connection: local
  tasks:
    - name: ntp role
       hosts: "{{type}}_ntpTC"
       include_role:
         name: ntp
       tags:
         - ntp
    - name: vlan role
       hosts: "{{type}}_vlanTC"
       include_role:
         name: vlan
       tags:
         - vlan

我当前的 site.yaml 有多个播放,每个播放代表一个测试用例并使用适当的主机。但是,根据角色/测试用例,我将需要使用来自主机组的不同设备来执行任务。这是示例:

ansible-playbook -i 库存/network_staging site.yml --tags=ntp,vlan -e type=C4507

~/site.yml

---
- name: NTP Test Case
  hosts: "{{type}}_ntpTC"
  gather_facts: false
  connection: local

  tasks:
    - name: ntp role
      include_role:
        name: ntp
      tags:
        - ntp

- name: VLAN Test Case
  hosts: "{{type}}_vlanTC"
  gather_facts: false
  connection: local

  tasks:
    - name: vlan role
      include_role:
        name: vlan
      tags:
        - vlan

~/inventories/network_staging/hosts/cisco

###main.yml inventory list
## IPs defined in ~/inventories/network_staging/host_vars/SW6.yml   SW7.yml and SW8.yml

##Cisco 4507 Test Cases
#NTP Test Case
[C4507_ntpTC]
SW8
#VLAN Test Case
[C4507_vlanTC]
SW7
SW6

~/roles/ntp/tasks/main.yml

---
# Tasking for NTP Test Case
- name: import ntp.yml
  tags:
    - ntp

~/roles/ntp/tasks/ntp.yml

---
- name: show NTP
  ios_command:
    commands:
      - <insert ntp show status commands on SW8 here….>

~/roles/vlan/tasks/main.yml

---
# Tasking for VLAN Test Case
- name: import vlan.yml
  tags:
    - vlan

~/roles/vlan/tasks/vlan.yml

---
- name: configure VLAN SW7
  ios_command:
    commands:
      - <insert vlan access switchport configuration here for SW7….>

- name: configure VLAN SW6
  ios_command:
    commands:
      - <insert vlan access switchport configuration here for SW6….>
      - <insert ping SW7 here>

问题 1: 在我的原始设计中,我可以在一场比赛中为每个任务使用不同的主机吗?

问题 2: 我目前的设计是我想要完成的最佳设计吗?

问题 3: 在我当前设计的角色/<>/tasks/<>.yml 文件中,我需要在不同的设备上执行不同的任务来完成测试用例角色。我已经定义了我的主机清单组,其中包括所有需要的设备,但是如何为某些任务指定特定的主机?

标签: ansible

解决方案


您可以尝试包含 when 语句。例如:

tasks:
  - name: ntp role
    include_role:
      name: ntp
    tags:
      - ntp
    when: ansible_hostname in groups['group_name']

推荐阅读