Sam
Sam

Reputation: 171

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.

- 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.

Upvotes: 0

Views: 1838

Answers (1)

error404
error404

Reputation: 2823

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   

Upvotes: 1

Related Questions