Using fact as loop control in Jinja2 template

I have a playbook that will use the user_find API call against our FreeIPA server to retrieve a list of all users. What I’m trying to do is get the total count, then use that count in my j2 file. I’m getting the count as follows:

  • name: Set IDM facts
    set_fact:
    idmcount: “{{ userfind.json.result.count|int }}”

  • name: Output data
    template:
    src: uid.csv.j2
    dest: uid.csv

In my j2 file, I’ve tried 2 different things:

Option 1:

{% for i in idmcount %}
{{ i }}
{% endfor %}

This prints the count as strings (the value is 1740):
1
7
4
0

Option 2:

{% for i in {{ idmcount }} %}
{{ i }}
{% endfor %}

This gives me the following error:

fatal: [localhost]: FAILED! => {“changed”: false, “msg”: “AnsibleError: template error while templating string: expected token ‘:’, got ‘}’. String: {% for i in {{ idmcount }} %}\n{{ i }}\n{% endfor %}\n”}

So how do I use that count as a loop control variable?

Thanks,
Harry

Do you want to loop over a range of numbers up to idmcount? I think that is what I am reading, in which case you want:

{% for i in range(1, idmcount|int + 1) %}

Thank you! That worked well. I must’ve really been over thinking it. However, this does lead to another question: now I’m putting in the actual content as follows:

{% for i in range(1, idmcount|int +1) %}
{{ users[i].uid }},{{ users[i].uidnumber }}
{% endfor %}

This works fine, but the values appear to be in (what I think) is the json format. For example:

[u’name1’],[u’1111’]

How do I strip out the “u’” and have just:
name,1111

Thanks,
Harry

It sounds like you have a data structure like this:

users

  • uid:
  • name1
    uidnumber:
  • 1111

In which case I’d recommend:

users

  • uid: name1
    uidnumber: 1111

Otherwise, You would need to use something like: {{ users[i].uid[0] }}

Perfect!!! Exactly what I needed.

Thank you very much!
Harry