ansible的入门及常见模块总结实战(代码片段)

author author     2023-03-09     151

关键词:

Ansible

帮助获取:

? ansible-doc -s 模块名 ##查看指定模块的帮助信息

? ansible-doc -l ##查看支持的所有模块

常用模块:

模块名 用途
file 文件管理,创建文件、目录或链接文件
copy / synchronize 用于传输文件或目录,对于copy传输慢建议采用synchronize(rsync封装)
cron 计划任务模块
user 用户管理
fetch 从客户端文件系统拉取文件到ansible服务端
service 服务状态管理
yum 包管理器,安装卸载软件
template 模板模块,该模块只在playbook中可以使用
setup 用于获取服务器的信息,可以结合template做变量引用
shell / command 命令代执行模块,commnad只能执行裸命令(即系统环境中有支持的命令),至于管道之类的功能不支持, shell模块可以做到

基本使用:

查看模块帮助
    ansible-doc -l 查看所有模块
    ansible-doc -s MODULE_NAME 查看指定模块的详细帮助

ansible命令应用基础
    语法: ansible <host-pattern> -f forks [-a args]
            <host-pattern>  在/etc/ansible/hosts中定义的主机组
            -f forks:启动的并发线程数
            -m module_name: 要使用的模块
            -a args: 模块特有的参数
            -u user: 指定用户执行
            -k passwd: 输入指定用户密码
            -C  假定playbook执行,并非真正的操作文件,只检测语法和流程

            --list-host 查看主机组里的主机
            --syntax-check  检测playbook语法

注:部分模块参数
    present 可以理解为True
    absent  可以理解为False

ansible属于SSH进行指令下发,所以对一切主机发号施令前请先配置好各主机通讯时的 [主机地址,SSH端口,用户名,密码/秘钥文件],当然你也可以在指令下发时在手动输入地址和用户认证信息

方案一:配置好免秘钥通讯

[[email protected] np]# ssh-keygen -t rsa          ##回车生成证书信息
[[email protected] np]# ssh-copy-id [email protected]  ##将自己的公钥发给别人
[[email protected] np]# ssh [email protected]     ##查看是否成功免秘钥

注:当主机过多时可以考虑使用expect脚本来完成,参考我的另一篇内容制作自定交互分发脚本:https://blog.51cto.com/swiki/1978831

使用ansible的第一个模块ping来检测服务器状态信息

[[email protected] np]# ansible 192.168.2.128 -m ping
192.168.2.128 | SUCCESS => 
    "changed": false, 
    "ping": "pong"

[[email protected] np]# ansible 192.168.2.129 -m ping
192.168.2.129 | SUCCESS => 
    "changed": false, 
    "ping": "pong"

注:ping模块不需要参数所以不用-a,其他需要参数则指定-a

这么操作也太low了,我如果要获取一个集群的状态岂不是要挨个去ping一次?

解决办法:在hosts重定义主机组:

[[email protected] np]# cat /etc/ansible/hosts
    [lb]
    192.168.2.128   
    192.168.2.130
    #192.168.2.13[1:9]  ##表示131-139的主机,还有很多表示方式不一一表述

    [db]
    192.168.2.130

注:hosts文件不光可以定义组还可以定义变量,自定义变量

通讯方案二:hosts中设置inventory变量来定制每台主机的账号和密码

[[email protected] np]# cat /etc/ansible/hosts
    [lb]
    192.168.2.128   ansible_ssh_user=root ansible_ssh_pass=root ##默认是22端口
    192.168.2.129   ansible_ssh_user=root ansible_ssh_pass=123  ##默认是22端口

注:如果128和129的账号和密码一样还可以这样:
    [lb]
    192.168.2.128
    192.168.2.129
    [lb:vars]
    ansible_ssh_user=root
    ansible_ssh_pass=root

不过在hosts中不光可以定义inventory变量还可以定义一些每台主机自己各不相同的自定义变量,用于playbook使用

你学到这个应该大概知道了在ansible与主机间通讯形式有三种:

1. 免秘钥
2. inventory变量
3. 参数指定

以下是一些inventory参数:

...
ansible_ssh_host
      将要连接的远程主机名.与你想要设定的主机的别名不同的话,可通过此变量设置.
ansible_ssh_port
      ssh端口号.如果不是默认的端口号,通过此变量设置.
ansible_ssh_user
      默认的 ssh 用户名
ansible_ssh_pass
      ssh 密码(这种方式并不安全,我们强烈建议使用 --ask-pass 或 SSH 密钥)
ansible_sudo_pass
      sudo 密码(这种方式并不安全,我们强烈建议使用 --ask-sudo-pass)
...
这里只列一部分,参考:https://ansible-tran.readthedocs.io/en/latest/docs/intro_inventory.html

这个时候?我们对lb集群进行ping状态监测:

[[email protected] np]# ansible lb -m ping
192.168.2.128 | SUCCESS => 
    "changed": false, 
    "ping": "pong"

192.168.2.129 | SUCCESS => 
    "changed": false, 
    "ping": "pong"

注:也可以用all表示hosts中所有主机

到这里基本快速已经完成了基础,开始学习一些常用的模块:

这里模块总结直接抄的我大表哥的博客总结,不然太费时间了,所以声明下:https://blog.51cto.com/dyc2005/2070729

1、copy模块(synchronize和copy使用方法一致)

从本地copy文件分发到目录主机路径 
参数说明:
src= 源文件路径
dest= 目标路径 
注意src= 路径后面带/ 表示带里面的所有内容复制到目标目录下,不带/是目录递归复制过去
content= 自行填充的文件内容
owner 属主
group 属组
mode权限
示例:

ansible all  -m copy -a "src=/etc/fstab dest=/tmp/fstab.ansible mode=600"
ansible all -m copy -a "content=‘hi there
‘ dest=/tmp/hi.txt"
到node1上查看
[[email protected] tmp]# ll
-rw------- 1 root root 465 2月   9 14:59 fstab.ansible
-rw-r--r-- 1 root root   9 2月   9 14:58 hi.txt

2、fetch模块

从远程主机拉取文件到本地
示例

[[email protected] ~]# ansible all  -m fetch -a "src=/tmp/hi.txt dest=/tmp"
172.16.3.152 | SUCCESS => 
    "changed": true, 
    "checksum": "279d9035886d4c0427549863c4c2101e4a63e041", 
    "dest": "/tmp/172.16.3.152/tmp/hi.txt", 
    "md5sum": "12f6bb1941df66b8f138a446d4e8670c", 
    "remote_checksum": "279d9035886d4c0427549863c4c2101e4a63e041", 
    "remote_md5sum": null

.......省略
说明:fetch使用很简单,src和dest,dest只要指定一个接收目录,默认会在后面加上远程主机及src的路径

3、command模块

在远程主机上执行命令,属于裸执行,非键值对显示;不进行shell解析;
示例1:

[[email protected] ~]# ansible all -m command -a "ifconfig"
172.16.3.152 | SUCCESS | rc=0 >>
enp0s3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.16.3.152  netmask 255.255.255.0  broadcast 172.16.3.255
        .....省略.....
172.16.3.216 | SUCCESS | rc=0 >>
enp0s3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.16.3.216  netmask 255.255.255.0  broadcast 172.16.3.255
        .....省略.....
示例2:

[[email protected] ~]# ansible all -m command -a "ifconfig|grep lo"
172.16.3.152 | FAILED | rc=2 >>
[Errno 2] 没有那个文件或目录

172.16.3.216 | FAILED | rc=2 >>
[Errno 2] 没有那个文件或目录
这就是因为command模块不是shell解析属于裸执行导致的
为了能达成以上类似shell中的解析,ansible有一个shell模块;

4、shell模块

由于commnad只能执行裸命令(即系统环境中有支持的命令),至于管道之类的功能不支持,
shell模块可以做到
示例:

[[email protected] ~]# ansible all -m shell -a "ifconfig|grep lo"
172.16.3.152 | SUCCESS | rc=0 >>
lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        loop  txqueuelen 0  (Local Loopback)

172.16.3.216 | SUCCESS | rc=0 >>
lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        loop  txqueuelen 0  (Local Loopback)

5、file模块

设置文件属性(创建文件)
常用参数:
path目标路径
state directory为目录,link为软件链接
group 目录属组
owner 属主
等,其他参数通过ansible-doc -s file 获取
示例1:创建目录

[[email protected] ~]# ansible all -m file -a "path=/var/tmp/hello.dir state=directory"
172.16.3.152 | SUCCESS => 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/var/tmp/hello.dir", 
    "size": 6, 
    "state": "directory", 
    "uid": 0

172.16.3.216 | SUCCESS => 
    "changed": true, 
     .....省略.....
示例2:创建软件链接

[[email protected] ~]# ansible all -m file -a "src=/tmp/hi.txt path=/var/tmp/hi.link state=link"
172.16.3.152 | SUCCESS => 
    "changed": true, 
    "dest": "/var/tmp/hi.link", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "size": 11, 
    "src": "/tmp/hi.txt", 
    "state": "link", 
    "uid": 0

172.16.3.216 | SUCCESS => 
    "changed": true, 
     .....省略.....

6、cron模块

通过cron模块对目标主机生成计划任务
常用参数:
除了分(minute)时(hour)日(day)月(month)周(week)外
name: 本次计划任务的名称
state: present 生成(默认) |absent 删除 (基于name)

示例:对各主机添加每隔3分钟从time.windows.com同步时间

[[email protected] ~]# ansible all -m cron -a "minute=*/3 job=‘/usr/sbin/update time.windows.com &>/dev/null‘  name=update_time"
172.16.3.152 | SUCCESS => 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "update_time"
    ]

172.16.3.216 | SUCCESS => 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "update_time"
    ]


#到node1上查看
[[email protected] tmp]# crontab -l
#Ansible: update_time
*/3 * * * * /usr/sbin/update time.windows.com &>/dev/null
示例2:删除计划任务

[[email protected] ~]# ansible all -m cron -a "name=update_time state=absent"
172.16.3.152 | SUCCESS => 
    "changed": true, 
    "envs": [], 
    "jobs": []

172.16.3.216 | SUCCESS => 
    "changed": true, 
    "envs": [], 
    "jobs": []

#node1上查看
[[email protected] tmp]# crontab -l
会发现已经被删除了

7、yum模块

