ansible自动化运维入门
1.ansible是什么?
Ansible是一个开源配置管理工具,可以使用它来自动化任务,部署应用程序实现IT基础架构。ansible基于python开发,提供了多种运维模块, Ansible可以用来自动化日常任务,比如,服务器的初始化配置、安全基线配置、更新和打补丁系统,安装软件包等,而且ansible配置十分简单,被控制机器只需要支持ssh登录即可被ansible进行管理,无需安装其他的agent,对于传统的运维方式,ansible大大提高了同时管理多台服务器的运维效率。
2.ansible配置
基于ubuntu20.04(管理服务器)
1 | sudo apt install ansible |
配置运维机器列表清单
1 | vim /etc/ansible/hosts |
常用的配置参数
1 | ansible_connection #主机连接类型,这可以是任何 ansible 连接插件的名称,如 smart、ssh、paramiko、local |
3.实现远程服务器批量管理的模式
1.ad-hoc模式
1 | ansible-doc -s module_name#查看该模块支持的参数 |
2.playbook模式
playbook模式是使用yaml文件格式将命令指定的参数以及目标类似于清单一样的描述下来
实例清单
1 | - hosts: mycentos |
4.ansible常用的模块
1.command模块
向远程主机执行命令 (不支持管道符)
1 | chdir 执行命令之前切换到指定目录 |
2.shell模块
shell模块基本和command相同,但是shell支持管道符
1 | ansible mywebserver -m shell -a "/home/test.sh" #在远程主机上执行远程主机的脚本(test.sh脚本在远程服务器) |
3.script模块
1 | ansible mywebserver -m script -a "/home/test.sh" #在远程主机上执行本地的脚本(test.sh脚本在主控端本地) |
4.copy模块
实现主控端向目标主机拷贝文件,类似于scp功能
1 | ansible mywebserver -m copy -a "src=/home/test.sh dst=/tmp/test.sh owner=root group=root mode=0755" |
5.stat模块
获取远程文件的状态信息
1 | ansible mywebserver -m stat -a "path=/etc/hosts" |
6.get_url
实现远程主机下载指定url文件到远程主机
1 | ansible mywebserver -m get_url "url=https://www.baidu.com dst=/tmp/index.html mode=0444 force=yes" |
7.yum
实现调用远程主机的yum包管理器下载指定的软件包
1 | ansible mywebserver -m yum -a "name=kubernetes-master state=latest" |
8.crontab
配置远程主机的计划任务
1 | ansible mywebserver -m cron -a "name=mywebserver hour='5,2' job='ls -alh > /dev/null'"#name为crontab中的注释 |
9.mount
远程主机分区挂载
1 | ansible mywebserver -m mount -a "name=/mnt/data src=/dev/sda1 fstype=ext4 opts=ro state=present" |
10.service
对远程主机服务进行管理
1 | ansible mywebserver -m service -a "name=nginx state=started|reloaded|stopped" |
11.user
远程主机用户管理
1 | ansible mywebserver -m user -a "name=centos comment='user'" |
参考: