目 录CONTENT

文章目录

自动化运维工具——Ansible

ZiChen D
2021-07-13 / 0 评论 / 0 点赞 / 383 阅读 / 21,246 字 / 正在检测是否收录...

自动化运维工具——Ansible

一、Ansible安装及介绍

1. Asible是什么?

Ansible是新出现的自动化运维工具,是基于Python开发的,他集合了多种运维工具(puppet、chef、func、fabric、cfengine)的优点,实现了批量系统部署、批量程序部署、批量执行命令等功能。

Ansible是基于paramiko(Python中作远程控制用的模块)工具开发而成的,他是基于模块化工作的,其本身没有批量部署的能力。真正具有批量部署能力的是Ansible中的模块,Ansible只是提供一种框架。Ansible不需要在远程主机上安装Client/Agents,因为它们本身是基于ssh来和远程主机通讯的。而Ansible目前已被红帽官方收购,是自动化运维工具中大家认可度最高的,并且因为其上手容易,学习简单,所以成为了每位运维工程师必须掌握的技能之一。

2. Ansible特点

  1. 部署简单,只需在控制端部署Ansible环境,连接端无需做任何操作;
  2. 默认使用SSH协议对设备进行管理,无需进行额外配置;
  3. 有大量常规运维操作模块,可实现日常绝大部分操作;
  4. 配置简单、功能强大、扩展性强;
  5. 支持API及自定义模块,可通过Python轻松扩展;
  6. 通过Playbooks来定制强大的配置、状态管理;
  7. 轻量级,在更新时,只需在操作机上进行一次更新即可,不用安装其他任何插件;
  8. 提供一个功能强大、操作性强的Web管理界面和REST API接口——AWX平台。

3. Ansible优点

  1. 跨平台支持:Ansible 能够提供Linux、Windows、UNIX和网络设备的无代
    理支持,适用于物理、虚拟、云和容器环境。
  2. 对人友好:Ansible Playbook采用YAML文本文件编写,易于阅读,有助于确保所有人都能理解它们的用途。
  3. 完美描述应用:可以通过 Ansible Playbook进行每种更改,并描述和记录应用环境的每一个方面。
  4. 轻松管理版本控制:Ansible Playbook和项目是纯文本。它们可以视作源代码,放在现有版本控制系统中。
  5. 支持动态清单:可以从外部来源动态更新 Ansible 管理的计算机列表,随时获取所有受管服务器的当前正确列表,不受基础架构或位置的影响。
  6. 编排可与其他系统轻松集成:能够利用环境中现有的 HP SA、Puppet、Jenkins、红帽卫星和其他系统,并且集成到 Ansible 工作流中。

4. Ansible架构图

架构图

Ansible的主要模块有:

Ansible:核心程序
HostInventory:记录由Ansible管理的主机信息,包括端口,密码,ip等。
Playbooks:剧本,多个任务定义在一个文件中,定义主机需要调用哪些模块来完成的功能
CoreModules:核心模块,主要通过调用核心模块来完成管理任务
CustomModules:自定义模块,完成核心模块无法完成的功能,支持多种语言
ConnectionPlugins:连接插件,Ansible和Host通信使用

安装Ansible

PS:因为在RedHat 8 中我们默认是带有Python 3的,所以,我们只需要输入

yum -y install ansible

即可完成安装。
如果系统报仓库中没有Ansible则先执行下面这条语句,再执行上面的语句

yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm 		//这句语句是将EPEL仓库启用

安装完成:

[root@dzc ~]# ansible --version		//查看版本
ansible 2.9.23
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.6.8 (default, Dec  5 2019, 15:45:45) [GCC 8.3.1 20191121 (Red Hat 8.3.1-5)]

创建用户一个用户试试:

[root@dzc ~]# ansible localhost -m ping
localhost | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
[root@dzc ~]# ansible localhost -m user -a "name=dzc"
localhost | CHANGED => {
    "changed": true,
    "comment": "",
    "create_home": true,
    "group": 1001,
    "home": "/home/dzc",
    "name": "dzc",
    "shell": "/bin/bash",
    "state": "present",
    "system": false,
    "uid": 1001
}

二、部署Ansible

1. 构建Ansible清单

1.1定义清单

清单定义的是Ansible将要管理的一批主机,这些主机也可以分配到组中,以进行集中管理,组可以包含子组,主机也可以是多个组的成员,清单还可以设置应用到它所定义的主机和组的数量

可以通过两种方式定义主机清单。静态主机清单可以通过文本文件定义。动态主机清单可以根据需要使用外部信息提供程序通过脚本或其他程序来生成。

1.2静态清单

静态清单文件是指定Ansible目标受管主机的文本文件。可以使用多种不同的格式编写此文件,包括INI样式或YAML

默认的清单文件为/etc/Ansible下的hosts文件,而我们一般使用是不会使用这个文件,所以我们需要在修改Ansible的配置文件

[root@dzc ansible]# vim ansible.cfg 	   //Ansible默认配置文件
[defaults]

# some basic default values...

#inventory      = /etc/ansible/hosts	     	//这个参数表示资源清单inventory文件的位置
**inventory      = /etc/ansible/inventory**	//修改清单存放位置
#library        = /usr/share/my_modules/	//指向存放Ansible模块的目录,支持多个目录方式,只要用冒号(:)隔开就可以
#module_utils   = /usr/share/my_module_utils/
#remote_tmp     = ~/.ansible/tmp
#local_tmp      = ~/.ansible/tmp
#plugin_filters_cfg = /etc/ansible/plugin_filters.yml
#forks          = 5				//并发连接数,默认为5
#poll_interval  = 15
#sudo_user      = root				//设置默认执行命令的用户
#ask_sudo_pass = True 
#ask_pass      = True 
#transport      = smart 
#remote_port    = 22				//指定连接被管节点的管理端口,默认为22端口,建议修改,能够更加安全
#module_lang    = C
#module_set_locale = False

[root@dzc ansible]# touch inventory	//默认没有这个文件,所以需要手动创建
[root@dzc ansible]# ls
ansible.cfg  hosts  **inventory**  roles

[root@dzc ansible]# vim inventory	//编辑文件,添加需要管理的主机IP
[root@dzc ansible]# cat inventory 
1.1.1.1				//未添加进组的主机

[webservers]			//创建组,以组来管理
2.2.2.2

配置文件的格式:

# Ex 1: Ungrouped hosts, specify before any group headers.

## green.example.com
## blue.example.com
## 192.168.100.1
## 192.168.100.10

# Ex 2: A collection of hosts belonging to the 'webservers' group

## [webservers]
## alpha.example.org
## beta.example.org
## 192.168.1.100
## 192.168.1.110

# If you have multiple hosts following a pattern you can specify
# them like this:

## www[001:006].example.com

# Ex 3: A collection of database servers in the 'dbservers' group

## [dbservers]
## 
## db01.intranet.mydomain.net
## db02.intranet.mydomain.net
## 10.25.1.56
## 10.25.1.57

# Here's another example of host ranges, this time there are no
# leading 0s:

## db-[99:101]-node.example.com

1.3验证清单

列出全部清单

[root@dzc ansible]# ansible all --list-hosts
  hosts (2):
    1.1.1.1
    2.2.2.2

列出指定组成员清单

[root@dzc ansible]# ansible webservers --list-hosts
  hosts (1):
    2.2.2.2

列出非组成员清单

[root@dzc ansible]# ansible ungrouped --list-hosts
  hosts (1):
    1.1.1.1

2. 配置文件

使用/etc/ansible/ansible.cfg
这是一个全局包,由ansible默认提供,如果找不到其他配置文件,则使用此文件。

使用~/.ansible.cfg
Ansible会在用户家目录里查找ansible.cfg文件,如果存在此配置文件并且当前工作目录中也没有ansible.cfg文件,则使用此配置取代/etc/ansible/ansible.cfg文件

使用./ansible.cfg
如果执行ansible命令的目录中存在ansible.cfg文件,则使用它,而不使用全局文件或用户的个人文件。这样,管理员可以创建一种目录结构,将不同的环境或项目存储在单独的目录中,并且每个目录包含为独特的一组设置而定制的配置文件。

推荐的做法是在需要运行Ansible命令的目录中创建ansible.cfg文件。此目录中也将包含任何供Ansible项目使用的文件,如清单和playbook。这是用于Ansible配置文件的最常用位置。实践中不常使用~/.ansible.cfg或/etc/ansible/ansible.cfg文件

使用ANSIBLE_CONFIG环境变量
我们可以通过将不同的配置文件放在不同的目录中,然后从适当的目录去执行Ansible命令,以此利用配置文件。但是,配置文件数量变多后,这种方法会存在 一定的局限性并且难以管理。所以就有了一个更加灵活的选项,就是ANSIBLE_CONFIG环境变量定义配置文件的位置。定义了此变量时,Ansible将使用变量所指定的配置文件,而不用上面提到的任何配置文件。

3. 帮助文档

ansible-doc 命令常用于获取模块信息及其使用帮助,一般用法如下:

ansible-doc -l			//获取全部模块的信息
ansible-doc -s MOD_NAME		//获取指定模块的使用帮助

ansible-doc的全部用法

[root@dzc ansible]# ansible-doc 
usage: ansible-doc [-h] [--version] [-v] [-M MODULE_PATH]
                   [--playbook-dir BASEDIR]
                   [-t {become,cache,callback,cliconf,connection,httpapi,inventory,lookup,netconf,shell,module,strategy,vars}]
                   [-j] [-F | -l | -s | --metadata-dump]
                   [plugin [plugin ...]]

plugin documentation tool

positional arguments:
  plugin                Plugin

optional arguments:
  --metadata-dump       **For internal testing only** Dump json metadata for
                        all plugins.
  --playbook-dir BASEDIR
                        Since this tool does not use playbooks, use this as a
                        substitute playbook directory.This sets the relative
                        path for many features including roles/ group_vars/
                        etc.
  --version             show program's version number, config file location,
                        configured module search path, module location,
                        executable location and exit
  -F, --list_files      Show plugin names and their source files without
                        summaries (implies --list)
  -M MODULE_PATH, --module-path MODULE_PATH
                        prepend colon-separated path(s) to module library (def
                        ault=~/.ansible/plugins/modules:/usr/share/ansible/plu
                        gins/modules)
  -h, --help            show this help message and exit
  -j, --json            Change output into json format.
  -l, --list            List available plugins
  -s, --snippet         Show playbook snippet for specified plugin(s)
  -t {become,cache,callback,cliconf,connection,httpapi,inventory,lookup,netconf,shell,module,strategy,vars}, --type {become,cache,callback,cliconf,connection,httpapi,inventory,lookup,netconf,shell,module,strategy,vars}
                        Choose which plugin type (defaults to "module").
                        Available plugin types are : ('become', 'cache',
                        'callback', 'cliconf', 'connection', 'httpapi',
                        'inventory', 'lookup', 'netconf', 'shell', 'module',
                        'strategy', 'vars')
  -v, --verbose         verbose mode (-vvv for more, -vvvv to enable
                        connection debugging)

See man pages for Ansible CLI options or website for tutorials

4. Ansible常用模块

command模块

这个模块可以直接在远程主机上执行命令,并将结果返回本主机。

[root@dzc ansible]# ansible webservers -m command -a 'ss -anlt'
192.168.159.3 | CHANGED | rc=0 >>
State     Recv-Q    Send-Q       Local Address:Port        Peer Address:Port    
LISTEN    0         128                0.0.0.0:22               0.0.0.0:*       
LISTEN    0         5                127.0.0.1:631              0.0.0.0:*       
LISTEN    0         128                0.0.0.0:111              0.0.0.0:*       
LISTEN    0         32           192.168.122.1:53               0.0.0.0:*       
LISTEN    0         128                   [::]:22                  [::]:*       
LISTEN    0         5                    [::1]:631                 [::]:*       
LISTEN    0         128                   [::]:111                 [::]:*  

