白日依山尽,黄河入海流。欲穷千里目,更上一层楼。 -- 唐·王之涣

Ansible系列-基础篇-Ansible常见模块的使用

欢迎关注个人公众号 DailyJobOps

原文地址: Ansible系列-基础篇-Ansible 常见模块的使用


在这里插入图片描述

上一篇中简单尝鲜了几个模块,本篇整理下实际中用到的模块及其用法Demo,总计有19个模块,分别为
ping、setup、debug、user、group、authorized_key、shell、script、command、service、systemd、copy、template、synchronize、file、lineinfile、yum、cron

基本模块

ping

ping 模块主要是验证管理节点目标节点之间的连通性,是否正常配置好了对应账号的ssh免密登录

1
2
3
4
5
6
7
8
(kfz-ansible) [james@devops-jumpserver-vm ]$ ansible devops-gitlab-vpc -m ping
devops-gitlab-vpc | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}

setup

上一篇中配置的时候提到ansible facts 收集目标主机信息,也可以使用 setup 模块。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
(kfz-ansible) [james@devops-jumpserver-vm]$ ansible devops-gitlab-vpc -m setup
devops-gitlab-vpc | SUCCESS => {
"ansible_facts": {
"ansible_all_ipv4_addresses": [
"172.17.115.136"
],
"ansible_all_ipv6_addresses": [],
"ansible_apparmor": {
"status": "disabled"
},
"ansible_architecture": "x86_64",
"ansible_bios_date": "04/01/2014",
"ansible_bios_vendor": "SeaBIOS",
"ansible_bios_version": "8c24b4c",
"ansible_board_asset_tag": "NA",
... ...
"ansible_virtualization_type": "kvm",
"gather_subset": [
"all"
],
"module_setup": true
},
"changed": false
}

这个模块的好处就是让了解到 Ansible 都有哪些内置的变量,这些变量在我们后续写playbook的时候,在role templates 中配置很有帮助,

举个列子,Ansible 批量部署 zabbix agent,每个agent的配置文件中的 ListenIPHostname 我们就可以使用facts中的变量 ansible_default_ipv4.addressansible_hostname

另外一旦知道知道都有哪些变量的时候,下次我们就可以再收集信息展示的时候,加参数通过filter来过滤我们想看的变量就可。比如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 这里只看 ansible_default_ipv4 变量
(kfz-ansible) [james@devops-jumpserver-vm]$ ansible devops-gitlab-vpc -m setup -a 'filter=ansible_default_ipv4'
devops-gitlab-vpc | SUCCESS => {
"ansible_facts": {
"ansible_default_ipv4": {
"address": "172.17.115.136",
"alias": "eth0",
"broadcast": "172.17.255.255",
"gateway": "172.17.255.253",
"interface": "eth0",
"macaddress": "00:16:3e:2e:6e:cf",
"mtu": 1500,
"netmask": "255.255.0.0",
"network": "172.17.0.0",
"type": "ether"
}
},
"changed": false
}

debug

顾名思义,就是我们想调试输出一些结果的时候,比如上面提到的我想知道目标主机的IP地址

这里有两种用法,一种是msg输出,需要带{{ variable-name }}, 另外一种是 var 用法,直接写变量名即可,不用添加 {{ }}

1
2
3
4
5
6
7
8
(kfz-ansible) [james@devops-jumpserver-vm]$ ansible devops-gitlab-vpc -m debug -a 'msg={{ ansible_default_ipv4.address }}'
devops-gitlab-vpc | SUCCESS => {
"msg": "172.17.115.136"
}
(kfz-ansible) [james@devops-jumpserver-vm ]$ ansible devops-gitlab-vpc -m debug -a 'var=ansible_default_ipv4.address'
devops-gitlab-vpc | SUCCESS => {
"ansible_default_ipv4.address": "172.17.115.136"
}

用户相关

user/group

远程管理用户/用户组

1
2
3
4
5
# 添加组
ansible devops-demo-vpc -m group -a 'name=demogroup'
# 添加用户
ansible devops-demo-vpc -m user -a 'name=demouser group=demogroup shell=/bin/bash password=newpasswd'

authorized_key

主要用来给目标主机用户配置公钥,默认到目标用户家目录的.ssh目录的authorized_keys文件 没有则创建authorized_keys文件

1
2
3
4
5
6
# 
- name: deliver authorized_keys
authorized_key:
user: james
key: "{{ lookup('file', '/etc/ansible/roles/authorized_keys') }}" # 使用 lookup从本地authorized_keys文件读取公钥内容
state: present # absent删除key

