【ansible】ansible模块的使用

模块

最常用的模块也就2、30个,针对特定业务只用10几个模块

常用模块帮助文档参考:

https://docs.ansible.com/ansible/2.9/modules/modules_by_category.html

https://docs.ansible.com/ansible/2.9/modules/list_of_all_modules.html

https://docs.ansible.com/ansible/latest/modules/list_of_all_modules.html

https://docs.ansible.com/ansible/latest/modules/modules_by_category.html

1 .Command 模块

功能:在远程主机执行命令,此为默认模块,可忽略 -m 选项

html 复制代码
注意:此命令不支持 $VARNAME < > | ; & 等,可能用shell模块实现
        $VARNAME    变量
        <    输入
        >    重定向输出
        |    管道符
        ;    并行执行
        &    后台执行

注意:此模块不具有幂等性

(操作)
html 复制代码
[root@test1 opt]# ansible web -a 'hostname'
192.168.67.13 | CHANGED | rc=0 >>
test3
192.168.67.12 | CHANGED | rc=0 >>
test2

#创建文件
[root@test1 opt]# ansible web -a "touch /opt/ky35.txt"
    #此处会警告,提示你用file模块更好
[WARNING]: Consider using the file module with state=touch rather than running
'touch'.  If you need to use command because file is insufficient you can add 'warn:
false' to this command task or set 'command_warnings=False' in ansible.cfg to get
rid of this message.
192.168.67.13 | CHANGED | rc=0 >>

192.168.67.12 | CHANGED | rc=0 >>

[root@test2 ~]# cd /opt/
[root@test2 opt]# ls
ky35.txt  rh

[root@test3 ~]# cd /opt/
[root@test3 opt]# ls
ky35.txt  rh

#不支持一些  重定向等功能
[root@test1 opt]# ansible web -a "echo hello > /opt/hello.log"
#不支持重定向,将echo后面的内容当成了整体打印了出来
192.168.67.13 | CHANGED | rc=0 >>
hello > /opt/hello.log
192.168.67.12 | CHANGED | rc=0 >>
hello > /opt/hello.log
#虽然没报错,但也没写入;
[root@test2 opt]# cat ky35.txt 
[root@test2 opt]# 
[root@test3 opt]# cat ky35.txt 
#使用shell模块就可以了
[root@test1 opt]# ansible web -m shell -a "echo hello > /opt/hello.log"

2.shell模块

功能:和command相似,用shell执行命令,支持各种符号,比如:*,$, >

注意:此模块不具有幂等性

(操作)
html 复制代码
#如果没有明确指明文件生成的目录,会默认在家目录下生成
[root@test1 opt]# ansible web -m shell -a "echo hello > /opt/hello.txt"
192.168.67.13 | CHANGED | rc=0 >>

192.168.67.12 | CHANGED | rc=0 >>

[root@test2 opt]# ls
hello.txt  ky35.txt  rh
[root@test3 opt]# ls
hello.txt  ky35.txt  rh


#修改默认模块
[root@test1 opt]# vim /etc/ansible/ansible.cfg 
113 # default module name for /usr/bin/ansible
114 #module_name = command
115 module_name = shell

#修改后shell就变成默认模块了
[root@test1 opt]# ansible web -a "echo $PATH"
192.168.67.13 | CHANGED | rc=0 >>
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
192.168.67.12 | CHANGED | rc=0 >>
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin

3.Script模块

功能:在被管理机上运行ansible服务器上的脚本(无需执行权限)

注意:此模块不具有幂等性

(操作)
html 复制代码
[root@test1 opt]# vim test.sh
  1 #!/bin/bash
  2 touch /opt/data

[root@test1 opt]# ls
fdisk.sh  hello.yml  rh  SCANIP.log  ssh_key.sh  test.sh

[root@test1 opt]# ansible web -m script -a '/opt/test.sh'
192.168.67.12 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.67.12 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.67.12 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}
192.168.67.13 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.67.13 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.67.13 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}

4.copy模块

功能:从ansible服务器上复制文件到被管理机上

注意: src=file 如果是没指明路径,则为当前目录或当前目录下的files目录下的file文件

关键字:

html 复制代码
src   	代表源文件路径
dest  	代表文件落地路径
owner 	属主
group 	属组
mode  	代表权限
backup  如果复制时有同名文件会先备份再复制

例子:

