Seite wählen

Ansible can talk to your favorite API

von | Apr 26, 2019 | Ansible, 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 http://dummy.restapiexample.com/api/v1/employees, the header Accept: application/json and register the content.

- name: Make requests to example api
  hosts: localhost
  connection: local
    - name: list employees
        method: GET
        url: "http://dummy.restapiexample.com/api/v1/employees"
        return_content: yes
          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 http://dummy.restapiexample.com/api/v1/create 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
        name: chris
        salary: 46000
        age: 27
        name: jessy
        salary: 70000
        age: 30
    - name: create employee
        method: POST
        url: "http://dummy.restapiexample.com/api/v1/create"
        return_content: yes
          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
Senior Consultant

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.
Mehr Beiträge zum Thema Ansible | Automation | DevOps

Automate Icinga for Windows with Ansible

This article will cover how to automate the monitoring of your windows infrastructure with Ansible and Icinga for Windows. For that, I developed a new Ansible role which you can find here: https://github.com/DanOPT/ansible-role-ifw The role will allow you to manage...

Ansible Continuous Deployment without AWX/Tower/AAP

Why Ansible? Ansible is a configuration management tool to automate tasks in your IT infrastructure. It offers a rather low barrier of entry, when compared to other tools. A local Ansible installation (i.e. on your machine) with SSH access to the infrastructure you...

Leap(p) to Red Hat Enterprise Linux 9

Ich muss mich direkt für das Wortspiel im Titel entschuldigen, aber es lag so nahe als ich mich für das Thema entschieden hatte, denn ich möchte einen neuen Blick auf Leapp werfen mit dem Upgrades von Red Hat Enterprise Linux (RHEL) durchgeführt werden können. Der...

Schulungsnotebooks in neuem Gewand

In diesem Jahr konnten wir endlich wieder mehr Vor-Ort Trainings durchführen als in den vergangenen Jahren und sogar vereinzelte Inhouse-Trainings bei Kunden waren möglich. Bisher haben wir bei unseren Präsenztrainings oder auch -workshops auf Notebooks mit CentOS 7...