主机中的Ansible双循环

我想遍历特定组的所有主机的variables。

在hostvars中使用以下数据(简化):

{ "server1": { "group_names": ["web"], "sites": { "website1": { "id": "site1", "domain": "..." } "website2": { "id": "site2", "domain": "..." } }, } "server2": { "group_names": ["web"], "sites": { "website3": { "id": "site3", "domain": "..." } } } } 

我想在第三台服务器(数据库服务器)上创build所有的数据库:

 - name: create databases - mysql_db: name: "{{ item.1.id }}" - with_subelements: - "{{ groups["web"] }}" - "{{ hostvars[item.0]['sites'] 

这是行不通的,我有错误: {"failed": true, "msg": "'item' is undefined"}

我应该怎样写这个angular色?

这里有一些对你的忍者魔法:

库存:

 localhost ansible_ssh_host=127.0.0.1 ansible_connection=local [web] host1 sites="{'web1':{'id':'z1'},'web2':{'id':'z2'}}" host2 sites="{'web3':{'id':'z3'}}" 

演示:

 --- - hosts: localhost gather_facts: no tasks: - debug: msg: "Site name – {{ item.key }}, id - {{ item.value.id }}" with_dict: "{{ dict(groups['web'] | map('extract',hostvars,'sites') | map('dictsort') | sum(start=[]) | list) }}" 

我做dictsort->sum->dict技巧,因为你的sites对象是一个字典(不是列表),并不是很容易迭代嵌套的字典。