html 复制代码
注意:拷贝前需要确保被管理机上有相应的用户
[root@test2 ~]# useradd zhangsan
[root@test2 ~]# passwd zhangsan 
Changing password for user zhangsan.
New password: 
BAD PASSWORD: The password is shorter than 8 characters
Retype new password: 
passwd: all authentication tokens updated successfully.


[root@test1 opt]# ansible web -m copy -a "src=/etc/passwd dest=/opt/ owner=zhangsan mode=700"
[root@test2 opt]# ll
total 5
-rwx------. 1 zhangsan root 2146 Mar 12 03:21 passwd
drwxr-xr-x. 2 root     root    6 Mar 26  2015 rh


# src 不写绝对路径会从当前路径执行
[root@test1 opt]# ansible web -m copy -a "src=test.sh dest=/opt/test.sh owner=zhangsan mode=700"
[root@test2 opt]# ll
total 8
-rwx------. 1 zhangsan root 2146 Mar 12 03:21 passwd
drwxr-xr-x. 2 root     root    6 Mar 26  2015 rh
-rwx------. 1 zhangsan root   28 Mar 12 04:12 test.sh
[root@test2 opt]# cat test.sh 
#!/bin/bash
touch /opt/data


#如目标存在,默认覆盖,此处指定先备份(源文件要有变动才会进行备份,有后缀的是旧的)
[root@test1 opt]# ansible web -m copy -a "src=/opt/test.sh dest=/opt/test.sh owner=zhangsan  mode=700 backup=yes"
[root@test2 opt]# ll
-rwx------. 1 zhangsan root   28 Mar 12 04:18 test.sh
-rwx------. 1 zhangsan root   32 Mar 12 04:18 test.sh.19336.2024-03-12@04:18:51~


#指定内容,直接生成目标文件  
[root@test1 opt]# ansible web -m copy -a "content='test line1\ntest line2\n' dest=/opt/test.txt"
[root@test2 opt]# cat test.txt 
test line1
test line2


[root@test1 opt]# ansible web -m copy -a "src=/opt dest=/backup"
[root@test2 ~]# cd /backup/
[root@test2 backup]# ls
opt

[root@test1 opt]# ansible web -m copy -a "src=/opt/ dest=/backup"
[root@test2 backup]# ls
data  fdisk.sh  hello.yml  opt  rh  SCANIP.log  ssh_key.sh  test.sh


etc  	不加  	/   	连etc  一起复制
etc   	加  		/	   	只复制etc下的文件

5.Get_url 模块

功能: 用于将文件从http、https或ftp下载到被管理机节点上

常用参数:
复制代码
url: 下载文件的URL,支持HTTP,HTTPS或FTP协议
dest:下载到目标路径(绝对路径),如果目标是一个目录,就用服务器上面文件的名称,如果目标设置了名称就用目标设置的名称
owner:指定属主
group:指定属组
mode:指定权限
force:如果yes,dest不是目录,将每次下载文件,如果内容改变,替换文件。如果否,则只有在目标不存在时才会下载该文件

checksum:对目标文件在下载后计算摘要,以确保其完整性
url_username:用于HTTP基本认证的用户名。对于允许空密码的站点,此参数可以不使用`url_password'
url_password:用于HTTP基本认证的密码。如果未指定`url_username'参数,则不会使用`url_password'参数
validate_certs:如果"no",SSL证书将不会被验证。适用于自签名证书在私有网站上使用
timeout: URL请求的超时时间,秒为单位
html 复制代码
#检查是否安装成功
[root@test2 opt]# rpm -q nginx
package nginx is not installed
#安装
[root@test1 ~]# ansible web -m get_url -a "url=https://nginx.org/download/nginx-1.18.0.tar.gz dest=/opt"
[root@test2 opt]# ls
nginx-1.18.0.tar.gz

#nginx安装路径
#wget https://nginx.org/download/nginx-1.18.0.tar.gz

#检测文件是否有问题
[root@test2 opt]# md5sum nginx-1.18.0.tar.gz 
b2d33d24d89b8b1f87ff5d251aa27eb8  nginx-1.18.0.tar.gz
[root@test3 opt]# md5sum nginx-1.18.0.tar.gz 
b2d33d24d89b8b1f87ff5d251aa27eb8  nginx-1.18.0.tar.gz

