Ansible concat 变量到字符串

Ansible concat vars to string

我花了一天的大部分时间试图解决这个问题,但到目前为止都失败了。我正在构建一些剧本来自动化 Splunk 中的功能,并试图从库存组 E.G. 转换主机列表。

[search_head]
1.2.3.4
5.6.7.8

我对播放的调试输出的预期(期望)结果应该是: https://1.2.3.4:8089, https://5.6.7.8:8089

我正在尝试通过 运行 以下针对 运行 主机的剧本来完成此操作:

---
  - 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 }}"`

使用模板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 %}

然而,当前播放 returns search_head_uri: ", " 告诉我循环是 运行,但 {{ host }} 没有解析。

打开 Jinja2 表达式或语句后,您应该使用 Jinja2 语法。你不能嵌套它们(即你不能在 {% %} 中使用 {{ }})。

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

这有效 - 结合上面的答案修复神社格式并使用 hostvars 到达 ansible_nodename.

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