ansiblejinja2ansible-templateansible-filter

How to get interpolated value of variable in Ansible / Jinja2


I'm trying to define Ansible variables this way:

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

And the result email is: "{{ vars[\"user\"][\"name\"] | regex_replace(\"\\W\", \"_\") }}@example.com.

I also tried to set email like this: {{ lookup("vars", "user.nick") }}@example.com
or {{ lookup("vars", "user")["nick"] }}@example.com,
and it says An unhandled exception occurred while running the lookup plugin 'vars'.

Is there a way to get resulting variable values as:

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

?

ansible 2.9.10, python version = 3.8.5


Solution

  • It's not possible cross-reference keys in a dictionary. It's necessary to declare the variables outside the dictionary. For example, the playbook

    - 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
    

    gives (abridged)

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

    A more flexible option is to create the variables in the loop. For example, the playbook

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

    gives (abridged)

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