三、Ansible基礎命令
Ansible命令執行過程及狀態
過程:
- 加載自己的配置文件,默認/etc/ansible/ansible.cfg
- 加載自己對應的模塊文件,如command ping
- 通過ansible將模塊或命令生成對應的臨時py文件,並將該文件傳輸至遠程服務器
- 給文件+x權限
- 執行並返回結果
- 刪除臨時py文件,sleep 10 退出
狀態:
- 綠色:執行成功並且不需要做改變的動作
- 黃色:執行成功並且對目標主機做變更
- 紅色:執行失敗
1、Ansible命令用法
1)Ansible命令
ansible ansible-doc ansible-playbook ansible-vault ansible-console ansible-galaxy ansible-pull
- Ansible-doc 顯示模塊幫助
ansible-doc [options] [module...]
-a 顯示所有模塊的文檔
-l --list 列出可用模塊
-s --snippet 顯示制定模塊的playbook片段
示例:
ansible-doc -l 列出所有模塊
ansible-doc ping 查看制定模塊幫助用法
ansible-doc -s ping 查看制定模塊幫助用法
- Ansible命令用法
ansible <host-pattern> [-m module_name] [-a args]
--version 顯示版本
-m module 制定模塊默認為 command
-v 詳細過程 -vv -vvv更詳細
--list-hosts 顯示主機列表 可以簡寫為--list
-k --ask-pass 提示數據ssh連接密碼 默認key驗證
-K --ask-become-pass 提示輸入sodu的口令
-C check 檢查並不執行
-T --timeout=TIMEOUT 執行命令的超時時間 默認10s
-u --user=REMOTE_USER 執行遠程執行的用戶
-b --become 代替舊版的sudo切換
試驗:使用white用戶連接web組下的服務器查看root家目錄下的內容:
[root@ansible ~]# ansible web -u white -k -m command -a 'ls /root'
SSH password:
172.16.111.7 | FAILED | rc=2 >>
ls: cannot open directory /root: Permission deniednon-zero return code
172.16.111.8 | FAILED | rc=2 >>
ls: cannot open directory /root: Permission deniednon-zero return code
顯示沒有權限
[root@ansible ~]# ansible web -m command -a 'ls /root' -u white -k -b -K
SSH password:
SUDO password[defaults to SSH password]:
172.16.111.8 | FAILED! => {
"changed": false,
"module_stderr": "Shared connection to 172.16.111.8 closed.\r\n",
"module_stdout": "\r\nWe trust you have received the usual lecture from the local System\r\nAdministrator. It usually boils down to these three things:\r\n\r\n #1) Respect the privacy of others.\r\n #2) Think before you type.\r\n #3) With great power comes great responsibility.\r\n\r\n\r\nSorry, user white is not allowed to execute '/bin/sh -c echo BECOME-SUCCESS-mpdogqixumfmgqlscdyojejjgicjppfi; /usr/bin/python /home/white/.ansible/tmp/ansible-tmp-1540363523.36-270983856118240/command.py; rm -rf \"/home/white/.ansible/tmp/ansible-tmp-1540363523.36-270983856118240/\" > /dev/null 2>&1' as root on node2.\r\n",
"msg": "MODULE FAILURE",
"rc": 1
}
172.16.111.7 | SUCCESS | rc=0 >>
a
anaconda-ks.cfg
CentOS-Base.repo
checkout
elasticsearch-6.0.0.rpm
nginx-1.12.2
nginx-1.12.2.tar.gz
update
此時發現 node1可以 2 不可以 查詢由於white用戶在node2沒有sudo授權 ,visudo修改 visudo -c檢測
[root@ansible ~]# ansible web -m command -a 'ls /root' -u white -k -b -K
SSH password:
SUDO password[defaults to SSH password]:
172.16.111.7 | SUCCESS | rc=0 >>
a
anaconda-ks.cfg
CentOS-Base.repo
checkout
elasticsearch-6.0.0.rpm
nginx-1.12.2
nginx-1.12.2.tar.gz
update
172.16.111.8 | SUCCESS | rc=0 >>
315586643?lang=zh-CN
anaconda-ks.cfg
elasticsearch-2.3.5.rpm
elasticsearch-6.0.0.rpm
kibana-4.5.4-1.x86_64.rpm
logstash-2.3.4-1.noarch.rpm
nginx-1.12.2
nginx-1.12.2.tar.gz
rh-nginx112-nginx-1.12.1-2.el7.x86_64.rpm
以上均是用口令驗證 並且需要使用root權限,存在安全隱患,生產上推薦基於KEY的驗證
2)基於key驗證配置
在ansible主控端生成公鑰,發送到所有被控端
[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:dOv+zF1JdDLy9dpJzfGf1cYl1zGuPC9m2w/0nsLFGPc root@ansible
The key's randomart image is:
+---[RSA 2048]----+
| o |
| . +|
| . . . ++*|
| . . ..+oXO|
| S . +Bo@|
| . o=BE|
| . .++==|
| . oo+++.|
| ..+.oo+|
+----[SHA256]-----+
You have new mail in /var/spool/mail/root
[root@ansible ~]# ssh-copy-id 172.16.111.7
/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/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.16.111.7's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh '172.16.111.7'"
and check to make sure that only the key(s) you wanted were added.
[root@ansible ~]# ssh-copy-id 172.16.111.8
/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/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.16.111.8's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh '172.16.111.8'"
and check to make sure that only the key(s) you wanted were added.
[root@ansible ~]# ssh-copy-id 172.16.111.9
/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/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.16.111.9's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh '172.16.111.9'"
and check to make sure that only the key(s) you wanted were added.
驗證
[root@ansible ~]# ansible all -m ping
172.16.111.9 | SUCCESS => {
"changed": false,
"ping": "pong"
}
172.16.111.7 | SUCCESS => {
"changed": false,
"ping": "pong"
}
172.16.111.8 | SUCCESS => {
"changed": false,
"ping": "pong"
}
3)Ansible的Host-pattern
匹配主機的列表
-
ALL :表示所有Inverntory中的所有主機
ansible all -m ping
-
* :通配符
ansible "*" -m ping
ansible 172.16.111.* -m ping
ansible "web" -m ping
-
邏輯或
ansible "web:app" -m ping
ansible "172.16.111.7:172.16.111.9" -m ping
-
邏輯與
ansible "web:&app" -m ping
-
邏輯非
ansible 'web:!app' -m ping
!!!注意!!!邏輯與或非分別為:& 、: 、:! 非這里只能為但引號 不能是雙引號
-
綜合邏輯
ansible 'web:&app:!db' -m ping
-
正則表達式
ansible "web:&app:!db" -m ping #注意區別綜合邏輯
ansible "~(web|db).*.white.com" -m ping
4)Ansible常用模塊
-
command:在主機執行命令,默認模塊 可以忽略 -m 選項
ansible web -m command -a 'ls /data'
此命令不支持@VARNAME < > | ; &等,需要用shell模塊實現
[root@ansible ~]# ansible-doc command - chdir #切換目錄 - creates #如果如果文件創建,則不執行命令 = free_form # - removes #如果文件不存在 則不執行命令 ansible web -m command -a 'removes =/data ls /data'
-
shell :和command類似 用shell執行命令
ansible web -m shell -a 'echo white|passwd -stdin wange'
調用bash執行命令 類似 cat /tmp/stanley.md|aws -F '|' '{print$1,$2}' &> /tmp/asd.txt 這些復雜命令 ,即使使用shell也可能會失敗,解決辦法:寫到腳本時,copy到遠程 執行 再把需要的結果拉回執行命令的機器
-
Script:運行腳本
-a "/PATH/TO/SCRIPT_FILE"
ansible web -m script -a f1.sh
-
Copy:從服務器復制文件到客戶端
ansible all -m copy -a 'src=/etc/hosts dest=/etc/hosts backup=yes'
src 源 dest目標 backup 備份 onwer 所有者 mode權限
-
Fetch:從客戶端取文件到服務端,與copy相反
ansibles web -m fetch -a 'src=/root/a.sh dest=/data/scripts/'
默認只支持單個文件,不支持多個文件或目錄,做個文件建議放進目錄內tar打包后進行拉取
此時抓取的文件會在/data/scripts/hostname/內hostname是被控端主機的主機名
-
File:設置文件屬性 state比較重要,可以根據state不同值實現不同效果
ansible web -m file -a "path=/root/a.sh owner=white mode=755"
ansible web -m file -a 'src=/app/testfile dest=/app/testfile-link state=link'
#創建文件 [root@ansible ~]# ansible all -m file -a 'path=/tmp/ads state=touch' [root@ansible ~]# ansible all -m shell -a 'ls -l /tmp|grep ads' 172.16.111.9 | SUCCESS | rc=0 >> -rw-r--r--. 1 root root 0 Oct 25 00:48 ads 172.16.111.7 | SUCCESS | rc=0 >> -rw-r--r--. 1 root root 0 Oct 24 16:48 ads 172.16.111.8 | SUCCESS | rc=0 >> -rw-r--r--. 1 root root 0 Oct 24 16:48 ads #刪除文件 [root@ansible ~]# ansible all -m file -a 'path=/tmp/ads state=absent' [root@ansible ~]# ansible all -m shell -a 'ls -l /tmp|grep ads' 172.16.111.9 | FAILED | rc=1 >> non-zero return code 172.16.111.7 | FAILED | rc=1 >> non-zero return code 172.16.111.8 | FAILED | rc=1 >> non-zero return code
如果要創建文件夾 state=directory 刪除也是用absent
#創建軟鏈接 [root@ansible ~]# ansible all -m file -a 'src=/etc/fstab dest=/data/fstab.link state=link' [root@ansible ~]# ansible all -m shell -a 'ls -l /data' 172.16.111.9 | SUCCESS | rc=0 >> total 0 lrwxrwxrwx. 1 root root 10 Oct 25 00:58 fstab.link -> /etc/fstab 172.16.111.7 | SUCCESS | rc=0 >> total 0 lrwxrwxrwx. 1 root root 10 Oct 24 16:58 fstab.link -> /etc/fstab drwxr-xr-x. 3 root root 21 Oct 22 17:10 svndata 172.16.111.8 | SUCCESS | rc=0 >> total 0 lrwxrwxrwx. 1 root root 10 Oct 24 16:58 fstab.link -> /etc/fstab drwxr-xr-x. 3 root root 21 Oct 22 16:33 svndata #刪除軟鏈接 [root@ansible ~]# ansible all -m file -a 'dest=/data/fstab.link state=absent'
-
Hostname: 修改主機名
ansible 172.16.111.7 -m hostname -a 'name=web01'
此時的修改是配置文件和臨時同時修改。重啟后仍然有效。
-
Cron:計划任務模塊
1)創建任務計划
ansible all -m cron -a 'minute=* weekday=1,3,5 job="/usr/bin/wall FBI warining" name=warningcron'
2)取消任務計划 禁用
ansible all -m cron -a 'disabled=true job="/usr/bin/wall FBI warining" name=warningcron'
#取消任務計划時,job和name一定要有 如果沒有name,則會新建一個計划任務然后注釋掉
3)再次打開任務計划
disabled=false
true 也可以用yes
false也可以用no
4)刪除計划任務
ansible all -m cron -a 'job="/usr/bin/wall FBI warining" name=warningcron state=absent'
-
Yum:管理包模塊
默認是安裝 present 或者installed都可以,多個包用,隔開
ansible all -m yum -a 'name=vsftpd'
也可以安裝獨立的二進制包,先用copy模塊把包復制到每個被控制端主機,然后name=/data/***路徑 安裝
查看已經安裝的
ansible all -m yum -a 'list=installed'
卸載 removed和absent都可以
ansible all -m yum -a 'name=vsftpd state=removed'
可以用shell 模塊 rpm -q查看
-
Service:服務模塊
控制遠程開啟服務並加入開啟自啟動
ansible all -m service -a 'name=vsftpd state=started enabled=yes'
enabled 加入開機自啟動
state=started 開啟服務
-
User:用戶管理
創建用戶
ansible all -m user -a 'name=nginx shell=/sbin/nologin system=yes home=/var/nginx groups=root,bin group=nginx uid=1005 comment="nginx serveice"'
home 家目錄
group 主組 groups 輔助組
刪除用戶
ansible all -m user -a 'name=nginx state=absent remove=yes'
remove=yes刪除家目錄
-
Group:組的管理
用法與user類似
創建組
ansible all -m group -a 'name=nginx system=yes gid=80'
刪除組
ansible all -m group -a 'name=nginx state=absent'
2、Ansible-galaxy
-
連接https://galaxy.ansible.com下載相應的roles
-
列出所有已安裝的galaxy
ansible-galaxy list
-
安裝galaxy
ansible-galaxy install geerlingguy.redis
-
刪除galaxy
ansible-galaxy remove geerlingguy.redis
進去后可搜索需要的工具,然后點擊進入,會提示安裝方法的
[root@ansible ~]# ansible-galaxy install stouts.nginx
- downloading role 'nginx', owned by stouts
- downloading role from https://github.com/Stouts/Stouts.nginx/archive/2.1.1.tar.gz
- extracting stouts.nginx to /etc/ansible/roles/stouts.nginx #部署位置
- stouts.nginx (2.1.1) was installed successfully
[root@ansible ~]# ansible-galaxy list
- stouts.nginx, 2.1.1
[root@ansible ~]# tree /etc/ansible/roles/stouts.nginx/
/etc/ansible/roles/stouts.nginx/
├── CONTRIBUTORS
├── defaults
│ └── main.yml
├── files
│ └── nginx.repo
├── handlers
│ └── main.yml
├── LICENSE
├── Makefile
├── meta
│ └── main.yml
├── README.md
├── runtests.sh
├── tasks
│ ├── install.deb.yml
│ ├── install.red.yml
│ ├── main.yml
│ └── nginx.yml
├── templates
│ └── nginx.conf.j2
├── test.yml
└── vars
├── Debian.yml
└── Ubuntu.yml
7 directories, 17 files
3、Ansible-pull
- 推送命令至遠程,效率無線提升,對運維要求較高
對應ansible-push操作,方向相反
4、Ansible-playbook
ansible-playbook hello.yml h后綴是yml或者yaml
[root@ansible ansible]# cat hello.yml
---
- hosts: web
remote_user: root
tasks:
- name: hello
command: hostname
[root@ansible ansible]# ansible-playbook hello.yml
###執行劇本
PLAY [web] *********************************************************************
TASK [Gathering Facts] *********************************************************
ok: [172.16.111.8]
ok: [172.16.111.7]
TASK [hello] *******************************************************************
changed: [172.16.111.7]
changed: [172.16.111.8]
PLAY RECAP *********************************************************************
172.16.111.7 : ok=2 changed=1 unreachable=0 failed=0
172.16.111.8 : ok=2 changed=1 unreachable=0 failed=0
5、Ansible-vault
對劇本文件進行加密
[root@ansible ansible]# ansible-vault encrypt hello.yml
New Vault password:
Confirm New Vault password:
Encryption successful
[root@ansible ansible]# cat hello.yml
$ANSIBLE_VAULT;1.1;AES256
35323762353637376337376338636534653933626364386632623763616538366361656437386335
3463326637303661333665303863326636313662643835610a363764303435333539323166623364
37343935313437336635343566303763623264643737616665626566323136346333393164353731
6164343333643238620a633666333438353130613937333539393832306461613932323566623863
36666661356135376534666636386161323663346331336165623133393163393061353432336530
36336635663834346261393530383765626362353365666136333565313832373430303835333834
33636663666535356563626535663637396230373435336461623130333264663461323461633765
34626333383938653430366232306535636130643165363535343038333939303332643266343535
3834
[root@ansible ansible]# ansible-playbook hello.yml
ERROR! Attempting to decrypt but no vault secrets found
加密后文件內容無法直接cat查看也不能直接運行 需要先解密,護着使用ansible-vault view 查看加密的內容,需提供口令,使用ansible-vault edit 編輯加密的內容,需提供口令,使用ansible-vault rekey 修改原來的口令
[root@ansible ansible]# ansible-vault decrypt hello.yml
Vault password:
Decryption successful
[root@ansible ansible]# ansible-playbook hello.yml
PLAY [web] *********************************************************************
TASK [Gathering Facts] *********************************************************
^[[Aok: [172.16.111.8]
ok: [172.16.111.7]
TASK [hello] *******************************************************************
changed: [172.16.111.7]
changed: [172.16.111.8]
PLAY RECAP *********************************************************************
172.16.111.7 : ok=2 changed=1 unreachable=0 failed=0
172.16.111.8 : ok=2 changed=1 unreachable=0 failed=0
[root@ansible ansible]# cat hello.yml
---
- hosts: web
remote_user: root
tasks:
- name: hello
command: hostname
解密后恢復正常
6、Ansible-console
交互式
[root@ansible ansible]# ansible-console
Vault password:
Welcome to the ansible console.
Type help or ? to list commands.
root@all (3)[f:5]$
root@all (3)[f:5]$ 中 root 賬戶 all :hosts內所有主機 (3)hosts內主機個數 [f:5] 並發數
交互式控制內,可以使用cd命令切換組,被控制端 ,然后直接執行命令
root@172.16.111.9 (1)[f:5]$ list
172.16.111.9
root@172.16.111.9 (1)[f:5]$ cd all
root@all (3)[f:5]$ list
172.16.111.7
172.16.111.8
172.16.111.9
root@all (3)[f:5]$ cd web
root@web (2)[f:5]$ list
172.16.111.7
172.16.111.8
root@web (2)[f:5]$ yum name=httpd state=present
172.16.111.7 | SUCCESS => {
"changed": false,
"msg": "",
"rc": 0,
"results": [
"httpd-2.4.6-80.el7.centos.1.x86_64 providing httpd is already installed"
]
}
172.16.111.8 | SUCCESS => {
"changed": false,
"msg": "",
"rc": 0,
"results": [
"httpd-2.4.6-80.el7.centos.1.x86_64 providing httpd is already installed"
]
}
root@web (2)[f:5]$ service name=httpd state=started