命令模块接受命令名称,后面是空格分隔的列表参数。给定的命令将在所有选定的节点上执行。它不会通过shell进行处理,比如$HOME和操作如"<",">","|",";","&" 工作(需要使用(shell)模块实现这些功能)。注意,该命令不支持| 管道命令。

下面来看一看该模块下常用的几个命令:

chdir       //在执行命令之前,先切换到该目录
executable //切换shell来执行命令,需要使用命令的绝对路径
free_form   //要执行的Linux指令,一般使用Ansible的-a参数代替。
creates  //一个文件名,当这个文件存在,则该命令不执行,可以用来做判断
removes //一个文件名,这个文件不存在,则该命令不执行

shell模块

shell模块可以在远程主机上调用shell解释器运行命令,支持shell的各种功能,例如管道等。

[root@dzc ansible]# ansible webservers -m shell -a 'cat /etc/passwd | grep "root"'
192.168.159.3 | CHANGED | rc=0 >>
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

只要是我们的shell命令,都可以通过这个模块在远程主机上运行,这里就不一一举例了。

copy模块

这个模块用于将文件复制到远程主机,同时支持给定内容生成文件和修改权限等。
其相关选项如下:

src    #被复制到远程主机的本地文件。可以是绝对路径,也可以是相对路径。如果路径是一个目录,则会递归复制,用法类似于"rsync"
content   #用于替换"src",可以直接指定文件的值
dest    #必选项,将源文件复制到的远程主机的绝对路径
backup   #当文件内容发生改变后,在覆盖之前把源文件备份,备份文件包含时间信息
directory_mode    #递归设定目录的权限,默认为系统默认权限
force    #当目标主机包含该文件,但内容不同时,设为"yes",表示强制覆盖;设为"no",表示目标主机的目标位置不存在该文件才复制。默认为"yes"
others    #所有的 file 模块中的选项可以在这里使用

用法举例:
复制文件

[root@dzc ansible]# ansible webservers -m copy -a 'src=/root/dzc dest=/root/' 
192.168.159.3 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
    "dest": "/root/dzc",
    "gid": 0,
    "group": "root",
    "md5sum": "d41d8cd98f00b204e9800998ecf8427e",
    "mode": "0644",
    "owner": "root",
    "secontext": "system_u:object_r:admin_home_t:s0",
    "size": 0,
    "src": "/root/.ansible/tmp/ansible-tmp-1626425466.0167131-212832-260946955496569/source",
    "state": "file",
    "uid": 0
}

file模块

该模块主要用于设置文件的属性,比如创建文件、创建链接文件、删除文件等。
  下面是一些常见的命令:

force  #需要在两种情况下强制创建软链接,一种是源文件不存在,但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no
group  #定义文件/目录的属组。后面可以加上mode:定义文件/目录的权限
owner  #定义文件/目录的属主。后面必须跟上path:定义文件/目录的路径
recurse  #递归设置文件的属性,只对目录有效,后面跟上src:被链接的源文件路径,只应用于state=link的情况
dest  #被链接到的路径,只应用于state=link的情况
state  #状态,有以下选项:
directory:如果目录不存在,就创建目录
file:即使文件不存在,也不会被创建
link:创建软链接
hard:创建硬链接
touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间
absent:删除目录、文件或者取消链接文件

[root@dzc ansible]# ansible webservers -m file -a 'path=/root/123 state=directory'
192.168.159.3 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "gid": 0,
    "group": "root",
    "mode": "0755",
    "owner": "root",
    "path": "/root/123",
    "secontext": "unconfined_u:object_r:admin_home_t:s0",
    "size": 6,
    "state": "directory",
    "uid": 0
}

