Mark
Mark

Reputation: 49

Unable to add curly braces within curly braces in a jinja2 syntax

I have a set of jinja2 actions within curly braces separated by pipes. Within that set of actions I need to add a variable, but I keep getting syntax errors.

debug:
  msg: "{{ item.path | basename | regex_replace('{{ variable }}', '') }}"
with_items: "{{ content.files }}"

Note that, the variable will contain some regex string for example... The problem ansible has with this, is that it contains a double quote inside a double quote. I tried escaping, inverting double quotes to single quotes...nothing worked.

When I run the above as is, it considers the variable as a literal value.

Upvotes: 1

Views: 827

Answers (1)

Tom Wilson
Tom Wilson

Reputation: 837

You don't need curly braces to denote variables inside of curly braces. Here's a simple playbook to demonstrate:

---
  - name: test
    hosts: localhost
    gather_facts: false
    vars:
      content:
        files:
          - path: /path1/itemXXX.jpg
          - path: /path2/itXem.pdf
      regex_pattern: '[X]+'  # Match one or more X's

    tasks:

      - debug:
          msg: "{{ item.path | basename | regex_replace(regex_pattern, '') }}"
        with_items: "{{ content.files }}"

Results are:

TASK [debug] ***********************************************************************************************************************************************************************
ok: [localhost] => (item={'path': '/path1/itemXXX.jpg'}) => {
    "msg": "item.jpg"
}
ok: [localhost] => (item={'path': '/path2/itXem.pdf'}) => {
    "msg": "item.pdf"
}

Upvotes: 2

Related Questions