-1

I'm using Ansible to get a list of user emails from an API and I want to loop over them.

This is the json response I get from the API:

"users": [
{
    "email": "email1@email.com",
    "id": 1,
    "is_admin": true
},
{
    "email": "email2@email.com",
    "id": 2,
    "is_admin": false
},
]

edit: the task after that which I need the email for:

- name: Send emails
      register: result
      uri:
        url: http://api
        method: GET
        body_format: json
        return_content: yes
        body:
          email: "{{ item.email }}"
          scope: SCOPE
      loop: "{{ users.json['users'] }}"

- name: Print result
  debug:
    var: result

the error I get:

fatal: [localhost]: FAILED! => {"msg": "template error while templating string: unexpected char '@' at 16. String: {{ email@email.com }}"}

If I use email: item.email the json request body will be "body": {"email": "item.email"} instead of the email value

How Can I get the full email of each user?

RabbitG
  • 103
  • 1
  • 8

1 Answers1

0

You need to remove the {{ and }} markers from your var: directive. The value of var is implicitly evaluated in a Jinja template context so you don't need those markers:

- name: Print returned json dictionary
  debug:
    var: item.email
  loop: "{{ users.json['users'] }}"

(Updated based on edits to your question)

The example you've shown doesn't generate the error you're asking about. Here's a complete reproducer with just the uri changed:

- hosts: localhost
  gather_facts: false
  vars:
    users:
      json:
        users:
          - email: email1@email.com
            id: 1
            is_admin: true
          - email: email2@email.com
            id: 2
            is_admin: false

  tasks:
    - name: Send emails
      register: result
      uri:
        url: https://eny1tdcqj6ghp.x.pipedream.net
        method: GET
        body_format: json
        return_content: true
        body:
          email: "{{ item.email }}"
          scope: SCOPE
      loop: "{{ users.json['users'] }}"

This runs without errors (although note that I'm suspicious about the use of a GET request with a JSON body; typically you would expect that to be a POST request).

You can see the result of running this playbook here, which shows that the values being sent in the request are exactly what we expect from the data.

larsks
  • 277,717
  • 41
  • 399
  • 399
  • I just tried this, but when I try to use the item.email in another API request it ends up looking like this: ` "body": {"email": "item.email" } ` instead of getting the actual email – RabbitG Mar 25 '22 at 13:16
  • My mistake @larsks, I didn't explain how I will use the item.email well. I edited the post to fix that – RabbitG Mar 25 '22 at 13:27