django集成ansibe实现自动化

动态生成主机列表和相关参数

def create_admin_domain(admin_node):workpath = BASE_DIR + '/tools/ansible/script'hosts_file = BASE_DIR + '/tools/ansible/host/' + createhostfile()yml_file = BASE_DIR + '/tools/ansible/yml/' + 'create_admin_domain.yml'domain_path = admin_node.domainpathapp_server_name=admin_node.app_server_namehost_ip = admin_node.asset_ipansible_ssh_user = admin_node.usernameansible_ssh_pass = admin_node.passwordwith open(hosts_file, 'w+') as f:f.writelines('[app_admin_domain]\n')domain_args = "%s-%s ansible_host=%s ansible_ssh_user=%s ansible_ssh_pass=%s domain_path=%s\n" % (host_ip,app_server_name,host_ip, ansible_ssh_user, ansible_ssh_pass, domain_path)f.writelines(domain_args)cmd = 'ansible-playbook -i %s %s --extra-vars "workpath=%s"' % (hosts_file, yml_file, workpath)print(cmd)p = Popen(cmd, stderr=PIPE, stdout=PIPE, shell=True)data = p.communicate()if p.returncode == 0:print("执行成功")else:print("执行失败")
动态生成参数代码
[app_admin_domain]
10.199.137.5-itsgl ansible_host=10.199.137.5 ansible_ssh_user=weblogic ansible_ssh_pass=weblogic domain_path=/its/weblogic/user_projects/domains/itsgl_domain
生成结果

 动态生成ansible的主机文件的时候 要注意主机别名在不同的主机清单文件中不能重复 否则只会执行第一个主机清单   后面的清单文件不会被执行

 with open(hosts_file, 'w+') as f:f.writelines('[app_jmsmodule_servernode]\n')data_args="%s-jmsmodule-%s ansible_host=%s ansible_ssh_user=%s ansible_ssh_pass=%s" \" ip=%s port=%s datafile=%s\n" %(host_ip,generate_random_str(6),host_ip,ansible_ssh_user,ansible_ssh_pass,host_ip,port,jms.datafile)#%s-jmsmodule-%s 代表别名字符串  生成的字符串在每个hosts文件中必须是唯一的
View Code

 

编写yml文件

