##腳本說明服務器
project -- 操做的項目輸入app
playbook -- 遠程服務器執行的規則定義code
import ansible from ansible.playbook import PlayBook from ansible.inventory import Inventory from ansible import callbacks from ansible import utils utils.VERBOSITY = 0 playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY) stats = callbacks.AggregateStats() runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY) project = "test" playbook = "/etc/ansible/test.yml" # 經過ansible的get_hosts方法獲取到本次操做的服務器列表 def get_invent(project): invent = [] inv = ansible.inventory.Inventory() invent_array = inv.get_hosts(pattern = project) for i in invent_array: invent.append(i.name) return invent # 將本次操做的服務器列表經過playbook的規則進行操做 def ansible_playbook(playbook,pro): pb = PlayBook( playbook=playbook, inventory = Inventory(pro), callbacks = playbook_cb, runner_callbacks=runner_cb, stats=stats ) pb.run() invent = get_invent(project) ansible_playbook(playbook, invent)