Ansible – Using Dictionary Keys with Variables

ansible

I'm trying to create a template task in an Ansible playbook which iterates a dictionary which contains some vairables:

- name: Task name
  lineinfile:
    path: /foo/bar
    regexp: "{{ item.regexp }}"
    line: "{{ item.line }}"
    with_items:
      - { regexp: "^(\/\/)?const NodeName", line: "const NodeName = '{{ inventory_hostname }}'" }
      - { regexp: "^(\/\/)?const ZoneName", line: "const ZoneName = '{{ inventory_hostname }}'" }
      - { regexp: "^(\/\/)?const {{ plugins_custom_dir_var_name }} =(.+)", line: "const {{ plugins_custom_dir_var_name }} = '{{ plugins_dest_dir }}'" }

This task gives me the following syntax error:

The offending line appears to be:\n\n    with_items:\n      - { regexp: \"^(\\/\\/)?const NodeName\", line: \"const NodeName = '{{ inventory_hostname }}'\" }\n                     ^ here\nWe could be wrong, but this one looks like it might be an issue with\nmissing quotes.  Always quote template expression brackets when they\nstart a value. For instance:\n\n    with_items:\n      - {{ foo }}\n\nShould be written as:\n\n    with_items:\n      - \"{{ foo }}\"\n"}

I cannot understand where I'm wrong.

Best Answer

You have a typo, with_items is not parameter.

- name: Task name
  lineinfile:
    path: /foo/bar
    regexp: "{{ item.regexp }}"
    line: "{{ item.line }}"
  with_items:
    - { regexp: "^(\/\/)?const NodeName", line: "const NodeName = '{{ inventory_hostname }}'" }
    - { regexp: "^(\/\/)?const ZoneName", line: "const ZoneName = '{{ inventory_hostname }}'" }
    - { regexp: "^(\/\/)?const {{ plugins_custom_dir_var_name }} =(.+)", line: "const {{ plugins_custom_dir_var_name }} = '{{ plugins_dest_dir }}'" }