模块

命令行

// ping 模块
$ ansible localhost -m ping
localhost | success >> {
"changed": false,
"ping": "pong"
}
// shell 模块
$ ansible localhost -m shell -a 'uptime'
localhost | success | rc=0 >>
11:00:11 up 66 days, 23:34, 1 user, load average: 0.00, 0.01, 0.05

Python API

通过ansible.runner模块来实现

使用API实现ping模块功能:

#!/usr/bin/env python
import ansible.runner
import json
runner = ansible.runner.Runner(
module_name='ping', //模块名
module_args='', //模块参数
pattern='localhost', //匹配主机或主机组
forks=2 //多线程
)
data = runner.run()
print data //打印输出结果默认json格式
//stdout
{'dark': {}, 'contacted': {'localhost': {'invocation': {'module_name': 'ping', 'module_args': ''}, u'changed': False, u'ping': u'pong'}}}

由于输出结果默认是json格式,那么我们可以格式化一下,让它更美观

sort_keys 按key排序
indent 缩进
separators 指定分隔符(默认分隔符', ',使用',',': ' 避免尾部空格)

上例中的输出格式化:

print json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')) //对json格式化输出
//stdout
{
"contacted": {
"localhost": {
"changed": false,
"invocation": {
"module_args": "",
"module_name": "ping"
},
"ping": "pong"
}
},
"dark": {}
}

使用API实现shell模块功能

#!/usr/bin/env python
import ansible.runner
import json
runner = ansible.runner.Runner(
module_name='shell',
module_args='uptime',
pattern='localhost',
forks=2
)
data = runner.run()
print json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))
//stdout
{
"contacted": {
"localhost": {
"changed": true,
"cmd": "uptime",
"delta": "0:00:00.002573",
"end": "2016-11-04 14:57:26.549208",
"invocation": {
"module_args": "uptime",
"module_name": "shell"
},
"rc": 0,
"start": "2016-11-04 14:57:26.546635",
"stderr": "",
"stdout": " 14:57:26 up 67 days, 3:31, 1 user, load average: 0.00, 0.06, 0.07"
}
},
"dark": {}
}

打印stdout

#!/usr/bin/env python
import ansible.runner
def result(contacted):
for k,v in contacted.items():
if k == 'stdout':
print v
def ping_module():
runner = ansible.runner.Runner(
module_name='ping',
module_args='',
pattern='localhost',
forks=2
)
data = runner.run()
print data
def shell_module():
runner = ansible.runner.Runner(
module_name='shell',
module_args='uptime',
pattern='localhost',
forks=2
)
data = runner.run()
result(data['contacted']['localhost'])
if __name__ == '__main__':
shell_module()
//stdout
15:34:09 up 67 days, 4:07, 1 user, load average: 0.00, 0.01, 0.05

playbook

playbook描述了在远程主机上执行的策略或一组任务

一个playbook文件由一个或多个play组成,每个play定义了一系列的task,每个task通过ansible的模块来实现特定的功能

exp.yml (playbook使用YAML语言编写,文件名以.yaml或.yml结尾)

- hosts: localhost_group //主机组
tasks:
- name: kernel release info //task1
command: uname -a
- name: memory info //task2
shell: free -m

这个playbook可以查看远程主机的内核版本信息和内存信息

ansible-playbook命令

命令行执行playbook

$ ansible-playbook -i /etc/ansible/hosts test.yml
PLAY [localhost_group] ********************************************************
GATHERING FACTS ***************************************************************
ok: [localhost]
TASK: [kernel info] ***********************************************************
changed: [localhost]
TASK: [memory info] ***********************************************************
changed: [localhost]
PLAY RECAP ********************************************************************
localhost : ok=3 changed=2 unreachable=0 failed=0

Python API

# encoding=utf8
#!/usr/bin/python
import ansible.runner
import ansible.playbook
import ansible.inventory
from ansible import callbacks
from ansible import utils
import json
playbook_path = "/home/ubuntu/scripts/exp.yml"
##添加主机信息
host = ansible.inventory.host.Host(
name = 'localhost'
)
##设置主机组并添加主机
group = ansible.inventory.group.Group(
name = 'localhost_group'
)
group.add_host(host)
##主机列表
example_inventory = ansible.inventory.Inventory()
example_inventory.add_group(group)
#回调信息
stats = callbacks.AggregateStats()
playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY)
runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY)
#创建实例,playbook位于playbook_path
pb = ansible.playbook.PlayBook(
playbook = playbook_path,
stats = stats,
callbacks = playbook_cb,
runner_callbacks = runner_cb,
inventory = example_inventory,
subset = 'all',
)
#运行playbook
pr = pb.run()
#打印结果
print json.dumps(pr, sort_keys=True, indent=4, separators=(',', ': '))

//stdout

PLAY [localhost_group] ********************************************************
GATHERING FACTS ***************************************************************
ok: [localhost]
TASK: [kernel info] ***********************************************************
changed: [localhost]
TASK: [memory info] ***********************************************************
changed: [localhost]
{
"localhost": {
"changed": 2,
"failures": 0,
"ok": 3,
"skipped": 0,
"unreachable": 0
}
}

ansible.runner更多信息

>>> import ansible.runner
>>> dir(ansible.runner)
['C', 'DefaultRunnerCallbacks', 'HAS_ATFORK', 'HostVars', 'ModuleReplacer', 'OUTPUT_LOCKFILE', 'PROCESS_LOCKFILE', 'Queue', 'ReturnData', 'Runner', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '_executor_hook', 'ansible', 'atfork', 'base64', 'check_conditional', 'collections', 'connection', 'errors', 'getpass', 'jinja2', 'module_common', 'module_replacer', 'multiprocessing', 'multiprocessing_runner', 'os', 'pipes', 'poller', 'pwd', 'random', 'return_data', 'signal', 'socket', 'split_args', 'string_functions', 'subprocess', 'sys', 'tempfile', 'template', 'time', 'traceback', 'utils', 'vv']
>>> help(ansible.runner.Runner)

Python yaml 模块自定义playbook

define_yaml.py

#!/usr/bin/env python
import yaml
import os
playbook_path = '/home/ubuntu/scripts'
Yml_args = {}
Yml = []
Yml_args["gather_facts"] = False
Yml_args["hosts"] = "localhost_group"
Yml_args["remote_user"] = "ubuntu"
Yml_task = []
Yml_task.append({'shell': 'uptime', 'name': 'uptime info'})
Yml_task.append({'shell': 'free -m', 'name': 'memory info'})
Yml_args["tasks"] = Yml_task
Yml.append(Yml_args)
Yml = yaml.dump(Yml)
Yml_path = os.path.join(playbook_path, "exp.yml")
with open(Yml_path, 'w') as f:
f.write(Yml)

运行并检测:

$ python define_yaml.py
$ ansible-playbook -i /etc/ansible/hosts exp.yml
PLAY [localhost_group] ********************************************************
TASK: [uptime info] ***********************************************************
changed: [localhost]
TASK: [memory info] ***********************************************************
changed: [localhost]
PLAY RECAP ********************************************************************
localhost : ok=2 changed=2 unreachable=0 failed=0
$ cat exp.yml
- gather_facts: false
hosts: localhost_group
remote_user: ubuntu
tasks:
- {name: uptime info, shell: uptime}
- {name: memory info, shell: free -m}

参考

Ansible Python API