Python API 2.0
Starting with 2.0 things is more complicated, but you get more discrete and readable classes:
#!/usr/bin/env python
Import JSON
From collections Import Namedtuple
From Ansible.parsing.dataloader Import Dataloader
From Ansible.vars import Variablemanager
From Ansible.inventory Import Inventory
From Ansible.playbook.play Import play
From Ansible.executor.task_queue_manager import Taskqueuemanager
From Ansible.plugins.callback import callbackbase
Class Resultcallback (Callbackbase):
"" Example callback plug-in for executing results
如果要将所有结果收集到单个对象进行处理 执行的结束,看看利用``json``回调插件 或编写自己的自定义回调插件"""def v2_runner_on_ok(self, result, **kwargs): """打印结果的json表示 该方法可以将结果存储在实例属性中以供以后检索 """ host = result._host print json.dumps({host.name: result._result}, indent=4)
options = namedtuple (' Options ', [' Connection ', ' module_path ', ' forks ', ' become ', ' become_method ', ' become_user ', ' check ‘])
Initialize needed objects
Variable_manager = Variablemanager ()
Loader = Dataloader ()
options = Options (connection= ' local ', module_path= '/path/to/mymodules ', forks=100, Become=none, Become_method=none, Become_user=none, Check=false)
passwords = Dict (vault_pass= ' secret ')
# Instantiate our resultcallback to handle the results coming in
Results_callback = Resultcallback ()
# Create inventory and pass it to Var manager
Inventory = Inventory (Loader=loader, Variable_manager=variable_manager, host_list= ' localhost ')
Variable_manager.set_inventory (Inventory)
Create play with Tasks
Play_source = Dict (
Name = "Ansible Play",
hosts = ' localhost ',
gather_facts = ' no ',
tasks = [
Dict (action=dict (module= ' shell ', args= ' ls '), register= ' shell_out '),
Dict (action=dict (module= ' Debug ', Args=dict (msg= ' {{shell_out.stdout}} ')))
]
)
Play = Play (). Load (Play_source, Variable_manager=variable_manager, Loader=loader)
Actually run it
TQM = None
Try
TQM = Taskqueuemanager (
Inventory=inventory,
Variable_manager=variable_manager,
Loader=loader,
Options=options,
Passwords=passwords,
Stdout_callback=results_callback, # Use our custom callback instead of the default
callback plugin
)
result = Tqm.run (play)
Finally
If TQM is not None:
Tqm.cleanup ()
Python API Pre 2.0
This is simple:
Import Ansible.runner
Runner = Ansible.runner.Runner (
Module_name= ' ping ',
Module_args= ',
Pattern= ' web* ',
forks=10
)
Datastructure = Runner.run ()
The Run method returns the results of each host, grouped according to whether it can be contacted. The return type is module-specific, as shown in the documentation for the module:
Copy Code
{
"Dark": {
"Web1.example.com": "Failure Message"
},
"Contacted": {
"Web2.example.com": 1
}
}
Copy Code
A module can return any type of JSON data, so ansible can be used as a framework to quickly build powerful applications and scripts.
Detailed API Examples
The following script prints out the uptime information for all hosts:
#!/usr/bin/python
Import Ansible.runner
Import Sys
Construct the Ansible runner and execute on all hosts
Results = Ansible.runner.Runner (
Pattern= ' * ', forks=10,
Module_name= ' command ', module_args= '/usr/bin/uptime ',
). Run ()
If results is None:
Print "No hosts found"
Sys.exit (1)
Print "Up ** *"
for (hostname, result) in results[' contacted '].items ():
If not ' failed ' in result:
Print "%s >>>%s"% (hostname, result[' stdout '])
Print "FAILED ** *"
for (hostname, result) in results[' contacted '].items ():
If ' failed ' in result:
Print "%s >>>%s"% (hostname, result[' msg ')
Print "Down ** * * * * * * *"
for (hostname, result) in results[' Dark '].items ():
Print "%s >>>%s"% (hostname, result)
The advanced programmer may also want to read the source to the ansible itself, because it uses the API (with all available options) to implement the executable command-line tool (LIB/ANSIBLE/CLI/).
Http://docs.ansible.com/ansible/latest/dev_guide/developing_api.html
Python API 2.0