ansible Api 2.3-2.4
官网示例(python3)
说明:
在学习2.0 api的过程中遇到了一个坑,最新版的ansible(2.4)和2.3版本api引用时发生了变化,本文主要使用2.3 api进行操作,2.4只做分析
ansible api (ansible2.4)
#!/usr/bin/env python
#-*-coding:utf-8 -*- import json
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager #这里用的ansbile 2.4
from ansible.inventory.manager import InventoryManager #这里用的ansible 2.4
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback import CallbackBase #自定义运行callback,即运行完api后调用v2_runner_on_ok函数,打印host和result
class ResultCallback(CallbackBase):
def v2_runner_on_ok(self, result, **kwargs):
#result所包含属性(_check_key..可用dir方法查看所包含的所有属性)
host = result._host
print(json.dumps({host.name: result._result}, indent=4)) #创建一个Options类型,列表里为属性,这里用来设置ansible执行时的参数,如ask_pass,sudo_user等等(namedtuple创建一个和tuple类似的对象,而且对象拥有可以访问的属性)
Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check', 'diff']) # initialize needed objects
loader = DataLoader() #可以通过options.(属性) 的方法去获取属性的值,如获取connection的值可以直接写成options.connection
options = Options(connection='local', module_path='/path/to/mymodules', forks=100, become=None, become_method=None, become_user=None, check=False,diff=False)
passwords = dict(vault_pass='secret') # Instantiate our ResultCallback for handling results as they come in
results_callback = ResultCallback() # 加载inventory变量,这里的sources的值可以是hosts文件,也可以是ip列表,如['xxx.xxx.xx.x','xx.xx.xx.xx']
inventory = InventoryManager(loader=loader, sources=['/etc/ansible/hosts']) #管理变量的类,包括主机、组、扩展等变量
variable_manager = VariableManager(loader=loader, inventory=inventory) # 创建一个任务
play_source = dict(
name = "Ansible Play",
hosts = 'test', #这里写在上面inventory里设置的sources所指定的文件里的组名
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, #ansible.parsing.dataloader模块创建,用于数据解析
options=options, #存放各类配置信息,ansible执行时的各种参数
passwords=passwords, #登录密码
stdout_callback=results_callback, #回调函数,调用最上面定义的callback函数
)
result = tqm.run(play)
finally:
if tqm is not None:
tqm.cleanup()
ansible2.3 api
#!/usr/bin/env python
# -*-coding:utf-8 -*- 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 # 自定义运行callback,即运行完api后调用v2_runner_on_ok函数,打印host和result
class ResultCallback(CallbackBase):
def v2_runner_on_ok(self, result, **kwargs): #执行完会生成一个result结果,通过result.__ditct__可打印所有的方法,其中_result和_host方法为主要内容 host = result._host
print(json.dumps({host.name: result._result}, indent=4)) # 创建一个Options类型,列表里为属性,这里用来设置ansible执行时的参数,如ask_pass,sudo_user等等(namedtuple创建一个和tuple类似的对象,而且对象拥有可以访问的属性)
Options = namedtuple('Options',
['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check', 'diff']) # initialize needed objects
loader = DataLoader() # 可以通过options.(属性) 的方法去获取属性的值,如获取connection的值可以直接写成options.connection
options = Options(connection='local', module_path='/path/to/mymodules', forks=100, become=None, become_method=None,
become_user=None, check=False, diff=False)
passwords = dict(vault_pass='secret') # Instantiate our ResultCallback for handling results as they come in
results_callback = ResultCallback() # 管理变量的类,包括主机、组、扩展等变量
variable_manager = VariableManager() # 加载inventory变量,这里的sources的值可以是hosts文件,也可以是ip列表,如['xxx.xxx.xx.x','xx.xx.xx.xx']
inventory = Inventory(loader=loader, variable_manager=variable_manager,host_list='/etc/ansible/hosts') # 创建一个任务
play_source = dict(
name="Ansible Play",
hosts='test',
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,
)
result = tqm.run(play)
finally:
if tqm is not None:
tqm.cleanup()
ansible-playbook api调用方式(ansible 2.3.1)
#!/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.executor.playbook_executor import PlaybookExecutor #引入executor模块
#用来加载解析yml文件或者json内容
loader = DataLoader()
variable_manager = VariableManager()
# 根据inventory加载对应变量,此处host_list参数可以有两种格式:
inventory = Inventory(loader=loader, variable_manager=variable_manager,host_list='/etc/ansible/hosts') #这里可通过分析源码得到参数
# 1: hosts文件(需要),
# 2: 可以是IP列表,此处使用IP列表
variable_manager.set_inventory(inventory)
passwords=None
#初始化
Options = namedtuple('Options',
['connection',
'remote_user',
'ask_sudo_pass',
'verbosity',
'ack_pass',
'module_path',
'forks',
'become',
'become_method',
'become_user',
'check',
'listhosts',
'listtasks',
'listtags',
'syntax',
'sudo_user',
'sudo'])
#初始化需要的对象
options = Options(connection='smart',
remote_user='root',
ack_pass=None,
sudo_user='root',
forks=,
sudo='yes',
ask_sudo_pass=False,
verbosity=,
module_path=None,
become=True,
become_method='sudo',
become_user='root',
check=None,
listhosts=None,
listtasks=None,
listtags=None,
syntax=None) # 多个yaml文件则以列表形式
playbook = PlaybookExecutor(playbooks=['/etc/ansible/test.yml'],inventory=inventory,
variable_manager=variable_manager,
loader=loader,options=options,passwords=passwords)
result = playbook.run()
print (result) #ansible-playbook模块没有与callback模块共用
test.yml
[root@bogon ~]# cat test.yml
---
- hosts: 10.10.10.11
gather_facts: false
sudo: True
remote_user: root
tasks:
- shell: ifconfig
register: output
- debug: var=output.stdout
[root@bogon ~]#
执行结果:
[root@bogon ~]# python aa.py PLAY [10.10.10.11] **************************************************************************************************************************************************************************** TASK [command] ********************************************************************************************************************************************************************************
changed: [10.10.10.11]
{"_ansible_parsed": true, "stderr_lines": [], "cmd": "ifconfig", "end": "2018-02-01 14:49:00.920984", "_ansible_no_log": false, "stdout": "ens32: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500\n inet 10.10.10.11 netmask 255.255.255.0 broadcast 10.10.10.255\n inet6 fe80::250:56ff:fe93:e5c6 prefixlen 64 scopeid 0x20<link>\n ether 00:50:56:93:e5:c6 txqueuelen 1000 (Ethernet)\n RX packets 10048045 bytes 1340025577 (1.2 GiB)\n RX errors 0 dropped 0 overruns 0 frame 0\n TX packets 9885546 bytes 975436242 (930.2 MiB)\n TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0\n\nlo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536\n inet 127.0.0.1 netmask 255.0.0.0\n inet6 ::1 prefixlen 128 scopeid 0x10<host>\n loop txqueuelen 1 (Local Loopback)\n RX packets 5214029 bytes 417704433 (398.3 MiB)\n RX errors 0 dropped 0 overruns 0 frame 0\n TX packets 5214029 bytes 417704433 (398.3 MiB)\n TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0\n\nvirbr0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500\n inet 192.168.122.1 netmask 255.255.255.0 broadcast 192.168.122.255\n ether 52:54:00:b7:6f:ef txqueuelen 1000 (Ethernet)\n RX packets 0 bytes 0 (0.0 B)\n RX errors 0 dropped 0 overruns 0 frame 0\n TX packets 0 bytes 0 (0.0 B)\n TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0", "changed": true, "rc": , "start": "2018-02-01 14:49:00.908486", "stderr": "", "delta": "0:00:00.012498", "invocation": {"module_args": {"warn": true, "executable": null, "_uses_shell": true, "_raw_params": "ifconfig", "removes": null, "creates": null, "chdir": null}}, "stdout_lines": ["ens32: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500", " inet 10.10.10.11 netmask 255.255.255.0 broadcast 10.10.10.255", " inet6 fe80::250:56ff:fe93:e5c6 prefixlen 64 scopeid 0x20<link>", " ether 00:50:56:93:e5:c6 txqueuelen 1000 (Ethernet)", " RX packets 10048045 bytes 1340025577 (1.2 GiB)", " RX errors 0 dropped 0 overruns 0 frame 0", " TX packets 9885546 bytes 975436242 (930.2 MiB)", " TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0", "", "lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536", " inet 127.0.0.1 netmask 255.0.0.0", " inet6 ::1 prefixlen 128 scopeid 0x10<host>", " loop txqueuelen 1 (Local Loopback)", " RX packets 5214029 bytes 417704433 (398.3 MiB)", " RX errors 0 dropped 0 overruns 0 frame 0", " TX packets 5214029 bytes 417704433 (398.3 MiB)", " TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0", "", "virbr0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500", " inet 192.168.122.1 netmask 255.255.255.0 broadcast 192.168.122.255", " ether 52:54:00:b7:6f:ef txqueuelen 1000 (Ethernet)", " RX packets 0 bytes 0 (0.0 B)", " RX errors 0 dropped 0 overruns 0 frame 0", " TX packets 0 bytes 0 (0.0 B)", " TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0"]} TASK [debug] **********************************************************************************************************************************************************************************
ok: [10.10.10.11] => {
"output.stdout": "ens32: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500\n inet 10.10.10.11 netmask 255.255.255.0 broadcast 10.10.10.255\n inet6 fe80::250:56ff:fe93:e5c6 prefixlen 64 scopeid 0x20<link>\n ether 00:50:56:93:e5:c6 txqueuelen 1000 (Ethernet)\n RX packets 10048045 bytes 1340025577 (1.2 GiB)\n RX errors 0 dropped 0 overruns 0 frame 0\n TX packets 9885546 bytes 975436242 (930.2 MiB)\n TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0\n\nlo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536\n inet 127.0.0.1 netmask 255.0.0.0\n inet6 ::1 prefixlen 128 scopeid 0x10<host>\n loop txqueuelen 1 (Local Loopback)\n RX packets 5214029 bytes 417704433 (398.3 MiB)\n RX errors 0 dropped 0 overruns 0 frame 0\n TX packets 5214029 bytes 417704433 (398.3 MiB)\n TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0\n\nvirbr0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500\n inet 192.168.122.1 netmask 255.255.255.0 broadcast 192.168.122.255\n ether 52:54:00:b7:6f:ef txqueuelen 1000 (Ethernet)\n RX packets 0 bytes 0 (0.0 B)\n RX errors 0 dropped 0 overruns 0 frame 0\n TX packets 0 bytes 0 (0.0 B)\n TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0"
}
{"output.stdout": "ens32: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500\n inet 10.10.10.11 netmask 255.255.255.0 broadcast 10.10.10.255\n inet6 fe80::250:56ff:fe93:e5c6 prefixlen 64 scopeid 0x20<link>\n ether 00:50:56:93:e5:c6 txqueuelen 1000 (Ethernet)\n RX packets 10048045 bytes 1340025577 (1.2 GiB)\n RX errors 0 dropped 0 overruns 0 frame 0\n TX packets 9885546 bytes 975436242 (930.2 MiB)\n TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0\n\nlo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536\n inet 127.0.0.1 netmask 255.0.0.0\n inet6 ::1 prefixlen 128 scopeid 0x10<host>\n loop txqueuelen 1 (Local Loopback)\n RX packets 5214029 bytes 417704433 (398.3 MiB)\n RX errors 0 dropped 0 overruns 0 frame 0\n TX packets 5214029 bytes 417704433 (398.3 MiB)\n TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0\n\nvirbr0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500\n inet 192.168.122.1 netmask 255.255.255.0 broadcast 192.168.122.255\n ether 52:54:00:b7:6f:ef txqueuelen 1000 (Ethernet)\n RX packets 0 bytes 0 (0.0 B)\n RX errors 0 dropped 0 overruns 0 frame 0\n TX packets 0 bytes 0 (0.0 B)\n TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0", "_ansible_no_log": false, "_ansible_verbose_always": true} PLAY RECAP ************************************************************************************************************************************************************************************
10.10.10.11 : ok= changed= unreachable= failed=
附:2.4源码目录结构:
vars目录
##ansible2.4
[root@slave3 ansible]# tree vars/
vars/
├── hostvars.py
├── hostvars.pyc
├── hostvars.pyo
├── __init__.py
├── __init__.pyc
├── __init__.pyo
├── manager.py
├── manager.pyc
├── manager.pyo
├── reserved.py
├── reserved.pyc
├── reserved.pyo
├── unsafe_proxy.py
├── unsafe_proxy.pyc
└── unsafe_proxy.pyo directories, files #ansible2.
root@ubuntu:/usr/local/lib/python3./dist-packages/ansible# tree vars/
vars/
├── hostvars.py
├── __init__.py #具体类和方法看下图
├── __pycache__
│ ├── hostvars.cpython-.pyc
│ ├── __init__.cpython-.pyc
│ ├── reserved.cpython-.pyc
│ └── unsafe_proxy.cpython-.pyc
├── reserved.py
└── unsafe_proxy.py directory, files
2.3
2.4的就不贴了,
2.3 的 VariableManager 类放到了 __init__下,可直接引用,2.4的则放在了manager下,
inventory
##ansible 2.3
root@ubuntu:/usr/local/lib/python3./dist-packages/ansible# tree inventory/
inventory/
├── dir.py
├── expand_hosts.py
├── group.py
├── host.py
├── ini.py
├── __init__.py
├── __pycache__
│ ├── dir.cpython-.pyc
│ ├── expand_hosts.cpython-.pyc
│ ├── group.cpython-.pyc
│ ├── host.cpython-.pyc
│ ├── ini.cpython-.pyc
│ ├── __init__.cpython-.pyc
│ ├── script.cpython-.pyc
│ └── yaml.cpython-.pyc
├── script.py
├── vars_plugins
│ ├── __init__.py
│ ├── noop.py
│ └── __pycache__
│ ├── __init__.cpython-.pyc
│ └── noop.cpython-.pyc
└── yaml.py directories, files
##ansible2.4
[root@slave3 ansible]# tree inventory/
inventory/
├── data.py
├── data.pyc
├── data.pyo
├── group.py
├── group.pyc
├── group.pyo
├── helpers.py
├── helpers.pyc
├── helpers.pyo
├── host.py
├── host.pyc
├── host.pyo
├── __init__.py
├── __init__.pyc
├── __init__.pyo
├── manager.py
├── manager.pyc
└── manager.pyo
2.3
2.4略
模块导入时:
##ansible2.3
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.executor.playbook_executor import PlaybookExecutor ##ansible2.
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager #参数略有改变
from ansible.executor.playbook_executor import PlaybookExecutor
简单整合 2.3.1
#!/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.executor.playbook_executor import PlaybookExecutor
from ansible.plugins.callback import CallbackBase
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager class ResultsCallback(CallbackBase):
def __init__(self,*args,**kwargs):
super(ResultsCallback,self).__init__(*args,**kwargs)
self.task_ok = {}
self.task_unreachable = {}
self.task_failed = {}
self.task_skipped = {}
self.task_stats = {}
# self.host_ok = {}
# self.host_unreachable = {}
# self.host_failed = {} def v2_runner_on_unreachable(self, result):
self.task_unreachable[result._host.get_name()] = result def v2_runner_on_ok(self, result, *args, **kwargs):
self.task_ok[result._host.get_name()] = result def v2_runner_on_failed(self, result, *args, **kwargs):
self.task_failed[result._host.get_name()] = result def v2_runner_on_skipped(self, result, *args, **kwargs):
self.task_skipped[result._host.get_name()] = result def v2_runner_on_stats(self, result, *args, **kwargs):
self.task_stats[result._host.get_name()] = result #chushihua
class Runner(object):
def __init__(self,*args,**kwargs):
self.loader = DataLoader()
self.variable_manager = VariableManager()
self.results_callback = ResultsCallback()
self.inventory = Inventory(loader=self.loader, variable_manager=self.variable_manager, host_list='/etc/ansible/hosts')
self.variable_manager.set_inventory(self.inventory)
self.passwords = None
Options = namedtuple('Options',
['connection',
'remote_user',
'verbosity',
'ack_pass',
'module_path',
'forks',
'become',
'become_method',
'become_user',
'check',
'listhosts',
'listtasks',
'listtags',
'syntax', ])
# 初始化需要的对象
self.options = Options(connection='smart',
remote_user='root',
ack_pass=None,
forks=100, verbosity=5,
module_path=None,
become=True,
become_method='sudo',
become_user='root',
check=None,
listhosts=None,
listtasks=None,
listtags=None,
syntax=None)
def run_ad_hoc(self):
play_source = dict(
name="Ansible Play",
hosts='test',
gather_facts='no',
tasks=[
dict(action=dict(module='shell', args='ls /home'), register='shell_out'),
dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
]
)
play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader) tqm = None
try:
tqm = TaskQueueManager(
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
passwords=self.passwords,
stdout_callback=self.results_callback,
)
result = tqm.run(play)
finally:
if tqm is not None:
tqm.cleanup() ##定义字典用于接收或者处理结果
result_raw = {'success': {}, 'failed': {}, 'unreachable': {}, 'skipped': {}, 'status': {}} # 循环打印这个结果,success,failed,unreachable需要每个都定义一个
for host, result in self.results_callback.task_ok.items():
result_raw['success'][host] = result._result
for host, result in self.results_callback.task_failed.items():
result_raw['failed'][host] = result._result for host, result in self.results_callback.task_unreachable.items():
result_raw['unreachable'][host] = result._result return result_raw def run_playbook(self):
playbook = PlaybookExecutor(playbooks=['/root/test.yml'], inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader, options=self.options, passwords=self.passwords) playbook._tqm._stdout_callback = self.results_callback
results = playbook.run() ##定义字典用于接收或者处理结果
result_raw = {'success': {}, 'failed': {}, 'unreachable': {}, 'skipped': {}, 'status': {}} # 循环打印这个结果,success,failed,unreachable需要每个都定义一个
for host, result in self.results_callback.task_ok.items():
result_raw['success'][host] = result._result
for host, result in self.results_callback.task_failed.items():
result_raw['failed'][host] = result._result for host, result in self.results_callback.task_unreachable.items():
result_raw['unreachable'][host] = result._result for host, result in self.results_callback.task_skipped.items():
result_raw['skipped'][host] = result._result for host, result in self.results_callback.task_stats.items():
result_raw['status'][host] = result._result return result_raw c = Runner()
print (c.run_ad_hoc(),c.run_playbook())
2.4.1
#!/usr/bin/env python import json
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.executor.playbook_executor import PlaybookExecutor
from ansible.plugins.callback import CallbackBase
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager class ResultsCallback(CallbackBase):
def __init__(self,*args,**kwargs):
super(ResultsCallback,self).__init__(*args,**kwargs)
self.task_ok = {}
self.task_unreachable = {}
self.task_failed = {}
self.task_skipped = {}
self.task_stats = {}
# self.host_ok = {}
# self.host_unreachable = {}
# self.host_failed = {} def v2_runner_on_unreachable(self, result):
self.task_unreachable[result._host.get_name()] = result def v2_runner_on_ok(self, result, *args, **kwargs):
self.task_ok[result._host.get_name()] = result def v2_runner_on_failed(self, result, *args, **kwargs):
self.task_failed[result._host.get_name()] = result def v2_runner_on_skipped(self, result, *args, **kwargs):
self.task_skipped[result._host.get_name()] = result def v2_runner_on_stats(self, result, *args, **kwargs):
self.task_stats[result._host.get_name()] = result #chushihua
class Runner(object):
def __init__(self,*args,**kwargs):
self.loader = DataLoader()
self.results_callback = ResultsCallback()
self.inventory = InventoryManager(loader=self.loader,sources=['/etc/ansible/hosts'])
self.variable_manager = VariableManager(loader=self.loader, inventory=self.inventory)
self.passwords = None
Options = namedtuple('Options',
['connection',
'remote_user',
'ask_sudo_pass',
'verbosity',
'ack_pass',
'module_path',
'forks',
'become',
'become_method',
'become_user',
'check',
'listhosts',
'listtasks',
'listtags',
'syntax',
'sudo_user',
'sudo',
'diff'])
# 初始化需要的对象
self.options = Options(connection='smart',
remote_user=None,
ack_pass=None,
sudo_user=None,
forks=5,
sudo=None,
ask_sudo_pass=False,
verbosity=5,
module_path=None,
become=None,
become_method=None,
become_user=None,
check=False,
diff=False,
listhosts=None,
listtasks=None,
listtags=None,
syntax=None) def run_ad_hoc(self):
play_source = dict(
name="Ansible Play ad-hoc",
hosts='test',
gather_facts='no',
tasks=[
dict(action=dict(module='shell', args='ls /home'), register='shell_out'),
#dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
]
)
play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader) tqm = None
try:
tqm = TaskQueueManager(
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
passwords=self.passwords,
stdout_callback=self.results_callback,
)
result = tqm.run(play)
finally:
if tqm is not None:
tqm.cleanup() ##定义字典用于接收或者处理结果
result_raw = {'success': {}, 'failed': {}, 'unreachable': {}, 'skipped': {}, 'status': {}} # 循环打印这个结果,success,failed,unreachable需要每个都定义一个
for host, result in self.results_callback.task_ok.items():
result_raw['success'][host] = result._result
for host, result in self.results_callback.task_failed.items():
result_raw['failed'][host] = result._result for host, result in self.results_callback.task_unreachable.items():
result_raw['unreachable'][host] = result._result return result_raw def run_playbook(self):
playbook = PlaybookExecutor(playbooks=['/root/test.yml'], inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader, options=self.options, passwords=self.passwords) playbook._tqm._stdout_callback = self.results_callback
results = playbook.run() ##定义字典用于接收或者处理结果
result_raw = {'success': {}, 'failed': {}, 'unreachable': {}, 'skipped': {}, 'status': {}} # 循环打印这个结果,success,failed,unreachable需要每个都定义一个
for host, result in self.results_callback.task_ok.items():
result_raw['success'][host] = result._result
for host, result in self.results_callback.task_failed.items():
result_raw['failed'][host] = result._result for host, result in self.results_callback.task_unreachable.items():
result_raw['unreachable'][host] = result._result for host, result in self.results_callback.task_skipped.items():
result_raw['skipped'][host] = result._result for host, result in self.results_callback.task_stats.items():
result_raw['status'][host] = result._result return result_raw c = Runner()
print (c.run_ad_hoc(),c.run_playbook())
#!/usr/bin/env python import json
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.executor.playbook_executor import PlaybookExecutor
from ansible.plugins.callback import CallbackBase
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager class PlaybookResultsCallback(CallbackBase):
def __init__(self,*args,**kwargs):
super(PlaybookResultsCallback,self).__init__(*args,**kwargs)
self.task_ok = {}
self.task_unreachable = {}
self.task_failed = {}
self.task_skipped = {}
self.task_stats = {} def v2_runner_on_unreachable(self, result):
self.task_unreachable[result._host.get_name()] = result def v2_runner_on_ok(self, result, *args, **kwargs):
self.task_ok[result._host.get_name()] = result def v2_runner_on_failed(self, result, *args, **kwargs):
self.task_failed[result._host.get_name()] = result def v2_runner_on_skipped(self, result, *args, **kwargs):
self.task_skipped[result._host.get_name()] = result def v2_runner_on_stats(self, result, *args, **kwargs):
self.task_stats[result._host.get_name()] = result class ResultsCallback(CallbackBase):
def __init__(self,*args,**kwargs):
super(ResultsCallback,self).__init__(*args,**kwargs)
self.host_ok = {}
self.host_unreachable = {}
self.host_failed = {} def v2_runner_on_unreachable(self, result):
self.host_unreachable[result._host.get_name()] = result def v2_runner_on_ok(self, result, *args, **kwargs):
self.host_ok[result._host.get_name()] = result def v2_runner_on_failed(self, result, *args, **kwargs):
self.host_failed[result._host.get_name()] = result #chushihua
class Runner(object):
def __init__(self,*args,**kwargs):
self.loader = DataLoader()
self.results_callback = ResultsCallback()
self.Playbook_results_callback = PlaybookResultsCallback()
self.inventory = InventoryManager(loader=self.loader,sources=['/etc/ansible/hosts'])
self.variable_manager = VariableManager(loader=self.loader, inventory=self.inventory)
self.passwords = None
self.results_raw = {} Options = namedtuple('Options',
['connection',
'remote_user',
'ask_sudo_pass',
'verbosity',
'ack_pass',
'module_path',
'forks',
'become',
'become_method',
'become_user',
'check',
'listhosts',
'listtasks',
'listtags',
'syntax',
'sudo_user',
'sudo',
'diff'])
# 初始化需要的对象
self.options = Options(connection='smart',
remote_user=None,
ack_pass=None,
sudo_user=None,
forks=5,
sudo=None,
ask_sudo_pass=False,
verbosity=5,
module_path=None,
become=None,
become_method=None,
become_user=None,
check=False,
diff=False,
listhosts=None,
listtasks=None,
listtags=None,
syntax=None) def run_ad_hoc(self):
play_source = dict(
name="Ansible Play ad-hoc",
hosts='test',
gather_facts='no',
tasks=[
dict(action=dict(module='shell', args='ls /home'), register='shell_out'),
#dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
]
)
play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader) tqm = None
try:
tqm = TaskQueueManager(
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
passwords=self.passwords,
stdout_callback=self.results_callback,
)
result = tqm.run(play)
finally:
if tqm is not None:
tqm.cleanup() ##定义字典用于接收或者处理结果
def get_adhoc_result(self):
self.results_raw = {'success': {}, 'failed': {}, 'unreachable': {}}
for host, result in self.results_callback.host_ok.items():
hostvisiable = host.replace('.', '_')
self.results_raw['success'][hostvisiable] = result._result for host, result in self.results_callback.host_failed.items():
hostvisiable = host.replace('.', '_')
self.results_raw['failed'][hostvisiable] = result._result for host, result in self.results_callback.host_unreachable.items():
hostvisiable = host.replace('.', '_')
self.results_raw['unreachable'][hostvisiable] = result._result
return self.results_raw def run_playbook(self,extra_vars=None):
if extra_vars: self.variable_manager.extra_vars = extra_vars
playbook = PlaybookExecutor(playbooks=['/root/test.yml'], inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader, options=self.options, passwords=self.passwords) playbook._tqm._stdout_callback = self.Playbook_results_callback
results = playbook.run() def get_playbook_result(self):
##定义字典用于接收或者处理结果
self.result_raw = {'success': {}, 'failed': {}, 'unreachable': {}, 'skipped': {}, 'status': {}} # 循环打印这个结果,success,failed,unreachable需要每个都定义一个
for host, result in self.Playbook_results_callback.task_ok.items():
self.result_raw['success'][host] = result._result for host, result in self.Playbook_results_callback.task_failed.items():
self.result_raw['failed'][host] = result._result for host, result in self.Playbook_results_callback.task_unreachable.items():
self.result_raw['unreachable'][host] = result._result for host, result in self.Playbook_results_callback.task_skipped.items():
self.result_raw['skipped'][host] = result._result for host, result in self.Playbook_results_callback.task_stats.items():
self.result_raw['status'][host] = result._result return self.result_raw c = Runner() c.run_ad_hoc()
c.run_playbook()
print (c.get_adhoc_result(),c.get_playbook_result())
模板
ansible Api 2.3-2.4的更多相关文章
- Python调用ansible API系列(五)综合使用
如何把动态生成资产信息.执行playbook以及自定义结果结合起来用呢? #!/usr/bin/env python # -*- coding: utf-8 -*- """ ...
- Python调用ansible API系列(四)动态生成hosts文件
方法一:通过最原始的操作文件的方式 #!/usr/bin/env python # -*- coding: utf-8 -*- """ 通过操作文件形式动态生成ansib ...
- ansible api 调用出现ssh交互式输入
发现在删掉 ~/.ssh/know_hosts 之后运行 ansible api 会出现以下提示 The authenticity of host '10.1.*.* (10.1.*.*)' can' ...
- ansible API(开发应用)
7. ansible API(开发应用) 官网链接
- windows下使用pycharm开发基于ansible api的python程序
Window下python安装ansible,基于ansible api开发python程序 在windows下使用pycharm开发基于ansible api的python程序时,发现ansible ...
- ansible api
##一个简单的python脚本,通过ansible的api调用get_url模块实现远程下载功能 #!/usr/bin/env python import json import ansible.ru ...
- Python调用ansible API系列(三)带有callback的执行adhoc和playbook
在第二篇文章中虽然可以执行adhoc和playbook但是执行结果的输出并不是特别直观,虽然没有报错但是到底什么结果其实你是不知道的尤其是在执行adhoc的时候,这时候我们要利用callback来设置 ...
- Python调用ansible API系列(一)获取资产信息
你想让ansible工作首先就需要设置资产信息,那么我们如何通过使用Python调取Ansible的API来获取资产信息呢? 要提前准备一个hosts文件 获取组或者主机 #!/usr/bin/env ...
- python学习之ansible api
Python API 2.0 从2.0的事情开始更复杂一些,但是你会得到更多离散和可读的类: #!/usr/bin/env python import json from collections im ...
随机推荐
- @ControllerAdvice+@ExceptionHandler处理架构异常捕获
1.注解引入 1) @ControllerAdvice - 控制器增强 @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) ...
- Educational Codeforces Round 53 (Rated for Div. 2) C. Vasya and Robot
题意:给出一段操作序列 和目的地 问修改(只可以更改 不可以删除或添加)该序列使得最后到达终点时 所进行的修改代价最小是多少 其中代价的定义是 终点序号-起点序号-1 思路:因为代价是终点序号减去 ...
- 「NOI2003」逃学的小孩
传送门:>HERE< 题意:给出一棵树(带权),要从一个节点C先走到距离它近的一个节点B,再走到A,要求最坏情况下的总路程(即最长). 解题思路: 乍一看,A,B,C都没给出,这怎么求? ...
- Sudoku POJ - 3076
Sudoku Time Limit: 10000MS Memory Limit: 65536K Total Submissions: 5769 Accepted: 2684 Descripti ...
- Leetcode 80.删除排序数组中的重复项 II By Python
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素最多出现两次,返回移除后数组的新长度. 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成. 示例 ...
- wcf 发布到iis后报错
HTTP Error 404.3 - Not Found http://iweb.adefwebserver.com/Default.aspx?tabid=57&EntryID=34 未能从程 ...
- Nginx优化文件编写
server_tokens off; #并不会让nginx执行的速度更快,关闭它可隐藏错误页面中的nginx版本号charset utf-8,gbk; #字符#sendfile on;#tcp_nop ...
- 为什么分布式一定要有redis?
为什么分布式一定要有redis? 孤独烟 架构师小秘圈 昨天 作者:孤独烟 来自:http://rjzheng.cnblogs.com/ 1.为什么使用redis 分析:博主觉得在项目中使用red ...
- 纪中2018暑假培训day1提高b组改题记录
收到意见,认为每天的程序和随笔放在一起写的博客太长了,于是分开整理 day1 模拟赛,看了看提高a组t1的样例就不太想写,于是转而写b组 t1: Description 给定一个n个点m条边的有向图, ...
- MVC aspx
客户端服务器---Model(模型)---View(视图)---Control(控制器) 1.ASP.NET MVC 2.新建项目引擎选aspx.在Controllers创建控制器,默认启动Home ...