Ansible concat vars 到字符串

标签 ansible jinja2 ansible-facts ansible-template

我花了一天的大部分时间试图解决这个问题,但到目前为止都失败了。我正在构建一些剧本来自动化 Splunk 中的功能,并尝试将 list 组中的主机列表转换为 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 %}

但是,当前播放返回 search_head_uri: ", ",这告诉我循环正在运行,但 {{ host }} 未解析。

最佳答案

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

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

关于Ansible concat vars 到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44838155/

相关文章:

oracle - 使用 Ansible playbook 运行 Oracle SQL 脚本

python - 如何连接可能为空的字符串?

ansible - 使用来自 git 存储库的 ansible 模块?

Ansible 从剧本(不是命令行)应用标签

google-app-engine - 在 GAE 上使用 jinja2 显示图像

json - 如何使用 set_fact 打印数组变量以在 ansible add_host 模块中使用

ansible_facts.packages "skipping"我的包检查

python - Flask的url_for不引用斜杠

python - jinja2:按定义的键顺序对字典进行排序?

postgresql - 强制 Ansible 从组中收集事实