ansible自动化运维

一.ansible介绍

ansible是一款基于python开发的自动化运维工具,它不需要安装客户端,而是通过sshd通信。
ansible是基于模块工作的,它本身并没有批量部署的能力,真正具有批量部署功能的是ansible上运行的模块,模块可以用任何语言开发。
支持编写yaml格式的playbook,playbook是剧本执行多个任务时,非必需可以让节点一次性运行多个任务。
ansible官方文档:
https://docs.ansible.com/
关于ansible介绍的书籍:
https://ansible-book.gitbooks.io/ansible-first-book/

二.ansible安装(centos7)

centos自带ansible2.4版本,可以查看一下是否有没有以及自带的版本:

yum list|grep ansible
ansible.noarch                              2.4.2.0-2.el7              extras   
ansible-doc.noarch                          2.4.2.0-2.el7              extras   

安装很简单,只需要在服务端安装即可:

yum install -y ansible ansible-doc

配置ansible,因为ansible通过ssh通信,所以需要将需要进行ansible自动化的机器配置好ssh,能进行ssh通信。
这里我两台虚拟机,一台192.168.247.160(安装了ansible),一台192.168.247.170。
下面是(ansible端)ssh操作,目的是160可以ssh其他主机(170和160):

cat .ssh/id_rsa.pub

如果没有id_rsa.pub,就需要执行ssh-keygen创建ssh密钥。将公钥传到其他主机:

vim .ssh/authorized_keys  将公钥复制到这个文件里面,注意160如果它本身也要进行ansible自动化,那么它自己也要进行复制

ssh通信成功之后,就可以配置/etc/ansible/hosts:

vim /etc/ansible/hosts

在这里插入图片描述
testhost是主机群的名字,可以自定义。下面是包括的主机,可以是ip,也可以是主机名,主机名的话,需要配置一下/etc/hosts文件。

三.ansible执行远程命令

查看testhost主机群包含的主机名:

ansible testhost -m command -a 'hostname'
说明:command是一个模块,-a是需要在远程执行的命令
这是除了command模块还可以shell模块

查看127.0.0.1 开启的端口:

ansible 127.0.0.1 -m command -a 'netstat -lnpt'

具体执行命令可以参考下面的地址:

https://ansible-book.gitbooks.io/ansible-first-book/begin/ansibleyong_ming_ling_guan_li_zhu_ji.html

四.ansible拷贝文件或者目录

ansible 192.168.247.170 -m copy -a "src=/tmp/dedecms.log dest=/tmp/123.txt owner=root group=root mode=0755"
//copy也是一个模块

五.ansible 远程执行脚本

远程执行脚本需要先将脚本拷贝到远程机器上去,然后才能远程执行脚本
例如有一个脚本:

vim /tmp/1.sh
#!/bin/bash
date >> /tmp/date.txt
ansible testhost -m copy -a "src=/tmp/1.sh dest=/tmp/1.sh owner=root group=root mode=0755"
ansible testhost -m shell -a "/tmp/1.sh"

command模块和shell的区别:
command不支持管道,shell可以
在这里插入图片描述
在这里插入图片描述

六.ansible 管理任务计划

创建crontab任务计划:

ansible testhost -m cron -a "name='test cron' job='/bin/touch /tmp/12.txt' hour=5"
//cron模块,job任务计划 hour小时,minute分钟, day日, month月, weekday周

删除任务计划:

ansible testhost -m cron -a "name='test cron' state=absent"

七.ansible安装和管理服务

安装httpd服务:

ansible testhost -m yum -a "name=httpd"

卸载:

ansible testhost -m yum -a "name=httpd state=removed"

启动服务:

ansible testhost -m service -a "name=httpd state=started enabled=no"

停止服务:

ansible testhost -m service -a "name=httpd state=stopped"

查看所有模块:

ansible-doc -l

查看指定模块:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值