ansible安装及常用命令
安装ansible
yum install ansible -y
在没有公网的内网中,可以
配置ansible
1. 配置hosts
配置文件修改vi /etc/ansible/hosts
配置文件格式如下
配置文件内容:
[test]
test-0002 ansible_ssh_host=192.168.100.2
test-0003 ansible_ssh_host=192.168.100.3
test-0004 ansible_ssh_host=192.168.100.4
[test2]
test-0005 ansible_ssh_host=192.168.100.5
[farthernode:children]
test
test2
[farthernode:vars]
ansible_ssh_user="root"
ansible_ssh_pass="root"
ansible_ssh_port="22"
- [test]和[test2]为分组,test_0001为别名,可以不设置;
- [farthernode:children]为分组父类,其中指定子分组,方便多群组管理,可选设置;
- [farthernode:vars]配置用户名和密码以及端口,用来第一次生成秘钥建立免密登录使用,建立免密后可以删除该配置。
2.编辑配置,取消首次连接提示
vi /etc/ansible/ansible.cfg
去掉注释:inventory = /etc/ansible/hosts
// 表示取消首次连接提示
去掉注释:host_key_checking = False
分发密钥,建立免密连接
启动ansible服务,设置开机自启动
systemctl start ansible
systemctl enable ansible
1. 在ansible管理端进行密钥生成
ssh-keygen -N '' -f /root/.ssh/id_rsa
2. 利用ansible命令发送密钥给其他节点:
ansible all -m copy -a "src=/root/.ssh/id_rsa.pub dest=/root/.ssh/authorized_keys"
向远程服务器节点拷贝文件
1. 拷贝ansible服务器home目录下的 maxwell.zip 文件到远程服务器的opt目录下
ansible test_0001 -m copy -a "src=/home/maxwell.zip dest=/opt"
2. 拷贝文件并赋权,给与脚本执行权限
ansible test_0001 -m copy -a "src=/home/start.sh dest=/opt mode=0755"
3. 把本地服务器的压缩包解压到远程服务器
ansible test_0001 -m unarchive -a "src=/opt/maxwell.zip dest=/opt/ mode=0755"
4. 解压远程服务器文件,copy=no表示不从本地复制到远程服务器。
ansible test_0001-m unarchive -a "src=/opt/maxwell.zip dest=/opt/ mode=0755 copy=no"
5. 远程执行服务器上的自定义脚本,启动程序
ansible test_0001 -m shell -a "/opt/start.sh"
通过ansible远程操作mysql
- 启动所有节点的mysql服务,并设置为开机启动
ansible all -m service -a 'enabled=true name=mysqld state=started'
- 单独启动test_0001节点的mysql服务
ansible test_0001 -m service -a 'enabled=true name=mysqld state=started'
- 使用脚本远程操作数据库
脚本示例:
创建脚本vi /home/dropmaxwell.sh
pass="password"
mysql -uroot -p$pass <<EOF
drop database maxwell;
EOF
- 脚本功能,删除maxwell数据库。使用ansible命令,批量拷贝到远程服务器
ansible all -m copy -a "src=/home/dropmaxwell.sh dest=/opt mode=0755"
- 远程执行,删除maxwell数据库
ansible all -m shell -a "/opt/dropmaxwell.sh"