[root@test1 ~]# ansible web -m get_url -a 'url=https://nginx.org/download/nginx-1.18.0.tar.gz dest=/opt checksum="md5:b2d33d24d89b8b1f87ff5d251aa27eb8"'
###   checksum 后面不要忘记 加 md5: ###

6.Fetch 模块

功能:从远程主机提取文件至ansible的主控端,与copy相反,但只能传文件,不能传目录

范例:

html 复制代码
[root@test1 ~]# ansible web -m fetch -a 'src=/etc/passwd dest=/opt'
#从多个被管理机上下载的文件会按IP区分
[root@test1 ~]# ll /opt/
total 20
drwxr-xr-x. 3 root root  17 Mar 12 22:10 192.168.67.12
drwxr-xr-x. 3 root root  17 Mar 12 22:10 192.168.67.13

[root@test1 opt]# tree 192.168.67.12 192.168.67.13
192.168.67.12
└── etc
    └── passwd
192.168.67.13
└── etc
    └── passwd

7.File模块

功能:设置文件属性,创建软链接等

html 复制代码
path   	指定文件路径
state  	文件状态 有:新建(touch) 删除(absent) 文件夹(directory)  连接文件(link)等
src    	源文件
mode   	权限
owner  	属主
group  	属组
recurse	递归
创建空文件
html 复制代码
[root@test1 opt]# ansible web -m file -a 'path=/opt/test.txt state=touch owner=zhangsan group=zhangsan mode=755'

[root@test2 opt]# ll
-rwxr-xr-x. 1 zhangsan zhangsan       0 Mar 12 22:44 test.txt
新建目录
html 复制代码
[root@test1 opt]# ansible web -m file -a 'path=/opt/backup state=directory'

[root@test2 opt]# ll
total 1016
drwxr-xr-x. 2 root     root           6 Mar 12 22:47 backup
新建软连接
html 复制代码
[root@test1 opt]# ansible web -m file -a 'src=/opt/backup path=/opt/backup-link state=link'

[root@test2 opt]# ls
backup  backup-link
#新建软连接 path|dest|name   这三个选项都可以使用

[root@test1 opt]# ansible web -m file -a 'src=/opt/backup name=/opt/backup-link3 state=link'
[root@test2 opt]# ls
backup  backup-link  backup-link3
删除文件和目录
html 复制代码
#目录
[root@test1 opt]# ansible all -m file -a "path=/opt/backup state=absent"

[root@test2 opt]# ls
backup-link  backup-link3

#文件
[root@test1 opt]# ansible all -m file -a "path=/opt/backup-link state=absent"

[root@test2 opt]# ls
backup-link3
递归修改目录及子目录的属性
html 复制代码
[root@test1 opt]# ansible web -m file -a "path=/opt/backup state=directory owner=mysql group=mysql"

[root@test2 opt]# ll
total 1016
drwxr-xr-x. 2 mysql mysql       6 Mar 12 23:17 backup


#注意使用该方式修改文件属性path只能纸箱目录;改文件的话要用递归的方式,通过修改文件所在的目录

[root@test1 opt]# ansible web -m file -a "path=/opt state=directory owner=zhangsan group=zhangsan recurse=yes"
[root@test2 opt]# ll
drwxr-xr-x. 2 zhangsan zhangsan       6 Mar 12 23:17 backup
-rwxr-xr-x. 1 zhangsan zhangsan       0 Mar 12 22:44 test.txt

8.stat模块

功能:检查文件或文件系统的状态

注意:对于Windows目标,请改用win_stat模块

选项
html 复制代码
path:文件/对象的完整路径(必须)
常用的返回值判断:
html 复制代码
exists: 判断是否存在
isuid: 调用用户的ID与所有者ID是否匹配
查看文件是否存在
html 复制代码
[root@test1 opt]# ansible web -m stat -a 'path=/opt/test.txt'

192.168.67.13 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
...省略

9.unarchive 模块

功能:解包解压缩

实现有两种用法:

1、把本机的压缩包拷贝到远程主机 后解压缩至特定目录,设置copy=yes,此为默认值,可省略

2、将远程主机上的某个压缩包解压缩到指定路径下,设置copy=no;

copy=no代表压缩文件是从远程主机上查找

