ansible系列之:ansible-playbook传递变量参数,使用python代码执行ansible命令

ansible系列之:ansible-playbook传递变量参数,使用python代码执行ansible命令

  • 一、task yaml中存在变量{{ flumeAgentName }}
  • 二、ansible-playbook命令中传入变量{{ flumeAgentName }}参数的值
  • 三、ansible-playbook目录结构
  • 四、python代码执行ansible命令

一、task yaml中存在变量{{ flumeAgentName }}

start.yml

---
- name: start flume agent
  shell: "systemctl start {{ flumeAgentName }}"
  args:
    executable: /bin/bash

二、ansible-playbook命令中传入变量{{ flumeAgentName }}参数的值

ansible-playbook start.yml --inventory=inventories/teflume --user=f --private-key=/Users/f/f.private_key --ssh-common-args='-o ProxyCommand="/usr/local/bin/ncat --proxy opticslinux-nj.nioint.com:8080 --proxy-type http %h %p"' --extra-vars flumeAgentName=flume-stg-test

三、ansible-playbook目录结构

ansible系列之:ansible-playbook传递变量参数,使用python代码执行ansible命令_第1张图片

四、python代码执行ansible命令

import os
import datetime


flumeAgentList = []

#判断存活的flume agent
def startFlumeAgent(user, privateKeyPath, flumeAgentList):

    for flumeAgent in flumeAgentList:
        print(f"开始启动的flume agent的名称为{flumeAgent}:",end="")
        stopCommand = f"""
            ansible-playbook start.yml --inventory=inventories/teflume --user=f --private-key=/Users/{user}/{user}.private_key --ssh-common-args='-o ProxyCommand="/usr/local/bin/ncat --proxy opticslinux-nj.nioint.com:8080 --proxy-type http %h %p"' --extra-vars flumeAgentName={flumeAgent}
        """

        print(stopCommand)

        os.chdir("/Users/f/PycharmProjects/firstProject/teflume/flumeAnsible")

        #执行stop命令
        commandOutput = os.popen(stopCommand).read().strip()

        #判断agent是否启动成功
        if commandOutput.find("failed=0") != -1 and commandOutput.find("unreachable=0") != -1:
            info = f"flume告警:{flumeAgent}启动成功"
        else:
            info = f"flume告警:{flumeAgent}启动失败"


    print(f"**********************flume agent全部启动成功*************************")

    print("")
    print("")
    print("")
    print("")




if __name__ == "__main__":
    now=datetime.datetime.now()
    cur=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print(f"当前时间:{cur}")
    print("----------------------开始运行程序------------------------")

    user = "f"
    privateKeyPath = f"/Users/{user}/{user}.private_key"

    # 每次停止flume agent前先调用获取全部正在运行的flume agent程序
    # 替换这部分
    flumeAgentList = ['flume-stg-test_0407\n','flume-stg-kafka_0406\n']
    startFlumeAgent(user, privateKeyPath, flumeAgentList)

你可能感兴趣的:(日常分享专栏,ansible系列,playbook,python)