Asible is a very good tool in the operation of tools, I personally prefer, can be flexibly configured according to the needs of yml files to achieve different business needs, because do not need to install the client, the start is very easy, In some cases you might want to write ansible as a library component of Python into your own script, and today's script script will show how ansible can be combined with Python scripts, that is, how to use ansible in a Python script, we step through, Let's look at the first example:
#!/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 are defined then ' all ' group are 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= (', ', ': '))
This example shows how we can run system commands through ansible in a Python script, and then we'll look at the second example, docking with our Yml file, and the simple Yml file reads as follows:
-Hosts:sample_group_name
Tasks
-Name:just an uname
Command:uname-a
The Python script that invokes playbook is as follows:
#!/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
# # A, set up a host (or more)
Example_host = Ansible.inventory.host.Host (
name = ' 10.11.12.66 ',
Port = 22
)
# with their 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 of the 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= (', ', ': '))
Here are 2 small examples to help you.