
太厲害了,終于有人能把Ansible講的明明白白了,建議收藏
文章目錄
- 一: ansible 的概述
- 1. ansible簡介
- 2. 官方網站
- 3. ansible 的特點
- 4. ansible的作業機制
- 二. Asible的安裝
- 1. 設定EPEL倉庫
- 2. 使用yum安裝Ansible
- 3. 查看ansible的版本
- ansible的命令引數
- 三. ansible的使用
- 1. 基于埠,用戶,密碼定義主機清單
- 測驗主機的連通性
- 2. 基于ssh密鑰來訪問定義主機清單
- 設定密鑰
- 拷貝密鑰并測驗
- 修改hosts
- ansible遠程執行命令測驗
- 案例1: 檢查節點的記憶體情況
- 案例2:給節點增加用戶
- 四. ansible的高級用法
- 1. ansible的常用模塊
- 1) ansible的3個遠程模塊的區別
- 案例1:使用shell模塊的案例
- 案例2:使用script 模塊
- 2) copy模塊的使用
- 案例1: 把ansible主機的/etc/hosts 拷貝到主機組機器中的/root/下
- 3. file模塊
- 案例5 給檔案設定權限
- 4. stat模塊獲取遠程檔案資訊
- 案例6 獲取檔案資訊
- 5. get_url 模塊
- 案例7
- 6. yum模塊
- 案例8 使用yum模塊安裝httpd
- 7. cron模塊遠程管理主機crontab配置
- 案例9: 增加每30分鐘執行 echo"我是互聯網老辛"
- 8. service 遠程管理主機系統服務模塊
- 案例10 使用service模塊重啟httpd
- 9. user模塊 管理遠程主機的用戶
- 案例11: 使用user模塊創建一個用戶itlaoxin
- 五. ansible 實戰案例
- 實戰一: 使用playbook 批量部署多臺LAMP環境
- 搭建思路
- 第一步:安裝httpd軟體
- 第二部:安裝MySQL
- 第三步:安裝PHP和php-mysql模塊
- 第四步:提供php的測驗頁
- 第五;定義組名
- 第六:使用playbook創建一個LAMP構建的任務
- 實戰二: 使用ansible部署k8s及集群
- 總結
一: ansible 的概述
1. ansible簡介
Ansible是一款為類Unix系統開發的自由開源的配置和自動化工具,
它用Python寫成,類似于saltstack和Puppet,但是有一個不同和優點是我們不需要在節點中安裝任何客戶端,
它使用SSH來和節點進行通信,Ansible基于 Python paramiko 開發,分布式,無需客戶端,輕量級,配置語法使用 YMAL 及 Jinja2模板語言,更強的遠程命令執行操作,
2. 官方網站
https://www.ansible.com/

我們可以看到上面的紅帽標志,紅帽公司于2015年10月收購了ansible,而ansible成立于2013年,
3. ansible 的特點
1、部署簡單,沒有客戶端,只需在主控端部署Ansible環境,被控端無需做任何操作;
2. 模塊化:呼叫特定的模塊,完成特定任務
3. 默認使用SSH協議對設備進行管理;
4. 主從集中化管理;
5、配置簡單、功能強大、擴展性強;
6、支持API及自定義模塊,可通過Python輕松擴展;
7、通過Playbooks來定制強大的配置、狀態管理
8. 對云計算平臺、大資料都有很好的支持;
9. 具有冪等性:一個操作在一個主機上執行一遍和執行N遍的結果是一樣的
ansible是基于模塊作業的,本身沒有批量部署的能力,真正具有批量部署的是ansible所運行的模塊,ansible只是提供一種框架,主要包括:
(1)、連接插件connection plugins:負責和被監控端實作通信;
(2)、host inventory:指定操作的主機,是一個組態檔里面定義監控的主機;
(3)、各種模塊核心模塊、command模塊、自定義模塊;
(4)、借助于插件完成記錄日志郵件等功能;
(5)、playbook:劇本執行多個任務時,非必需可以讓節點一次性運行多個任務
4. ansible的作業機制
Ansible 在管理節點將 Ansible 模塊通過 SSH 協議推送到被管理端執行,執行完之后自動洗掉,可以使用 SVN 等來管理自定義模塊及編排

