# 自動化運維工具ansible
## 1.安裝
```
yum install -y ansible cowsay
```
## 2.配置
```
vim /etc/ansible/hosts
```
將要管理的主機加入配置文件,前提要做好ssh-key秘鑰登錄,這里不做描述
```
[nodes]
192.168.2.4
192.168.2.5
192.168.2.6
```
## 3.常用模塊
`ping`模塊:檢測被控主機是否能ping通
```shell
ansible nodes -m ping #ansible后加主機可以是all、在hosts文件配置的標簽如nodes、或者ip,-m指定模塊
```
`command`模塊:執行命令,只能執行簡單的命令,無法解釋特殊符號,如管道|,統配*等等,不指定模塊默認是執行此模塊
```shell
ansible all -m command -a "ifconfig" #-a后指定動作
```
`shell`模塊:
```shell
ansible all -m shell -a "hostname >/tmp/hostname.txt"
```
`copy`模塊:把管理機的文件復制到被控主機
```shell
ansibe all -m copy -a "src=/scripts/lnmp.sh dest=/root"
```
```shell
ansibe all -m copy -a "src=/scripts/lnmp.sh dest=/root/LNMP.sh owner=nobody group=nobody mode=700"
```
`script`模塊:相當于結合`shell`模塊和`copy`模塊,先把腳本傳到服務器上再執行
```shell
ansible all -m script -a "/scripts/lnmp.sh"
```
`file`模塊:修改文件用戶,組,權限,路徑,創建目錄或文件
要指定path,state(directory|touch|link)
```shell
ansible all -m file -a "path=/www state=directory"
```
`yum`模塊:指定包名,版本state有:present,latest
```shell
ansible all -m yum -a "name=nginx state=present"
```
`cron`模塊:定時任務,相當于`vi /var/spool/cron/root`
```shell
ansible all -m cron -a 'name="backup etc" minute=00 hour=00 job="tar zcf /tmp/backup.tar.gz /backup/* >/dev/null 2>&1" state=present'
```
刪除某個定時任務,指定state為adsent即可
```shell
ansible all -m cron -a 'name="backup etc" state=absent'
```
## 3.playbook劇本
```
vim /etc/ansible/xxx.yml
```
```yaml
---
- hosts: all
task:
- name: show hostname
command: hostname
```
執行
```shell
ansible-playbook -C /etc/ansible/xxx.yml #檢測playbook語法是否正確
```
```shell
ansible-playbook /etc/ansible/xxx.yml
```
添加定時任務,如cron.yml
```yaml
---
- hosts: all
tasks:
- name: add cron
cron:
name: "backup etc"
minute: 00
hour: 00
job: "tar zcf /tmp/backup.tar.gz /backup/* >/dev/null 2>&1"
state: present
```
## 4.absible注冊變量
在playbook里使用變量,使用vars定義好后,用連個花括號表示引用`{{}}`
```yaml
---
- hosts: all
vars:
file: shz.txt
dir: /root/
tasks:
- name: touch file
file: path={{dir}}/{{file}} state=touch
```
使用系統命令作為變量
```yaml
---
- hosts: all
tasks:
- name: get ip address
shell: hostname -I
register: ip
- name: print ip var to file
shell: echo {{ip.stdout}} >/tmp/ip.txt
```
如下實例一個打包備份配置文件的playbook
```yaml
---
- hosts: all
tasks:
- name: get ip
shell: hostname -I
register: ip
- name: get date
shell: date +%F
register: date
- name: mkdir
file: path=/backup/{{ip.stdout}} state=directory
- name: tar
shell: tar zcf /backup/etc-{{ip.stdout}}-{{date.stdout}}.tar.gz /etc/*
```
如何調試變量
`debug`模塊:msg={{xxx}}
```yaml
---
- hosts: all
tasks:
- name: get ip
shell: hostname -I
register: ip
- name: debug test
debug: msg={{ip}}
```
然后直接執行即可,不需要`-C`檢查錯誤
## 5.ansible循環和判斷
循環
```yaml
---
- hosts: all
tasks:
- name: show ip
shell: echo 192.168.2.{{item}} >/tmp/test1.txt
with_items:
- 4
- 5
- 6
```
條件,when指定主機名 `ansible_hostname`叫做ansible內置變量
```yaml
---
- hosts: all
tasks:
- name: install nfs
yum: name=nfs-utils,rpcbind state=present
when: ( ansible_hostname == "node3" )
```
查看ansible所有內置變量
```
ansible 192.168.2.5 -m setup
```