# Ansible安裝配置
## 1,ansible安裝
```
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-6.repo
#m01
yum install ansible -y
yum install libselinux-python -y
#backup nfs01
yum install libselinux-python -y
```
## 2,修改配置文件
```
[root@m01 ~]# tree /etc/ansible/
/etc/ansible/
├── ansible.cfg #ansible的配置文件
├── hosts #ansible管理了 哪些服務器 服務器列表
└── roles
1 directory, 2 files
[root@m01 ~]# cat /etc/ansible/hosts
[oldboy]
172.16.1.31
172.16.1.41
```
### 2.1分發密鑰
* #0,生成密鑰
```
ssh-keygen -t dsa
```
* #1,取消第一次連接的提示
```
sed -i 's/#host_key_checking = False/host_key_checking = False/g' /etc/ansible/ansible.cfg
```
* #2,修改/etc/ansible/hosts文件
```
cat >> /etc/ansible/hosts<<EOF
[oldboy]
10.0.0.22
10.0.0.24
[oldboy:vars]
ansible_ssh_user=root
ansible_ssh_pass=123456
ansible_ssh_port=22
EOF
```
* #3,分發密鑰
```
ansible oldboy -m authorized_key -a "user=root key='{{ lookup('file', '/root/.ssh/id_dsa.pub') }}'"
```
## 3,測試ad-hoc
```
#執行命令
ansible oldboy -m command -a "hostname"
#ansible oldboy -m command -a "yum install cowsay -y
#復制文件到oldboy配置的主機的/tmp/目錄下 并且更改文件屬主,并把權限改為0755
ansible oldboy -m copy -a "src=/etc/hosts dest=/tmp owner=oldboy mode=0755"
#執行命令
ansible oldboy -m command -a "ls -l /tmp/hosts"
#復制文件 如果目標主機有文件,則備份
ansible oldboy -m copy -a "src=/etc/hosts dest=/tmp backup=yes"
#查看文檔
ansible-doc -l|wc -l
ansible-doc -s copy
#復制文件
ansible oldboy -m copy -a "src=/server/scripts/yum-htop.sh dest=/server/scripts/ "
#執行腳本
ansible oldboy -m shell -a "/bin/sh /server/scripts/yum-htop.sh"
ansible oldboy -m script -a "/server/scripts/yum.sh"
ansible oldboy -m cron -a "name='restart network' minute=00 hour=00 job=' /etc/init.d/network restart >/dev/null 2>&1'"
ansible oldboy -a "crontab -l"
```
## 4,測試playbook
```
mkdir -p /server/playbook
vim ifconfig.yml
- hosts: oldboy
tasks:
- command: ifconfig
- shell: ifconfig >/tmp/ip.log
ansible-playbook -C ifconfig.yml
ansible-playbook ifconfig.yml
vim print-ip.yml
- hosts: all
tasks:
- name: get ip address
shell: ifconfig eth0 |awk -F "[ :]+" 'NR==2{print $4}' >>/tmp/ip.log
ansible-playbook -C print-ip.yml
ansible-playbook print-ip.yml
ansible all -a "tail -1 /tmp/ip.log
ansible oldboy -m cron -a 'name="restart network" minute=00 hour=00 job="/etc/init.d/network restart >/dev/null 2>&1" state=present'
#添加定時任務
cat add-cron.yml
- hosts: oldboy
tasks:
- name: add restart network cron
cron: name="restart network" minute=00 hour=00 job="/etc/init.d/network restart >/dev/null 2>&1" state=present
ansible oldboy -a "crontab -l"
ansible-playbook -C add-cron.yml
ansible-playbook add-cron.yml
- hosts: oldboy
tasks:
- name: add restart network cron
cron:
name: restart network
minute: 00
hour: 00
job: /etc/init.d/network restart >/dev/null 2>&1
state: present
```
## 注意:
centos6.8 使用ansible-doc -l報錯
解決方法:
```
sed -i 's@#deprecation_warnings = True@deprecation_warnings = False@g' /etc/ansible/ansible.cfg
mv /usr/lib/python2.6/site-packages/ansible/modules/extras/cloud/misc/rhevm.py /tmp/
```