Using a GraphQL endpoint from an Ansible playbook

Posted on wo 28 september 2022 in ansible

Calling a GraphQL API from an Ansible playbook

I recently had to call a GraphQL API from an Ansible playbook, and considering I had never done that before and there is little to no documentation about this online, it was a bit tricky.

In the end, I got everything working, and figured I would share here for posterity (and myself, when I have to do this again in the future!)

A GraphQ API call consists of either one or two parts: the actual query or mutation and optionally a set of variable as input to the query or mutation.

I found it works easiest to drop both the query and the variables into separate files. This allows me to edit them with appropriate syntax highlighting and formatting. The variables are probably dynamic, so they are in a template. For simplicity, I put the mutation (I was mutating, not querying) in a template file as well.

Ok, so in the end, my mutation looked like this:

mutation createEventUrl($createDto: EventUrlCreateInput!) {
  createEventUrl(createDto: $createDto) {
    id
  }
}

While the input variables looked like this:

{ "createDto": {
  "url": "https://foo.bar.baz.9099/webhooks"
  }
}

The Ansible task was called like this, with two lookups in the body: one for the mutation itself (as "query") and one for the variables:

  - name: test graphql
    ansible.builtin.uri:
      url: https://graphql.api.url.here/
      method: POST
      headers:
        content-type: "application/json"
      body_format: json
      body:
        query: '{{ lookup("template", "./templates/create_event_url.graphql") }}'
        variables: '{{ lookup("template", "./templates/create_event_url_variables.graphql") }}'
    connection: local

This worked quite nicely for me, hope this helps!