查看一下:
[root@dzc ansible]# ansible webservers -m shell -a 'ls /root/123'
192.168.159.3 | CHANGED | rc=0 >>
//因为现在为空,所以没有内容显示

blocakinfile模块

blockinfile模块可以帮助我们在指定的文件中插入"一段文本",这段文本是被标记过的,换句话说就是,我们在这段文本.上做了记号,以便在以后的操作中可以通过"标记"找到这段文本,然后修改或者删除它

path:必须参数,指定要操作的文件
block:此参数用于指定我们想要操作的那一段文本,此参数有别名"content",使用content或block的作用是相同的
marker:给需要的内容打上标记,以方便更容易的去找到我们所需要的内容
state:将指定的一段文本"插入"到文件中
insertafter:文本插入在某一行的后面
insertbefore:文本插入在某一行的前面
backup:是否在修改文件之前对文件进行备份
create:当要操作的操作的文件不存在时,是否创建对应的文件

[root@dzc ansible]# ansible webservers -m blockinfile -a "path=/root/dzc block='systemctl start firewalld.service'"
192.168.159.3 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "msg": "Block inserted"
}

查看一下:
[root@master ansible]# ansible webservers -m command -a 'cat /root/dzc'
192.168.159.3 | CHANGED | rc=0 >>
123
234
345
# BEGIN ANSIBLE MANAGED BLOCK
systemctl start firewalld.service		//添加完成
# END ANSIBLE MANAGED BLOCK

fetch模块

该模块用于从远程某主机获取(复制)文件到本地。
  有两个选项:

dest:用来存放文件的目录
src:在远程拉取的文件,并且必须是一个file,不能是目录

[root@dzc ansible]# ansible webservers -m fetch -a 'src=/root/dzc dest=/usr/'
192.168.159.3 | CHANGED => {
    "changed": true,
    "checksum": "08fad39a90db9ac2080b7605f4a7835f8d3bc70d",
    "dest": "/usr/192.168.159.3/root/dzc",
    "md5sum": "30de1f8bf62343e33a264ced86cf0393",
    "remote_checksum": "08fad39a90db9ac2080b7605f4a7835f8d3bc70d",
    "remote_md5sum": null
}

查看一下:
[root@dzc ~]# cd /usr/
[root@dzc usr]# ls
192.168.159.3  bin  games  include  lib  lib64  libexec  local  sbin  share  src  tmp
//发现有名为192.168.159.3的文件,即为复制成功

cron模块

该模块适用于管理cron计划任务的。
  其使用的语法跟我们的crontab文件中的语法一致,同时,可以指定以下选项:

day= //日应该运行的工作( 1-31, *, */2, )
hour= //小时 ( 0-23, *, */2, )
minute= //分钟( 0-59, *, */2, )
month= //月( 1-12, *, /2, )
weekday= //周 ( 0-6 for Sunday-Saturday,, )
job= //指明运行的命令是什么
name= //定时任务描述
reboot //任务在重启时运行,不建议使用,建议使用special_time
special_time //特殊的时间范围,参数:reboot(重启时),annually(每年),monthly(每月),weekly(每周),daily(每天),hourly(每小时)
state #指定状态,present表示添加定时任务,也是默认设置,absent表示删除定时任务
user //以哪个用户的身份执行

[root@dzc ansible]# ansible webservers -m cron -a 'name="ntp update every 5 min" minute=*/5 job="/sbin/ntpdate 172.10.0.1 &> /dev/null"'
192.168.159.3 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "envs": [],
    "jobs": [
        "ntp update every 5 min"
    ]
}

查看一下:
[root@dzc ansible]# ansible webservers -m shell -a 'crontab -l'
192.168.159.3 | CHANGED | rc=0 >>
#Ansible: ntp update every 5 min
*/5 * * * * /sbin/ntpdate 172.10.0.1 &> /dev/null

yum模块

顾名思义,该模块主要用于软件的安装。
  其选项如下:

name=  //所安装的包的名称
state=  //present--->安装, latest--->安装最新的, absent---> 卸载软件。
update_cache  //强制更新yum的缓存
conf_file  //指定远程yum安装时所依赖的配置文件(安装本地已有的包)。
disable_pgp_check  //是否禁止GPG checking,只用于presentor latest。
disablerepo  //临时禁止使用yum库。 只用于安装或更新时。
enablerepo  //临时使用的yum库。只用于安装或更新时。

[root@dzc ansible]# ansible webservers -m yum -a 'name=httpd state=present'
192.168.159.3 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "msg": "",
    "rc": 0,
    "results": [
        "Installed: apr-1.6.3-9.el8.x86_64",
        "Installed: mod_http2-1.11.3-3.module+el8.2.0+4377+dc421495.x86_64",
        "Installed: apr-util-1.6.1-6.el8.x86_64",
        "Installed: redhat-logos-httpd-81.1-1.el8.noarch",
        "Installed: apr-util-bdb-1.6.1-6.el8.x86_64",
        "Installed: httpd-2.4.37-21.module+el8.2.0+5008+cca404a3.x86_64",
        "Installed: httpd-tools-2.4.37-21.module+el8.2.0+5008+cca404a3.x86_64",
        "Installed: httpd-filesystem-2.4.37-21.module+el8.2.0+5008+cca404a3.noarch",
        "Installed: apr-util-openssl-1.6.1-6.el8.x86_64"
    ]
}

service模块

该模块用于服务程序的管理。
  其主要选项如下:

arguments #命令行提供额外的参数
enabled //设置开机启动。
name= //服务名称
runlevel #开机启动的级别,一般不用指定。
sleep //在重启服务的过程中,是否等待。如在服务关闭以后等待2秒再启动。(定义在剧本中。)
state //有四种状态,分别为:started--->启动服务, stopped--->停止服务, restarted--->重启服务, reloaded--->重载配置

[root@dzc ansible]# ansible webservers -m service -a 'name=sshd state=restarted enabled=true'
192.168.159.3 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "enabled": true,
    "name": "sshd",
    "state": "started",
    "status": {
        "ActiveEnterTimestamp": "Fri 2021-07-16 16:26:47 CST",
        "ActiveEnterTimestampMonotonic": "7077495",
        "ActiveExitTimestampMonotonic": "0",
        "ActiveState": "active",
        "After": "network.target sysinit.target system.slice systemd-journald.socket sshd-keygen.target basic.target",
        "AllowIsolate": "no",
        "AllowedCPUs": "",
---------------------中间部分省略---------------------
        "WatchdogTimestamp": "Fri 2021-07-16 16:26:47 CST",
        "WatchdogTimestampMonotonic": "7077494",
        "WatchdogUSec": "0"
    }
}

查看一下端口是否开启:
[root@dzc ansible]# ansible webservers -m shell -a 'ss -antl | grep ":22"'
192.168.159.3 | CHANGED | rc=0 >>
LISTEN    0         128                0.0.0.0:22               0.0.0.0:*       
LISTEN    0         128                   [::]:22                  [::]:* 

user模块

该模块主要是用来管理用户账号。
  其主要选项如下:

comment //用户的描述信息
createhome //是否创建家目录
force //在使用state=absent时, 行为与userdel –force一致.
group //指定基本组
groups //指定附加组,如果指定为(groups=)表示删除所有组
home //指定用户家目录
move_home //如果设置为home=时, 试图将用户主目录移动到指定的目录
name //指定用户名
non_unique //该选项允许改变非唯一的用户ID值
password //指定用户密码
remove //在使用state=absent时, 行为是与userdel –remove一致
shell //指定默认shell
state //设置帐号状态,不指定为创建,指定值为absent表示删除
system //当创建一个用户,设置这个用户是系统用户。这个设置不能更改现有用户
uid //指定用户的uid

