自动化运维服务器,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"

  1. [test]和[test2]为分组,test_0001为别名,可以不设置;
  2. [farthernode:children]为分组父类,其中指定子分组,方便多群组管理,可选设置;
  3. [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

  1. 启动所有节点的mysql服务,并设置为开机启动
    ansible all -m service -a 'enabled=true name=mysqld state=started'
  2. 单独启动test_0001节点的mysql服务
    ansible test_0001 -m service -a 'enabled=true name=mysqld state=started'
  3. 使用脚本远程操作数据库
    脚本示例:
    创建脚本 vi /home/dropmaxwell.sh
pass="password"
mysql -uroot -p$pass	<<EOF
drop database maxwell;
EOF
  1. 脚本功能,删除maxwell数据库。使用ansible命令,批量拷贝到远程服务器

ansible all -m copy -a "src=/home/dropmaxwell.sh dest=/opt mode=0755"

  1. 远程执行,删除maxwell数据库

ansible all -m shell -a "/opt/dropmaxwell.sh"

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值