Ansible自動化運維工具學習-第一天

Ansible入門學-第一天

什麼是Ansible??

在博主看來Ansibe就是一個自動化運維工具,能夠批量的執行命令,批量部署業務,批量管理配置.
簡單的來說在Controller上用特定的工具特定的語法.執行你想要命令或者部署業務,Controller能夠根據你所指
定的主句列表下發命令或者配置.
假設我們有如下一個服務器集羣,現要求備份集羣所有服務器的/etc目錄並打包成etc.tar.gz請問怎麼做?
在這裏插入圖片描述
方法大致如下

  1. 實體機就一臺一臺進去操作(笨方法不建議.萬一是分佈式集羣,都不在一個城市你怎麼辦???)
  2. 虛機或者雲主機進控制檯一臺一臺進行操作(這個可行性稍微比上面強一點,但是一臺一臺操作也太麻煩)
  3. SSH遠程一臺一臺進行操作(恭喜進步了,這樣比上面兩個強)
  4. 寫腳本用FTP傳到每一臺機器上,然後只需要運行腳本就好了(恭喜恭喜,又向自動化邁進了一步)
  5. 用自動化運維工具操作(恭喜!!)

現在已經明確了需求,也明確了選擇哪種方式去做,但是!!自動化運維工具那麼多該怎麼選???
既然這樣就不得不提Ansible的優點了(當然我並不否認其他產品,只是個人比較喜歡Ansible)

  1. 沒有客戶端(agent).這意味着,我在現有集羣環境下不用一臺一臺進去安裝客戶端,然後在用Controller操作
  2. 沒有服務端(server),不用在擔心服務突然掛掉啦!!只需要運行命令就可以了
  3. 基於模塊工作,可以使用任意語言開發模塊,開放性,包容性很高
  4. 語法易讀,playbook基於YMAL構建
  5. 基於推送模式,快捷高效有木有???!!?!!
  6. 模塊冪等性,同一個playbook在同一臺服務器執行時安全的.不像shell腳本第二次執行可能出現一些問題

好,現在我們也明白了爲什麼用Ansible那關鍵問題來了,這個工具怎麼安裝??
首先我們要有一臺服務器:

[root@shell ~]# cat /etc/os-release 
NAME="CentOS Linux"
VERSION="8 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="8"
PLATFORM_ID="platform:el8"
PRETTY_NAME="CentOS Linux 8 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:8"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"

CENTOS_MANTISBT_PROJECT="CentOS-8"
CENTOS_MANTISBT_PROJECT_VERSION="8"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="8"

[root@shell ~]# whoami
root
[root@shell ~]# nmcli device status 
DEVICE      TYPE      STATE   CONNECTION 
ens160      ethernet  已連接  ens160     
ens192      ethernet  已連接  ens192     
virbr0      bridge    已連接  virbr0     
lo          loopback  未託管  --         
virbr0-nic  tun       未託管  --         
[root@shell ~]# 

可以看到 我這是一臺Centos8 現在是在root用戶下 有兩塊網卡 ens160用於連接外網 ens192用於連接內網
首先我們要確保能上網(這個應該不需要多說了吧🤣),檢查我們的Python版本

