Ansible作为python模块库使用
Posted python运维技术
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ansible作为python模块库使用相关的知识,希望对你有一定的参考价值。
最近在后台发送消息的小伙伴我没能回复的,比较抱歉,因为平时比较忙消息可能无法及时回复,还请尽可能选择留言的方式进行交流,以下是正文:
Asible是运维工具中算是非常好的利器,我个人比较喜欢,可以根据需求灵活配置yml文件来实现不同的业务需求,因为不需要安装客户端,上手还是非常容易的,在某些情况下你可能需要将ansible作为python的一个库组件写入到自己的脚本中,今天的脚本脚本就将展示下ansible如何跟python脚本结合,也就是如何在python脚本中使用ansible,我们逐步展开,先看第一个例子:
#!/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=(',', ': '))
这个例子展示我们如何在python脚本中运行如何通过ansible运行系统命令.
我们接下来看第二个例子,跟我们的yml文件对接,简单的yml文件内容如下:
- hosts: sample_group_name
tasks:
- name: just an uname
command: uname -a
调用playbook的python脚本如下:
#!/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=(',', ': '))
今天展示2个小例子希望对大家有帮助。
以上是关于Ansible作为python模块库使用的主要内容,如果未能解决你的问题,请参考以下文章
Ansible------Ansible概述,搭建,常用模块介绍