shell/script/command/raw

这里是把 shell 和 script、command放到一起做对比,其实还有个raw

其中 command 执行单一命令不能使用管道符、重定向符等,raw 类型command,可以使用管道符等;

shell 和 script 类似,都可以执行脚本,却别在于script执行的脚本在ansible管理机上,而shell执行的脚本必须先放到目标节点上去,才能执行;

另外shell执行可以使用环境变量,bash等,但是script只是执行脚本,不能带 bash

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# check remote host load
ansible devops-demo-vpc -m command -a 'uptime'
# check remote host data disk
ansible devops-demo-vpc -m raw -a 'df -h |grep data'

# execute bash script
# check if exist t.sh on remote host, not exist on remote ,exist on local
(kfz-ansible) [root@devops-ansible /data/temp]# ansible devops-demo-vpc -m shell -a ' ls -l /tmp/t.sh'
devops-demo-vpc | FAILED | rc=2 >>
ls: cannot access /tmp/t.sh: No such file or directorynon-zero return code

# if use base when script, error here
(kfz-ansible) [root@devops-ansible /data/temp4]# ansible devops-demo-vpc -m script -a 'bash /data/temp/t.sh'
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: If you are using a module and expect the file to exist on the remote, see the remote_src option
devops-demo-vpc | FAILED! => {
"changed": false,
"msg": "Could not find or access 'bash'\nSearched in:\n\t/data/temp/files/bash\n\t/data/temp/bash\n\t./files/bash\n\t./bash on the Ansible Controller.\nIf you are using a module and expect the file to exist on the remote, see the remote_src option"
}

# script on local and use script module to execute on remote host
(kfz-ansible) [root@devops-ansible /data/temp]# ansible devops-demo-vpc -m script -a ' /data/temp/t.sh |grep result'
devops-demo-vpc | CHANGED => {
"changed": true,
"rc": 0,
"stderr": "Shared connection to test-liuchao-01-vm closed.\r\n",
"stderr_lines": [
"Shared connection to test-liuchao-01-vm closed."
],
"stdout": "result: I am on host [test-liuchao-01-vm]\r\n",
"stdout_lines": [
"result: I am on host [test-liuchao-01-vm]"
]
}

(kfz-ansible) [root@devops-ansible /data/temp]# ansible devops-demo-vpc -m copy -a 'src=t.sh dest=/tmp/t-remote.sh mode=0755'
devops-demo-vpc | CHANGED => {
"changed": true,
"checksum": "14d91fbe7abd4e406124460149048fd7d88d2216",
"dest": "/tmp/t-remote.sh",
"gid": 0,
"group": "root",
"md5sum": "916c5f68555199e2019030dd0b3cdc62",
"mode": "0755",
"owner": "root",
"size": 84,
"src": "/root/.ansible/tmp/ansible-tmp-1637916752.9830978-13704-278698223191801/source",
"state": "file",
"uid": 0
}
(kfz-ansible) [root@devops-jumpserver-vm /data/temp Fri Nov 26 16:52:34]# ansible devops-demo-vpc -m shell -a 'bash /tmp/t-remote.sh'
devops-demo-vpc | CHANGED | rc=0 >>
hello Ansible
result: I am on host [devops-demo-vpc]

服务管理

service / systemd

都是用来管理服务器上的服务,区别在于Service服务管理用于centos6及以前的系统,而systemd命令应用于centos7系统

核心参数 name\state\enabled

1
2
3
4
5
# enable and start nginx
ansible devops-demo-vpc -m service -a 'name=nginx enabled=true state=started'

# reload
ansible devops-demo-vpc -m service -a 'name=nginx state=reloaded'

文件管理

copy

把管理节点的文件copy到目标节点,并配置相关属性

1
2
3
4
5
6
7
8
9
10
11
# 常规copy文件到目标主机
ansible devops-demo-vpc -m copy -a 'scr=t.sh dest=/tmp/t-remote.sh mode=0755 owner=james group=james'

# 有时候不是copy文件,而是直接指定内容
ansible devops-demo-vpc -m copy -a 'content="hello world, hello Ansible" dest=/tmp/t-remote.txt'

# force=yes 远程存在同名文件则强制覆盖
ansible devops-demo-vpc -m copy -a 'scr=t.sh dest=/tmp/t-remote.txt force=yes'

# backup是远程存在同名文件则先备份在覆盖
ansible devops-demo-vpc -m copy -a 'scr=t.sh dest=/tmp/t-remote.txt backup=yes'

