Jun 13, 2016
As the title suggests, in this tutorial, we will write a python script to run Ansible programmatically.
Ansible is an IT automation tool written in Python. You can find out more here.
We will use Ansible Python API 2.0 to write the script.
This API enables us to use Ansible programmatically through Python.
The play will be able to install docker and run a container in a Debian based machine.
So let’s begin! (make sure you have ansible installed).
First setup all the imports
Here we have some important modules to set the ground for the play.
The data loader is for loading data from a YAML or JSON formatted string/file. But in this play we don’t require it, so will initialize empty.
The VariableManager is for setting different variables and specifying the inventory file.
The Inventory is for initializing an inventory.
The Play is used to set up the play.
The TaskQueueManager is for actually running the play.
Now we will initialize the objects that are needed for the play.
Here we have set few options, such as the connection type, path to extra ansible modules (since we didn’t need here so set that empty), the number of forks to create.
We have also set become, become_method and become_user to run the command as root user.
Finally initiated an inventory with a list of hosts to run (here we are playing around with localhost).
Writing the play
Everything here is self explanatory. We create a dictionary for play with it’s name. hosts and tasks. tasks is a list of tasks we want to run.
Inside each list, there is a name for the task, an action to perform, and other things like register (if we want to cache some output in a variable),
with_items (to loop over items). Every action includes another dictionary with a module that will run in the task and it’s arguments.
Configure the play
We have loaded the play with required configuration and the play data we wrote earlier.
Running the play
Here the TaskQueueManager object is created with all the configurations we cooked earlier. Then we run the play using tqm.run(play).
If the TaskQueueManager was initiated successfully then it’s cleaned up in the end.