[Ansible专栏]Ansible常用模块介绍和使用

时间:2022-11-29 16:58:29

微信公众号:运维开发故事,作者:姜总

一、简介

前面我们介绍了,ansible能作为自动化配置管理,其实是由ansible的多种多样的模块来实现的。截止目前,ansible的模块已经高达3000+之多。但是个人在日常工作中,比较常见的大约20多个。下面我就大概介绍一些常见常用的模块。

二、invenroty清单文件

# cat /etc/ansible/hosts
[websrvs]
10.10.108.[30:33]

[dbsrvs]
10.10.108.30

[appsrvs]
10.10.108.[30:33]

三、常用模块

3.1 ping 模块

ping模块执行成功后,会给你返回绿色的消息,并且有一个pong响应。all代表所有被管理的主机。

[root@ayunw ansible-example]# ansible dbsrvs -m ping
10.10.108.30 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}

[root@ayunw ansible-example]# ansible all -m ping
10.10.108.30 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
10.10.108.32 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
10.10.108.31 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
10.10.108.33 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}

3.2 command 模块

因为ansible的默认模块是command,所以这里可以使用 -m 指定模块名 command,也可以直接省略。

[root@ayunw ansible-example]# ansible dbsrvs -m command -a "free -m"
10.10.108.30 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 7821 395 7110 16 314 7179
Swap: 4095 0 4095

[root@ayunw ansible-example]# ansible dbsrvs -a "free -m"
10.10.108.30 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 7821 395 7111 16 314 7179
Swap: 4095 0 4095

3.3 shell模块

shell模块和command模块比较类似,但是shell被大家称为万能模块,很多操作command不支持,但是shell却支持。注意最后一种情况shell模块也是不支持的。但是可以将命令写在一个脚本,将脚本拷贝到远端执行,然后执行shell模块获取结果。

