ansible模块以及playbook编写

本文介绍了Ansible的基本用法,包括通过ssh协议进行管理,使用模块如copy、script、fetch、shell、file、service、yum、cron来执行任务,以及playbook的编写和执行,还有在Ubuntu中的特殊处理。此外,提到了tags、notify、handlers的概念以及如何获取节点信息和使用vars、template、roles。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ansible

由python开发,使用ssh协议,paramiko库,sshpass库。

组成:

主机清单:host inventory :可以去操作哪些主机

模块 module 插件plugins :可以实现某个功能的库

playbook 剧本 :告诉主机清单里的电脑,做什么事情

步骤:

1.建立ssh免密通道

ssh-copy-id -i id_rsa.pub root@192.168.10.141

2.安装ansible

yum install -y ansible

3.将建立了免密通道主机加入主机清单

cd /etc/ansible
vim hosts

写入如下信息即可。(可以用:接端口[ssh的])

在这里插入图片描述

若没有建立免密通道,则可以这样写

在这里插入图片描述

4.copy模块

ansible all -m copy -a "src=/root/print.sh dest=/root"

all:所有组,如上面的webservers就是一组

-m:模块

-a:参数arguments

5.script模块

ansible all -m script -a "~/print.sh"

-f:指定进程数。fork

ansible-doc -s fetch:查看fetch模块的用法

6.fetch模块

ansible all -m fetch -a "src=/etc/passwd dest=/root"

command模块(裸执行,不进行shell解析,不好用)

7.shell模块(执行shell命令)

ansible all -m shell -a "touch ~/feng.txt"

8.file模块

ansible all -m file -a " path=~/fanwenhao.txt state=touch"

9.service模块

ansible all -m service -a "name=sshd state=restarted enabled=true"

10.yum模块

ansible all -m yum -a "name=net-tools state=installed"

11.cron模块

ansible all -m cron -a "minute=*/1 job='bash ~/create_file.sh' name=create_file"
作用:supervisor软件的作用是管理和监控Linux系统中的进程,可以自动启动、重启或停止指定的进程,并记录进程的日志和事件 。supervisor软件需要配置相关参数,如进程名称、命令、工作目录等 。

playbook

编辑redis_first.yaml文件

- hosts: all     #也可以针对特定的组,如webservers
  remote_user: root  #也可以为其他用户
  tasks:        
  - name: install redis
    yum: name=redis state=latest    #ubuntu则为apt
  - name: start redis
    service: name=redis state=started

ubuntu:

在这里插入图片描述

ubuntu比较特殊,当用普通用户执行时,需要接become、become_method、become_user,执行ansible-playbook时要接-kK,-k是提示输入SSH密码,-K是输入sudo密码

小提示:安装都用latest,卸载都用absent比较好

语法检测命令

ansible-playbook --syntax-check redis_first.yaml

运行

ansible-playbook redis_first.yaml

tags、notify、handlers

redis只监听127.0.0.1,修改一下为0.0.0.0

在这里插入图片描述

执行完copy后会触发notify,然后handler会捕获,然后执行handler的命令。

-t:configfile,直接执行configfile标签的任务。

setup

获取节点信息

ansible 192.168.10.133 -m setup

vars、template、roles

cron:

首先要用playbook安装cron

在这里插入图片描述

使用:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EBf5ynBx-1684583431671)(C:\Users\xuzixuan\AppData\Roaming\Typora\typora-user-images\image-20230322195313694.png)]

var和template

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值