尝试构建与属性匹配的服务器列表(在本例中为ec2_tag),以便为特定任务安排特定服务器。
我尝试与selectattr
匹配:
servers: "{{ hostvars[inventory_hostname]|selectattr('ec2_tag_Role', 'match', 'cassandra_db_seed_node') | map(attribute='inventory_hostname') |list}}"
虽然我从Ansible获得了类似错误:
fatal: [X.X.X.X]: FAILED! => {"failed": true, "msg": "Unexpected templating type error occurred on ({{ hostvars[inventory_hostname]|selectattr('ec2_tag_Role', 'match', 'cassandra_db_seed_node') | map(attribute='inventory_hostname') |list}}): expected string or buffer"}
我在这里缺少什么?
答案 0 :(得分:5)
构建复杂的过滤器链时,使用debug
模块打印中间结果...并逐个添加过滤器以获得所需的结果。
在您的示例中,您在第一步时出错:hostvars[inventory_hostname]
仅是您当前主机的事实字典,因此无需从中选择元素。
您需要一个hostvars
'值列表,因为selectattr
适用于列表,而不是dict。
但是在Ansible hostvars
中是一个特殊的变量,实际上并不是一个字典,所以你不能只是在它上面调用.values()
而不会跳过一些箍。
请尝试以下代码:
- hosts: all
tasks:
- name: a kind of typecast for hostvars
set_fact:
hostvars_dict: "{{ hostvars }}"
- debug:
msg: "{{ hostvars_dict.values() | selectattr('ec2_tag_Role','match','cassandra_db_seed_node') | map(attribute='inventory_hostname') | list }}"
答案 1 :(得分:2)
您可以使用group_by
模块创建ad-hoc组,具体取决于hostvar:
can't set attributes of built-in/extension type 'int'
这将创建一个名为- group_by:
key: 'ec2_tag_role_{{ ec2_tag_Role }}'
的组,这意味着稍后您可以创建任何这些组的游戏:
ec2_tag_role_*