ansible的安装及简单使用
安装ansible的yum源
yum search ansible #检查ansible
yum -y install centos-release-ansible-29 #安装centos-release-ansible-29
安装ansible
yum –y install ansible #安装ansible
ansible --version #查看版本
密钥
ssh-keygen #生成密钥
ssh-copy-id root@192.168.126.141 #发送到被管理主机
ssh-copy-id root@192.168.126.137
配置ansible清单文件,添加主机
vim /etc/ansible/hosts #清单目录
[webservers] #写一个组组名随意
192.168.126.141 #除本机外另外多台的IP
192.168.126.137
测试被管理主机是否可达
ansible webservers –m ping #ansible [设置清单里面的组] -m [调用的模块]
(绿色通过无更改)
(红色警告)
(黄色通过有更改)
ansible常用的模块
command:作用: 在被管理节点执行命令
| && > 不支持
例:
ansible webservers -m command -a ifconfig
ansible webservers -m command -a ‘yum –y install nginx’
shell:作用: 在被管理节点执行shell命令
例子:ansible webs -m shell -a ‘ss -ntl | grep 22’
yum:作用: 调用yum命令安装软件
选项:
name: 指定你要安装的软件包的名字
state: 指定你的操作
present、installed、latest 安装软件
absent、removed 卸载软件
例子:
ansible webs -m yum -a ‘name=httpd state=latest’
systemd:作用: 管理服务的 启动、停止、重启、重载
选项:
name: 指定你要管理的服务名
state: 指定你的操作
started 启动
stopped 停止
restarted 重启
reloaded 重载
enabled: yes 将服务设置为开机自启
ansible webs -m systemd -a ‘name=httpd state=started enabled=yes’
service作用: 管理服务的 启动、停止、重启、重载
选项:
name: 指定你要管理的服务名
state: 指定你的操作
started 启动
stopped 停止
restarted 重启
reloaded 重载
enabled: yes 将服务设置为开机自启
给Apache创建一个测试页面
ansible webs -m shell -a ‘echo $(hostname) > /var/www/html/index.html’
copy作用: 复制管理节点文件到被管理节点
选项:
src: 管理节点源文件路径
dest: 被管理节点目标文件路径
例子:
ansible webs -m copy -a ‘src=a.txt dest=/opt/’