Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Writing a list to a file in Ansible

Im trying to loop through a list and write each element to a line. If i use with_list I get the below error when the list only has 1 element:

fatal: [localhost]: FAILED! => {"msg": "Invalid data passed to 'loop', it requires a list, got this instead:  ['10.0.0.65']. Hint: If you passed a list/dict of just one element, try adding wantlist=True to your lookup invocation or use q/query instead of lookup."}

I am not using lookup or query as I am iterating the entire list which may vary in size.

If I use with_items it creates the file however it writes the elements as a list ie with square brackets and single quotes.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

- name: add controllers
  lineinfile:
    path: /home/sam/Documents/TFCloudK8/ansible/inv
    line: "{{ item }}"
  with_items: "{{ controllers }}"

Controllers is a list with a single IP in and is written to the file as:

 ['10.0.0.65']

I just need to write the IP to the file, am I going about this the wrong way? Any help appreciated.

>Solution :

You can define the playbook like below:

---
- name: single ip
  vars:
    controllers:
    - ["10.10.10.10"]
  hosts: localhost
  tasks:
    - name: add controllers
      lineinfile:
        path: /tmp/test
        line: "{{ item }}"
      with_items: "{{ controllers }}"

Output:

PLAY [single ip] *************************************************************************************************************************************************************************************

TASK [Gathering Facts] *******************************************************************************************************************************************************************************
ok: [localhost]

TASK [add controllers] *******************************************************************************************************************************************************************************
changed: [localhost] => (item=10.10.10.10)

PLAY RECAP *******************************************************************************************************************************************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading