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.pswp.cn/news/450906.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/450906.shtml
英文地址,請注明出處:http://en.pswp.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;并且可確保各用…