由圖可以看出Ansible的組成由一下模塊組成:
Ansible: ansible的核心模塊
Host Inventory:主機清單,也就是被管理的主機串列
Playbooks:ansible的劇本,可想象為將多個任務放置在一起,一塊執行
Core Modules:ansible的核心模塊
Custom Modules:自定義模塊
Connection Plugins:連接插件,用于與被管控主機之間基于SSH建立連接關系
Plugins:其他插件,包括記錄日志等
二. Asible的安裝
1. 設定EPEL倉庫
Ansible倉庫默認不在yum倉庫中,因此我們需要使用下面的命令啟用epel倉庫
[root@itlaoxin162 ~]# yum install epel-release -y
2. 使用yum安裝Ansible
[root@itlaoxin162 ~]# yum install ansible
3. 查看ansible的版本
[root@itlaoxin162 ~]# ansible --version
ansible 2.9.18
ansible的命令引數
anisble命令語法: ansible [-i 主機檔案] [-f 批次] [組名] [-m 模塊名稱] [-a 模塊引數]
| 引數 | 功能 |
|---|---|
| -v | 詳細模式,如果執行成功,輸出詳細結果 |
| -i | 指定host檔案路徑,默認在/etc/ansible/hosts |
| -f,-forks=NUM | NUM默認是整數5,指定fork開啟同步行程的個數 |
| -m | 指定使用的module名稱,默認command模塊 |
| -a | 指定模塊的引數 |
| -k | 提示輸入SSH密碼,而不是使用基于ssh密鑰認證 |
| -sudo | 指定使用sudo獲取root權限 |
| -K | 提示輸入sudo密碼 |
| -u | 指定移動端的執行用戶 |
| -C | 測驗命令執行會改變什么內容,不會真正的去執行 |
ansible-doc 詳細引數
[root@itlaoxin162 ~]# ansible-doc -l
列出所有模塊串列
指定查看某個模塊的引數
ansible-doc -s 模塊名字
[root@itlaoxin162 ~]# ansible-doc -s onyx_ospf
- name: Manage OSPF protocol on Mellanox ONYX network devices
onyx_ospf:
interfaces: # List of interfaces and areas. Required if `state=present'.
ospf: # (required) OSPF instance number 1-65535
router_id: # OSPF router ID. Required if `state=present'.
state: # OSPF state.
[root@itlaoxin162 ~]# ansible-doc -s service
- name: Manage services
service:
arguments: # Additional arguments provided on the command line.
enabled: # Whether the service should start on boot. *At least one of
state and enabled are
required.*
name: # (required) Name of the service.
pattern: # If the service does not respond to the status command,
name a substring to look
for as would be found in
the output of the `ps'
command as a stand-in for a
status result. If the
string is found, the
service will be assumed to
be started.
runlevel: # For OpenRC init scripts (e.g. Gentoo) only. The runlevel
that this service belongs
to.
sleep: # If the service is being `restarted' then sleep this many
seconds between the stop
三. ansible的使用
1. 基于埠,用戶,密碼定義主機清單
格式:
ansible基于ssh連接-i (inventory)引數后指定的遠程主機時,也可以寫埠,用戶,密碼,
如:
ansible_ssh_port: 指定ssh埠 ansible_ssh_user:指定 ssh 用戶 ansible_ssh_pass: 指定 ssh 用戶登錄是認證密碼(明文密碼不安全) ansible_sudo_pass: 指明 sudo 時候的密碼
添加的內容如下:
[root@itlaoxin162 ~]# grep -v ^# /etc/ansible/hosts |grep -v ^$
[web-servers]
192.168.1.163 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass=12345678
[root@itlaoxin16
直接添加到檔案文末就可以;
測驗主機的連通性
[root@itlaoxin162 ~]# ansible -i /etc/ansible/hosts web-servers -m ping
[WARNING]: Invalid characters were found in group names but not replaced, us
see details
192.168.1.163 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
查看組下所有的IP:
[root@itlaoxin162 ~]# ansible all --list
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
hosts (1):
192.168.1.163
[root@itlaoxin162 ~]#
2. 基于ssh密鑰來訪問定義主機清單
設定密鑰
[root@itlaoxin162 ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:CWdEZJbtzH4+ypeXe80jPnBr9UX/0yChZtX5DCjKckg root@itlaoxin162
The key's randomart image is:
+---[RSA 2048]----+
| o*o |
| +. . |
| . o+ o . |
| E+ .= + + .|
| . oSo + . =.|
| o + =.o...=|
| o o oooo+*|
| . ==ooB|
| ooo++oo|
+----[SHA256]-----+
[root@itlaoxin162 ~]#
拷貝密鑰并測驗
[root@itlaoxin162 ~]# ssh-copy-id root@192.168.1.163
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.1.163's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.1.163'"
and check to make sure that only the key(s) you wanted were added.
**登陸測驗:**
[root@itlaoxin162 ~]# ssh 192.168.1.163
Last login: Wed Apr 21 08:13:14 2021 from 192.168.1.162
71服務器也發送密鑰
[root@itlaoxin162 ~]# ssh-copy-id root@192.168.1.71
修改hosts
vim /etc/ansible/hosts

查看組態檔中剛剛修改的內容
[root@itlaoxin162 ~]# grep -v "^#" /etc/ansible/hosts |grep -v "^$"
[web-servers]
192.168.1.163
192.168.1.71
ansible遠程執行命令測驗
ping模塊 主要用來檢測網路的連通性
command模塊,執行shell命令
使用ping檢查‘web-servers’或者ansible節點的連通性,
[root@itlaoxin162 ~]# ansible -i /etc/ansible/hosts 'web-servers' -m ping
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.163 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
192.168.1.71 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
[root@itlaoxin162 ~]#
這條命令我們也可以不指定hosts,效果是一樣的,我們只要指定組即可
[root@itlaoxin162 ~]# ansible 'web-servers' -m ping
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
192.168.1.163 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
[root@itlaoxin162 ~]#
有時候我們為了方便閱讀也把主機組名寫在最后面
web-servers 這個組名,放在最后面
[root@itlaoxin162 ~]# ansible -m command -a "uptime" 'web-servers'
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED | rc=0 >>
08:37:28 up 11 min, 3 users, load average: 0.02, 0.15, 0.17
192.168.1.163 | CHANGED | rc=0 >>
08:37:28 up 1:58, 5 users, load average: 0.00, 0.01, 0.05
[root@itlaoxin162 ~]#
案例1: 檢查節點的記憶體情況
[root@itlaoxin162 ~]# ansible -m command -a "free -m " 'web-servers'
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 3770 826 2283 15 661 2709
Swap: 2047 0 2047
192.168.1.163 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 3770 892 1076 38 1802 2588
Swap: 2047 0 2047
[root@itlaoxin162 ~]#
案例2:給節點增加用戶
[root@itlaoxin162 ~]# ansible -m command -a "useradd itoldxin" 'web-servers'
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED | rc=0 >>
192.168.1.163 | CHANGED | rc=0 >>
[root@itlaoxin162 ~]#
查看是否創建用戶成功
[root@itlaoxin162 ~]# ansible -m command -a "id itoldxin" 'web-servers'
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED | rc=0 >>
uid=1001(itoldxin) gid=1001(itoldxin) 組=1001(itoldxin)
192.168.1.163 | CHANGED | rc=0 >>
uid=1001(itoldxin) gid=1001(itoldxin) 組=1001(itoldxin)
[root@itlaoxin162 ~]#
四. ansible的高級用法
1. ansible的常用模塊
1) ansible的3個遠程模塊的區別
-
command : ansible的默認模塊,不指定-m引數的時候,使用的就是command模塊; 常見的命令都可以使用,但命令的執行不是通過shell來執行的,所以< > | and & z這些操作都不可以,不支持管道,沒法批量執行命令
-
shell模塊: 使用shell模塊的時候默認是通過/bin/sh來執行的,所以在終端輸入的各種命令都可以使用
-
scripts模塊
使用scripts模塊可以在本地寫一個腳本,在遠程服務器上執行
案例1:使用shell模塊的案例
[root@itlaoxin162 ~]# ansible -i /etc/ansible/hosts web-servers -m shell -a "source ~/.bash_profile && df -h|head -n 1"
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED | rc=0 >>
檔案系統 容量 已用 可用 已用% 掛載點
192.168.1.163 | CHANGED | rc=0 >>
檔案系統 容量 已用 可用 已用% 掛載點
[root@itlaoxin162 ~]#
注意: shell也可以把一個腳本copy到遠程端然后再執行,但這樣的話就需要呼叫兩次ansible,所以script的出現就解決了這個問題;
案例2:使用script 模塊
先寫一個腳本:
[root@itlaoxin162 ~]# cat !$
cat /etc/ansible/test.sh
#!/bin/bash
date
hostname
echo "大家好,我是互聯網老辛,腳本執行成功"
[root@itlaoxin162 ~]#
執行查看結果:
[root@itlaoxin162 ~]# ansible -i /etc/ansible/hosts web-servers -m script -a "/etc/ansible/test.sh"
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED => {
"changed": true,
"rc": 0,
"stderr": "Shared connection to 192.168.1.71 closed.\r\n",
"stderr_lines": [
"Shared connection to 192.168.1.71 closed."
],
"stdout": "2021年 04月 21日 星期三 08:59:33 CST\r\nk8s-master\r\n大家好,我是互聯網老辛,腳本執行成功\r\n",
"stdout_lines": [
"2021年 04月 21日 星期三 08:59:33 CST",
"k8s-master",
"大家好,我是互聯網老辛,腳本執行成功"
]
}
192.168.1.163 | CHANGED => {
"changed": true,
"rc": 0,
"stderr": "Shared connection to 192.168.1.163 closed.\r\n",
"stderr_lines": [
"Shared connection to 192.168.1.163 closed."
],
"stdout": "2021年 04月 21日 星期三 08:59:33 CST\r\nitlaoxin-163\r\n大家好,我是互聯網老辛,腳本執行成功\r\n",
"stdout_lines": [
"2021年 04月 21日 星期三 08:59:33 CST",
"itlaoxin-163",
"大家好,我是互聯網老辛,腳本執行成功"
]
}
[root@itlaoxin162 ~]#
可以看到已經執行成功
2) copy模塊的使用
copy模塊:實作主控端向目標主機拷貝檔案,類似scp功能
案例1: 把ansible主機的/etc/hosts 拷貝到主機組機器中的/root/下
[root@itlaoxin162 ~]# ansible -i /etc/ansible/hosts web-servers -m copy -a "src=/etc/hosts dest=/root owner=root group=root mode=0777"
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "700a03c76a37e929d448b3be6419f4289d9314e6",
"dest": "/root/hosts",
"gid": 0,
"group": "root",
"md5sum": "138004edd9d16f2818e20842fc1f273d",
"mode": "0777",
"owner": "root",
"secontext": "system_u:object_r:admin_home_t:s0",
"size": 183,
"src": "/root/.ansible/tmp/ansible-tmp-1618966980.44-20046-203314294949142/source",
"state": "file",
"uid": 0
}
192.168.1.163 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "700a03c76a37e929d448b3be6419f4289d9314e6",
"dest": "/root/hosts",
"gid": 0,
"group": "root",
"md5sum": "138004edd9d16f2818e20842fc1f273d",
"mode": "0777",
"owner": "root",
"secontext": "system_u:object_r:admin_home_t:s0",
"size": 183,
"src": "/root/.ansible/tmp/ansible-tmp-1618966980.45-20045-254958397204815/source",
"state": "file",
"uid": 0
}
[root@itlaoxin162 ~]#
查看是否執行成功:
[root@itlaoxin162 ~]# ansible -m command -a "ls /root/hosts" 'web-servers'
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED | rc=0 >>
/root/hosts
192.168.1.163 | CHANGED | rc=0 >>
/root/hosts
[root@itlaoxin162 ~]#
注意: command 不能使用ll命令,但可以使用ls -l的命令
[root@itlaoxin162 ~]# ansible -m command -a "ls -l /root/hosts" 'web-servers'
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED | rc=0 >>
-rwxrwxrwx. 1 root root 183 4月 21 09:03 /root/hosts
192.168.1.163 | CHANGED | rc=0 >>
-rwxrwxrwx. 1 root root 183 4月 21 09:03 /root/hosts
[root@itlaoxin162 ~]#
3. file模塊
案例5 給檔案設定權限
[root@itlaoxin162 ~]# ansible -i /etc/ansible/hosts web-servers -m file -a "path=/root/hosts mode=0755"
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 0,
"group": "root",
"mode": "0755",
"owner": "root",
"path": "/root/hosts",
"secontext": "system_u:object_r:admin_home_t:s0",
"size": 183,
"state": "file",
"uid": 0
}
192.168.1.163 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 0,
"group": "root",
"mode": "0755",
"owner": "root",
"path": "/root/hosts",
"secontext": "system_u:object_r:admin_home_t:s0",
"size": 183,
"state": "file",
"uid": 0
}
[root@itlaoxin162 ~]#
查看權限:
[root@itlaoxin162 ~]# ansible -m command -a "ls -l /root/hosts" 'web-servers'
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED | rc=0 >>
-rwxr-xr-x. 1 root root 183 4月 21 09:03 /root/hosts
192.168.1.163 | CHANGED | rc=0 >>
-rwxr-xr-x. 1 root root 183 4月 21 09:03 /root/hosts
[root@itlaoxin162 ~]#
4. stat模塊獲取遠程檔案資訊
案例6 獲取檔案資訊
[root@itlaoxin162 ~]# ansible -i /etc/ansible/hosts web-servers -m stat -a "path=/root/hosts"
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"stat": {
"atime": 1618966982.400622,
"attr_flags": "",
"attributes": [],
"block_size": 4096,
"blocks": 8,
"charset": "us-ascii",
"checksum": "700a03c76a37e929d448b3be6419f4289d9314e6",
"ctime": 1618967480.9315438,
"dev": 64768,
"device_type": 0,
"executable": true,
"exists": true,
"gid": 0,
"gr_name": "root",
"inode": 78337,
"isblk": false,
"ischr": false,
"isdir": false,
"isfifo": false,
"isgid": false,
"islnk": false,
"isreg": true,
"issock": false,
"isuid": false,
"mimetype": "text/plain",
"mode": "0755",
"mtime": 1618966981.7806218,
"nlink": 1,
"path": "/root/hosts",
"pw_name": "root",
"readable": true,
"rgrp": true,
"roth": true,
"rusr": true,
"size": 183,
"uid": 0,
"version": "693378940",
"wgrp": false,
"woth": false,
"writeable": true,
"wusr": true,
"xgrp": true,
"xoth": true,
"xusr": true
}
}
192.168.1.163 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"stat": {
"atime": 1618966982.6472814,
"attr_flags": "",
"attributes": [],
"block_size": 4096,
"blocks": 8,
"charset": "us-ascii",
"checksum": "700a03c76a37e929d448b3be6419f4289d9314e6",
"ctime": 1618967481.0644567,
"dev": 64768,
"device_type": 0,
"executable": true,
"exists": true,
"gid": 0,
"gr_name": "root",
"inode": 33662547,
"isblk": false,
"ischr": false,
"isdir": false,
"isfifo": false,
"isgid": false,
"islnk": false,
"isreg": true,
"issock": false,
"isuid": false,
"mimetype": "text/plain",
"mode": "0755",
"mtime": 1618966982.176287,
"nlink": 1,
"path": "/root/hosts",
"pw_name": "root",
"readable": true,
"rgrp": true,
"roth": true,
"rusr": true,
"size": 183,
"uid": 0,
"version": "1103139934",
"wgrp": false,
"woth": false,
"writeable": true,
"wusr": true,
"xgrp": true,
"xoth": true,
"xusr": true
}
}
5. get_url 模塊
實作遠程主機下載指定的url地址,支持sha256sum檔案校驗
案例7
ansible -i /etc/ansible/hosts web-servers -m get_url -a "url=https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm dest=/tmp/ mode=0440 force=yes"
注:url=https://xxx 的等號=前后不能有空格
擴展:查看force=yes的作用
6. yum模塊
yum模塊linux平臺軟體包管理,
yum模塊可以提供的status狀態: latest ,present,installed #這三個代表安裝;removed, absent #這兩個是卸載
案例8 使用yum模塊安裝httpd
ansible -i /etc/ansible/hosts web-servers -m yum -a “name=httpd state=latest”
7. cron模塊遠程管理主機crontab配置
案例9: 增加每30分鐘執行 echo"我是互聯網老辛"
ansible -i /etc/ansible/hosts web-servers -m cron -a “name=‘list dir’ minute=’*/30’ job=‘echo 我是互聯網老辛”’”
8. service 遠程管理主機系統服務模塊
service模塊常用引數:
(1)、name引數:此引數用于指定需要操作的服務名稱,比如 nginx,httpd,
(2)、state引數:此引數用于指定服務的狀態
比如,我們想要啟動遠程主機中的httpd,則可以將 state 的值設定為 started;
如果想要停止遠程主機中的服務,則可以將 state 的值設定為 stopped,
此引數的可用值有 started、stopped、restarted(重啟)、reloaded,
enabled引數:此引數用于指定是否將服務設定為開機 啟動項,設定為 yes 表示將對應服務設定為開機啟動,設定為 no 表示不會開機啟動,
注:想使用service模塊啟動服務,被啟動的服務,必須可以使用service 命令啟動或關閉
案例10 使用service模塊重啟httpd
[root@itlaoxin162 ~]# ansible -i /etc/ansible/hosts web-servers -m service -a "name=httpd state=restarted"
9. user模塊 管理遠程主機的用戶
案例11: 使用user模塊創建一個用戶itlaoxin
[root@itlaoxin162 ~]# ansible -i /etc/ansible/hosts web-servers -m user -a "name=itlaoxin state=present"
[WARNING]: Invalid characters were found in group names but not replaced, use
-vvvv to see details
192.168.1.71 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"comment": "",
"create_home": true,
"group": 1002,
"home": "/home/itlaoxin",
"name": "itlaoxin",
"shell": "/bin/bash",
"state": "present",
"system": false,
"uid": 1002
}
192.168.1.163 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"comment": "",
"create_home": true,
"group": 1002,
"home": "/home/itlaoxin",
"name": "itlaoxin",
"shell": "/bin/bash",
"state": "present",
"system": false,
"uid": 1002
}
[root@itlaoxin162 ~]#
五. ansible 實戰案例
playbooks的介紹
1) 在playbooks 中定義任務:
- name: task description #任務描述資訊
module_name: module_args #需要使用的模塊名字: 模塊引數
2) ansible-playbook 執行 命令:
ansible-playbook site.yml
- playbook是由一個或多個"play"組成的串列,play的主要功能在于將事先歸為一組的主機裝扮成事先通過ansible中的task定義好的角色,
github上提供了大量的實體供大家參考: https://github.com/ansible/ansible-examples
實戰一: 使用playbook 批量部署多臺LAMP環境
先介紹下: Playbook常用檔案夾作用:
- files:存放需要同步到異地服務器的原始碼檔案及組態檔;
- handlers:當服務的組態檔發生變化時需要進行的操作,比如:重啟服務,重新加載組態檔,handlers ['h?ndl?z] 處理程式
- meta:角色定義,可留空;
- tasks:需要進行的執行的任務;
- templates:用于執行lamp安裝的模板檔案,一般為腳本;
- vars:本次安裝定義的變數
搭建思路
思路:我們搭建lanp架構,大概需要:
yum 安裝服務
service 啟動
copy 把網站拷貝過去
在playbooks 中定義任務:
name: task description #任務描述資訊
module_name: module_args #需要使用的模塊名字:
github上提供了大量的實體供大家參考:
https://github.com/ansible/ansible-examples 4.2
使用Playbook批量部署多臺LAMP環境步驟
我們可以在ansible服務器上安裝LAMP環境,然后,再將組態檔通過ansible拷貝到遠程主機上
第一步:安裝httpd軟體
[root@ansible ~]# yum -y install httpd -y
第二部:安裝MySQL
[root@ansible ~]# yum install mariadb-server mariadb -y #安裝mysql服務
[root@ansible ~]# mkdir -p /mysqldata/data/ #創建目錄作為資料存放的位置
[root@ansible ~]# chown -R mysql:mysql /mysqldata/ #授權
[root@ansible ~]# vim /etc/my.cnf #改變資料存放目錄改:
2 datadir=/var/lib/mysql
改為:2 datadir=/mydata/data/
[root@ansible data]# systemctl start mariadb
第三步:安裝PHP和php-mysql模塊
[root@ansible ~]# yum -y install php php-mysql
第四步:提供php的測驗頁
[root@ansible ~]# vim /var/www/html/index.php
[root@ansible ~]# cat /var/www/html/index.php
<?php
phpinfo();
?>
[root@ansible ~]# systemctl reload httpd #啟動httpd服務
httpd測驗:http://192.168.43.162
確保已經出現上面的測驗頁,而且,要看到MySQL已經被整合進來了,才能進行下一步操作
第五;定義組名
[root@ansible ~]# vim /etc/ansible/hosts #還使用之前定義好的,這里不用修改
[webservers]
192.168.1.163
192.168.1.71
然后,將公鑰資訊復制到被控制節點,ansible和兩個節點間通過ssh進行連接,下面3個命令之前已經做過,不用執行了,
[root@ansible ~]# ssh-keygen
[root@ansible ~]# ssh-copy-id root@192.168.1.163
[root@ansible ~]# ssh-copy-id root@192.168.1.71
第六:使用playbook創建一個LAMP構建的任務
1、創建相關檔案
[root@ansible ~]# mkdir -pv /etc/ansible/lamp/roles/{prepare,httpd,mysql,php}/{tasks,files,templates,vars,meta,default,handlers}
我們將上面搭建成功的LAMP環境的httpd和MySQL的組態檔拷貝到對應目錄下
[root@ansible ~]# cd /etc/ansible/ [root@ansible ansible]# cp /etc/httpd/conf/httpd.conf lamp/roles/httpd/files/
[root@ansible ansible]# cp /etc/my.cnf lamp/roles/mysql/files/
[root@ansible ansible]# 寫prepare(前期準備)角色的playbooks
[root@ansible ansible]# vim lamp/roles/prepare/tasks/main.yml
[root@ansible ansible]# cat lamp/roles/prepare/tasks/main.yml
- name: delete yum config
shell: rm -rf /etc/yum.repos.d/* #洗掉原有的yum組態檔
- name: provide yumrepo file
shell: wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo #下載新的yum組態檔
- name: clean the yum repo
shell: yum clean all #清除原有的yum快取資訊
- name: clean the iptables
shell: iptables -F #清除原有防火墻規則,不然后可能上不了網
[root@ansible ansible]#
2、構建httpd的任務
[root@ansible ansible]# cd /etc/ansible/lamp/roles/
[root@ansible roles]# mv /var/www/html/index.php httpd/files/
[root@ansible roles]# vim httpd/tasks/main.yml
[root@ansible roles]# cat httpd/tasks/main.yml
[root@ansible roles]# cat httpd/tasks/main.yml
- name: web server install
yum: name=httpd state=present #安裝httpd服務
- name: provide test page
copy: src=index.php dest=/var/www/html #提供測驗頁
- name: delete apache config
shell: rm -rf /etc/httpd/conf/httpd.conf #洗掉原有的apache組態檔,如果不洗掉,下面的copy任務是不會執行的,因為當源檔案httpd.conf和目標檔案一樣時,copy命令是不執行的,如果copy命令不執行,那么notify將不呼叫handler,
- name: provide configuration file
copy: src=httpd.conf dest=/etc/httpd/conf/httpd.conf #提供httpd的組態檔
notify: restart httpd #當前面的copy復制成功后,通過notify通知名字為restart httpd的handlers運行
3、構建httpd的handlers
[root@ansible roles]# vim httpd/handlers/main.yml
[root@ansible roles]# cat httpd/handlers/main.yml
- name: restart httpd
service: name=httpd enabled=yes state=restarted
[root@ansible roles]#
4、部署我們的MariaDB資料庫
創建MySQL服務的任務,需要安裝MySQL服務,改變屬主資訊,啟動MySQL
[root@ansible roles]# cd /etc/ansible/lamp/roles/
[root@ansible roles]# vim mysql/tasks/main.yml
[root@ansible roles]# cat mysql/tasks/main.yml
-name: install the mysql
yum: name=mariadb-server state=present #安裝mysql服務
- name: mkdir date directory
shell: mkdir -p /mydata/data #創建掛載點目錄
- name: provide configration file
copy: src=my.cnf dest=/etc/my.cnf #提供mysql的組態檔
- name: chage the owner
shell: chown -R mysql:mysql /mydata/ #更改屬主和屬組
- name: start mariadb
service: name=mariadb enabled=yes state=started #啟動mysql服務
5、構建PHP的任務
[root@ansible roles]# vim php/tasks/main.yml
- name: install php
yum: name=php state=present #安裝php
- name: install php-mysql
yum: name=php-mysql state=present #安裝php與mysql互動的插件
6、定義整個的任務
[root@ansible roles]# cd /etc/ansible/lamp/roles/
[root@ansible roles]# vim site.yml
[root@ansible roles]# cat site.yml
- name: LAMP build
remote_user: root
hosts: web-servers
roles:
- prepare
- mysql
- php
- httpd
注:所有yml的組態檔中,空格必須嚴格對
開始部署:
[root@ansible roles]# ansible-playbook -i /etc/ansible/hosts /etc/ansible/lamp/roles/site.yml
然后,在瀏覽器中訪問這兩臺節點主機,可以直接訪問成功.
總結:做此實驗室,需要準備干凈環境,selinux、防火墻都要關閉
實戰二: 使用ansible部署k8s及集群
安裝git命令
[root@itlaoxin162 ~]# yum install git
使用git下載相應的ansible-k8s-insatall 包:
[root@itlaoxin162 ~]# git clone https://github.com/lizhenliang/ansible-install-k8s
正克隆到 'ansible-install-k8s'...
remote: Enumerating objects: 157, done.
remote: Counting objects: 100% (157/157), done.
remote: Compressing objects: 100% (123/123), done.
remote: Total 157 (delta 46), reused 114 (delta 20), pack-reused 0
接收物件中: 100% (157/157), 150.68 KiB | 110.00 KiB/s, done.
處理 delta 中: 100
進入到ansbile-install-k8s目錄
修改hosts檔案,根據規劃修改對應IP和名稱,
cd ansible-install-k8s
[root@itlaoxin162 ansible-install-k8s]# vim hosts
[root@itlaoxin162 ansible-install-k8s]# vim group_vars/all.yml
部署命令:
單Master版
ansible-playbook -i hosts single-master-deploy.yml -uroot -k
多master版
ansible-playbook -i hosts multi-master-deploy.yml -uroot -k
總結
ansible入門很簡單,需要反復練習,才能熟練,
我是互聯網老辛,歡迎點贊收藏,關注我,后期更多精彩內容;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/278973.html
標籤:其他
