Ansible concat vars to string

被刻印的时光 ゝ 提交于 2019-12-18 09:22:38

问题


I've spent most of the day trying to solve this problem and have thus far failed. I am building some playbooks to automate functions in Splunk, and am attempting to convert a list of hosts from an inventory group E.G.

[search_head]
1.2.3.4
5.6.7.8

My expected (desired) result from the debug output of the play should be: https://1.2.3.4:8089, https://5.6.7.8:8089

I am attempting to complete this by running the following playbook against a running host:

---
  - name: Build search head list to initialize the captain
    hosts: search_head
    remote_user: ansible
    vars:
      inventory_file: ./inventory-ec2-single-site
      search_head_uri: "{{ lookup('template', './bootstrap-sh-deployer.j2') }}"
pre_tasks:
  - include_vars: 
      dir: 'group_vars'
      extensions:
        - yml
        - yaml
tasks:
  - name: dump array
    debug:
        msg: "{{ search_head_uri }}"`

With the template bootstrap-sh-deployer.j2:

{%- set search_head_uri = [] %}
{% for host in groups['search_head'] %}
    {%- if search_head_uri.append("https://{{ host }}:8089") %} 
{%- endif %}
{%- if not loop.last %}, {% endif -%}
{%- endfor %}

However, the current play returns search_head_uri: ", " which tells me that the loop is running, but {{ host }} is not resolving.


回答1:


Once you open a Jinja2 expression or a statement you should use Jinja2 syntax. You cannot nest them (i.e. you can't use {{ }} inside {% %}).

{%- if search_head_uri.append("https://" + host + ":8089") %}



回答2:


This worked - Combination of the answer above to fix jinja formatting and using hostvars to get to the ansible_nodename.

{%- set search_head_uri = [] %}
{% for host in groups['search_head'] %}
    {{ "https://" + hostvars[host]['ansible_nodename'] + ":8089" }}
    {%- if not loop.last %}, {% endif -%}
{%- endfor %}


来源:https://stackoverflow.com/questions/44838155/ansible-concat-vars-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!