WSL Docker 給已存在的容器新增埠對映的方法
Ansible
由於公司升級伺服器和處理問題抓包,
可能需要同時操作多臺伺服器(繁瑣的解壓、copy、備份),
我便發現了ansible工具!
現在通過下班時間部署在自己虛擬機器測試與總結,有錯誤與不足的地方請提醒,
參考資料有部落格園大神分享與同事分享文件!(本文章裡都有附屬連結)
歡迎交流:
本版為ansible --version:ansible 2.9.21
簡單配置
/etc/ansible/:ansible目錄
-
vim ansible.cfg
-
#forks = 5 #ssh併發數量
#ask_pass = True #使用金鑰還是密碼遠端,True代表使用密碼
#host_key_checking = False #是否校驗金鑰(第一次ssh時是否提示yes/no)
-
-
開啟/etc/ansible/host檔案最下邊新增自定義模組名
- 示例:[test] #模組名字
- 192.168.XXX.XXX
- 示例:[test] #模組名字
執行狀態
- 黃色:成功執行並伴隨著狀態的改變
綠色:成功執行並且沒有發生狀態的改變
紅色: 執行失敗
免密操作
-
方式一
- 將主機金鑰傳送到控制的機器
- ssh-keygen
- ssh-copy-id 1.1.1.1 傳送祕鑰對到這個ip
- 將主機金鑰傳送到控制的機器
-
方式二
- vim host
- 示例:
- [db] #自定義模組名
- 172.25.70.1 ansible_ssh_user="root" ansible_ssh_pass="redhat"
- 地址後加 ansible_ssh_user=使用者名稱 ansible_ssh_port=埠 ansible_ssh_pass=密碼
測試&幫助操作
ansible test --list #檢視自定義test模組列表資訊
ansible test -m ping #測試伺服器是否連線成功
ansible-doc -l #列出所有模組
ansible-doc -l | grep yum #在所有模組中過濾關鍵詞
ansible-doc yum #檢視模組幫助
ansible -h #檢視幫助選項
常用模組
shell模組
-
可以使用"<",">","|",";","&"等符號特殊符號
示例:
ansible test -m shell -a 'df -h' #檢視磁碟掛載情況
-
ansible test -m shell -a 'ls -l /home/' #檢視home目錄
-
ansible test -m shell -a "rm -rf ~/*" #刪除所有檔案
-
ansible test -m shell -a 'mkdir /home/2233.txt' #建立檔案 (報錯不用理會)
-
ansible test -m shell -a 'tar -cf ybt.tar.gz /home/*' #壓縮目錄檔案
-
chdir 在執行命令前,進入到指定目錄中
示例:ansible test -m shell -a 'chdir=/home/ ls-l'
script模組
- 執行本目錄下指令碼copy到遠端主機後臺執行後刪除 (test為模組名)
- 示例:ansible test -m script -a "./joben.sh"
- 示例:ansible test -m script -a 'chdir=/root/cin/etc/ A/bak.sh'
- chdir=在執行命令前,進入到控制主機指定目錄中 在相對路徑A執行指令碼bak.sh
unarchive模組
-
管理機上的壓縮檔案到遠端主機解壓:
ansible test -m unarchive -a "src=本地目錄壓縮包 dest=遠端要解壓到的目錄 mode=0755 copy=yes"- 示例:ansible test -m unarchive -a 'src=/root/jo.tar.gz dest=/root/ copy=yes'
-
解壓遠端主機上的檔案到目錄:
ansible all -m unarchive -a "src=遠端主機/目錄/檔案 dest=遠端要解壓到的目錄 mode=0755 copy=no" #mode可省略 -
owner=修改屬主
group=修改屬組mode= 修改許可權
copy模組
-
ansible test -m copy -a "src=本地 dest=目標"
-
以下是copy並備份示例(注:檔案內容一樣不備份不替換!)backup=no 不備份
-
(注:檔案內容不一樣,直接替換)
-
示例:ansible test -m copy -a "src=/test/test1.txt dest=/usr/local/ backup=yes "
-
示例:ansible test -m copy -a 'src=kk.kk.l dest=/home/' # 預設將本目錄檔案copy到遠端機
-
src=本地 dest=目標
owner=修改屬主
group=修改屬組mode= 修改許可權
fetch模組
fetch模組與copy類似,但是作用相反,可以將其他主機的檔案拷貝到本地
- ansible test -m fetch -a "src=目標路徑 dest=本地路徑"
- ansible test -m fetch -a 'src=/home/test.txt dest=./'
file模組
path=/路徑/檔案 #" path + file " = " dest + file " = " name + file "
state=選項
owner=修改屬主
group=修改屬組
mode= 修改許可權
state absent 將資料進行刪除
state directory 建立一個空目錄資訊
state file 檢視指定目錄資訊是否存在
state touch 建立一個空檔案資訊
state hard/link 建立連結檔案
-
ansible test -m file -a 'path=/home/bi.txt state=touch' # 建立檔案
-
ansible test -m file -a 'path=/home/bi.txt state=absent' # 刪除檔案或目錄
-
ansible test -m file -a'path=/home/* state=absent' # 刪除檔案
-
ansible test -m file -a 'path=/home/test/ state=directory' # 建立目錄
-
ansible test -m file -a "path=/home/mydir owner=sshd group=dc mode=0777" # 修改許可權和組
-
建立軟連線示例:src原始檔 path存放軟體路徑檔案
- ansible test -m file -a 'src=/home/l.txt path=/home/k state=link'
-
ansible test -m file -a 'src=/home/l.txt path=/home/kke state=hard' # 建立硬連結
lineinfile模組
單個檔案新增內容
- ansible test -m lineinfile -a "path=目標路徑 line='新增的內容'"
- ansible test -m lineinfile -a "path=/home/test.txt line='strive'"
- 在內容之後插入(insertafter)
- ansible test -m lineinfile -a "path=目標路徑 line='新增的內容' insertafter='在哪個位置之後'"
- ansible test -m lineinfile -a "path=/home/test.txt line='shen' insertafter='strive'"
replace模組
- 替換
- ansible test -m replace -a "path=目標路徑 regexp=舊內容 replace=新內容"
- ansible test -m replace -a "path=/home/test.txt regexp='hello' replace='hello wrold'"
user模組
-
ansible test -m user -a 'name=shen' # 建立使用者
-
建立使用者:dba,使用BASH Shell,附加組為admins,dbagroup,家目錄為/home/dba,注意:附加組必須為已經存在的組。
-
ansible test -m user -a "name=dba groups=admins,dbagroup append=yes home=/home/dba shell=/bash/shell state=present"
-
groups設定,groups=group1,group2.。。。
增量新增屬組,append=yes
狀態,state=present
家目錄:home=/home/dba
shell:shell=/bash/shell
-
ansible test -m user -a 'name=dba groups=shen' # 修改使用者屬組
-
ansible test -m user -a 'name=shen remove=yes state=absent' #刪除使用者shen
-
修改密碼:
-
password_hash:# 加密函式
-
ansible test -m user -a "name=dudu password={{'123'| password_hash('sha512')}}"
-
密碼為123 password_hash('sha512')}}為固定格式
-
cron定時任務
定時任務模組:點選參考部落格
引數
day= #日應該執行的工作( 1-31, *, */2, )
hour= # 小時 ( 0-23, *, */2, )
minute= #分鐘( 0-59, *, */2, )
month= # 月( 1-12, *, /2, )
weekday= # 周 ( 0-6 for Sunday-Saturday,, )
job= #指明執行的命令是什麼
name= #定時任務描述
reboot # 任務在重啟時執行,不建議使用,建議使用special_time
special_time #特殊的時間範圍,引數:reboot(重啟時),annually(每年),monthly(每月),weekly(每週),daily(每天),hourly(每小時)
state #指定狀態,present表示新增定時任務,也是預設設定,absent表示刪除定時任務
user # 以哪個使用者的身份執行
示例:ansible test -m cron -a 'name="定時任務測試" minute=/5 hour=/1 job="echo 1 >> /root/1.txt"' #設定定時任務
檢視:
刪除剛剛的定時任務:ansible test -m cron -a "name='定時任務測試' minute=/5 hour=/1 job='echo 1 >> /root/1.txt' state=absent"
yum模組
主要用於安裝軟體
name= #所安裝的包的名稱
state= #present--->安裝, latest--->安裝最新的, absent---> 解除安裝軟體。
disable_pgp_check #是否禁止GPG checking,只用於presentor latest
update_cache #強制更新yum的快取
示例:ansible test -m yum -a 'name=lrzsz,httpd state=present' #安裝lrzsz,httpd 解除安裝name格式一樣
可以直接安裝rpm包
格式:ansible test -m yum -a 'name=/遠端主機目錄/rpm包 disable_pgp_check=yes '
- disable_pgp_check 忽略GPG檢查
service模組
該模組用於服務程式的管理:點選參考部落格
arguments #命令列提供額外的引數
enabled #設定開機啟動。
name= #服務名稱
runlevel #開機啟動的級別,一般不用指定。
sleep #在重啟服務的過程中,是否等待。如在服務關閉以後等待2秒再啟動。(定義在劇本中。)
state #有四種狀態,分別為:started--->啟動服務, stopped--->停止服務, restarted--->重啟服務, reloaded--->過載配置
示例:
-
開啟ssh服務:ansible test -m service -a 'name=sshd state=started enabled=true'
-
關閉:ansible test -m service -a 'name=sshd state=stopped'
group模組
該模組主要用於新增或刪除組:點選參考部落格
gid= #設定組的GID號
name= #指定組的名稱
state= #指定組的狀態,預設為建立,設定值為absent為刪除
system= #設定值為yes,表示建立為系統組
示例:建立組:ansible test -m group -a 'name=shen gid=123'
檢視:
刪除:ansible test -m group -a 'name=shen state=absent'
檢視:
hostname模組
修改主機名
示例:ansible 192.168.23.138 -m hostname -a 'name=kexiao'
setup模組
ansible_facts用於採集被管理裝置的系統資訊,所有收集的資訊都被儲存在變數中,每次執行playbook預設第一個任務就是Gathering Facts,使用setup模組可以檢視收集到的facts資訊。
ansible_memtotal_mb #總記憶體
ansible_hostname #主機名
ansible_fqdn #主機的域名
示例:
ansible test -m setup -a 'filter="ipv4"' #獲取test組ip4相關的資訊 注:filter=過濾
ansible test -m setup -a 'filter="bios"' #獲取主機板bios資訊
#查詢與cpu相關的變數
ybt root /etc/ansible/templates #ansible test -m setup |grep "cpu"
"ansible_processor_vcpus": 1,
"ansible_processor_vcpus": 1,
ybt root /etc/ansible/templates #ansible test -m setup |grep "processor"
"ansible_processor": [
"ansible_processor_cores": 1,
"ansible_processor_count": 1,
"ansible_processor_threads_per_core": 1,
"ansible_processor_vcpus": 1,
"ansible_processor": [
"ansible_processor_cores": 1,
"ansible_processor_count": 1,
"ansible_processor_threads_per_core": 1,
"ansible_processor_vcpus": 1,
debug模組
debug模組可以顯示變數的值,可以輔助排錯,通過msg可以顯示變數的值
[root@ybt ansible]# cat ybt.yml
---
#ybt demo
- hosts: test #-空格host:空格 主機清單主機列表
remote_user: root # 在遠端主機以root身份執行
tasks: #要執行的命令
- debug: # 執行什麼命令
msg: "{{ansible_memtotal_mb}}" #總記憶體大小變數
# 備註呼叫debug模組顯示某些具體的變數值
yum_repository模組
引數
name:倉庫名
description:描述資訊,
baseurl:連結
gpgcheck:是否校驗
gpgkey:紅帽校驗連結
enabled:是否開啟
state:present|absent:預設present,absent表示刪除
lvg模組和lvol
lvg模組:建立、刪除卷組(VG),修改卷組大小
lvol模組:建立、刪除邏輯卷(LV),修改邏輯卷大小
vg:卷組名,pvs:物理磁碟,更多個分割槽則為擴充套件
Ansible-playbook
playbook:如果將ansible的單個模組看作是linux的單條命令,那麼playbook就相當於shell指令碼
簡單playbook演示:
#這是一個劇本
---
#ybt demo
- hosts: test #-空格host:空格 主機清單主機列表
remote_user: root # 在遠端主機以root身份執行
tasks: #要執行的任務 任務集
- name: hello # 描述說明 但是是必須的
shell: 'df-h' # 執行什麼命令
ansible-playbook ybt.yml #ansible 執行劇本
playbook加密操作(瞭解)
[root@ybt ansible]# ansible-vault encrypt ybt.yml #加密操作
New Vault password:
Confirm New Vault password:
Encryption successful
[root@ybt ansible]# ansible-playbook ybt.yml #不能直接運行了
ERROR! Attempting to decrypt but no vault secrets found
[root@ybt ansible]# ansible-vault decrypt ybt.yml #解密
Vault password:
Decryption successful
# 解密後就可以執行了 加密後檢視是加密形態,解密後正常
#可通過ansible-vault view檢視加密檔案
[root@ybt ansible]# ansible-vault view ybt.yml
Vault password:
[root@ybt ansible]# ansible-vault deit ybt.yml #輸入口令後編輯
YUML語言語法:
- 在單一文件中,可用連續三個連字號(---)區分多個檔案,另外,還有選擇性的連續三個點好(...)用來表示檔案結尾
- 建議註明Playbook的功能
-
註釋
- 縮排必須統一,不能空格和tab混用
- 縮排的級別也必須是一致的,(與python一致!)
- 區別大小寫,k/v的值大小寫敏感
- k/v的值可同行寫也可換行寫。同行使用 :分隔 (鍵值對)
- v可以是字串,也可以是另一個列表
- 一個完整的程式碼塊功能,最少元素需包括name:task
- 副檔名通常為yml或yaml
list:列表,其所有元素均使用 "-" 開頭
示例:
# 這是一個示例描述
- APP
- PHONE
Dictionary:字典,通常由多個key與value構成
示例:
---
# 描述
-name: hello #name就是key hello就是value 下邊都是!
job:Developer
skill:Elite #第一種寫法
可以將key:value放置於{}中進行表示,用,分隔多個key:value
---
# 描述
{name: hello,job:Developer,skill:Elite} #第二種寫法
playbook執行中出現錯誤,不退出playbook強制執行剩餘命令
taks:
-name: hello
shell: df -h ||/bin/true #加上//bin/true本條命令執行失敗,繼續向下執行
或者
taks:
-name: hello
shell: df -h
ignore_errors:True #加上ignore_errors:True忽略錯誤
playbook檢測
&針對某臺主機
- 選項
- --check 只檢測,不執行
- --list-hosts 列出執行任務的主機
- --limit 只針對主機列表中的某臺主機執行
- -v顯示過程 -vv -vvv 更詳細
示例:
- ansible-playbook ybt.yml --check -v 或ansible-playbook -C ybt.yml
- ansible-playbook ybt.yml --list-hosts
- ansible-playbook ybt.yml --limit 192.168.23.138
- ansible-playbook ybt.yml --list-tasks #檢視plakbook有幾個任務
handlers¬ify的使用
notify寫在某個任務下,這個任務一旦執行立馬觸發執行handlers
示例:
ybt root /etc/ansible #cat httpd.yml
---
- hosts: test
remote_user: root
tasks:
- name: '安裝http'
yum: name=httpd
notify: start http #一旦安裝httpd動作發生,就直接執行handlers,不在執行其他
#notify: 這裡名字需要與handlers的name:名字一致
- name: '關閉服務'
service: name=httpd state=stopped
handlers:
- name: start http
service: name=httpd state=restarted
tags使用
tags給某個或多個任務設定標籤
- 也可以給多個任務設定同一個標籤名,執行一個標籤執行多個任務
執行語法:ansible-playbook -t 標籤名,標籤名 playbook.yml
檢視標籤資訊:ansible-playbook playbook.yml --list-tags
示例:
ybt root /etc/ansible #cat httpd.yml
---
- hosts: test
remote_user: root
tasks:
- name: '安裝http'
yum: name=httpd
notify: start http
tags: tags1 #設定標籤,起名為tags1
- name: '關閉服務'
service: name=httpd state=stopped
- name: tags2 #設定標籤,起名為tags2
service: name=httpd state=restarted
handlers:
- name: start http
service: name=httpd state=restarted
#只執行tags1 tags2標籤
ybt root /etc/ansible #ansible-playbook -t tags1,tags2 httpd.yml
playbook變數
變數賦值並執行:ansible-playbook -e '變數名=具體值 變數名=具體值' playbook.yml
playbook內部變數寫法:{{變數名}}
playbook劇本中定義變數賦值
vars:
-變數名: 具體值
-變數名: 具體值
# 注:命令列變數,高於配置檔案變數;命令列優先順序更高
示例:
---
- hosts: test
remote_user: root
vars:
- pk1: httpd #宣告變數
- pk2: vsftpd
tasks:
- name: '安裝http'
yum: name={{pk1}} #使用變數
- name: '安裝vsftpd'
yum: name={{pk2}}
- name: '啟動'
service: name={{pk1}},{{pk2}} state=started
定義host清單變數
[test]
192.168.23.137 n=137 #定義單臺機器變數, n=137
192.168.23.138 n1=138
[test:vars] #定義test整個組的變數 語法為:清單名:vars
ht=/home/cin/etc/ #將scr賦值給n2
hb=/home/cin/bin/
#單臺變數優先順序高於組變數優先順序
變數定義優先順序排序: 主機清單 < playbook指令碼定義 < 命令列
示例:
ybt root /etc/ansible #cat var.yml
---
- hosts: test
remote_user: root
tasks:
- name: 'hosts清單變數使用'
file: path={{ht}} state=directory #使用了清單變數
編輯變數檔案
playbook指令碼可隨時呼叫
vars.yml # 定義一個專門儲存變數的檔案
playbook指令碼呼叫
- hosts: test
remote_user: root
vars_files: #呼叫格式
- vars.yml #呼叫變數檔案
示例:
#定義變數檔案(只存放變數)
ybt root /etc/ansible #cat vars.yml
var1: /home/cin/etc/
var2: /home/cin/bin/
var3: /etc/ansible/testybt/
#使用檔案變數
ybt root /etc/ansible #cat var.yml
---
- hosts: test
remote_user: root
vars_files: #呼叫變數檔案
- vars.yml #變數檔名
tasks:
- name: '變數檔案使用'
file: path={{var2}} state=directory
#執行
ybt root /etc/ansible #ansible-playbook var.yml
模板templates
-
文字檔案,巢狀有指令碼(使用模板程式設計語音編寫)
-
Jinja2語音,使用字面量,有下面形式
- 字串:使用單引號或雙引號
- 數字:整數,浮點數
- 列表:{n,n1..}
- 元組:(n,n2)
- 字典:{key:value,....}
- 布林:true/false
-
算術運算+ - * / // % **
-
比較 == != > < >= <=
-
邏輯 and or not
-
流表示式For If When
[root@ybt ansible]# mkdir templates #ansible 建立templates目錄與ansible目錄平級
# template模組只能用於ansible-playbook
# templates檔案必須放於templates目錄下,命名為.j2結尾
示例:
cp /etc/nginx/nginx.conf ./
mv nginx.conf nginx.conf.j2 #製作nginx模板 裡邊可以自定義變數不在演示
#使用template模板
ybt root /etc/ansible #cat nginx.yml
---
- hosts: test
remote_user: root
tasks:
- name: install nginx
yum: name=nginx
- name: copy template
#nginx.conf.j2就在template所以不用寫路徑了
template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
- name: start nginx
service: name=nginx state=started
#執行
ybt root /etc/ansible #ansible-playbook nginx.yml
#注:有的伺服器有http服務,所以nginx是起不來的,因為80埠衝突
when條件判斷
-
when可以定義判斷條件,條件為真時才執行某個任務。
-
常見條件操作符有:==、!=、>、>=、<、<=。
-
多個條件可以使用and(並且)或or(或者)分割,when表示式中呼叫變數不要使用{{ }}。
示例:
ybt root /etc/ansible #cat var.yml
---
- hosts: test
remote_user: root
vars_files:
- vars.yml
tasks:
- name: '變數檔案使用'
file: path={{var3}} state=directory
when: ansible_hostname== 'll' #when判斷:只有主機名==ll才執行
#執行
ybt root /etc/ansible #ansible-playbook var.yml
PLAY [test] ***********************************************************************
TASK [Gathering Facts] ************************************************************
ok: [192.168.23.138]
ok: [192.168.23.137]
TASK [變數檔案使用] *********************************************************************
skipping: [192.168.23.138]
changed: [192.168.23.137]
PLAY RECAP ************************************************************************
192.168.23.137 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
192.168.23.138 : ok=1 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0
with_items迭代
- 有重複性執行的任務時,可以使用迭代機制
- 對迭代項的引用,固定變數名為item
- 要在task中使用with_items給定要迭代的元素列表
- 列表格式:字串,字典
示例:
[root@ybt ansible]# cat touch.yml
---
#迭代演示
- hosts: test
remote_user: root
tasks:
- name: '建立檔案'
file: name=/home/{{ item }} state=touch #{{ item }} 固定變數引用
with_items:
- ybt1
- ybt2
- ybt3
檢視:
for迴圈
語法
#格式
{% for 變數名 in playbook變數名 %}
迴圈內容{{變數名}}
{% endfor %}
#示例
[root@ybt templates]# cat for.j2 #templates模板
{% for i in ybt %} #ybt為playbook裡定義的變數名; i是將ybt賦值給i
test {{ i }}
{% endfor %}
示例:
[root@ybt ansible]# cat for.yml
---
#for 迴圈示例
- hosts: test
remote_user: root
vars:
ybt: #自定義變數名列表名
- ybt1
- ybt2
- ybt3 #變數列表值
tasks:
- name: copy
template: src=templates/for.j2 dest=/home/ybt/for.txt #模板測試
執行:ansible-playbook for.yml
檢視結果:
roles角色
- 相當於java的呼叫方法
目錄規劃
/etc/ansible/roles/ 呼叫檔案應該與roles目錄同級
/roles/project/:專案名稱,有以下子目錄
files/: 存放copy或script模組等呼叫的檔案
templates/: 模板
tasks/: 任務 建立主配置檔案,mian.yml(定義檔案執行次序)- include: 執行檔案
handlers/:
vars/: 定義變數
meta/: 定義依賴關係
default/: 定義預設變數
示例:
ybt root /etc/ansible/roles #tree #ansible同級目錄建立 roles角色目錄
.
├── httpd
│ └── tasks
│ ├── install.yml
│ └── main.yml
└── nginx
└── tasks
├── install.yml
├── main.yml
└── service.yml
4 directories, 5 files
#上邊目錄與檔案結構都是最簡單的示例,
#以nginx示例,只是安裝了nginx 和啟動了nginx
#當然可以複雜化,比如新增模板,公用變數等
#檔案展示,其實就是一個檔案只做一件事
ybt root /etc/ansible/roles/nginx #cat tasks/main.yml
# 檔名字必須事main 寫入服務執行順序
- include: install.yml #先安裝 名字為自己定義的檔名字
- include: service.yml #啟動
ybt root /etc/ansible/roles/nginx #cat tasks/service.yml
- name: start nginx
service: name=nginx state=started #啟動
ybt root /etc/ansible/roles/nginx #cat tasks/install.yml
- name: install nginx
yum: name=nginx #安裝
#編寫執行檔案 檔案位置必須與roles目錄同級
ybt root /etc/ansible #cat nginx_roles.yml
---
- hosts: test
remote_user: root
roles:
- nginx
#執行
ansible-playbook nginx_roles.yml
參考資料連結:
- bilibili(馬哥教育)(重點學習參考)
- https://www.bilibili.com/video/BV18t411f7CN (重點學習參考,幾乎%95)
- 部落格園 (省時間可以看這個)