简介
这个方式用于ansible调用playbook方法实现远程服务器执行某个脚本,脚本中的某些参数需要由管理服务器传入的情况。
下面的例子是ansible实际调用script模块实现远程服务器执行一个shell脚本
脚本内容
ansible 执行脚本
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# edit: mesopodamia@gmail.com
import ansible
from ansible.playbook import PlayBook
from ansible.inventory import Inventory
from ansible import callbacks
from ansible import utils
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
vars = "hello world"
ansible_command = "/usr/local/bin/ansible-playbook"
playbook = "/home/eric/playbook/deploy.yml"
hosts = ['192.168.0.99']
# Boilerplace callbacks for stdout/stderr and log output
utils.VERBOSITY = 0
playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY)
stats = callbacks.AggregateStats()
runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY)
# pro输入数据是列表
def ansible_playbook(playbook,pro,vars):
pb = PlayBook(
playbook=playbook,
inventory = Inventory(pro),
callbacks = playbook_cb,
runner_callbacks = runner_cb,
stats = stats,
extra_vars = {'var':vars}
)
return pb.run()
if __name__ == "__main__":
ansible_playbook(playbook,hosts,vars)
远程调用脚本(eric.sh)
#!/usr/bin/env bash
echo `date` > /tmp/date.txt
echo $1 > /tmp/date.txt
ansible中playbook的设置
playbook的定义(deploy.yml)
- hosts: all
roles:
- role: init
具体的角色init中task的main.yml定义
- script: ~/bin/eric.sh "{{ var }}"
来源:oschina
链接:https://my.oschina.net/u/96940/blog/519991