如何在Ansible / Jinja2中获取变量的插值

时间:2020-08-10 09:29:10

标签: ansible jinja2 ansible-template ansible-filter

我正在尝试通过以下方式定义Ansible变量:

user:
  name: First Last
  nick: '{{ vars["user"]["name"] | regex_replace("\W", "_") }}'
  email: '{{ vars["user"]["nick"] }}@example.com'

结果email为:"{{ vars[\"user\"][\"name\"] | regex_replace(\"\\W\", \"_\") }}@example.com

我还试图像这样设置email{{ lookup("vars", "user.nick") }}@example.com
{{ lookup("vars", "user")["nick"] }}@example.com
并说An unhandled exception occurred while running the lookup plugin 'vars'

是否可以通过以下方式获得结果变量值:

user:
  name: First Last
  nick: First_Last
  email: First_Last@example.com

可用2.9.10, python版本= 3.8.5

1 个答案:

答案 0 :(得分:2)

字典中不可能有交叉引用键。有必要在字典外声明变量。例如,剧本

- hosts: localhost
  vars:
    my_name: First Last
    my_nick: "{{ my_name | regex_replace('\\W', '_') }}"
    user:
      name: "{{ my_name }}"
      nick: "{{ my_nick }}"
      email: "{{ my_nick }}@example.com"
  tasks:
    - debug:
        var: user

给予(删节)

  user:
    email: First_Last@example.com
    name: First Last
    nick: First_Last

一个更灵活的选择是在循环中创建变量。例如,剧本

- hosts: localhost
  vars:
    users:
      "First Last":
        domain: example.com
  tasks:
    - debug:
        msg:
          - "name: {{ name }}"
          - "nick: {{ nick }}"
          - "email: {{ email }}"
      loop: "{{ users|dict2items }}"
      vars:
        name: "{{ item.key }}"
        nick: "{{ item.key|regex_replace('\\W', '_') }}"
        email: "{{ nick ~ '@' ~ item.value.domain }}"

给予(删节)

  msg:
  - 'name: First Last'
  - 'nick: First_Last'
  - 'email: First_Last@example.com'