如何将变量从 Ansible 清单传递给角色?

How to pass variables from Ansible inventory to role?

我有 nginx 负载均衡器角色,它具有如下上游变量:

nginx_lb_upstreams: 
 - name: backend
   balancing_method: least_conn      
   servers:
    - address: 192.168.10.10
      weight: 3
    - address: 192.168.10.11
      weight: 2      

库存中存在组"AppServers",具有相关的负载平衡权重:

[AppServers]
192.168.77.10 weight=3
192.168.77.11 weight=2
192.168.77.12 weight=1

如何正确地将具有相关权重的 AppServers 地址传递给 nginx_lb_upstreams?类似下面但使用循环或 with_items 语句:

nginx_lb_upstreams: 
 - name: backend
   balancing_method: least_conn      
   servers:
    - address: groups['AppServers']
      weight: groups['AppServers']['weight']

UPD:作为解决方法,我正在使用初始化 servers,如下所示:

nginx_lb_upstreams: 
 - name: backend
   balancing_method: least_conn      
   servers: "{{ groups['AppServers'] }}"

并在模板中使用 hostvars:

{% for server in upstream.servers %}
server {{ server }} {%- if hostvars[server].weight is defined %} weight={{ hostvars[server].weight }} {%- endif %};
{% endfor %}

您不能按照您想要的方式生成变量。好吧,您也许可以使用 set_fact 但这会很难看。在您的角色中,您可以执行以下操作:

- name: show configured lbs
  debug: msg="host {{item}} weight hostvars[item].weight"
  with_items: groups['AppServers']

有关详细信息,请参阅 http://docs.ansible.com/ansible/playbooks_variables.html#magic-variables-and-how-to-access-information-about-other-hosts