【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 选项

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

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

(操作)
[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执行命令,支持各种符号,比如:*,$, >

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

(操作)
#如果没有明确指明文件生成的目录,会默认在家目录下生成
[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服务器上的脚本(无需执行权限)

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

(操作)
[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文件

关键字:

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

例子:

注意:拷贝前需要确保被管理机上有相应的用户
[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请求的超时时间,秒为单位

#检查是否安装成功
[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相反,但只能传文件,不能传目录

范例:

[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模块

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

path   	指定文件路径
state  	文件状态 有:新建(touch) 删除(absent) 文件夹(directory)  连接文件(link)等
src    	源文件
mode   	权限
owner  	属主
group  	属组
recurse	递归
创建空文件
[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
新建目录
[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
新建软连接
[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
删除文件和目录
#目录
[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
递归修改目录及子目录的属性
[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模块

选项
path:文件/对象的完整路径(必须)
常用的返回值判断:
exists: 判断是否存在
isuid: 调用用户的ID与所有者ID是否匹配
查看文件是否存在
[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代表压缩文件是从远程主机上查找

常见参数
copy:默认为yes,当copy=yes,拷贝的文件是从ansible主机复制到远程主机上,如果设置为copy=no,会在远程主机上寻找src源文件
remote_src:和copy功能一样且互斥,yes表示在远程主机,不在ansible主机,no表示文件在ansible主机上
src:源路径,可以是ansible主机上的路径,也可以是远程主机(被管理端或者第三方主机)上的路径,如果是远程主机上的路径,则需要设置copy=no
dest:远程主机上的目标路径
mode:设置解压缩后的文件权限
copy=yes
#先创建一个包
[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
[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模块

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

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

0600    文件权限=600

11.Hostname模块

功能:管理主机名

[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

关键字:

name  会生成一行注释,显示标题如下显示
job   执行的命令
创建定时任务
[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脚本我并没有实际写入,只是用来展示一下
查看定时任务
#Ansible: backup mysql
30 2 * * 1-5 /root/mysql_backup.sh
disabled
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表示启用
删除定时任务
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 相关版本的软件包

关键字:
name			   所安装的包的名称
state              present--->安装, latest--->安装最新的, absent---> 卸载软件。
update_cache       强制更新yum的缓存
conf_file          指定远程yum安装时所依赖的配置文件(安装本地已有的包)。
disable_pgp_check  是否禁止GPG checking,只用于presentor latest。
disablerepo        临时禁止使用yum库。 只用于安装或更新时。
enablerepo         临时使用的yum库。只用于安装或更新时
安装
[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
#注意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
升级
#升级除kernel和foo开头以外的所有包
ansible web -m yum -a 'name=* state=lastest exclude=kernel*,foo*'

#别用,看看就行,或者单独升级
删除
[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仓库模块

关键字:

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 源。

#安装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 模块

功能:管理服务

关键字:
name参数:		此参数用于指定需要操作的服务名称,比如 nginx。
state参数:	此参数用于指定服务的状态,比如,我们想要启动远程主机中的 nginx,则可以将 state 的值设置为 started;如果想要停止远程主机中的服			   务,则可以将 state 的值设置为 stopped。此参数的可用值有 started、stopped、restarted、reloaded。
enabled参数:	此参数用于指定是否将服务设置为开机 启动项,设置为 yes 表示将对应服务设置为开机启动,设置为 no 表示不会开机启动。
开启服务
#确保被管理机上有要操作的服务
[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

关闭服务
[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"
重新加载配置
[root@test1 opt]# ansible web -m service -a "name=httpd state=reloaded"

#相当于重启;在别处相当于不用启动就可以直接读取配置
#重启服务
[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
[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是一样的,能改的话尽量改掉
挂载(有问题)
#临时挂载
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 模块

功能:管理用户

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参数设置的值与用户当前的加密过的密码字符串不一致,则不会更新用户的密码字符串,保持之前的密码设定
创建用户
[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 模块

功能:管理组

创建组
[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:
删除组
[root@test1 opt]# ansible web -m group -a 'name=nginx state=absent'

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

19.reboot模块

重启被管理机
[root@test1 opt]# ansible 192.168.67.13 -m reboot

20.Lineinfile 模块 

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

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

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

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

关键字:
path	        指定要操作的文件
regexp	        使用正则表达式匹配对应的行
line	        修改为新的内容
insertafter	    将文本插入到“指定的行”之后
insertbefore	将文本插入到“指定的行”之前
state	        删除对应的文本时,需要state=absent
backrefs	    1.支持后向引用、2.当未匹配到内容则不操作文件
backup	        是否在修改文件之前对文件进行备份
create	        当要操作的文件并不存在时,是否创建对应的文件

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命令,主要也是基于正则进行匹配和替换,建议使用

添加 #
\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]# 
删除 #
[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 信息

关键字:

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个数(只显示总的个数)。
显示被管理机所有信息
ansible web -m setup
#信息太多了,不好用
获取被管理机的 IPV4 地址
[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
}
获取被管理机的内存信息
[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”关键字结尾的信息

[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
}

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
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值