ansible在playbook中变量传入到执行脚本的方法

匆匆过客 提交于 2020-03-27 15:31:52

3 月,跳不动了?>>>

简介

这个方式用于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 }}"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!