[root@shell ~]# python3
Python 3.6.8 (default, May 21 2019, 23:51:36) 
[GCC 8.2.1 20180905 (Red Hat 8.2.1-3)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 

下面就可以安裝Ansible這個神奇的工具了(好激動,好怕出問題啊😣)

[root@shell ~]# pip3 install ansible --user
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip3 install --user` instead.
Collecting ansible
  Downloading https://files.pythonhosted.org/packages/1b/5c/8a59aba5ca0d40df673aab53d51e9f5890a9c2135c299a909aed5fdee164/ansible-2.8.6.tar.gz (12.7MB)
    100% |????????????????????????????????| 12.7MB 12kB/s 
Requirement already satisfied: jinja2 in /usr/lib/python3.6/site-packages (from ansible)
Requirement already satisfied: PyYAML in /usr/lib64/python3.6/site-packages (from ansible)
Requirement already satisfied: cryptography in /usr/lib64/python3.6/site-packages (from ansible)
Requirement already satisfied: MarkupSafe>=0.23 in /usr/lib64/python3.6/site-packages (from jinja2->ansible)
Requirement already satisfied: idna>=2.1 in /usr/lib/python3.6/site-packages (from cryptography->ansible)
Requirement already satisfied: asn1crypto>=0.21.0 in /usr/lib/python3.6/site-packages (from cryptography->ansible)
Requirement already satisfied: six>=1.4.1 in /usr/lib/python3.6/site-packages (from cryptography->ansible)
Requirement already satisfied: cffi!=1.11.3,>=1.7 in /usr/lib64/python3.6/site-packages (from cryptography->ansible)
Requirement already satisfied: pycparser in /usr/lib/python3.6/site-packages (from cffi!=1.11.3,>=1.7->cryptography->ansible)
Installing collected packages: ansible
  Running setup.py install for ansible ... done
Successfully installed ansible-2.8.6

還好沒出問題,就是我的網速有點慢(我懷疑我被同事限了速,但是沒有證據😑)
測試一下是不是正常

[root@shell ~]# ansible -version
Usage: ansible <host-pattern> [options]

Define and run a single task 'playbook' against a set of hosts

Options:
  -a MODULE_ARGS, --args=MODULE_ARGS
                        module arguments
  --ask-vault-pass      ask for vault password
  -B SECONDS, --background=SECONDS
                        run asynchronously, failing after X seconds
                        (default=N/A)
  -C, --check           don't make any changes; instead, try to predict some
                        of the changes that may occur
  -D, --diff            when changing (small) files and templates, show the
                        differences in those files; works great with --check

目測沒有出問題
現在Ansible也安裝完了,那怎麼使用呢???
那我們就測試一下!!!
Topo如下
在這裏插入圖片描述
配SSH免密登錄

[root@Ansible ~]# 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:I4u5Rb2vtdBAl69AbdhB69CRFbSr/kc73Nuc6KK9PVk root@test1
The key's randomart image is:
+---[RSA 2048]----+
|         .+++.   |
|         =.= .   |
|        = O .    |
|       + = . .   |
|      o S . o    |
|     + o * o  .E |
|    o o o =  ooo |
|     o   =.o.o*.+|
|    .   .o=+==.++|
+----[SHA256]-----+
[root@Ansible ~]# ssh-copy-id [email protected]
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '172.10.10.3 (172.10.10.3)' can't be established.
ECDSA key fingerprint is SHA256:+qRYt/KK1tOKToIGiMkCuMWC95n1QdzaHCDqEStM42Y.
Are you sure you want to continue connecting (yes/no)? ued
Please type 'yes' or 'no': yes
/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@172.10.10.1's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@172.10.10.1'"
and check to make sure that only the key(s) you wanted were added.

[root@Ansible ~]# 

同上配置172.10.10.5的免密登錄

創建playbook的目錄(hosts等文件都放在目錄裏)

[root@Ansible ~]# mkdir playbook
[root@Ansible ~]# cd playbooks/
[root@Ansible playbooks]# vim hosts 
172.10.10.3

那我們就測試一下吧

[root@Ansible playbooks]# ansible -i hosts 172.10.10.3 -m ping
172.10.10.3 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}

看來成功了,沒有問題

通過ansible.cfg簡化配置

[root@Ansible playbooks]# cat ansible.cfg 
[defaults]
inventory = hosts ##定義inventory的位置
remote_user = root ##定義SSH登錄的用戶名
private_key_file = /root/.ssh/id_rsa  ##定義私鑰的位置
host_key_checking = false ##關閉主機密鑰檢查

重新配置我們hosts吧

[root@Ansible playbooks]# vim hosts 
[test1]
172.10.10.3 ansible_host=172.10.10.3 ansible_port=22

[test2]
172.10.10.5 ansible_host=172.10.10.5 ansible_port=22

再讓我們測試一下 配置是否生效

[root@Ansible playbooks]# ansible test1 -a ls
172.10.10.3 | CHANGED | rc=0 >>
公共
模板
視頻
圖片
文檔
下載
音樂
桌面
anaconda-ks.cfg
initial-setup-ks.cfg

[root@Ansible playbooks]# ansible test1 -m ping
172.10.10.3 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
[root@Ansible playbooks]# 

通過測試我們可以看到同組內執行效果
現在我們創建一個test3包含這兩臺主機然後進行測試

[root@Ansible playbooks]# cat hosts 
[test1]
172.10.10.3 ansible_host=172.10.10.3 ansible_port=22

[test2]
172.10.10.5 ansible_host=172.10.10.5 ansible_port=22

[test3]
172.10.10.3 ansible_host=172.10.10.3 ansible_port=22
172.10.10.5 ansible_host=172.10.10.5 ansible_port=22


[root@Ansible playbooks]# ansible test3 -m ping
172.10.10.5 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
172.10.10.3 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}

效果很明顯.
現在回到我們最初的問題怎麼通過Ansible進行集羣/etc目錄備份(已上面所學的知識)
那我們試一下吧!!!

[root@Ansible playbooks]# ansible test3 -a "tar -czf etc.tar.gz /etc"
[WARNING]: Consider using the unarchive module rather than running 'tar'.  If you need to use command because unarchive is
insufficient you can add 'warn: false' to this command task or set 'command_warnings=False' in ansible.cfg to get rid of
this message.

172.10.10.3 | CHANGED | rc=0 >>
tar: 從成員名中刪除開頭的“/”

172.10.10.5 | CHANGED | rc=0 >>
tar: 從成員名中刪除開頭的“/[root@Ansible playbooks]# ansible test3 -a "ls ~"
172.10.10.3 | CHANGED | rc=0 >>
公共
模板
視頻
圖片
文檔
下載
音樂
桌面
anaconda-ks.cfg
etc.tar.gz
initial-setup-ks.cfg

172.10.10.5 | CHANGED | rc=0 >>
公共
模板
視頻
圖片
文檔
下載
音樂
桌面
anaconda-ks.cfg
etc.tar.gz
initial-setup-ks.cfg

結果顯而易見了,我們已經通過Ansible現在所學的知識完成了既定目標
給自己鼓鼓掌吧!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章