Utilitzant Ansible com a llibreria de programació en Python

Traducció de l’original en anglès. Llegeix-lo en: CastellanoEnglish

Ansible és una eina molt potent. Utilitzant playbooks, una cosa semblant a un receptari, és molt fàcil automatitzar tasques de manteniment de sistemes. He fet servir Puppet i altres eines semblants, però en la meva modesta opinió Ansible és la millor.

En alguns casos necessites gestionar sistemes dinàmics i aprofitar Ansible com a llibreria de Python és un complement molt bo per als teus scripts. Aquest és el meu darrer requisit i per això vaig decidir compartir alguns fragments senzills de Python que t'ajuden a entendre com fer servir Ansible com a llibreria de Python.

Primer de tot, un exemple de com cridar un mòdul d'Ansible amb només un host a l'inventari (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=(',', ': '))

Com a segon exemple, farem servir un Playbook d'Ansible senzill amb aquest codi (test.yml):

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

El codi de Python que fa servir aquest playbook és (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 vols baixar els fitxers d'exemple pots anar al meu compte de github: github.com/oriolrius/programming-ansible-basics

Espero que us hagi estat útil.

7 comentaris

Els comentaris del blog antic, tal com es van escriure. Els comentaris estan tancats.

  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"