Usando Ansible como librería de programación en Python

Traducción del original en inglés. Léela en: CatalàEnglish

Ansible es una herramienta muy potente. Usando playbooks, algo parecido a un recetario, es muy fácil automatizar tareas de mantenimiento de sistemas. He usado Puppet y otras herramientas parecidas, pero en mi humilde opinión Ansible es la mejor.

En algunos casos necesitas gestionar sistemas dinámicos y aprovechar Ansible como librería de Python es un complemento muy bueno para tus scripts. Este es mi último requisito y por eso decidí compartir algunos fragmentos sencillos de Python que te ayudan a entender cómo usar Ansible como librería de Python.

Primero de todo, un ejemplo de cómo llamar a un módulo de Ansible con solo un host en el inventario (test_modules.py):

#!/usr/bin/python 
import ansible.runner
import ansible.playbook
import ansible.inventory
from ansible import callbacks
from ansible import utils
import json

# the fastest way to set up the inventory

# hosts list
hosts = ["10.11.12.66"]
# set up the inventory, if no group is defined then 'all' group is used by default
example_inventory = ansible.inventory.Inventory(hosts)

pm = ansible.runner.Runner(
    module_name = 'command',
    module_args = 'uname -a',
    timeout = 5,
    inventory = example_inventory,
    subset = 'all' # name of the hosts group 
    )

out = pm.run()

print json.dumps(out, sort_keys=True, indent=4, separators=(',', ': '))

Como segundo ejemplo, vamos a usar un Playbook de Ansible sencillo con ese código (test.yml):

- hosts: sample_group_name
  tasks:
    - name: just an uname
      command: uname -a

El código de Python que usa ese playbook es (test_playbook.py):

#!/usr/bin/python 
import ansible.runner
import ansible.playbook
import ansible.inventory
from ansible import callbacks
from ansible import utils
import json

### setting up the inventory

## first of all, set up a host (or more)
example_host = ansible.inventory.host.Host(
    name = '10.11.12.66',
    port = 22
    )
# with its variables to modify the playbook
example_host.set_variable( 'var', 'foo')

## secondly set up the group where the host(s) has to be added
example_group = ansible.inventory.group.Group(
    name = 'sample_group_name'
    )
example_group.add_host(example_host)

## the last step is set up the invetory itself
example_inventory = ansible.inventory.Inventory()
example_inventory.add_group(example_group)
example_inventory.subset('sample_group_name')

# setting callbacks
stats = callbacks.AggregateStats()
playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY)
runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY)

# creating the playbook instance to run, based on "test.yml" file
pb = ansible.playbook.PlayBook(
    playbook = "test.yml",
    stats = stats,
    callbacks = playbook_cb,
    runner_callbacks = runner_cb,
    inventory = example_inventory,
    check=True
    )

# running the playbook
pr = pb.run()  

# print the summary of results for each host
print json.dumps(pr, sort_keys=True, indent=4, separators=(',', ': '))

Si quieres descargar los archivos de ejemplo puedes ir a mi cuenta de github: github.com/oriolrius/programming-ansible-basics

Espero que os haya sido útil.

7 comentarios

Los comentarios del blog antiguo, tal como se escribieron. Los comentarios están cerrados.

  1. D

    Hi, very nice vriteup. Based on your example - what would be the proper way of for example install list of packages (given as command line arguments) using "apt" module without calling ansible.runner for each individual package but doing the whole thing in a single run? Can it be done?

    1. Oriol Rius

      A simple way is create a variable with a list of packages and then use it as list. This is the most robust solution. But the fastest way is run all packages as a long command line.

  2. Steve

    I am running a playbook that is supposed to create some config files, using your example code. However, the config files are not created, but my code is executed without error messages. What am I missing? FYI the files are created when I run the playbook from the command line.

    1. Oriol Rius

      This example, don't create configuration files. You don't need that if you run Ansible as a library.

      1. Steve

        Thank you for your reply Oriol. I was probably not clear enough. My playbook creates some files on the local computer, as well as performing other tasks. However, the files that are supposed to be created on the local computer running the python script are not created, although the playbook seems to run just fine. These files are successfully created when running the playbook from the command line. I figure it is a Python problem, but I just can't get it to work.

        1. Oriol Rius

          I don't know how to help you if I can't see the code. If you want send me your code to: oriol@joor.net and I'll try to find the bug.

  3. Shastinathan Sivasubramanian

    Hi I am getting the below error when i tried to run the below play book. i have exactly used the above code only changed the IP. My playbook works just fine when i execute from CLI.

    Error MSG:

    /Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /app/ansible_run.py

    PLAY [sample_group_name] ******************************************************

    GATHERING FACTS ***************************************************************

    ok: [10.*.*.*]

    TASK: [debug msg=“Ansible is great"] *******************************************

    FATAL: no hosts matched or all hosts have already failed -- aborting

    {

    “10.*.*.*: {

    "changed": 0,

    "failures": 0,

    "ok": 1,

    "skipped": 0,

    "unreachable": 0

    }

    }

    Process finished with exit code 0

    Playbook.yml

    - hosts: sample_group_name

    user: username

    sudo: no

    tasks:
    - debug: msg=“Ansible is great"