Linux 基于匹配属性生成列表(ansible)

Linux 基于匹配属性生成列表(ansible),linux,ansible,Linux,Ansible,尝试构建与属性(在本例中为ec2_标记)匹配的服务器列表,以便为特定任务调度特定服务器 我正在尝试与selectattr匹配: servers: "{{ hostvars[inventory_hostname]|selectattr('ec2_tag_Role', 'match', 'cassandra_db_seed_node') | map(attribute='inventory_hostname') |list}}" 虽然我从Ansible得到了一个类型错误: fatal: [X.X.

尝试构建与属性(在本例中为ec2_标记)匹配的服务器列表,以便为特定任务调度特定服务器

我正在尝试与
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"}

这里我缺少什么?

当您构建复杂的过滤器链时,请使用
debug
模块打印中间结果。。。并逐一添加过滤器,达到预期效果

在您的示例中,您在第一步就犯了错误:
hostvars[inventory\u hostname]
仅是当前主机的事实记录,因此没有可供选择的元素

您需要一个
hostvars
'值的列表,因为
selectattr
应用于列表,而不是dict

但是在Ansible
hostvars
中,hostvars是一个特殊的变量,实际上不是一个dict,因此您不能在它上面调用
.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 }}"
您可以使用该模块创建临时组,具体取决于主机变量:

- group_by:
    key: 'ec2_tag_role_{{ ec2_tag_Role }}'
这将创建一个名为
ec2\u tag\u role.*
的组,这意味着以后您可以创建一个与这些组中的任何一个一起玩的游戏:

- hosts: ec2_tag_role_cassandra_db_seed_node
  tasks:
    - name: Your tasks...

另外,为了澄清我以前使用过上面的语法,它很有效,这似乎与hostvars[inventory_hostname]生成的对象类型特别相关,谢谢!这对我来说很有效:
-groupby:key:“ec2_-tag_-role_u{{ec2_-tag_-role}”-debug:msg=“{{groups.ec2_-tag_-role_-cassandra_-db_-seed_-node}”
对此进行了投票,因为它确实解释了
hostvars
是一个特殊变量,可以帮助人们理解为什么
selectattr
不起作用,但上面的代码给出了原始错误。虽然它似乎用数组来包装所有内容。