Select Page

Ansible can talk to your favorite API

by | Apr 26, 2019 | Ansible, IT Automation, DevOps

Ansible is a powerful opensource config management and deployment tool, which can manage nearly any situtation. In many “DevOp” scenarios we come across multiple platforms, which we need to combine. Mostly applications provide an REST Api or web connectors to manage resources, jobs and deployments within the product.
Ansible provides various modules which can execute commands at specific APIs, such as the vmware-guest-module to create virtual machines or the jenkins-job-module to manage jobs over the Jenkins API.
In cases where no module is available, we can use the module “uri”.

The module takes several parameters, of which the “url” is the only required one. For this example I picked an example online API “http://dummy.restapiexample.com/”.
To get a list of all employees we use the method GET on , the header Accept: application/json and register the content.


- name: Make requests to example api
  hosts: localhost
  connection: local
  tasks:
    - name: list employees
      uri:
        method: GET
        url: "http://dummy.restapiexample.com/api/v1/employees"
        return_content: yes
        headers:
          Accept: application/json
      register: response

    - debug:
        msg: "{{ response.content }}"

# Result
TASK [list employees] *************************************************************************
ok: [localhost]

TASK [debug] **********************************************************************************
ok: [localhost] => {
    "msg": [
        {
            "employee_age": "23",
            "employee_name": "test",
            "employee_salary": "46000",
            "id": "12008",
            "profile_image": ""
        }
    ]
}

Now we create a new user in our application, for this we talk to a different url and send a body with our user to create.
When the api accepts JSON I use a little trick to generate a valid json body out of yaml variables with the Ansible filter to_json

For this we create a variable with the same key value structure as the API expects it, in this case the structure looks like this {“name”:”test”,”salary”:”123″,”age”:”23″}.


- name: Make requests to example api
  hosts: localhost
  connection: local
  vars:
    data:
      chris:
        name: chris
        salary: 46000
        age: 27
      jessy:
        name: jessy
        salary: 70000
        age: 30
  tasks:
    - name: create employee
      uri:
        method: POST
        url: "http://dummy.restapiexample.com/api/v1/create"
        return_content: yes
        headers:
          Accept: application/json
        body_format: json
        body: "{{ item.value | to_json }}" //Render valid json from each dictionary in the variable data.
      with_dict: "{{ data }}"
      register: post_content

    - debug:
        msg: "{{ item.content }}"
      with_items: "{{ post_content.results }}"

# Result
ansible-playbook create_user.yaml

PLAY [Make requests to example api] ********************************************************************

TASK [Gathering Facts] *********************************************************************************
ok: [localhost]

TASK [create employee] *********************************************************************************
ok: [localhost] => (item={'value': {u'salary': 46000, u'age': 27, u'name': u'chris'}, 'key': u'chris'})
ok: [localhost] => (item={'value': {u'salary': 70000, u'age': 30, u'name': u'jessy'}, 'key': u'jessy'})

With this information given, you can now explore your own favorite API and hopefully reduce your daily tasks as simple Ansible playbooks.

Check out our Blog for more awesome posts and if you need help with Ansible send us a message!

Thilo Wening
Thilo Wening
Manager Consulting

Thilo hat bei NETWAYS mit der Ausbildung zum Fachinformatiker, Schwerpunkt Systemadministration begonnen und unterstützt nun nach erfolgreich bestandener Prüfung tatkräftig die Kollegen im Consulting. In seiner Freizeit ist er athletisch in der Senkrechten unterwegs und stählt seine Muskeln beim Bouldern. Als richtiger Profi macht er das natürlich am liebsten in der Natur und geht nur noch in Ausnahmefällen in die Kletterhalle.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

More posts on the topic Ansible | IT Automation | DevOps

Kritischer Fehler in Puppet Version 7.29.0 und 8.5.0

Eine Warnung an alle Nutzer von Puppet, aber auch Foreman oder dem Icinga-Installer, die Version 7.29.0 und 8.5.0 von Puppet enthält einen kritischen Fehler, der die Erstellung eines Katalogs und somit die Anwendung der Konfiguration verhindert. Daher stellt bitte...

Foreman Birthday Event 2023 – Recap

Two years ago I started my recap of the event with "Last week on Thursday we had the Foreman Birthday event and I can proudly say it was a big success." and I can do the same for this one. At the beginning of the year planning for the event started in the background...

Was ist Ansible Semaphore?

Als Open Source Consultants müssen meine Kolleg:innen und ich uns regelmäßig mit neuen Technologien, Tools oder anderen Neuerungen auseinandersetzen. Dabei testen wir besonders neue Software die uns und unseren Kund:innen das Leben potenziell leichter machen können...