Ansible 如何在变量中保存hostvars中的主机列表(localhost除外) 我想要什么

Ansible 如何在变量中保存hostvars中的主机列表(localhost除外) 我想要什么,ansible,Ansible,例如,我在相同的服务器上安装了redis复制设置和应用程序。我想告诉我的应用程序,有些主机有redis实例 应用程序从.env文件读取主机它也是一个模板: REDIS_URLS=rediscache://{{ redis_hosts|join(",") }} 我可以这样描述剧本中的主持人: ... vars: redis_hosts: - 'redis1.exmaple.com:6379' - 'redis2.exmaple.com:6379' ..

例如,我在相同的服务器上安装了redis复制设置和应用程序。我想告诉我的应用程序,有些主机有redis实例

应用程序从.env文件读取主机它也是一个模板:

REDIS_URLS=rediscache://{{ redis_hosts|join(",") }}
我可以这样描述剧本中的主持人:

  ...
  vars:
    redis_hosts:
      - 'redis1.exmaple.com:6379'
      - 'redis2.exmaple.com:6379'
  ...
  ...
  vars:
    redis_hosts:
      - 'localhost:6379' # it's always here
      - '{{ item.key }}:6379'
      with_dict: hostvars
      when: item.key != inventory_hostname
  ...
但是

有什么问题 我不想手动指定这个主机,因为Ansible已经知道它们都是hostvars密钥。 当redis实例与应用程序位于同一服务器中时,我希望请求localhost而不是公共主机名。 所以我想到了这样的事情:

  ...
  vars:
    redis_hosts:
      - 'redis1.exmaple.com:6379'
      - 'redis2.exmaple.com:6379'
  ...
  ...
  vars:
    redis_hosts:
      - 'localhost:6379' # it's always here
      - '{{ item.key }}:6379'
      with_dict: hostvars
      when: item.key != inventory_hostname
  ...
但它显然不起作用

或者我可以将逻辑移到.env文件:


但我也有一个角色,它需要相同的主机列表。

例如,您可以从列表中删除当前节点作为清单\u主机名,并将其替换为本地主机:

但似乎您有一点复制粘贴:如果您的资源清册中有redis主机,为什么会有单独的变量redis_主机

您可以从库存组构建此列表,假设它是redis:


把逻辑移到使用这个变量的地方。是的,我也试过了。实际上,这对于.env文件来说是很好的。但我也有一个角色,它使用相同的主机列表。我的资源清册中没有redis_主机,我使用hostvars字典的键来完成此操作。哦,对不起!现在我明白了。第二种解决方案在我的情况下非常有效。
# msg is constructed from inventory group 'redis'
- debug:
    msg: "{{ redis_list | join(',') }}"
  vars:
    redis_nodes: "{{ ['localhost'] + groups['redis'] | difference([inventory_hostname]) }}"
    redis_port: 6379
    redis_list: "{{ redis_nodes | map('regex_replace','$',':'+redis_port|string) | list }}"