template

template 的作用和copy一样,区别在于源文件是jinja2格式,文件中可以配置 Ansible变量,然后在目标节点上替换成对应的目标值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
(kfz-ansible) [james@devops-jumpserver-vm]$ ansible devops-baseimage-vpc -m template -a 'src=/tmp/ansible-template-jinja2.j2 dest=/tmp/ansible-template-jinja2.txt mode=0644 '
devops-baseimage-vpc | CHANGED => {
"changed": true,
"checksum": "60fcb9b1049408735a56fd7282254abf52fd6125",
"dest": "/tmp/ansible-template-jinja2.txt",
"gid": 0,
"group": "root",
"md5sum": "ef974d5fd45dddce50b765d6b20d6abe",
"mode": "0644",
"owner": "root",
"size": 61,
"src": "/home/james/.ansible/tmp/ansible-tmp-1637489176.9135442-5845-46738029442091/source",
"state": "file",
"uid": 0
}
(kfz-ansible) [james@devops-jumpserver-vm]$ ansible devops-baseimage-vpc -m shell -a 'cat /tmp/ansible-template-jinja2.txt'
devops-baseimage-vpc | CHANGED | rc=0 >>
Hostname is: devops-baseimage-vpc
Host IP is: 172.17.115.134

另外一个需要住的就是在roles中,copy默认是从files目录获取文件,template默认是 templates 文件夹获取模板文件

synchronize

主要用于目录、文件的同步,基于 rsync实现,主要是有pushpull 两种方式, 如果是push 推送,则src是管理节点,dest是目标节点;如果是pull拉取,则src是目标节点,dest是管理节点

1
2
3
4
5
# 推送至远程目标节点
ansible devops-demo-vpc -m synchronize -a 'mode=push src=/opt/scripts dest=/opt/target/scripts recursive=yes archive=yes
# 从远程目标节点获取到本地
ansible devops-demo-vpc -m synchronize -a 'mode=pull src=/opt/target/scripts dest=/opt/scripts recursive=yes archive=yes

file

在目标节点创建文件或目录,删除文件或目录,修改文件或目录的权限等;核心参数有:path、state、owner、group、mode、recurse

1
2
3
4
5
6
7
8
# 创建目录
ansible devops-demo-vpc -m file -a 'path=/opt/script state=directory'
# 创建文件并设置属主、属组及权限
ansible devops-demo-vpc -m file -a 'path=/opt/script/test.sh owner=test group=test mode=755'
# 删除文件
ansible devops-demo-vpc -m file -a 'path=/opt/script/test.sh state=absent'
# 递归创建目录
ansible devops-demo-vpc -m file -a 'path=/opt/script/sub1/sub2/sub3 state=directory recurse=true'

lineinfile

在文件中添加、修改、删除一行记录,在实践中用的很多,这里做简单介绍,后续有单独文章详细介绍

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 在文件的匹配行之前插入一行记(在匹配的 Listen 80这行后面插入 server_name www.colinspace.com)
- name: insert after match line demo
lineinfile:
dest: /etc/nginx.conf
insertafter: '^listen 80'
line: 'server_name www.colinspace.com'

# 修改匹配的行
- name: update match line demo
lineinfile:
dest: /etc/nginx.conf
regex: 'server_name www.*'
line: 'server_name blog.colinspace.com'
mode: 0644

Linux系统维护

yum

顾名思义,就是我们在Centos下进行yum安装,核心参数主要关注: name 需要安装的软件名、state 软件的状态(present、absent、removed、latest)和 enablerepo 特殊情况指定yum源

1
2
3
4
# 安装Nginx
ansible devops-demo-vpc -m yum -a 'name=nginx state=present'
# 卸载Nginx (absent和removed一样)
ansible devops-demo-vpc -m yum -a 'name=nginx state=remove'

cron

管理Linux定时任务,核心参数说明
name 定时任务的名称、 state 任务的状态、minute/hour/day/month/weekday 分别设定任务执行的时间配置、user指定是哪个用户配置任务,默认是管理员

1
2
3
4
5
6
# 每天凌晨 01:05 执行脚本
ansible devops-demo-vpc -m cron -a 'name="Demo cron" hour=1 minute=05 job="bash /tmp/1.sh" '
# 删除上述任务(注意任务名保持一致)
ansible devops-demo-vpc -m cron -a 'name="Demo cron" state=absent"
#

作者

Colin

发布于

2021-06-02

许可协议