文章目錄
- 0. 老男孩思想-人脈的本質
- 1. Ansible
- 1.1 密鑰認證
- 1.2 安裝ansible
- 1.3 添加ansible配置文件
- 1.4 配置主機清單文件(Inventory)
- 1.5 測試
- 1.6 ansible的模塊思想
- 1.7 command模塊
- 1.8 需求:每臺服務器的密碼都不同,怎么批量執行業務?
- 1.9 ansible常用模塊
- 1.9.1 shell模塊
- 1.9.2 script模塊
- 1.9.3 file模塊
- 1.9.4 user/group模塊
- 1.9.5 yum/apt模塊
- 1.9.6 copy模塊
- 1.9.7 systemd模塊
- 2. 思維導圖
0. 老男孩思想-人脈的本質
- 人與人之間的連接本質是通過需求連接的,即人脈的本質就是需求的滿足。
- 需求越強,連接越緊密,關系越好;反之,就會朝著陌生的方向發展。
- 員工與老板、父母與孩子、學生與老師、妻子與丈夫皆是如此。
1. Ansible
Ansible 是一款開源的 IT 自動化工具,用于配置管理、應用部署、任務編排等。它基于 SSH(無需客戶端)和 YAML 語法,以 無代理(Agentless) 方式運行,適合大規模服務器管理。
- 無代理架構:無需在目標機器安裝客戶端,降低維護成本。
1.1 密鑰認證
- ansible管理端服務器:m02
- 客戶端:web01、web02、web03
# 下載sshpass
[root@m02 /server/scripts]# yum install -y sshpass.x86_64
# 編寫分發密鑰腳本并執行
[root@m02 /server/scripts]# cat fenfa.sh
#!/bin/bash
##############################################################
# File Name:key_authentication.sh
# Version:V1.0
# Author:SunKexu
# Organization:www.oldboyedu.com
# Desc:批量密鑰認證
##############################################################
export LANG=en_US.UTF-8# vars
#ips="5 6 7 8 9 10 31 41 "
ips="7 8 9"
# 密碼可能有特殊符號,用單引號
pass='SKX2554.'
user="root"
# command
# 生成密鑰
create_key(){key_file="$HOME/.ssh/id_rsa"[ ! -f ${key_file} ] && {ssh-keygen -t rsa -f ${key_file} -P ''}return $?
}
# 分發密鑰
distribute_key(){for ip in ${ips}dosshpass -p $pass ssh-copy-id -o StrictHostKeyChecking=no ${user}@10.0.0.$ipdonereturn $?
}
# 檢查
check(){for ip in $ipsdossh -o StrictHostKeyChecking=no ${user}@10.0.0.$ip hostname -Idonereturn $?
}
# main 啟動函數
main(){create_keydistribute_keycheck
}
main[root@m02 /server/scripts]# bash fenfa.sh
……
1.2 安裝ansible
- pip:Python包管理工具
# 安裝pip工具
[root@m02 ~]# yum install -y python3-pip
……
[root@m02 ~]# pip3 --version
pip 20.2.2 from /usr/lib/python3.7/site-packages/pip (python 3.7)
# 升級pip
[root@m02 ~]# python3 -m pip install -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple --upgrade pip
……
[root@m02 ~]# pip3 --version
pip 24.0 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)
# 配置pip下載源
[root@m02 ~]# pip3 config set global.index-url https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple
Writing to /root/.config/pip/pip.conf
# 安裝ansible
[root@m02 ~]# pip3 install ansible
……
[root@m02 ~]# ansible --version
[DEPRECATION WARNING]: Ansible will require Python 3.8 or newer on the controller starting with
Ansible 2.12. Current version: 3.7.9 (default, Jun 10 2022, 11:25:35) [GCC 7.3.0]. This feature
will be removed from ansible-core in version 2.12. Deprecation warnings can be disabled by setting
deprecation_warnings=False in ansible.cfg.
/usr/local/lib/python3.7/site-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 3.7 is no longer supported by the Python core team and support for it is deprecated in cryptography. The next release of cryptography will remove support for Python 3.7.from cryptography.exceptions import InvalidSignature
ansible [core 2.11.12] config file = Noneconfigured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']ansible python module location = /usr/local/lib/python3.7/site-packages/ansibleansible collection location = /root/.ansible/collections:/usr/share/ansible/collectionsexecutable location = /usr/local/bin/ansiblepython version = 3.7.9 (default, Jun 10 2022, 11:25:35) [GCC 7.3.0]jinja version = 3.1.6libyaml = True
1.3 添加ansible配置文件
[root@m02 ~]# mkdir -p /etc/ansible
[root@m02 ~]# vim /etc/ansible/ansible.cfg
[root@m02 ~]# cat /etc/ansible/ansible.cfg
[defaults]
host_key_checking = False # 禁用主機密鑰檢查
deprecation_warnings = False
interpreter_python=/usr/bin/python3
[inventory]
[privilege_escalation]
[paramiko_connection]
[ssh_connection]
[persistent_connection]
[accelerate]
[selinux]
[colors]
[diff]
1.4 配置主機清單文件(Inventory)
- ansible管理的客戶端主機信息
[root@m02 ~]# vim /etc/ansible/hosts
[root@m02 ~]# cat /etc/ansible/hosts
[lb] # 主機組
172.16.1.5 # 主機信息
172.16.1.6
[web]
172.16.1.[7:10]
[db]
172.16.1.51
172.16.1.52
[nfs]
172.16.1.31
[bak]
172.16.1.41
- 嵌套組
[root@m02 ~]# cat /etc/ansible/hosts
[lb]
172.16.1.5
172.16.1.6
[web]
172.16.1.[7:10]
[db]
172.16.1.51
172.16.1.52
[nfs]
172.16.1.31
[bak]
172.16.1.41[data:children] #嵌套組
db # 其他組名
nfs
bak
1.5 測試
- ansible:向主機分發命令
- -i:指定主機清單文件;后面寫主機組名,或全部主機all
- 操作的目標主機組,
all
表示清單中定義的所有主機。
- 操作的目標主機組,
- -m:指定模塊
- -i:指定主機清單文件;后面寫主機組名,或全部主機all
[root@m02 ~]# ansible -i /etc/ansible/hosts all -m ping
……
172.16.1.7 | SUCCESS => {"changed": false, # 表示本次操作未對目標主機造成任何變更(ping 是只讀操作)"ping": "pong"
}
172.16.1.6 | SUCCESS => {"changed": false,"ping": "pong"
}
172.16.1.9 | SUCCESS => {"changed": false,"ping": "pong"
}
……
- 指定嵌套組
[root@m02 ~]# ansible -i /etc/ansible/hosts data -m ping
/usr/local/lib/python3.7/site-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 3.7 is no longer supported by the Python core team and support for it is deprecated in cryptography. The next release of cryptography will remove support for Python 3.7.from cryptography.exceptions import InvalidSignature
172.16.1.51 | SUCCESS => {"changed": false,"ping": "pong"
}
172.16.1.41 | SUCCESS => {"changed": false,"ping": "pong"
}
172.16.1.31 | SUCCESS => {"changed": false,"ping": "pong"
}
172.16.1.52 | SUCCESS => {"changed": false,"ping": "pong"
}
- 直接指定主機ip
[root@m02 ~]# ansible 172.16.1.7 -m ping
/usr/local/lib/python3.7/site-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 3.7 is no longer supported by the Python core team and support for it is deprecated in cryptography. The next release of cryptography will remove support for Python 3.7.from cryptography.exceptions import InvalidSignature
172.16.1.7 | SUCCESS => {"changed": false,"ping": "pong"
}
1.6 ansible的模塊思想
-
Ansible 提供了豐富的模塊,涵蓋了文件管理、軟件包安裝、服務管理等各種常見的運維任務。這些模塊封裝了底層的shell 命令,用戶無需關心具體的實現細節,只需關注目標狀態。
-
ansible官方模塊列表:
[Index of all Modules — Ansible Community Documentation](https://docs.ansible.com/ansible/latest/collections/index_module.html)
-
Ansible的模塊思想將自動化任務分解為 原子化、可復用、聲明式 的單元,通過標準化接口和冪等性保證,實現了:
- 降低學習成本:用戶關注 “做什么”,而非 “怎么做”。
- 提升可靠性:內置錯誤處理和狀態管理。
- 生態擴展:社區和廠商可快速貢獻新模塊。
-
ansible的模塊化設計與傳統shell腳本對比
特性 | 傳統腳本 | Ansible模塊 |
---|---|---|
維護性 | 邏輯混雜,難以復用 | 功能解耦,易于維護 |
可讀性 | 需解析腳本邏輯 | 聲明式語法,直觀清晰 |
跨平臺支持 | 需手動適配不同系統 | 模塊自動適配 |
安全性 | 可能殘留臨時文件或進程 | 執行后自動清理 |
1.7 command模塊
- 模塊選項:
- -a:argv,向模塊傳遞參數,也可以是命令;不能識別復雜符號,如管道
[root@m02 ~]# ansible -i /etc/ansible/hosts all -m command -a "hostname -I"
……
172.16.1.6 | CHANGED | rc=0 >>
10.0.0.6 172.16.1.6
172.16.1.5 | CHANGED | rc=0 >>
10.0.0.5 172.16.1.5
……
- 安裝軟件包
ansible -i /etc/ansible/hosts all -m command -a 'rpm -e tree'
ansible -i /etc/ansible/hosts all -m command -a 'yum install -y tree'
1.8 需求:每臺服務器的密碼都不同,怎么批量執行業務?
- ansible的主機清單可以指定用戶名和密碼,在服務器數量較少的時候可以這樣做
- ansible默認使用SSH連接客戶機,因此需要指定ssh端口
[web]
10.0.0.7 ansible_user=root ansible_port=22 ansible_password=123456
10.0.0.7 ansible_user=root ansible_port=22 ansible_password=123456
……
1.9 ansible常用模塊
模塊分類 | 模塊 | 說明 |
---|---|---|
執行命令/腳本 | command | 默認模塊,一般用于執行簡單命令;不支持特殊符號,如:|、{、}、$…… |
shell | 能執行較多的命令,支持特殊符號 | |
script | 1.分發腳本(管理端指定文件) 2.執行腳本(客戶機運行) | |
文件、目錄管理 | file | 與文件、目錄、軟連接相關; path=路徑 src=原文件 mode=文件權限(0644、0755) owner、group state=對文件、目錄的操作(touch、directory、link、absent(刪除)) |
用戶管理 | user/group | 對用戶/組管理 name=指定用戶名 uid=指定用戶id create_home=true/false,是否創建家目錄 state:添加用戶present(默認),刪除用戶:absent |
軟件包管理 | yum/apt | name:軟件包名字 state:present安裝軟件,absent:刪除軟件 |
分發配置文件 | copy | src:指定管理機的文件 dest:指定客戶機上的路徑 modeo owner group |
服務管理 | systemd | 服務管理模塊 name:服務名字 enabled:是否開機自啟動 state:指定服務狀態(started、stopped、restarted、reloaded) |
1.9.1 shell模塊
[root@m02 ~]# ansible -i /etc/ansible/hosts data -m shell -a 'rpm -qa |grep tree'
……
172.16.1.41 | CHANGED | rc=0 >>
tree-1.8.0-2.ky10.x86_64
ostree-help-2020.4-2.ky10.noarch
ostree-2020.4-2.ky10.x86_64
172.16.1.51 | CHANGED | rc=0 >>
tree-1.8.0-2.ky10.x86_64
ostree-help-2020.4-2.ky10.noarch
ostree-2020.4-2.ky10.x86_64
……
1.9.2 script模塊
- 編寫測試腳本
[root@m02 ~]# cat /server/scripts/check_info.sh
#!/bin/bash
##############################################################
# File Name:/server/scripts/check_info.sh
# Version:V1.0
# Author:SunKexu
# Organization:www.oldboyedu.com
# Desc:測試模塊
##############################################################
hostnamectl
- 測試script模塊
[root@m02 ~]# ansible -i /etc/ansible/hosts data -m script -a '/server/scripts/check_info.sh'
……
172.16.1.51 | CHANGED => {"changed": true,"rc": 0,"stderr": "Shared connection to 172.16.1.51 closed.\r\n","stderr_lines": ["Shared connection to 172.16.1.51 closed."],"stdout": " Static hostname: db01\r\n Icon name: computer-vm\r\n Chassis: vm\r\n Machine ID: 882086c957f84ef49c0e846c2f4f3968\r\n Boot ID: 6b6950319fad4dfda19e2323adfe5bc8\r\n Virtualization: vmware\r\n Operating System: Kylin Linux Advanced Server V10 (Lance)\r\n Kernel: Linux 4.19.90-52.22.v2207.ky10.x86_64\r\n Architecture: x86-64\r\n","stdout_lines": [" Static hostname: db01"," Icon name: computer-vm"," Chassis: vm"," Machine ID: 882086c957f84ef49c0e846c2f4f3968"," Boot ID: 6b6950319fad4dfda19e2323adfe5bc8"," Virtualization: vmware"," Operating System: Kylin Linux Advanced Server V10 (Lance)"," Kernel: Linux 4.19.90-52.22.v2207.ky10.x86_64"," Architecture: x86-64"]
}
……
1.9.3 file模塊
-
模塊參數:
- path:指定目標路徑
- src:指定原文件路徑
- state:指定對目標的操作
- directory:創建目錄
- touch:創建文件
- link:創建軟鏈接
- absent:刪除指定文件或目錄
- mode:指定目標文件/目錄的權限,0755,0644……
- owner:指定目標文件/目錄的所有者
- group:指定目標文件/目錄的所屬組
-
創建目錄
[root@m02 ~]# ansible -i /etc/ansible/hosts all -m file -a 'path=/backup state=directory'
172.16.1.7 | SUCCESS => {"changed": false,"gid": 0,"group": "root","mode": "0755","owner": "root","path": "/backup","size": 31,"state": "directory","uid": 0
}
172.16.1.9 | SUCCESS => {"changed": false,"gid": 0,"group": "root","mode": "0755","owner": "root","path": "/backup","size": 20,"state": "directory","uid": 0
}
172.16.1.8 | CHANGED => {"changed": true,"gid": 0,"group": "root","mode": "0755","owner": "root","path": "/backup","size": 6,"state": "directory","uid": 0
}
……
- 創建文件
[root@m02 ~]# ansible -i /etc/ansible/hosts all -m file -a 'path=/backup/skx.txt state=touch'
……
172.16.1.8 | CHANGED => {"changed": true,"dest": "/backup/skx.txt","gid": 0,"group": "root","mode": "0644","owner": "root","size": 0,"state": "file","uid": 0
}
172.16.1.6 | CHANGED => {"changed": true,"dest": "/backup/skx.txt","gid": 0,"group": "root","mode": "0644","owner": "root","size": 0,"state": "file","uid": 0
}
……
- 創建軟鏈接
[root@m02 ~]# ansible -i /etc/ansible/hosts all -m file -a 'src=/etc/hosts path=/backup/hosts state=link'
……
172.16.1.5 | CHANGED => {"changed": true,"dest": "/backup/hosts","gid": 0,"group": "root","mode": "0777","owner": "root","size": 10,"src": "/etc/hosts","state": "link","uid": 0
}
172.16.1.7 | CHANGED => {"changed": true,"dest": "/backup/hosts","gid": 0,"group": "root","mode": "0777","owner": "root","size": 10,"src": "/etc/hosts","state": "link","uid": 0
}
……# 檢查
[root@m02 ~]# ansible -i /etc/ansible/hosts all -m command -a 'ls -l /backup/hosts'
……
172.16.1.7 | CHANGED | rc=0 >>
lrwxrwxrwx 1 root root 10 7月 9 20:59 /backup/hosts -> /etc/hosts
172.16.1.6 | CHANGED | rc=0 >>
lrwxrwxrwx 1 root root 10 7月 9 20:59 /backup/hosts -> /etc/hosts
172.16.1.8 | CHANGED | rc=0 >>
lrwxrwxrwx 1 root root 10 7月 9 20:59 /backup/hosts -> /etc/hosts
……
- 刪除軟鏈接
[root@m02 ~]# ansible -i /etc/ansible/hosts all -m file -a 'path=/backup/hosts state=absent'
……
172.16.1.8 | CHANGED => {"changed": true,"path": "/backup/hosts","state": "absent"
}
172.16.1.9 | CHANGED => {"changed": true,"path": "/backup/hosts","state": "absent"
}
……
- 創建目錄,并指定權限和所屬用戶/組
[root@m02 ~]# ansible -i /etc/ansible/hosts all -m file -a 'path=/backup/skx state=directory mode=0700 owner=oldboy group=oldboy'
……
172.16.1.5 | FAILED! => {"changed": false,"gid": 0,"group": "root","mode": "0755","msg": "chown failed: failed to look up user oldboy", # 沒有該用戶"owner": "root","path": "/backup/skx","size": 6,"state": "directory","uid": 0
}
172.16.1.7 | CHANGED => {"changed": true,"gid": 1000,"group": "oldboy","mode": "0700","owner": "oldboy","path": "/backup/skx","size": 6,"state": "directory","uid": 1000
}
……
1.9.4 user/group模塊
- user模塊參數:
- name:指定用戶名
- uid:指定用戶id
- group:指定用戶所屬組
- shell:指定命令解釋器
- create_home:是否創建家目錄(true/false)
- state:指定對該用戶的操作;present:創建用戶(默認),absent:刪除用戶
- group模塊參數:
- name:指定用戶組名
- gid:指定組id
- state:指定對該用戶組的操作;present:創建用戶組(默認),absent:刪除用戶組
- 創建用戶
[root@m02 ~]# ansible -i /etc/ansible/hosts all -m user -a 'name=www-ans uid=2999 group=www-ans shell=/sbin/nologin create_home=false state=present'
……
172.16.1.7 | FAILED! => {"changed": false,"msg": "Group www-ans does not exist"
}
172.16.1.5 | FAILED! => {"changed": false,"msg": "Group www-ans does not exist"
}
……# Ansible 的 user 模塊默認不會自動創建用戶組,因此需要先確保組存在。
# 創建用戶組
[root@m02 ~]# ansible -i /etc/ansible/hosts all -m group -a 'name=www-ans gid=2999 state=present'
……
172.16.1.6 | CHANGED => {"changed": true,"gid": 2999,"name": "www-ans","state": "present","system": false
}
172.16.1.9 | CHANGED => {"changed": true,"gid": 2999,"name": "www-ans","state": "present","system": false
}
……# 創建用戶
[root@m02 ~]# ansible -i /etc/ansible/hosts all -m user -a 'name=www-ans uid=2999 group=www-ans shell=/sbin/nologin create_home=false state=present'
……
172.16.1.9 | CHANGED => {"changed": true,"comment": "","create_home": false,"group": 2999,"home": "/home/www-ans","name": "www-ans","shell": "/sbin/nologin","state": "present","system": false,"uid": 2999
}
172.16.1.6 | CHANGED => {"changed": true,"comment": "","create_home": false,"group": 2999,"home": "/home/www-ans","name": "www-ans","shell": "/sbin/nologin","state": "present","system": false,"uid": 2999
}
……
1.9.5 yum/apt模塊
-
yum模塊參數:
- name:指定軟件包名稱
- state:指定對軟件包的操作
- present:安裝軟件(默認)
- absent:刪除軟件
- latest:更新軟件
-
安裝軟件
[root@m02 ~]# ansible -i /etc/ansible/hosts all -m yum -a 'name=wget state=present'
……
172.16.1.6 | CHANGED => {"ansible_facts": {"pkg_mgr": "dnf"},"changed": true,"msg": "","rc": 0,"results": ["Installed: wget-1.20.3-6.ky10.x86_64"]
}
172.16.1.9 | CHANGED => {"ansible_facts": {"pkg_mgr": "dnf"},"changed": true,"msg": "","rc": 0,"results": ["Installed: wget-1.20.3-6.ky10.x86_64"]
}
……
1.9.6 copy模塊
-
推薦分發文件或壓縮包,分發目錄極其緩慢
-
copy模塊參數:
- src:管理機上的原文件路徑
- dest:客戶機上的目標路徑
- backup:如果客戶機上有目標文件,是否要備份(true/false(默認))
-
分發文件
[root@m02 ~]# ansible -i /etc/ansible/hosts all -m copy -a 'src=/etc/hosts dest=/etc/hosts backup=true'
……
172.16.1.8 | SUCCESS => {"changed": false,"checksum": "a85d59aa0b622911d06dee4a51b95c62cde849bd","dest": "/etc/hosts","gid": 0,"group": "root","mode": "0644","owner": "root","path": "/etc/hosts","size": 311,"state": "file","uid": 0
}
172.16.1.5 | SUCCESS => {"changed": false,"checksum": "a85d59aa0b622911d06dee4a51b95c62cde849bd","dest": "/etc/hosts","gid": 0,"group": "root","mode": "0644","owner": "root","path": "/etc/hosts","size": 311,"state": "file","uid": 0
}
……
1.9.7 systemd模塊
-
模塊參數:
- name:服務名稱
- enabled:是否開機自啟動(true/false)
- state:指定服務狀態
reloaded:重新加載服務的配置文件
restarted:重啟服務
started:啟動服務
stopped:停止服務
-
批量啟動nginx服務
[root@m02 ~]# ansible -i /etc/ansible/hosts web -m systemd -a 'name=nginx enabled=true state=restarted'
……
172.16.1.9 | CHANGED => {"changed": true,"enabled": true,"name": "nginx","state": "started","status": {"ActiveEnterTimestamp": "Thu 2025-07-10 08:13:46 CST","ActiveEnterTimestampMonotonic": "2570669227","ActiveExitTimestampMonotonic": "0",……
2. 思維導圖
https://kdocs.cn/join/gpuxq6r?f=101\r\n邀請你加入共享群「老男孩教育Linux運維99期-孫克旭」一起進行文檔協作