---- hosts: app_admin_domaintasks:- name: mkdir app_admin_domain directoryfile: path={{domain_path}}/ state=directory mode=0755- name: copy local war to admin pathcopy: src={{local_file}} dest={{domain_path}}/ backup=yes
View Code
---- hosts: app_jmsmodule_servernodetasks:- name: copy data file to remote hostcopy: src={{datafile}} dest=/its/weblogic/user_projects/domains/wlst/jmsmodule_data- name: create jmsmoduleshell: sh /its/weblogic/wlserver_10.3/common/bin/wlst.sh /its/weblogic/user_projects/domains/wlst/jmsmodule.py {{ip}} {{port}} /its/weblogic/user_projects/domains/wlst/jmsmodule_data
View Code
---- hosts: app_jms_servernodetasks:- name: create jms serversshell: sh /its/weblogic/wlserver_10.3/common/bin/wlst.sh  /its/weblogic/user_projects/domains/wlst/jmsserver.py {{ip}} {{port}} {{jmsname}} {{jmstarget}}
View Code
---- hosts: app_server_domaintasks:- name: check {{domain_path}} is exitsshell: ls {{domain_path}}ignore_errors: Trueregister: result- name: mkdir {{domain_path}} directoryfile: path={{domain_path}}/ state=directory mode=0755when: result|failed- name: copy mb file to {{domain_path}}copy: src={{local_file}}/ dest={{domain_path}} backup=yes- name: excute cpdomain shellshell: cd {{domain_path}} && bash cpdomain.sh {{appname}} {{apport}}
yml一次执行多条shell
---- hosts: app_server_domaintasks:- name: upload itsmb_domaincopy: src={{local_file}} dest={{domain_parent}}- name: check {{domain_path}} is exitsshell: ls {{domain_path}}ignore_errors: Trueregister: result- name: mkdir {{domain_path}} directoryfile: path={{domain_path}}/ state=directory mode=0755when: result|failed- name: copy mbmodain file to {{domain_path}}shell: cp -r {{domain_parent}}/itsmb_domain/*  {{domain_path}}- name: excute cpdomain shellshell: cd {{domain_path}} && bash cpdomain.sh {{appname}} {{apport}}
View Code

 

调试

(jade) [root@node3 jadehare]# ansible-playbook -i /mnt/hgfs/jadehare/tools/ansible/host/host_2018102310040032 /mnt/hgfs/jadehare/tools/ansible/yml/create_admin_domain.yml --extra-vars "workpath=/mnt/hgfs/jadehare/tools/ansible/script" -vvv
No config file found; using defaultsPLAYBOOK: create_admin_domain.yml *********************************************************************
1 plays in /mnt/hgfs/jadehare/tools/ansible/yml/create_admin_domain.ymlPLAY [app_admin_domain] *******************************************************************************TASK [Gathering Facts] ********************************************************************************
Using module file /root/.pyenv/versions/3.5.3/envs/jade/lib/python3.5/site-packages/ansible/modules/system/setup.py
<ansible_host=10.199.137.5> ESTABLISH SSH CONNECTION FOR USER: weblogic
<ansible_host=10.199.137.5> SSH: EXEC sshpass -d12 ssh -C -o ControlMaster=auto -o ControlPersist=60s -o User=weblogic -o ConnectTimeout=10 -o ControlPath=/root/.ansible/cp/471b94e774 ansible_host=10.199.137.5 '/bin/sh -c '"'"'echo ~ && sleep 0'"'"''
<ansible_host=10.199.137.5> (255, b'', b'ssh: Could not resolve hostname ansible_host=10.199.137.5: Name or service not known\r\n')
fatal: [ansible_host=10.199.137.5]: UNREACHABLE! => {"changed": false,"msg": "Failed to connect to the host via ssh: ssh: Could not resolve hostname ansible_host=10.199.137.5: Name or service not known\r\n","unreachable": true
}to retry, use: --limit @/mnt/hgfs/jadehare/tools/ansible/yml/create_admin_domain.retryPLAY RECAP ********************************************************************************************
ansible_host=10.199.137.5  : ok=0    changed=0    unreachable=1    failed=0   (jade) [root@node3 jadehare]# ansible-playbook -i /mnt/hgfs/jadehare/tools/ansible/host/host_2018102310310691 /mnt/hgfs/jadehare/tools/ansible/yml/create_admin_domain.yml --extra-vars "workpath=/mnt/hgfs/jadehare/tools/ansible/script"PLAY [app_admin_domain] *********************************************************************************TASK [Gathering Facts] **********************************************************************************
ok: [10.199.137.5]TASK [mkdir app_admin_domain directory] *****************************************************************
ok: [10.199.137.5]TASK [copy local war to admin path] *********************************************************************
fatal: [10.199.137.5]: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'local_file' is undefined\n\nThe error appears to have been in '/mnt/hgfs/jadehare/tools/ansible/yml/create_admin_domain.yml': line 6, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n      file: path={{domain_path}}/ state=directory mode=0755\n    - name: copy local war to admin path\n      ^ here\n"}to retry, use: --limit @/mnt/hgfs/jadehare/tools/ansible/yml/create_admin_domain.retryPLAY RECAP **********************************************************************************************
10.199.137.5               : ok=2    changed=0    unreachable=0    failed=1   
View Code

 

问题

  1.you must install the sshpass program

只需要安装sshpass即可,CentOS系统的默认yum源里面并没有这个软件
在ansible主机上安装好即可$ wget http://sourceforge.net/projects/sshpass/files/latest/download -O sshpass.tar.gz 
$ tar -xvf sshpass.tar.gz 
$ cd sshpass-1.06 
$ ./configure 
$ sudo make install  
View Code

 

2.Failed to connect to the host via ssh: ssh: Could not resolve hostname ansible_host=10.199.137.5: Name or service not known

  在执行ansible或者ansible-playbook命令的时候 不能直接指定IP地址 必须使用别名

[beijing]
1.1.1.1-aa    ansible_host=1.1.1.1
1.1.1.2-bb    ansible_host=1.1.1.2
1.1.1.3-cc    ansible_host=1.1.1.3[root]# ansible beijing -m ping
1.1.1.1-aa | SUCCESS => {"changed": false,"ping": "pong"
}
1.1.1.3-bb | SUCCESS => {"changed": false,"ping": "pong"
}
1.1.1.2-cc | SUCCESS => {"changed": false,"ping": "pong"单独使用host里1.1.1.1这个IP会显示没有符合
[root@ansible ansible]# ansible 1.1.1.1 -m ping[WARNING]: Could not match supplied host pattern, ignoring: 1.1.1.1 需要使用别名才能正常运行
[root@ansible ansible]# ansible 1.1.1.1-aa -m ping
1.1.1.1-aa | SUCCESS => {"changed": false,"ping": "pong"
}这就要求我们在动态生成主机清单文件的时候必须生成一个别名 否则会出现异常
格式如下 10.199.137.5-itsgl就是一个别名字符串
10.199.137.5-itsgl ansible_host=10.199.137.5 
别名解决方案

 

3.ansible playbook判断指定的目录或者文件是否存在

---- hosts: app_server_domaintasks:- name: check {{domain_path}} is exitsshell: ls {{domain_path}}ignore_errors: Trueregister: result- name: mkdir {{domain_path}} directoryfile: path={{domain_path}}/ state=directory mode=0755when: result|failed- name: copy mb file to {{domain_path}}copy: src={{local_file}}/ dest={{domain_path}} backup=yeswhen: result|failed- name: excute cpdomain shellshell: sh {{domain_path}}/cpdomain.shwhen: result|failed
yml语法
ansible 的常用模块中没有判定当文件存在或者不存在时执行某个命令---- name: judge a file or dir is exitsshell: ls /home/sfyignore_errors: Trueregister: result- shell: echo "file exit"when: result|succeeded- shell: echo "file not exit"when: result|failed
View Code

 

django把复杂数据结构参数传递给后台脚本

    1.由django把数据内容写入指定的文件

    2.调用脚本的时候把文件路径传递给脚本

    3.脚本读取指定路径的文件内容

    with open(jms.datafile,'w+') as f:dict={}dict["name"]=jms.jmsmodule_namedict["resources"]=[]resourcelist=JmsModuleSet.objects.all().filter(jmsmodule=jms.id)for res in resourcelist:dict["resources"].append({"resourcename":res.resource_name,"type":res.jmsmoduleset_type})dict["targets"]=[]taglist=jms.server_list.all()for tag in taglist:dict["targets"].append(tag.app_server_name)f.write(str(dict))writelogfile(jms.deploylogfile,"%s 写内容入完毕" %jms.datafile)
views中被内容写入文件
import osdef create_jmsmodule(ip,port,filename):f = open(filename, "r")re = f.read()jsmodule = eval(re)f.close()wls:/itsgl_domain/edit !> f=open("/wlst/jmsmodule_data","r")
wls:/itsgl_domain/edit !> re=f.read()
wls:/itsgl_domain/edit !> print re
{'resources': [{'resourcename': 'aa1111', 'type': 'queue'}, {'resourcename': 'aaa2', 'type': 'connectFactory'}], 'targets': ['wtjscxnw', 'wtmhnw'], 'name': 'aaaa'}
wls:/itsgl_domain/edit !> obj=eval(re)
wls:/itsgl_domain/edit !> print obj
{'targets': ['wtjscxnw', 'wtmhnw'], 'name': 'aaaa', 'resources': [{'type': 'queue', 'resourcename': 'aa1111'}, {'type': 'connectFactory', 'resourcename': 'aaa2'}]}
wls:/itsgl_domain/edit !> 
脚本读取文件内容
def jms_add(request):apps_id = request.GET.get('mid', '')jmsobj= JmsModule.objects.filter(id=apps_id)[0]if request.POST:apps_form = JmsModuleSetForm(request.POST)apps_form.instance.jmsmodule=jmsobj
django保存外键对象

 

 

ansible查看详细命令执行情况

(jade) [root@node3 jadehare]# ansible-playbook -i /mnt/hgfs/jadehare/tools/ansible/host/host_2018102611079748 /mnt/hgfs/jadehare/tools/ansible/yml/create_server_domain.yml --extra-vars "workpath=/mnt/hgfs/jadehare/tools/ansible/script" -vvv详细信息如下:
changed: [10.199.137.5-createserver-6FUGa1] => {"changed": true,"cmd": "bash /its/weblogic/user_projects/domains/wtdsrwnw_domain/cpdomain.sh wtdsrwnw 8111","delta": "0:00:00.038308","end": "2018-10-26 11:16:14.366728","invocation": {"module_args": {"_raw_params": "bash /its/weblogic/user_projects/domains/wtdsrwnw_domain/cpdomain.sh wtdsrwnw 8111","_uses_shell": true,"chdir": null,"creates": null,"executable": null,"removes": null,"warn": true}},"rc": 0,"start": "2018-10-26 11:16:14.328420","stderr": "sed:无法读取 startWebLogic.sh:没有那个文件或目录\nsed:无法读取 bin/startWebLogic.sh:没有那个文件或目录\nsed:无法读取 bin/setDomainEnv.sh:没有那个文件或目录\nsed:无法读取 bin/stopWebLogic.sh:没有那个文件或目录\nsed:无法读取 bin/startManagedWebLogic.sh:没有那个文件或目录\nsed:无法读取 bin/stopManagedWebLogic.sh:没有那个文件或目录\nsed:无法读取 init-info/startscript.xml:没有那个文件或目录\nsed:无法读取 init-info/tokenValue.properties:没有那个文件或目录\nsed:无法读取 config/config.xml:没有那个文件或目录\nsed:无法读取 config/config.xml:没有那个文件或目录\nsed:无法读取 bin/setDomainEnv.sh:没有那个文件或目录","stderr_lines": ["sed:无法读取 startWebLogic.sh:没有那个文件或目录","sed:无法读取 bin/startWebLogic.sh:没有那个文件或目录","sed:无法读取 bin/setDomainEnv.sh:没有那个文件或目录","sed:无法读取 bin/stopWebLogic.sh:没有那个文件或目录","sed:无法读取 bin/startManagedWebLogic.sh:没有那个文件或目录","sed:无法读取 bin/stopManagedWebLogic.sh:没有那个文件或目录","sed:无法读取 init-info/startscript.xml:没有那个文件或目录","sed:无法读取 init-info/tokenValue.properties:没有那个文件或目录","sed:无法读取 config/config.xml:没有那个文件或目录","sed:无法读取 config/config.xml:没有那个文件或目录","sed:无法读取 bin/setDomainEnv.sh:没有那个文件或目录"],"stdout": "","stdout_lines": []
}
META: ran handlers
META: ran handlersPLAY RECAP **********************************************************************************************
10.199.137.5-createserver-6FUGa1 : ok=4    changed=2    unreachable=0    failed=0 
调试选项

 

转载于:https://www.cnblogs.com/yxh168/p/9835437.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/450906.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

extend 对象继承

function extend(o, n, override) {for (var p in n) {if (n.hasOwnProperty(p) && (!o.hasOwnProperty(p) || override))o[p] n[p];} }// 默认参数 var options {pageIndex: 1,pageTotal: 2 };// 新设置参数 var userOptions {pageIndex: 3,pageSize: 10 }extend(o…

【spring容器启动】之bean的实例化和初始化(文末附:spring循环依赖原理)

本次我们通过源码介绍ApplicationContext容器初始化流程&#xff0c;主要介绍容器内bean的实例化和初始化过程。ApplicationContext是Spring推出的先进Ioc容器&#xff0c;它继承了旧版本Ioc容器BeanFactory&#xff0c;并进一步扩展了容器的功能&#xff0c;增加了bean的自动识…

如何将自己的Java项目部署到外网

见&#xff1a;http://jingyan.baidu.com/article/90bc8fc864699af653640cf7.html 做b/s模式的web开发不同于c/s模式的客户端开发&#xff0c;c/s模式我们只要做好生成可执行文件发送给其他人&#xff0c;其他人就可以用了。但是c/s模式不同&#xff0c;在同一局域网下&#xf…

[Swift]LeetCode916.单词子集 | Word Subsets

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号&#xff1a;山青咏芝&#xff08;shanqingyongzhi&#xff09;➤博客园地址&#xff1a;山青咏芝&#xff08;https://www.cnblogs.com/strengthen/&#xff09;➤GitHub地址&a…

揭秘腾讯研究院输出策略:产品和人才的孵化器

直到现在&#xff0c;腾讯研究院创始人郑全战仍坚持面试招入研究院的每一个人&#xff0c;并做详细记录。天赋上的灵性、性格中的包容是他看重的&#xff0c;当然首先人要踏实。大约6年前&#xff0c;郑全战加入腾讯&#xff0c;负责筹建中国互联网公司中的第一个研究院&#x…

java后端必会【基础知识点】

&#xff08;一&#xff09;java集合类&#xff08;done&#xff09; 在java集合类中最常用的是Collection和Map的接口实现类。Collection又分为List和Set两类接口&#xff0c;List的实现类有ArrayList、LinkedList、Vector、Stack&#xff0c;Set接口的实现类有HashSet、Tree…

无法连接虚拟设备ide1:0,主机上没有相对应的设备... 解决

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 运行虚拟机出现报错&#xff1a; 无法连接虚拟设备ide1:0&#xff0c;主机上没有相对应的设备&#xff0c;您 要在每次开启此虚拟机时都…

缴满15年能领多少钱 养老金计算公式网上疯传

社保人员称我省计算方式与各设区市平均工资挂钩&#xff0c;与网上不同 最近&#xff0c;关于“延迟退休”引起各方高度关注&#xff0c;成为广大居民十分关心的话题。是否延迟退休尚无定论&#xff0c;但在网上有不少关于养老金的计算。那网上流传的计算方法是否科学&#xff…

48_并发编程-线程-资源共享/锁

一、数据共享多个线程内部有自己的数据栈&#xff0c;数据不共享&#xff1b;全局变量在多个线程之间是共享的。1 # 线程数据共享不安全加锁2 3 import time4 from threading import Thread, Lock5 6 7 num 1008 9 def func(t_lock): 10 global num 11 t_lock.acquire…

移动硬盘提示无法访问设备硬件出现致命错误,导致请求失败的资料寻回方案

J盘打不开设备硬件出现致命错误,导致请求失败&#xff0c;是因为这个I盘的文件系统内部结构损坏导致的。要恢复里面的数据就必须要注意&#xff0c;这个盘不能格式化&#xff0c;否则数据会进一步损坏。具体的恢复方法看正文 工具/软件&#xff1a;星空数据恢复软件 步骤1&…

VMware10上新建虚拟机步骤图解

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 第一种 : 自定义方式&#xff1a; 安装虚拟机的过程步骤&#xff0c;基本上过程的每一步都有截图&#xff0c;跟着过程就可以很容易的创…

怎么理解 IaaS、SaaS 和 PaaS 的区别?

原文链接&#xff1a;怎么理解 IaaS、SaaS 和 PaaS 的区别&#xff1f; 一、定义层面的区别 SaaS、PaaS、IaaS简单的说都属于云计算服务&#xff0c;也就是云计算服务。我们对于云计算的概念&#xff0c;维基百科有以下定义&#xff1a; Cloud computing is a new form of In…

三星“打法”:先模仿对手 再吃掉对手

台湾地区电子业者将三星视为“台湾公敌”&#xff0c;事实上&#xff0c;它几乎是全球电子业者的敌人。 这家韩国电子业巨头十年之间夺取了日本企业在这一领域中纵横30年的荣光&#xff0c;更是建立起了令人叹为观止的垂直整合帝国。 韩国政府的大力支持、日元升值韩元贬值等均…

SharpZipLib 压缩ZIP导出

1      var uploadSectionDir Path.Combine("Upload", "QQ", DateTime.Now.ToString("yyyyMMdd"));2 string uploadDir Path.Combine(HttpRuntime.AppDomainAppPath, uploadSectionDir);3 if (!Directory.Exi…

java动态调用c++库

前言 最近在做一个通过java程序调用c动态语言库&#xff0c;在网上百度&#xff0c;谷歌找了诸多例子&#xff0c;还是屡试不爽。经过一番折腾还是披荆斩棘&#xff0c;创出一条道路。希望分享给正在迷茫的朋友们... 使用的环境 spring boot gradle JNI介绍 JNI全拼是Java Nat…

如何删除虚拟机上的操作系统、删除新建的虚拟机

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 打开VMware&#xff0c;我安装了三个虚拟系统&#xff0c;要对win98进行删除&#xff0c;从磁盘上删除~~ 2、双击你要删除的系统&#xf…

什么是QoS技术

QoS&#xff08;Quality of Service&#xff09;是服务质量的简称。从传统意义上来讲&#xff0c;无非就是传输的带宽、传送的时延、数据的丢包率等&#xff0c;而提高服务质量无非也就是保证传输的带宽&#xff0c;降低传送的时延&#xff0c;降低数据的丢包率以及时延抖动等。…

一套完整的用户增长系统架构

互联网的世界里一切都是为了增长&#xff0c;灵光一现的创新可能会让一个产品成功&#xff0c;但绝不可能长久。 在用户增长的领域里&#xff0c;如何复用一套框架&#xff0c;找到最佳实践的一条路径&#xff0c;再配备一点运气&#xff0c;去实现商业成功是我一直所探索的话题…

编译性语言、解释性语言和脚本语言

什么是编译性语言、解释性语言和脚本语言 计算机不能直接理解高级语言&#xff0c;只能直接理解机器语言&#xff0c;所以必须要把高级语言翻译成机器语言&#xff0c;计算机才能值型高级语言编写的程序。  翻译的方式有两种&#xff0c;一个是编译&#xff0c;一个是解释。…

对多租户的理解

一、 多租户定义 多租户定义&#xff1a; 多租户技术或称多重租赁技术&#xff0c;简称SaaS&#xff0c;是一种软件架构技术&#xff0c;是实现如何在多用户环境下&#xff08;此处的多用户一般是面向企业用户&#xff09;共用相同的系统或程序组件&#xff0c;并且可确保各用…