[root@dzc ansible]# ansible webservers -m user -a 'name=dzc uid=12345'
192.168.159.3 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "comment": "",
    "create_home": true,
    "group": 12345,
    "home": "/home/dzc",
    "name": "dzc",
    "shell": "/bin/bash",
    "state": "present",
    "system": false,
    "uid": 12345
}

查看一下:
[root@dzc ansible]# ansible webservers -m shell -a 'cat /etc/passwd |grep dzc'
192.168.159.3 | CHANGED | rc=0 >>
dzc:x:12345:12345::/home/dzc:/bin/bash

group模块

该模块主要用于添加或删除组。
  常用的选项如下:

gid= //设置组的GID号
name= //指定组的名称
state= //指定组的状态,默认为创建,设置值为absent为删除
system= //设置值为yes,表示创建为系统组

[root@dzc ansible]# ansible webservers -m group -a 'name=2ban gid=10705'
192.168.159.3 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "gid": 10705,
    "name": "2ban",
    "state": "present",
    "system": false
}

查看一下:
[root@dzc ansible]# ansible webservers -m shell -a 'cat /etc/group | grep 10705' 
192.168.159.3 | CHANGED | rc=0 >>
2ban:x:10705:

script模块

该模块用于将本机的脚本在被管理端的机器上运行。
  该模块直接指定脚本的路径即可,我们通过例子来看一看到底如何使用的:
  首先,我们写一个脚本,并给其加上执行权限:

[root@dzc ansible]# ansible webservers -m script -a '/root/zc.sh'
192.168.159.3 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 192.168.159.3 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 192.168.159.3 closed."
    ],
    "stdout": "",
    "stdout_lines": []
}

查看一下:
[root@dzc ansible]# ansible webservers -m shell -a 'cat /root/dzc'
192.168.159.3 | CHANGED | rc=0 >>
文件系统                 1K-块    已用     可用 已用% 挂载点
devtmpfs               1891948       0  1891948    0% /dev
tmpfs                  1921028       0  1921028    0% /dev/shm
tmpfs                  1921028    9868  1911160    1% /run
tmpfs                  1921028       0  1921028    0% /sys/fs/cgroup
/dev/mapper/rhel-root 52403200 4861484 47541716   10% /
/dev/sr0               8238560 8238560        0  100% /mnt/cdrom
/dev/mapper/rhel-home 47212008  374072 46837936    1% /home
/dev/nvme0n1p1         1038336  234188   804148   23% /boot
tmpfs                   384204       4   384200    1% /run/user/0
tmpfs                   384204    1168   383036    1% /run/user/42

setup模块

该模块主要用于收集信息,是通过调用facts组件来实现的。
  facts组件是Ansible用于采集被管机器设备信息的一个功能,我们可以使用setup模块查机器的所有facts信息,可以使用filter来查看指定信息。整个facts信息被包装在一个JSON格式的数据结构中,ansible_facts是最上层的值。
  facts就是变量,内建变量 。每个主机的各种信息,cpu颗数、内存大小等。会存在facts中的某个变量中。调用后返回很多对应主机的信息,在后面的操作中可以根据不同的信息来做不同的操作。如redhat系列用yum安装,而debian系列用apt来安装软件。

[root@dzc ansible]# ansible webservers -m setup -a 'filter="*mem*"'	//查看内存
192.168.159.3 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 2310,
        "ansible_memory_mb": {
            "nocache": {
                "free": 2834,
                "used": 918
            },
            "real": {
                "free": 2310,
                "total": 3752,
                "used": 1442
            },
            "swap": {
                "cached": 0,
                "free": 4043,
                "total": 4043,
                "used": 0
            }
        },
        "ansible_memtotal_mb": 3752,
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false
}

查看一下:
[root@dzc ansible]# ansible webservers -m shell -a 'free -m'
192.168.159.3 | CHANGED | rc=0 >>
              total        used        free      shared  buff/cache   available
Mem:           3752         830        2307          10         614        2666
Swap:          4043           0        4043
0

评论区