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

How to get interpolated value of variable in Ansible / Jinja2

我正在尝试以这种方式定义 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

?

ansible 2.9.10, python版本=3.8.5

字典中不可能有 cross-reference 个键。有必要在字典外声明变量。例如,剧本

- 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'