最近問了個朋友關(guān)于代碼發(fā)布的問題,他們測試環(huán)境是用webhook,線上用的則是ansible。
介紹
那ansible是什么呢?在它的github主頁介紹有段話
Ansible is a radically simple IT automation system. It handles configuration-management, application deployment, cloud provisioning, ad-hoc task-execution, and multinode orchestration - including trivializing things like zero downtime rolling updates with load balancers.
翻譯下來就是:
ansible是一個很簡單的IT自動化系統(tǒng)持痰。它可以用來進行配置管理,應(yīng)用部署祟蚀,云資源分配工窍,執(zhí)行ad-hoc任務(wù),還有多節(jié)點編排 - 包括瑣碎的事情前酿,如零停機更新與負載均衡器患雏。
安裝
- ubuntu
sudo apt-get install ansible
安裝后的配置文件在/etc/ansible/
目錄,ansible.cfg為ansible配置文件罢维,hosts為遠程主機配置文件
- pip安裝
若還未安裝pip(安裝和管理python包的工具)淹仑,可執(zhí)行下列命令安裝
sudo easy_install pip
然后安裝pip
sudo pip install ansible
特點
- 使用python編寫
- ansible無需客戶端,直接通過ssh來進行連接,這也意味著它比較慢匀借,這也讓ansible不需要在遠程主機上啟動守護進程颜阐,而且ssh數(shù)據(jù)傳輸是經(jīng)過加密的,主機不容易被攻破吓肋,更安全
命令介紹
ansible中的臨時命令的執(zhí)行是通過Ad-Hoc來完成凳怨,能夠快速執(zhí)行,而且不需要保存執(zhí)行的命令蓬坡,例如:
ansible -i ~/hosts all -m command -a 'who' -u root
ansible web -u Ponny -m script -a '/home/vagrant/my.sh' //腳本是主機上的腳本
主要參數(shù)如下:
-u username 指定ssh連接的用戶名猿棉,即執(zhí)行后面命令的用戶
-i inventory_file 指定所使用的inventory文件的位置磅叛,默認為/etc/ansible/hosts
-m module 指定使用的模塊屑咳,默認為command
-f 10 指定并發(fā)數(shù),并發(fā)量大的時候弊琴,提高該值
--sudo [-k] 當(dāng)需要root權(quán)限執(zhí)行的化兆龙,-k參數(shù)用來輸入root密碼
-a 使用模塊的參數(shù)
playbook
在github上有playbook的簡單示例,我自己編寫了個簡單的my.yml如下:
---
- hosts: web
remote_user: Ponny
tasks:
- name: change dir
command: cd /Users/Ponny/localhost
- name: test connection
file: path=my.test state=touch owner=Ponny group=staff mode=0777
本來想的做法是先change目錄敲董,再創(chuàng)建文件紫皇,但似乎并不成功,因為task不能更改work目錄
運行劇本:
ansible-playbook -i /etc/ansible/hosts my.yml
注意點
- command模塊有個需要注意的地方
If you want to run a command through the shell (say you are using '<', '>','|', etc), you actually want the [shell] module instead. The [command] module is much more secure as it's not affected by the user's environment. 'creates', 'removes', and 'chdir' can be specified after the command. For instance, if you only want to run a command if a certain file does not exist, use this.
就是說如果你用的命令里有 '<', '>', '|' 等這些符號腋寨,執(zhí)行是不成功的聪铺,最好用shell模塊來代替,