[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "touch /tmp/a.txt"
[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.
10.10.108.30 | CHANGED | rc=0 >>

[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "ls -al /tmp/ | grep 'a.txt'"
10.10.108.30 | CHANGED | rc=0 >>
-rw-r--r--. 1 root root 0 Aug 9 09:37 a.txt

[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "ls -al /tmp/ | grep "a.txt""
10.10.108.30 | CHANGED | rc=0 >>
-rw-r--r--. 1 root root 0 Aug 9 09:37 a.txt

# 会报错,shell万能模块也不支持这种方式
[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "cat /etc/passwd |awk -F ':' '{print $1,$3}' >> /tmp/pwd.txt"
10.10.108.30 | FAILED | rc=1 >>
awk: cmd. line:1: {print ,}
awk: cmd. line:1: ^ syntax error
awk: cmd. line:1: {print ,}
awk: cmd. line:1: ^ syntax error
awk: cmd. line:1: {print ,}
awk: cmd. line:1: ^ unexpected newline or end of stringnon-zero return code

注意: 你可能会注意到上面出现了​​WARNING​​​警告。这不是报错,它只是告诉你,应该选择​​file​​​模块进行创建文件的操作会更好,而不是使用​​shell​​​模块操作。当然它还告诉你可以在​​ansible.cfg​​​配置文件中设置​​command_warnings=False​​以关闭警告。

3.4 copy 模块

从ansible管理节点拷贝文件到远程主机。

[root@ayunw ansible-example]# cat getPasswd.sh
#!/bin/bash
# -*- Author -*- : ayunw

cat /etc/passwd |awk -F ':' '{print $1}'

[root@ayunw ansible-example]# ansible dbsrvs -m copy -a "src=getPasswd.sh dest=/usr/local/src/ mode=0755 owner=root group=root"
10.10.108.30 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "ce9c09f15cb6f62b550f819276d06b0e6cd59110",
"dest": "/usr/local/src/getPasswd.sh",
"gid": 0,
"group": "root",
"mode": "0755",
"owner": "root",
"path": "/usr/local/src/getPasswd.sh",
"secontext": "system_u:object_r:usr_t:s0",
"size": 54,
"state": "file",
"uid": 0
}

# 默认目标节点存在文件会覆盖,所以最好设置 backup=yes
[root@ayunw ansible-example]# ansible dbsrvs -m copy -a "src=getPasswd.sh dest=/usr/local/src/ mode=0755 owner=root group=root backup=yes"

[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "ls -al /tmp/ | grep 'getPasswd.sh'"
10.10.108.30 | CHANGED | rc=0 >>
-rw-r--r--. 1 root root 54 Aug 9 09:50 getPasswd.sh

[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "cat /tmp/getPasswd.sh"
10.10.108.30 | CHANGED | rc=0 >>
#!/bin/bash

cat /etc/passwd |awk -F ':' '{print $1}'

[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "bash /usr/local/src/getPasswd.sh"
10.10.108.30 | CHANGED | rc=0 >>
root
bin
daemon
adm
lp
sync
shutdown
halt
mail
operator
games
ftp
nobody
systemd-network
dbus
polkitd
sshd
postfix

# 拷贝目录下所有文件到远程,不包括目录本身。文件多了以后,速度会非常慢
[root@ayunw ansible-example]# ansible dbsrvs -m copy -a "src=/etc/ansible/ dest=/opt/"
10.10.108.30 | CHANGED => {
"changed": true,
"dest": "/opt/",
"src": "/etc/ansible/"
}

3.5 fetch 模块

从远程主机获取文件到ansible管理节点,但是不支持目录操作

[root@ayunw ansible-example]# ansible dbsrvs -m fetch -a "src=/etc/yum.repos.d/epel.repo dest=/usr/local/src"
10.10.108.30 | CHANGED => {
"changed": true,
"checksum": "2feedd589b72617f03d75c4b8a6e328cc1aad918",
"dest": "/usr/local/src/10.10.108.30/etc/yum.repos.d/epel.repo",
"md5sum": "bddf35db56cf6be9190fdabeae71c801",
"remote_checksum": "2feedd589b72617f03d75c4b8a6e328cc1aad918",
"remote_md5sum": null
}

[root@ayunw ansible-example]# ls -al /usr/local/src/10.10.108.30/etc/yum.repos.d/
total 4
drwxr-xr-x. 2 root root 23 Aug 11 15:05 .
drwxr-xr-x. 3 root root 25 Aug 11 15:05 ..
-rw-r--r--. 1 root root 664 Aug 11 15:05 epel.repo

3.6 file 模块

# 创建软连接
[root@ayunw ansible-example]# ansible test -m file -a 'src=/etc/passwd path=/tmp/passwd.link state=link'

# 查看刚创建的/tmp下的软连接
[root@ayunw ansible-example]# ansible all -m shell -a 'ls -l /tmp/passwd.link'

# 创建文件。如果文件已经存在,则会更新文件的时间戳
[root@ayunw ansible-example]# ansible all -m file -a 'name=d.txt state=touch'

# 删除文件
[root@ayunw ansible-example]# ansible test -m file -a 'path=/tmp/cc.txt state=absent'

# 创建目录(可以递归创建,直接加上文件名即可)
# 如果state=directory,那么如果目录不存在,那么所有的子目录将被创建(而且提供权限的创建),如果目录# 已经存在,则不进行任何操作。如果state=file,文件将不会被创建
[root@ayunw ansible-example]# ansible test -m file -a 'path=/tmp/bj state=directory'

# 删除目录(可以递归删除,无需任何参数,直接加上)
[root@ayunw ansible-example]# ansible test -m file -a 'path=/tmp/bj state=absent'

# 修改文件权限等属性
[root@ayunw ansible-example]# ansible test -m file -a 'path=/tmp/bb.txt mode=700 owner=root group=root'

# 递归授权目录权限
ansible dbsrvs -m file -a "path=/data owner=bgx group=bgx recurse=yes"

3.7 hostname 模块

管理远程主机上的主机名

# 查看主机名
[root@ayunw ansible-example]# ansible test -m shell -a 'hostname'

# 更改主机名
[root@ayunw ansible-example]# ansible test -m hostname -a 'name=master'

3.8 yum 模块

# 安装一个httpd服务,默认安装最新版
# 使用state=present来安装,多个包用','分割
[root@ansible-server ~]# ansible dbsrvs -m yum -a 'name=httpd'

[root@ayunw ansible-example]# ansible test -m yum -a 'name=httpd state=present'

# 检查是否安装成功
[root@ansible-server ~]# ansible dbsrvs -a 'rpm -qi httpd'

3.9 cron 模块

# 创建计划任务
[root@ayunw ansible-example]# ansible test -m cron -a 'minute=*/5 name=Ajob job="/usr/sbin/ntpdate 172.16.8.100 &> /dev/null" state=present'
[root@ayunw ansible-example]# ansible dbsrvs -m cron -a "minute=* hour=* day=* month=* weekday=* job='/bin/sh test.sh'"
[root@ayunw ansible-example]# ansible dbsrvs -m cron -a "job='/bin/sh /server/scripts/test.sh'"

# 设置定时任务注释信息,防止重复,name设定
ansible dbsrvs -m cron -a "name='cron01' job='/bin/sh /server/scripts/test.sh'"

# 注释相应定时任务,使定时任务失效
ansible dbsrvs -m cron -a "name='ansible cron01' minute=0 hour=0 job='/bin/sh test.sh' disabled=yes"

# 删除相应定时任务(怎么创建的就要怎么删除)
[root@ayunw ansible-example]# ansible test -m cron -a 'minute=*/5 name=Ajob job="/usr/sbin/ntpdate 172.16.8.100 &> /dev/null state=absent"'

# 查看计划任务
[root@ayunw ansible-example]# ansible test -m shell -a "crontab -l"
172.16.20.115 | SUCCESS | rc=0 >>
#Ansible: Ajob
*/5 * * * * /usr/sbin/ntpdate 172.16.8.100 &> /dev/null

# 删除任务计划
[root@ayunw ansible-example]# ansible test -m shell -a "crontab -r"

3.10 service 模块

用来管理服务器上的服务

# 利用ansible的yum模块安装一个nginx
[root@ayunw ansible-example]# ansible test -m yum -a 'name=nginx state=present'

# 启动nginx
[root@ayunw ansible-example]# ansible test -m shell -a '/etc/init.d/nginx start'

# 或者利用ansible的service模块(推荐)
[root@ayunw ansible-example]# ansible test -m service -a 'name=nginx state=started'

# 查看状态
[root@ayunw ansible-example]# ansible test -m shell -a 'service nginx status'
[WARNING]: Consider using service module rather than running service

# 停止nginx服务
[root@ayunw ansible-example]# ansible test -m service -a 'name=nginx state=stopped'
[root@ayunw ansible-example]# ansible test -m shell -a 'service nginx status'
[WARNING]: Consider using service module rather than running service

[root@ayunw ansible-example]# ansible test -m service -a 'name=nginx state=started enabled=yes runlevel=2345'

[root@ayunw ansible-example]# ansible test -m shell -a 'chkconfig --list nginx'

3.11 group 模块

用于添加远程主机上的组

[root@ayunw ansible-example]# ansible test -m group -a 'name=hr gid=2000 state=present'

3.12 user 模块

管理远程主机上的用户的账号

# 创建用户指定uid和gid,不创建家目录也不允许登陆
ansible dbsrvs -m user -a "name=ayunw uid=888 group=888 shell=/sbin/nologin create_home=no"
[root@ayunw ansible-example]# ansible dbsrvs -m user -a 'name=martin group=hr groups=root uid=500 shell=/bin/bash home=/home/martin comment="martin user"'

# 删除用户
[root@ayunw ansible-example]# ansible dbsrvs -m user -a 'name=martin state=absent remove=yes'

# 给新创建的用户生成ssh密钥对
ansible dbsrvs -m user -a "name=oo uid=6677 group=adm generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa" -i ./hosts

# 将明文密码进行hash加密,然后进行用户创建
ansible dbsrvs -m debug -a "msg={{ '123456' | password_hash('sha512', 'salt') }}"

3.13 setup 模块

可收集远程主机的facts变量的信息,相当于收集了目标主机的相关信息(如内核版本、操作系统信息、cpu、…),保存在ansible的内置变量中,之后我们有需要用到时,直接调用变量即可.这在ansible-playbook 中很有用。

[root@ayunw ansible-example]# ansible dbsrvs -m setup

# 使用setup获取ip地址以及主机名使用filter过滤
ansible dbsrvs -m setup -a 'filter=ansible_default_ipv4'
# 获取内存信息
ansible dbsrvs -m setup -a 'filter=ansible_memory_mb'

# 获取主机名
ansible dbsrvs -m setup -a 'filter=ansible_nodename'

# 仅显示与ansible相关的内存信息
ansible dbsrvs -m setup -a 'filter=ansible_*_mb'

3.14 authorized_key模块

为特定的用户账号添加或删除 SSH authorized keys

# 方法一
ansible web -m authorized_key -a "user=root key='{{lookup('file','/root/.ssh/id_rsa.pub')}}' path=/root/.ssh/authorized_keys manage_dir=no"

# 方法二、
vim pub_ssh_key.yml
---
- hosts: webs
remote_user: osmgr
become: yes
become_user: root
become_method: sudo
tasks:
- name: deliver authorized_keys
authorized_key:
user: osmgr
key: "{{ lookup('file', '/home/osmgr/.ssh/id_rsa.pub') }}"
state: present

ansible-playbook pub_ssh_key.yml

3.15 synchronize 模块

使用rsync 模块,系统必须安装rsync 包,否则无法使用这个模块

ansible dbsrvs -m shell -a 'yum -y install rsync'

ansible web -m synchronize -a 'src=time.sh dest=/tmp/'

3.16 lineinfile 模块

正则匹配,更改某个关键参数值。比如这里修改SELINUX的值

ansible dbsrvs -a 'cat /etc/selinux/config | grep ^SELINUX=' 

ansible dbsrvs -m shell -a 'cat /etc/selinux/config|grep "^SELINUX="'
10.10.108.30 | CHANGED | rc=0 >>
SELINUX=enforcing

# 通过lineinfifle模块修改SELinux的配置信息,改为disable
ansible dbsrvs -m lineinfile -a "path=/etc/selinux/config regexp='^SELINUX=' line='SELINUX=disabled'"

# 或者是使用ansible-playbook
vim set_selinux_disable.yml
---
- hosts: dbsrvs
tasks:
- name: seline modify enforcing
lineinfile:
dest: /etc/selinux/config
regexp: '^SELINUX='
line: 'SELINUX=enforcing'

# 删除/etc/fstab文件中以#号开头的行
ansible dbsrvs -m lineinfile -a "dest=/etc/fstab state=absent regexp='^#'"

3.17 replace 模块

和 sed 命令比较类似,用于正则匹配和替换

# 查看远端节点的 /etc/fstab 源文件
[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "cat /etc/fstab"
10.10.108.30 | CHANGED | rc=0 >>

#
# /etc/fstab
# Created by anaconda on Tue Jul 5 14:09:37 2022
#
# 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
#
/dev/mapper/centos-root / xfs defaults 0 0
UUID=c47c20e8-8ed5-4d86-9209-f0e8876bb9e6 /boot xfs defaults 0 0
/dev/mapper/centos-swap swap swap defaults 0 0

# 使用replace模块
[root@ayunw ansible-example]# ansible dbsrvs -m replace -a "path=/etc/fstab regexp=^(UUID.*) replace='#\1'"
10.10.108.30 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"msg": "1 replacements made"
}

# 查看结果
[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "cat /etc/fstab"
10.10.108.30 | CHANGED | rc=0 >>

#
# /etc/fstab
# Created by anaconda on Tue Jul 5 14:09:37 2022
#
# 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
#
/dev/mapper/centos-root / xfs defaults 0 0
#UUID=c47c20e8-8ed5-4d86-9209-f0e8876bb9e6 /boot xfs defaults 0 0
/dev/mapper/centos-swap swap swap defaults 0 0

# 将注释的UUID信息恢复
ansible dbsrvs -m replace -a "path=/etc/fstab regexp='^#(.*)' replace='\1'"

[root@ayunw ansible-example]# ansible dbsrvs -m shell -a "cat /etc/fstab"
10.10.108.30 | CHANGED | rc=0 >>


/etc/fstab
Created by anaconda on Tue Jul 5 14:09:37 2022

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

/dev/mapper/centos-root / xfs defaults 0 0
UUID=c47c20e8-8ed5-4d86-9209-f0e8876bb9e6 /boot xfs defaults 0 0
/dev/mapper/centos-swap swap swap defaults 0 0

参数说明:

  • \1:表示引用前面的小括号内容



温馨提示

一名常年穿梭于Google、阿里、百度、腾讯的一线运维从业者。是<<运维开发故事>>公众号的成员之一。不定期分享技术干货和对技术的理解与感悟。