我正在尝试编写一本开始扮演角色剧本并将其主机列表传递给它的剧本。 “主”剧本中有一些负载平衡逻辑,我不想在每个角色剧本中都重复,也无法放入site.yml中。
inventory.yml
[webservers]
Web1
Web2
Web3
Web4
master.yml
---
- name: Split Inventory into Odd/Even
hosts: all
gather_facts: false
tasks:
- name: Set Group Odd
set_fact:
group_type: "odd"
when: (inventory_hostname.split(".")[0])[-1] | int is odd
- name: Set Group Even
set_fact:
group_type: "even"
when: (inventory_hostname.split(".")[0])[-1] | int is even
- name: Make new groups "odd" or "even"
group_by:
key: "{{ group_type }}"
- name: Perform Roles on Odd
include: webservers.yml hosts={{ groups['odd'] | join(' ')}}
- name: Perform Roles on Even
include: webservers.yml hosts={{ groups['even'] | join(' ')}}
webservers.yml
- name: Perform Tasks on Webservers
hosts: webservers:&"{{ hosts | replace('\"','')}}"
roles:
- pause
join('')将主机列表展平为一个字符串,每个字符串之间用空格隔开。当我运行剧本时,它将主机列表传递给webservers.yml,但是它在开头和结尾添加了双引号,导致webservers.yml不执行任何操作,因为没有主机匹配。我假设replace('\“','')会删除字符串周围的引号,但事实并非如此。这是来自webservers.yml的示例输出:
[WARNING]: Could not match supplied host pattern, ignoring: Web4"
[WARNING]: Could not match supplied host pattern, ignoring: "Web2
有什么想法吗? hosts:
处理过滤是否不同?
答案 0 :(得分:0)
我觉得您用错误的方式使用了角色和戏剧。执行任务时,请勿更改主机列表,否则将执行此任务或角色。基本上,只有玩(带有“主持人:...,任务:...,角色:...”的东西)才能控制跑步的位置。
几乎没有例外,例如您可以与代表团一起玩,等等。但是对于您而言,任何尝试使用任务或角色来控制主机列表的尝试只会带来痛苦和仇恨(朝自己,对Ansible等)。
要正确执行此操作,只需在剧本中添加另一个剧本即可(剧本是剧本列表)。
这是您的代码,稍作修改。
---
- name: Split Inventory into Odd/Even
hosts: all
gather_facts: false
tasks:
- name: Set Group Odd
set_fact:
group_type: "odd"
when: (inventory_hostname.split(".")[0])[-1] | int is odd
- name: Set Group Even
set_fact:
group_type: "even"
when: (inventory_hostname.split(".")[0])[-1] | int is even
- name: Make new groups "odd" or "even"
group_by:
key: "{{ group_type }}"
- name: Doing odd things
hosts: odd
gather_facts: false
tasks:
- name: Perform Roles
include: webservers.yml
- name: Doing even things
hosts: even
gather_facts: false
tasks:
- name: Perform Roles
include: webservers.yml
您可以看到,我刚刚将一个剧本分配了两个组(“奇数”和“偶数”)。动态组被保留在剧本中的剧本之间,在这一点上它们与其他任何组都没有什么不同。
P.S。不要使用“ include”,而要使用“ import_tasks”(在较新版本的ansible中,includes很危险,请尽量避免使用它们。)