故名思义就是yum安装软件包的模块;
常用参数说明:
enablerepo,disablerepo表示启用与禁用某repo库
name 安装包名
state (present‘ orinstalled‘, latest‘)表示安装, (absent‘ or `removed‘) 表示删除
示例:通过安装epel扩展源并安装nginx

[[email protected] ~]# ansible all -m yum -a "name=epel-release state=installed"
[[email protected] ~]# ansible all -m yum -a "name=nginx state=installed"

8、service模块

服务管理模块
常用参数:
name:服务名
state:服务状态
enabled: 是否开机启动 true|false
runlevel: 启动级别 (systemed方式忽略)

示例:

[[email protected] ~]# ansible all -m service -a "name=nginx state=started enabled=true"
到node1上查看
[[email protected] tmp]# systemctl status nginx
● nginx.service - The nginx HTTP and reverse proxy server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: active (running) since 五 2018-02-09 15:54:29 CST; 1min 49s ago
 Main PID: 10462 (nginx)
   CGroup: /system.slice/nginx.service
           ├─10462 nginx: master process /usr/sbin/nginx
           └─10463 nginx: worker process
......省略......

9、script模块

把本地的脚本传到远端执行;前提是到远端可以执行,不要把Linux下的脚本同步到windows下执行;
直接上示例:
本地ansible上的脚本:

[[email protected] ~]# cat test.sh 
#!/bin/bash
echo "ansible script test!" > /tmp/ansible.txt
[[email protected] ~]# ansible all -m script -a "/root/test.sh"
172.16.3.152 | SUCCESS => 
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 172.16.3.152 closed.
", 
    "stdout": "", 
    "stdout_lines": []

172.16.3.216 | SUCCESS => 
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 172.16.3.216 closed.
", 
    "stdout": "", 
    "stdout_lines": []

到node1上查看
[[email protected] tmp]# ls
ansible.txt  fstab.ansible  hi.txt 
[[email protected] tmp]# cat ansible.txt
ansible script test!
script模块这个功能可以做很多事,就看你怎么用了~
以上是常用模块,至于其他模块的使用可通过官方模块列表获得~

playbook

学会了上面的就可以开始搞playbook了:

开搞之前你需要知道为什么要用playbook?因为我们到此之前学的都是单个功能,复制个文件什么的,这些我想说我在CRT下面开个窗口都能做,那么playbook到底能做什么呢?

playbook你可以理解为一个剧本,就是playbook中,可以定义哪些主机依次分别该干哪些事,从而完成一项复杂庞大的任务,通常我们用它来部署服务,我们先写一个简单的(注意基于yaml语法):

---
- hosts: lb         ##指定lb组的主机做以下的事情
  remote_user: root ##以哪个用户的身份去执行
  tasks:    ##任务列表
  - name: install nginx     ##第一步,给这个任务命名为安装nginx
    yum: name=nginx state=installed ##模块名: 参数
  - name: installed nginx config  ##第二步,准备配置文件
    copy: src=~/playbook/nginx.conf_v2 dest=/etc/redis.conf owner=redis mode=0640  
  - name: start nginx   ##启动nginx
    service: name=nginx state=started

如何执行playbook?

[[email protected] np]# ansible-playbook --syntax-check nginx.yml  ##没有错误抛出即可
[[email protected] np]# ansible-playbook nginx.yml    ##执行之前,准备好playbook中需要的配置文件

好了这就是一个简单的nginx的playbook,以后你给新机器装nginx就可以这么搞了,把配置文件搞好每次执行这个文件即可

不行了不行了,今天赶火车实在没时间了,先排版到这吧,下周一给小伙伴补齐playbook和roles

ansible学习总结——ansible入门详解(代码片段)

一、Ansible 简介1、Ansible 是什么ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet、chef、func、fabric)的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能。ansible是... 查看详情

ansible学习总结——ansible入门详解(代码片段)

一、Ansible 简介1、Ansible 是什么ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet、chef、func、fabric)的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能。ansible是... 查看详情

ansible的常见模块用法(代码片段)

...解:1,主配置文件:/etc/asiable/ansiable.cfgmodule_name=command##ansible的默认模块是command模块,但是在使用的时候非常的有局限性,建议改成shell模块host_key_checking=False##检查对应要控制主机的的host_key,建议取消注释,以减轻管理时需要... 查看详情

ansible自动化运维工具简单入门(代码片段)

三、Ansible的使用1、Ansible命令执行过程及状态过程:加载自己的配置文件,默认/etc/ansible/ansible.cfg加载自己对应的模块文件,如commandping通过ansible将模块或命令生成对应的临时py文件,并将该文件传输至远程服务器给文件+x权限... 查看详情

12-2107课上问题分析及总结(代码片段)

文章目录Day01~微服务架构入门核心知识点常见问题分析常见Bug分析课后作业作业答案Day02~Nacos注册中心入门核心知识点常见问题分析常见Bug分析课后作业Day03~服务发现及调用核心知识点常见问题分析常见Bug分析课后作业Day01~微服... 查看详情

ansible常见模块使用(代码片段)

...模块部署简单,基于SSH支持playbook编排任务无需代理 Ansible主要组成部分 USER普通用户 CMDB(配置管理数据库)API调用 公有云私有云 查看详情

ansible概述及各模块应用(代码片段)

ansible概述及各模块应用ansible概述ansible特点ansible工作原理==ansible工具优点==ansible环境部署ansible命令模块command模块cron模块user模块group模块copy模块file模块ping模块service模块模块shell模块script模块yum模块setup模块ansible概... 查看详情

ansible概述及各模块应用(代码片段)

ansible概述及各模块应用ansible概述ansible特点ansible工作原理==ansible工具优点==ansible环境部署ansible命令模块command模块cron模块user模块group模块copy模块file模块ping模块service模块模块shell模块script模块yum模块setup模块ansible概... 查看详情

ansible的安装配置及常用模块介绍(代码片段)

Ansible的安装、配置及常用模块介绍 ansible安装方式1、ansible安装常用两种方式,yum安装和pip程序安装这里提供二种安装方式,任选一种即可:1、使用yum安装yuminstallepel-release-yyuminstallansible–y2、使用pip(python的包管理模块)安... 查看详情

ansible概述及常用命令模块(代码片段)

Ansible概述及常用命令模块一、Ansible概述特点二、部署ansible1.使用yum安装epel源和ansible2.配置主机清单3.配置密钥对验证三、ansible常用命令行模块1.command模块2.shell模块3.cron模块4.user模块5.group模块6.copy模块7.file模块8.hostname模块9.ping... 查看详情

ansible概述及常用命令模块(代码片段)

Ansible概述及常用命令模块一、Ansible概述特点二、部署ansible1.使用yum安装epel源和ansible2.配置主机清单3.配置密钥对验证三、ansible常用命令行模块1.command模块2.shell模块3.cron模块4.user模块5.group模块6.copy模块7.file模块8.hostname模块9.ping... 查看详情

webpack使用入门及常用配置总结(代码片段)

转自:https://www.cnblogs.com/y896926473/articles/6011711.html官网:https://www.webpackjs.com/concepts/1.webpack简介webpack是一个模块打包工具。它使得模块相互依赖并且可构建等价于这些模块的静态资源。相比于已经存在的模块打包器(modulebundler)... 查看详情

ansible概述及各模块应用(代码片段)

ansible概述及各模块应用ansible概述ansible特点ansible工作原理==ansible工具优点==ansible环境部署ansible命令模块command模块cron模块user模块group模块copy模块file模块ping模块service模块模块shell模块script模块yum模块setup模块ansible概... 查看详情

ansible入门(代码片段)

第一章Ansible概述1.1Ansible的介绍简单易用的一款工具支持多节点发布、远程任务执行.无代理架构,基于ssh通信,无需在agent端安装代理能够调用特定的模块来完成特定任务支持自定义模块功能支持playbook剧本,连续任务按先后设... 查看详情

ansible学习总结——ansible19个常用模块使用示例(代码片段)

一、模块列表1、setup2、ping3、file4、copy5、command6、shell7、script8、cron9、yum10、service11、group12、user13、stat14、mount15、fetch16、synchronize17、get_url18、hostname19、wait_for二、模块示例1、setup(搜集系统信息)搜集主机的 查看详情

ansible-基本使用-2(代码片段)

ansible 基本模块及常见命令参数使用命令格式ansiblewebserver|www.a.com|1.1.1.1  (主机组/主机名/主机ip)  -m(模块参数)  shell(模块名字)  -a(命令参数)  “echoxxx”  远程登录方式密码方式之免交互  vi/etc/ansible/h... 查看详情

ansible安装及部分模块初步使用(代码片段)

Ansible安装及初步使用Ansible概述由于互联网的快速发展导致产品更新换代速度逐渐加快,运维人员每天都要进行大量的维护操作,仍旧按照传统的方式进行维护工作会使得工作效率低下。这时,部署自动化运维就可以尽可能安全... 查看详情

ansible自动化运维详解ansible管理方式常用参数及常用模块(代码片段)

文章目录ansible自动化运维详解(二)ansible管理方式、常用参数及常用模块一、ansible实现管理的方式二、ansible命令常用参数三、ansible基本颜色代表的信息四、ansible常用模块(1)4.1、command4.2、shell4.3、script4.4、cop... 查看详情