常见参数
html 复制代码
copy:默认为yes,当copy=yes,拷贝的文件是从ansible主机复制到远程主机上,如果设置为copy=no,会在远程主机上寻找src源文件
remote_src:和copy功能一样且互斥,yes表示在远程主机,不在ansible主机,no表示文件在ansible主机上
src:源路径,可以是ansible主机上的路径,也可以是远程主机(被管理端或者第三方主机)上的路径,如果是远程主机上的路径,则需要设置copy=no
dest:远程主机上的目标路径
mode:设置解压缩后的文件权限
copy=yes
html 复制代码
#先创建一个包
[root@test1 opt]# tar zcvf all.tar /opt/*
tar: Removing leading `/' from member names
/opt/hello.yml
/opt/rh/
/opt/SCANIP.log
/opt/ssh_key.sh
/opt/test.sh
[root@test1 opt]# ls
all.tar

[root@test1 opt]# ansible web -m unarchive -a 'src=/opt/all.tar dest=/opt'
[root@test2 opt]# ls
backup  opt
copy=no
html 复制代码
[root@test1 opt]# ansible web -m unarchive -a 'src=https://nginx.org/download/nginx-1.18.0.tar.gz dest=/opt/nginx copy=no'

[root@test2 opt]# tree nginx
nginx
└── nginx-1.18.0
    ├── auto
    │   ├── cc

# copy=no  代表压缩文件不是去本机上查找 

10.Archive模块

功能:打包压缩被管理节点的文件并保存在被管理节点

html 复制代码
ansible web -m archive -a "path=/var/log/ dest=/data/log.tar.bz2 format=bz2 owner=zhangsan mode=0600"
#注意压缩包所在的目录是要存在的

0600    文件权限=600

11.Hostname模块

功能:管理主机名

html 复制代码
[root@test1 opt]# ansible 192.168.67.12 -m hostname -a 'name=node2'

[root@test2 opt]# su
[root@node2 opt]# 

#一般不使用此模块,主机名会一致

12.Cron 模块

功能:计划任务

支持时间:minute,hour,day,month,weekday

关键字:

html 复制代码
name  会生成一行注释,显示标题如下显示
job   执行的命令
创建定时任务
html 复制代码
[root@test1 opt]# ansible 192.168.67.12 -m cron -a 'hour=2 minute=30 weekday=1-5 name="backup mysql" job=/root/mysql_backup.sh'

#此处的mysql脚本我并没有实际写入,只是用来展示一下
查看定时任务
html 复制代码
#Ansible: backup mysql
30 2 * * 1-5 /root/mysql_backup.sh
disabled
html 复制代码
ansible 192.168.67.12 -m cron -a 'hour=2 minute=30 weekday=1-5 name="backup mysql" job=/root/mysql_backup.sh   disabled=yes'

ansible 192.168.67.12 -m cron -a 'hour=2 minute=30 weekday=1-5 name="backup mysql" job=/root/mysql_backup.sh   disabled=no'
# disabled=yes 表示不启用;=no表示启用
删除定时任务
html 复制代码
1.
[root@test1 opt]# ansible 192.168.67.12 -m cron -a "name='backup mysql' state=absent"
192.168.67.12 | CHANGED => {
...省略
[root@node2 opt]# crontab -l
[root@node2 opt]# 

2.
#ansible 192.168.67.12 -m cron -a 'state=absent name=Synctime'

13.Yum和 Apt 模块

功能:yum 管理软件包,只支持RHEL,CentOS,fedora,不支持Ubuntu其它版本apt 模块管理 Debian 相关版本的软件包

关键字:
html 复制代码
name			   所安装的包的名称
state              present--->安装, latest--->安装最新的, absent---> 卸载软件。
update_cache       强制更新yum的缓存
conf_file          指定远程yum安装时所依赖的配置文件(安装本地已有的包)。
disable_pgp_check  是否禁止GPG checking,只用于presentor latest。
disablerepo        临时禁止使用yum库。 只用于安装或更新时。
enablerepo         临时使用的yum库。只用于安装或更新时
安装
html 复制代码
[root@test1 opt]# ansible web -m yum -a 'name=httpd state=present'
[root@node2 opt]# rpm -q httpd
httpd-2.4.6-99.el7.centos.1.x86_64
启用epel源安装nginx
html 复制代码
#注意epel源要提前在被管理机上装好
[root@node2 opt]# yum -y install epel-release.noarch

[root@test1 opt]# ansible web -m yum -a 'name=nginx state=present enablerepo=epel'

[root@node2 opt]# rpm -q nginx
nginx-1.20.1-10.el7.x86_64
升级
html 复制代码
#升级除kernel和foo开头以外的所有包
ansible web -m yum -a 'name=* state=lastest exclude=kernel*,foo*'

#别用,看看就行,或者单独升级
删除
html 复制代码
[root@test1 opt]# ansible web -m yum -a 'name=httpd state=absent'

[root@node2 opt]# rpm -q httpd
package httpd is not installed

14.yum_repository

功能:建立yum仓库模块

关键字:

html 复制代码
name参数:			必须参数,用于指定要操作的唯一的仓库ID,也就是".repo"配置文件中每个仓库对应的"中括号"内的仓库ID。
baseurl参数:		此参数用于设置 yum 仓库的 baseurl。
description参数:	此参数用于设置仓库的注释信息,也就是".repo"配置文件中每个仓库对应的"name字段"对应的内容。
file参数:			此参数用于设置仓库的配置文件名称,即设置".repo"配置文件的文件名前缀,在不使用此参数的情况下,默认以 name 参数的仓库ID作					  为".repo"配置文件的文件名前缀,同一个".repo" 配置文件中 可以存在多个 yum 源。
enabled参数:		此参数用于设置是否激活对应的 yum 源,此参数默认值为 yes,表示启用对应的 yum 源,设置为 no 表示不启用对应的 yum 源。
gpgcheck参数:		此参数用于设置是否开启 rpm 包验证功能,默认值为 no,表示不启用包验证,设置为 yes 表示开启包验证功能。
gpgcakey参数:		当 gpgcheck 参数设置为 yes 时,需要使用此参数指定验证包所需的公钥。
state参数:		默认值为 present,当值设置为 absent 时,表示删除对应的 yum 源。
html 复制代码
#安装epel源
[root@test1 opt]# ansible web -m yum_repository -a 'name=epel description=epel  baseurl=https://download.fedoraproject.org/pub/epel/$releasever/$basearch/ gpgcheck=no file=epel'


- name: Add multiple repositories into the same file (1/2)
 yum_repository:
   name: epel
   description: EPEL YUM repo
   file: external_repos
   baseurl: https://download.fedoraproject.org/pub/epel/$releasever/$basearch/

15.Service 模块

功能:管理服务

关键字:
html 复制代码
name参数:		此参数用于指定需要操作的服务名称,比如 nginx。
state参数:	此参数用于指定服务的状态,比如,我们想要启动远程主机中的 nginx,则可以将 state 的值设置为 started;如果想要停止远程主机中的服			   务,则可以将 state 的值设置为 stopped。此参数的可用值有 started、stopped、restarted、reloaded。
enabled参数:	此参数用于指定是否将服务设置为开机 启动项,设置为 yes 表示将对应服务设置为开机启动,设置为 no 表示不会开机启动。
开启服务
html 复制代码
#确保被管理机上有要操作的服务
[root@node2 opt]# rpm -q httpd
httpd-2.4.6-99.el7.centos.1.x86_64

[root@test1 opt]# ansible web -m service -a "name=httpd state=started enabled=yes"
[root@node2 opt]# systemctl status httpd.service 
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2024-03-13 01:20:57 PDT; 25s ago
     Docs: man:httpd(8)
           man:apachectl(8)
 Main PID: 64207 (httpd)
   Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec"
   CGroup: /system.slice/httpd.service
           ├─64207 /usr/sbin/httpd -DFOREGROUND
           ├─64208 /usr/sbin/httpd -DFOREGROUND
           ├─64209 /usr/sbin/httpd -DFOREGROUND
           ├─64210 /usr/sbin/httpd -DFOREGROUND
           ├─64211 /usr/sbin/httpd -DFOREGROUND
           └─64212 /usr/sbin/httpd -DFOREGROUND
关闭服务
html 复制代码
[root@test1 opt]# ansible web -m service -a "name=httpd state=stopped"

[root@node2 opt]# systemctl status httpd.service 
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: inactive (dead) since Wed 2024-03-13 01:22:45 PDT; 35s ago
     Docs: man:httpd(8)
           man:apachectl(8)
  Process: 64363 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=0/SUCCESS)
  Process: 64207 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=0/SUCCESS)
 Main PID: 64207 (code=exited, status=0/SUCCESS)
   Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec"
重新加载配置
html 复制代码
[root@test1 opt]# ansible web -m service -a "name=httpd state=reloaded"

#相当于重启;在别处相当于不用启动就可以直接读取配置
html 复制代码
#重启服务
[root@test1 opt]# ansible web -m service -a "name=httpd state=restarted"

#开启服务并设置为开机自启
[root@test1 opt]# ansible 192.168.67.12 -m service -a 'name=httpd state=started enabled=yes'


####
ansible all -m shell -a "sed -i 's/^Listen 80/Listen 8080/' 
/etc/httpd/conf/httpd.conf"
####

16.mount 挂载和卸载

功能: 挂载和卸载文件系统

查看uuid
html 复制代码
[root@test1 opt]# ansible web -a "blkid"
192.168.67.13 | CHANGED | rc=0 >>
/dev/sda1: UUID="d7635d39-6630-42cf-beff-1ed8a9ffd98c" TYPE="xfs" 
/dev/sda2: UUID="0bc2857b-7b5a-4f99-967e-5e212a6ab69b" TYPE="swap" 
/dev/sda3: UUID="8b116f9e-a295-41c2-8642-58dd15f4087f" TYPE="xfs" 
192.168.67.12 | CHANGED | rc=0 >>
/dev/sda1: UUID="d7635d39-6630-42cf-beff-1ed8a9ffd98c" TYPE="xfs" 
/dev/sda2: UUID="0bc2857b-7b5a-4f99-967e-5e212a6ab69b" TYPE="swap" 
/dev/sda3: UUID="8b116f9e-a295-41c2-8642-58dd15f4087f" TYPE="xfs" 

#我这两台机器是克隆出来的,所以uuid是一样的,能改的话尽量改掉
挂载(有问题)
html 复制代码
#临时挂载
mount websrvs -m mount -a 'src="UUID=b3e48f45-f933-4c8e-a700-22a159ec9077" path=/home fstype=xfs opts=noatime state=present'
#临时取消挂载
mount websrvs -m mount -a 'path=/home fstype=xfs opts=noatime state=unmounted'
#永久挂载
ansible websrvs -m mount -a 'src=10.0.0.8:/data/wordpress path=/var/www/html/wp-content/uploads opts="_netdev" state=mounted'
#永久卸载
ansible websrvs -m mount -a 'src=10.0.0.8:/data/wordpress path=/var/www/html/wp-content/uploads state=absent'

17.User 模块

功能:管理用户

html 复制代码
comment         用户的描述信息
createhome      是否创建家目录
force           在使用state=absent时, 行为与userdel --force一致.
group           指定基本组
groups          指定附加组,如果指定为(groups=)表示删除所有组
home            指定用户家目录
move_home       如果设置为home=时, 试图将用户主目录移动到指定的目录
name            指定用户名
non_unique      该选项允许改变非唯一的用户ID值
password        指定用户密码,使用 SHA512 hash
remove          在使用state=absent时, 行为是与userdel --remove一致
shell           指定默认shell
state           设置帐号状态,不指定为创建,指定值为absent表示删除
system          当创建一个用户,设置这个用户是系统用户。这个设置不能更改现有用户
uid             指定用户的uid
update_ password 
  always      如果password参数设置的值与用户当前的加密过的密码字符串不一致,则直接更新用户的密码,默认值即为always
  on_create   如果password参数设置的值与用户当前的加密过的密码字符串不一致,则不会更新用户的密码字符串,保持之前的密码设定
创建用户
html 复制代码
[root@test1 opt]# ansible web -m user -a 'name=user1 comment="test user" uid=2048 home=/app/user1 group=root'

[root@node2 opt]# tail -3f /etc/passwd
mysql:x:1003:1003::/home/mysql:/bin/bash
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
user1:x:2048:0:test user:/app/user1:/bin/bash

18.Group 模块

功能:管理组

创建组
html 复制代码
[root@test1 opt]# ansible web -m group -a 'name=nginx gid=88 system=yes'

查看用户组
[root@node2 opt]# getent group | grep 88
libvirt:x:988:
nginx:x:88:
删除组
html 复制代码
[root@test1 opt]# ansible web -m group -a 'name=nginx state=absent'

[root@test2 opt]# getent group | grep 88
libvirt:x:988:

19.reboot模块

重启被管理机
html 复制代码
[root@test1 opt]# ansible 192.168.67.13 -m reboot

20.Lineinfile 模块

功能:相当于sed,可以修改文件内容

ansible在使用sed进行替换时,经常会遇到需要转义的问题,而且ansible在遇到特殊符号进行替换时,存在问题,无法正常进行替换 。其实在ansible自身提供了两个模块:lineinfile模块和replace模块,可以方便的进行替换一般在ansible当中去修改某个文件的单行进行替换的时候需要使用lineinfile模块

regexp参数 :使用正则表达式匹配对应的行,当替换文本时,如果有多行文本都能被匹配,则只有最后面被匹配到的那行文本才会被替换,当删除文本时,如果有多行文本都能被匹配,这么这些行都会被删除。

如果想进行多行匹配进行替换需要使用replace模块

关键字:
html 复制代码
path	        指定要操作的文件
regexp	        使用正则表达式匹配对应的行
line	        修改为新的内容
insertafter	    将文本插入到"指定的行"之后
insertbefore	将文本插入到"指定的行"之前
state	        删除对应的文本时,需要state=absent
backrefs	    1.支持后向引用、2.当未匹配到内容则不操作文件
backup	        是否在修改文件之前对文件进行备份
create	        当要操作的文件并不存在时,是否创建对应的文件
html 复制代码
1.
#将/etc/httpd/conf/httpd.conf下以 Listen 开头的行修改为 Listen 80
[root@test1 opt]# ansible web -m lineinfile -a "path=/etc/httpd/conf/httpd.conf regexp='^Listen' line='Listen 80'"

[root@node2 opt]# cat /etc/httpd/conf/httpd.conf | grep "^Listen"
Listen 80

2.
[root@test1 opt]# ansible web -m lineinfile -a "path=/etc/selinux/config regexp='^SELINUX=' line='SELINUX=disabled'"

[root@node2 opt]# cat /etc/selinux/config | grep "^SELINUX"
SELINUX=disabled
SELINUXTYPE=targeted 


3.
[root@test1 opt]# ansible web -m lineinfile -a 'dest=/etc/fstab state=absent regexp="^#"'

[root@node2 opt]# cat /etc/fstab | grep "^#"
#
# /etc/fstab
# Created by anaconda on Wed Aug  9 02:29:17 2023
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
[root@node2 opt]# cat /etc/fstab | grep "^#"
[root@node2 opt]# 

21.replace 模块

该模块有点类似于sed命令,主要也是基于正则进行匹配和替换,建议使用

添加
html 复制代码
\1    为后向引用:用于重复搜索前面某个分组匹配的文本;\1指向第一个括号中的文本

[root@test1 opt]# ansible web -m replace -a "path=/etc/fstab regexp='^(UUID.*)' replace='#\1'"

[root@node2 opt]# cat /etc/fstab | grep "^UUID.*"
UUID=8b116f9e-a295-41c2-8642-58dd15f4087f /                       xfs     defaults        0 0
UUID=d7635d39-6630-42cf-beff-1ed8a9ffd98c /boot                   xfs     defaults        0 0
UUID=0bc2857b-7b5a-4f99-967e-5e212a6ab69b swap                    swap    defaults        0 0
[root@node2 opt]# cat /etc/fstab | grep "^UUID.*"
[root@node2 opt]# 
删除
html 复制代码
[root@test1 opt]# ansible web -m replace -a "path=/etc/fstab regexp='^#(UUID.*)' replace='\1'"

[root@node2 opt]# cat /etc/fstab | grep "^#UUID.*"
#UUID=8b116f9e-a295-41c2-8642-58dd15f4087f /                       xfs     defaults        0 0
#UUID=d7635d39-6630-42cf-beff-1ed8a9ffd98c /boot                   xfs     defaults        0 0
#UUID=0bc2857b-7b5a-4f99-967e-5e212a6ab69b swap                    swap    defaults        0 0
[root@node2 opt]# cat /etc/fstab | grep "^#UUID.*"
[root@node2 opt]# 

22.setup模块

功能:setup 模块用于收集远程主机的一些基本信息;这些 facts 信息可以直接以变量的形式使用,但是如果主机较多,会影响执行速度

可以使用 gather_facts: no 来禁止 Ansible 收集 facts 信息

关键字:
html 复制代码
ansible_all_ipv4_addresses:仅显示ipv4的信息。
ansible_devices:仅显示磁盘设备信息。
ansible_distribution:显示是什么系统,例:centos,suse等。
ansible_distribution_major_version:显示是系统主版本。
ansible_distribution_version:仅显示系统版本。
ansible_machine:显示系统类型,例:32位,还是64位。
ansible_eth0:仅显示eth0的信息。
ansible_hostname:仅显示主机名。
ansible_kernel:仅显示内核版本。
ansible_lvm:显示lvm相关信息。
ansible_memtotal_mb:显示系统总内存。
ansible_memfree_mb:显示可用系统内存。
ansible_memory_mb:详细显示内存情况。
ansible_swaptotal_mb:显示总的swap内存。
ansible_swapfree_mb:显示swap内存的可用内存。
ansible_mounts:显示系统磁盘挂载情况。
ansible_processor:显示cpu个数(具体显示每个cpu的型号)。
ansible_processor_vcpus:显示cpu个数(只显示总的个数)。
显示被管理机所有信息
html 复制代码
ansible web -m setup
#信息太多了,不好用
获取被管理机的 IPV4 地址
html 复制代码
[root@test1 opt]# ansible web -m setup -a "filter=ansible_all_ipv4_addresses"
192.168.67.12 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "192.168.122.1", 
            "192.168.67.12"
        ], 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}
获取被管理机的内存信息
html 复制代码
[root@test1 opt]# ansible web -m setup -a "filter=ansible_memory_mb"
192.168.67.12 | SUCCESS => {
    "ansible_facts": {
        "ansible_memory_mb": {
            "nocache": {
                "free": 1018, 
                "used": 805
            }, 
            "real": {
                "free": 154, 
                "total": 1823, 
                "used": 1669
            }, 
            "swap": {
                "cached": 2, 
                "free": 2040, 
                "total": 2047, 
                "used": 7
            }
        }, 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}
通配符模糊匹配

显示以"mb"关键字结尾的信息

html 复制代码
[root@test1 opt]# ansible web -m setup -a "filter=*mb"
192.168.67.12 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 155, 
        "ansible_memory_mb": {
            "nocache": {
                "free": 1019, 
                "used": 804
            }, 
            "real": {
                "free": 155, 
                "total": 1823, 
                "used": 1668
            }, 
            "swap": {
                "cached": 2, 
                "free": 2040, 
                "total": 2047, 
                "used": 7
            }
        }, 
        "ansible_memtotal_mb": 1823, 
        "ansible_swapfree_mb": 2040, 
        "ansible_swaptotal_mb": 2047, 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}
html 复制代码
ansible all -m setup
ansible all -m setup -a "filter=ansible_nodename"
ansible all -m setup -a "filter=ansible_hostname"
ansible all -m setup -a "filter=ansible_domain"
ansible all -m setup -a "filter=ansible_memtotal_mb"
ansible all -m setup -a "filter=ansible_memory_mb"
ansible all -m setup -a "filter=ansible_memfree_mb"
ansible all -m setup -a "filter=ansible_os_family"
ansible all -m setup -a "filter=ansible_distribution_major_version"
ansible all -m setup -a "filter=ansible_distribution_version"
ansible all -m setup -a "filter=ansible_processor_vcpus"
ansible all -m setup -a "filter=ansible_all_ipv4_addresses"
ansible all -m setup -a "filter=ansible_architecture"
ansible all -m setup -a "filter=ansible_uptime_seconds"
ansible all -m setup -a "filter=ansible_processor*"
ansible all -m setup -a 'filter=ansible_env'
相关推荐
维尔切31 分钟前
Linux中基于Centos7使用lamp架构搭建个人论坛(wordpress)
linux·运维·架构
tan77º1 小时前
【项目】分布式Json-RPC框架 - 项目介绍与前置知识准备
linux·网络·分布式·网络协议·tcp/ip·rpc·json
TPBoreas2 小时前
Jenkins启动端口修改失败查找日志
运维·服务器·jenkins
正在努力的小河4 小时前
Linux设备树简介
linux·运维·服务器
荣光波比4 小时前
Linux(十一)——LVM磁盘配额整理
linux·运维·云计算
小张快跑。4 小时前
Tomcat下载、安装及配置详细教程
java·服务器·tomcat
LLLLYYYRRRRRTT4 小时前
WordPress (LNMP 架构) 一键部署 Playbook
linux·架构·ansible·mariadb
轻松Ai享生活5 小时前
crash 进程分析流程图
linux
没有不重的名么5 小时前
Tmux Xftp及Xshell的服务器使用方法
服务器·人工智能·深度学习·机器学习·ssh
wdxylb5 小时前
云原生俱乐部-杂谈1
服务器·云原生