大网数据广告活动
服务器运维问答

Save rendered Jinja to variable

· 52CE 我爱测

I'd like to split up some Jinja templating into multiple lines to keep lines under 120 characters, and register a variable for easy reuse. Is there a way to do something like the following? Is there a built-in (or community) modu…

问题原文

原帖链接 · cov · CC BY-SA 4.0

I'd like to split up some Jinja templating into multiple lines to keep lines under 120 characters, and register a variable for easy reuse. Is there a way to do something like the following? Is there a built-in (or community) module for this? If possible, I'd like to do it without using temporary files.

- jinja: "https://{{ username }}:{{ token }}@hosting.com/organization"
  vars:
    username: "{{ hashivault_secrets.value.data.USERNAME }}"
    token: "{{ hashivault_secrets.value.data.TOKEN }}"
  register: url

So the use/reuse could look something like

   - pip:
       name: my-internal-package
     env:
       PIP_EXTRA_INDEX_URL: "{{ url }}"

I'm currently using Ansible 2.9.

已采纳解答

原帖链接 · flowerysong · CC BY-SA 4.0

You can just set a var directly:

  vars:
    url: https://{{ username }}:{{ token }}@hosting.com/organization
    username: "{{ hashivault_secrets.value.data.USERNAME }}"
    token: "{{ hashivault_secrets.value.data.TOKEN }}"

Or you can use set_fact:

- set_fact:
    url: https://{{ username }}:{{ token }}@hosting.com/organization
  vars:
    username: "{{ hashivault_secrets.value.data.USERNAME }}"
    token: "{{ hashivault_secrets.value.data.TOKEN }}"

The main practical difference (beyond setting variables not requiring an additional task) is that variables are evaluated at the time of use so the value of the first url might change over time if hashivault_secrets changes, while set_fact will result in a static value based on the evaluation of the template at the time the set_fact task runs. Both behaviours are useful, depending on the circumstances.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2021-10-29)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。