Adding task output to a file in a loop

I have a shell script that I’m trying to convert to Ansible. It currently is similar to the following:

for uid in {1000…6500}
user = ipa user-find --uid=$uid --raw |grep uid: | awk ‘{print $2}’
echo “user,uid” >> uid.csv
do

How do I accomplish this in Ansible? I know I can use the shell module with a loop similar to the following:

  • name: Get user name based on the UID
    shell: “set -o pipefail && /bin/ipa user-find --uid={{ uid }} --raw | grep uid: | awk ‘{print $2}’”
    register: output
    loop: {{ range(1000, 6500, 1) | list }}

But how can I have each iteration add the values I need to a file? I know that I can use lineinfile, but I need to have it do this for each iteration of the loop.

Thanks,
Harry

I would use a template , you can use the registered results in a for
loop inside jinja2.

Each time through the loop, will the registered output overwrite the previous values?

Harry

for uid in {1000..6500}
  user = ipa user-find --uid=$uid --raw |grep uid: | awk '{print $2}'
  echo "user,uid" >> uid.csv
do

This is the Ansible equivalent, I think.

The module "getent" creates the dictionary "getent_passwd". Next "set_fact"
creates the list of dictionaries with attributes "user" and "uid" only. Next
"set_fact" selects required "uid" and module "template" writes the file.

  - getent:
      database: passwd
  - set_fact:
      my_list: "{{ getent_passwd|
                   dict2items|
                   json_query('.{user: key, uid: to_number(value[1])}')
                   }}"
  - set_fact:
      my_list: "{{ my_list|
                   json_query('[?uid >= `1000`]')|
                   json_query('[?uid <= `65000`]')|
                   sort(attribute='uid')|
                   list }}"
  - template:
      src: uid.csv.j2
      dest: uid.csv

This is the template

  > cat uid.csv.j2
  {% for item in my_list %}
  {{ item.user }},{{ item.uid }}
  {% endfor %}

Notes

  * The function "to_number" is needed to store uid as numbers
    https://jmespath.readthedocs.io/en/latest/proposals/functions.html#to-number

  * The file "uid.csv" will be created on the remote host.

  * To create the file on the controller use "delegate_to" and mark the file
    by the remote hostname. For example

  - template:
      src: uid.csv.j2
      dest: "{{ inventory_hostname }}-uid.csv"
    delegate_to: localhost

    ,or use module "fetch". See parameter "flat"
    https://docs.ansible.com/ansible/latest/modules/fetch_module.html#parameter-flat

HTH,

  -vlado

OK, I’m finally getting back to this. I failed to mention that I’m trying to query our LDAP server, which is Red Hat IDM (based off of FreeIPA). Here’s what I have so far but its not working: