outputting dictionary variables using copy module not working

14 views
Skip to first unread message

Abey Thomas

unread,
Oct 12, 2017, 8:00:47 AM10/12/17
to Ansible Project
Hi,

I am running ansible on centos 7.4.1708 . Not sure what I am doing wrong but the dictionary variables are not completely written by the copy module.

Here is my complete YAML file :

---
- hosts: localhost
  gather_facts: False
  vars:
    var_dict1:
      127.0.0.1: localhost
      10.10.10.10: hostnameinternal1
      10.20.10.10: hostnameinternal2
  tasks:

  - name: Copy the contents of var_dict1 to output1
    copy:
      content: |
        {% for key in var_dict1 %}
        {{ item.key}}    {{item.value}}
        {% endfor %}
      dest: "/usershome/output1"
    run_once: yes
    with_dict: "{{ var_dict1 }}"


and here is the file /usershome/output1
127.0.0.1    localhost
127.0.0.1    localhost
127.0.0.1    localhost

my version
ansible 2.3.2.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = Default w/o overrides
  python version = 2.7.5 (default, Aug  4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]


The first entry in the file is correct but the rest are duplicates of the first entry . I can correctly see that in verbose the item key and value are different inside the loop but not in the output file.

What is going wrong here?

Regards,
Abey

Kai Stian Olstad

unread,
Oct 12, 2017, 9:30:16 AM10/12/17
to ansible...@googlegroups.com
Because of the with_dict the task will run 3 times, one for each item in
var_dict1.
Only the last will stick since the file will be overwritten.

Do this instead
- name: Copy the contents of var_dict1 to output1
copy:
content: |
{% for key, value in var_dict1.iteritems() %}
{{ key }} {{ value }}
{% endfor %}
dest: "/usershome/output1"
run_once: yes

--
Kai Stian Olstad

Abey Thomas

unread,
Oct 12, 2017, 10:10:20 AM10/12/17
to Ansible Project
Hi Kai,

Thanks that worked. Did not know about iteritems until now.

Regards,
Abey
Reply all
Reply to author
Forward
0 new messages