一 安装使用
1.1 离线安装ansible
首先,在一台能联网的机器上,下载ansible的epel源以及createrepo rpm包
### createrepo命令在无网环境可以使用yum install --downloadonly --downloaddir=路径 把rpm包下载到本地目录
### 然后使用rpm -ivh --force --nodeps *.rpm安装createrepo命令
# yum install createrepo && yum install yum-utils
# yum install https:*//dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
其次下载ansible需要的所有依赖包到本地目录
# mkdir /root/mypackages
### 若没有yumdownloader命令,则可以使用 yum install --downloadly命令代替
# yumdownloader --resolve --destdir /root/mypackages/ ansible
离线机器上配置本地yum,/root/centos76需要用createrepo命令制造成yum源
# vi /etc/yum.repos.d/centos76.repo
[centos76]
name=centos76
baseurl=file:///root/centos76
gpgcheck=0
enabled=1
上传ansible所有的rpm包到指定目录,并用createrepo命令制成本地yum源,并上传createrepo命令需要的所有rpm包
# rz
# tar zxvf ansible.tar.gz
# mv mypackages/* /root/centos76/Packages/
# yum install createrepo
# yum clean all
# createrepo /root/centos76 # 提前使用rpm -ivh的方式安装createrepo的rpm包
# yum update
# yum repolist
# yum list|grep ansible # 查看ansible源
安装ansible
# yum install -y ansible
1.2 ansible小试牛刀
ansible是集合众多运维工具的优点为一身、基于python开发的自动化运维工具,实现批量配置、批量部署、批量运行命令等等功能。
通过账号密码管理多台主机
# vim /etc/ansible/hosts
[webservers]
172.24.110.171
[webservers]是名字自定义的组,通过分组管理,执行命令判断是否连接成功
# ansible webservers -m ping -uroot -k
当然也可以,在配置文件中指定账号和密码
[webservers]
172.24.110.171:22 ansible_ssh_user=root ansible_ssh_pass="1qaz2wsx!@"
# ansible webservers -m ping
指定私钥文件,进行ssh认证(推荐)
# ssh-keygen -t rsa
# ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.24.110.171 #回车输入密码
# vim /etc/ansible/hosts
[webservers]
172.24.110.171:22 ansible_ssh_private_key_file=/root/.ssh/id_rsa
# ansible webservers -m ping
二 ansible常见模块
2.1 shell模块
shell模块 执行shell命令
- name: 在指定目录执行cmd命令.
shell:
cmd: ls -l | grep log
chdir: somedir/
- cmd 可执行命令
- chdir 工作目录
# ansible webservers -m shell -a 'chdir=/root echo 'xx'> test.txt && cat test.txt'
2.2 copy模块
copy模块 文件复制
- name: 复制本机文件到远程主机,并指定属主、属组、权限
copy:
src: /srv/myfiles/foo.conf
dest: /etc/foo.conf
owner: foo
group