1.安装
ansible支持python2.7, python3现在支持的不是很好,所以用python2.7安装ansible
a)配置epel源
wget http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
rpm -ivh epel-release-latest-7.noarch.rpm
yum -y install ansible
b)源码安装:
yum install gcc -y
yum install gcc-c++ -y
yum install autoconf -y
yum install python-devel -y
yum install libffi-devel -y
yum install openssl-devel -y
下载ansible-2.3.1.0.tar.gz
tar xf ansible-2.3.1.0.tar.gz
安装ansible:
cd ansible-2.3.1.0
python setup.py install
查看ansible:
ansible --version
2.生成密钥对(免秘钥交互)
#生成秘钥
ssh-keygen -t rsa -p ''
#拷贝秘钥到客户组
ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.4.2
ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.4.2
ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.4.4
主机:
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
3.ansible配置:
a)拷贝ansible源码examples/ansible.cfg, examples/ansible.cfg到/etc/ansible/目录下:
cp -rf examples/ansible.cfg /etc/ansible/
cp -rf examples/ansible.cfg /etc/ansible/
vim ansible.cfg
host_key_checking = False
inventory = /etc/ansible/hosts
vim /etc/ansible/hosts
[targets]
localhost ansible_connection=local
#other1.example.com ansible_connection=ssh ansible_user=mpdehaan
#other2.example.com ansible_connection=ssh ansible_user=mdehaa
192.168.4.2 ansible_connection=ssh ansible_port=22 ansible_user=root ansible_ssh_pass=aaa
192.168.4.3 ansible_connection=ssh ansible_port=22 ansible_user=root ansible_ssh_pass=aaa
192.168.4.4 ansible_connection=ssh ansible_port=22 ansible_user=root ansible_ssh_pass=aaa
4.sshpass安装
tar xvzf sshpass-1.06.tar.gz
cd sshpass-1.06
./configure
make
make install
4.测试
ansible all -m ping
ansible targets -a 'uptime'
ansible targets -m command -a 'w'
ansible targets -a 'pwd'
5.ansible的使用
a)copy模块
使用copy模块,可以将本地文件一键复制到远程服务器; -a后跟上参数,参数中指定本地文件和远端路径;
ansible targets -m copy -a "src=~/ansible-2.3.1.0.tar.gz dest=~/ansible-2.3.1.0.tar.gz"
b)ansible远程分发并执行脚本
首次按创建一个简单的脚本:
vim /tmp/test.sh
#!/bin/bash
echo `date` > /tmp/ansible_test.txt
然后,将脚本分发到各个服务器:
ansible targets -m copy -a "src=~/test.sh dest=~/test.sh"
执行脚本:
ansible targets -m command -a "sh ~/test.sh"
ansible targets -m shell -a "sh ~/test.sh"