ansible 安装配置以及一些常用模块

摘要

本文部分内容来源于网络,个人收集整理,请勿传播

ansible是目前非常火的运维自动化批量管理工具之一

  • saltstack
  • ansible
  • puppet
  • chef

ansible和saltstack都是使用python语言写的,而在选择以及使用的过程中,ansible相对saltstack具有以下几个优势

  • 使用ssh-key控制agent,无需安装agent
  • 配置起来相对简单,学习门槛低
  • 并发以及性能方面还是saltstack占优的,不过在小集群(300以下)的表现上ansible也非常给力;
  • 二次开发扩展:由于两个都是python语言写的,这方面都还不错,不过在日常使用中吗,saltstack的api调用要比ansible的好用很多,state和playbook孰强孰若还真不好说
  • 操作界面,没用过ui
  • 第三方插件的丰富程度这点ansible完胜
  • 支持windows
  • 开源社区的活跃程度这点ansible完胜
  • 安全性:saltstack相对要更好一些
  • 自动注册:这点ansible貌似没有

基础

原理

工作机制

组成部分

  • Ansible:核心、
  • Modules:包括 Ansible 自带的核心模块及自定义模块
  • Plugins:完成模块功能的补充,包括连接插件、邮件插件等
  • Playbooks:剧本;定义 Ansible 多任务配置文件,由Ansible 自动执行
  • Inventory:定义 Ansible 管理主机的清单

安装

1
pip install ansible

目录结构

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
.
├── config
│   └── ansible.cfg
├── inventory
│   ├── group_vars
│   │   └── ris-credit-gateway
│   ├── host_vars
│   │   └── demo
│   ├── inventory.py
│   ├── host1
│   └── host2
├── playbook
│   ├── push-flow.retry
│   └── push-flow.yml
├── README.md
├── roles
│   └── push-flow
│   ├── files
│   │   ├── config
│   │   │   ├── ris-credit-gateway
│   │   │   │   └── flow_config
│   │   ├── flow_config
│   │   ├── flow.sh
│   │   ├── init.sh
│   │   └── README.md
│   ├── tasks
│   │   ├── main.yml
│   │   └── push.yml
│   ├── templates
│   │   └── demo
│   └── vars
│   └── main.yml
└── tools
├── hosts
└── push-key.sh

配置

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
54
# cat /etc/ansible/ansible.cfg
[defaults]
inventory = /etc/ansible/hosts
remote_tmp = $HOME/.ansible/tmp
roles_path = /data/ansible/roles:/etc/ansible/roles
transport = smart
gathering = smart
fact_caching_timeout = 30
require_sudo = False
module_name = shell
private_key_file = /root/.ssh/id_rsa
ansible_managed = Ansible managed: {file} modified on %Y-%m-%d %H:%M:%S by {uid} on {host}
#action_plugins = /data/ansible/ansible_plugins/action_plugins
#connection_plugins = /data/ansible/ansible_plugins/connection_plugins
#lookup_plugins = /data/ansible/ansible_plugins/lookup_plugins
#vars_plugins = /data/ansible/ansible_plugins/vars_plugins
#filter_plugins = /data/ansible/ansible_plugins/filter_plugins
nocolor = 0
fact_caching = memory
host_key_checking = False
timeout = 10
pattern = *
forks = 20
poll_interval = 15
remote_user = devops
remote_port = 9555
log_path = /data/logs/ansible/ansible.log

[inventory]

[privilege_escalation]
become=True
become_exe=sudo
become_method=sudo
become_user=root
become_ask_pass=False

[paramiko_connection]
record_host_keys=False

[ssh_connection]
pipelining = True

[persistent_connection]
[accelerate]
accelerate_port = 5099
accelerate_timeout = 30
accelerate_connect_timeout = 5.0
accelerate_daemon_timeout = 30
#accelerate_multi_key = yes

[selinux]
[colors]
[diff]
1
2
3
4
5
6
7
8
9
10
11
cat /etc/ansible/hosts
[all: children]
manager
other

[manager]
ansible ansible_ssh_host=172.16.1.1
jenkins ansible_ssh_host=172.16.1.2

[other]
other ansible_ssh_host=172.16.1.3

配置文件解析

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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# config file for ansible -- http://ansible.com/
# ==============================================

# nearly all parameters can be overridden in ansible-playbook
# or with command line flags. ansible will read ANSIBLE_CONFIG,
# ansible.cfg in the current working directory, .ansible.cfg in
# the home directory or /etc/ansible/ansible.cfg, whichever it
# finds first

[defaults] --->通用默认配置

# some basic default values...

inventory = /etc/ansible/hosts 这个是默认库文件位置,脚本,或者存放可通信主机的目录
#library = /usr/share/my_modules/ Ansible默认搜寻模块的位置
remote_tmp = $HOME/.ansible/tmp Ansible 通过远程传输模块到远程主机,然后远程执行,执行后在清理现场.在有些场景下,你也许想使用默认路径希望像更换补丁一样使用
pattern = * 如果没有提供“hosts”节点,这是playbook要通信的默认主机组.默认值是对所有主机通信
forks = 5 在与主机通信时的默认并行进程数 ,默认是5d
poll_interval = 15 当具体的poll interval 没有定义时,多少时间回查一下这些任务的状态, 默认值是5秒
sudo_user = root sudo使用的默认用户 ,默认是root
#ask_sudo_pass = True 用来控制Ansible playbook 在执行sudo之前是否询问sudo密码.默认为no
#ask_pass = True 控制Ansible playbook 是否会自动默认弹出密码
transport = smart 通信机制.默认 值为’smart’。如果本地系统支持 ControlPersist技术的话,将会使用(基于OpenSSH)‘ssh’,如果不支持讲使用‘paramiko’.其他传输选项包括‘local’, ‘chroot’,’jail’等等
#remote_port = 22 远程SSH端口。 默认是22
module_lang = C 模块和系统之间通信的计算机语言,默认是C语言

# plays will gather facts by default, which contain information about
# the remote system.
#
# smart - gather by default, but don't regather if already gathered
# implicit - gather by default, turn off with gather_facts: False
# explicit - do not gather by default, must say gather_facts: True
gathering = implicit 控制默认facts收集(远程系统变量). 默认值为’implicit’, 每一次play,facts都会被收集

# additional paths to search for roles in, colon separated
#roles_path = /etc/ansible/roles roles 路径指的是’roles/’下的额外目录,用于playbook搜索Ansible roles

# uncomment this to disable SSH key host checking
#host_key_checking = False 检查主机密钥

# change this for alternative sudo implementations
sudo_exe = sudo 如果在其他远程主机上使用另一种方式执sudu操作.可以使用该参数进行更换

# what flags to pass to sudo 传递sudo之外的参数
#sudo_flags = -H

# SSH timeout SSH超时时间
timeout = 10

# default user to use for playbooks if user is not specified
# (/usr/bin/ansible will use current user as default)
#remote_user = root 使用/usr/bin/ansible-playbook链接的默认用户名,如果不指定,会使用当前登录的用户名

# logging is off by default unless this path is defined
# if so defined, consider logrotate
#log_path = /var/log/ansible.log 日志文件存放路径

# default module name for /usr/bin/ansible
#module_name = command ansible命令执行默认的模块

# use this shell for commands executed under sudo
# you may need to change this to bin/bash in rare instances
# if sudo is constrained
#executable = /bin/sh 在sudo环境下产生一个shell交互接口. 用户只在/bin/bash的或者sudo限制的一些场景中需要修改

# if inventory variables overlap, does the higher precedence one win
# or are hash values merged together? The default is 'replace' but
# this can also be set to 'merge'.
#hash_behaviour = replace 特定的优先级覆盖变量

# list any Jinja2 extensions to enable here:
#jinja2_extensions = jinja2.ext.do,jinja2.ext.i18n 允许开启Jinja2拓展模块

# if set, always use this private key file for authentication, same as
# if passing --private-key to ansible or ansible-playbook
#private_key_file = /path/to/file 私钥文件存储位置

# format of string {{ ansible_managed }} available within Jinja2
# templates indicates to users editing templates files will be replaced.
# replacing {file}, {host} and {uid} and strftime codes with proper values.
ansible_managed = Ansible managed: {file} modified on %Y-%m-%d %H:%M:%S by {uid} on {host} 这个设置可以告知用户,Ansible修改了一个文件,并且手动写入的内容可能已经被覆盖.

# by default, ansible-playbook will display "Skipping [host]" if it determines a task
# should not be run on a host. Set this to "False" if you don't want to see these "Skipping"
# messages. NOTE: the task header will still be shown regardless of whether or not the
# task is skipped.
#display_skipped_hosts = True 显示任何跳过任务的状态 ,默认是显示

# by default (as of 1.3), Ansible will raise errors when attempting to dereference
# Jinja2 variables that are not set in templates or action lines. Uncomment this line
# to revert the behavior to pre-1.3.
#error_on_undefined_vars = False 如果所引用的变量名称错误的话, 将会导致ansible在执行步骤上失败

# by default (as of 1.6), Ansible may display warnings based on the configuration of the
# system running ansible itself. This may include warnings about 3rd party packages or
# other conditions that should be resolved if possible.
# to disable these warnings, set the following value to False:
#system_warnings = True 允许禁用系统运行ansible相关的潜在问题警告

# by default (as of 1.4), Ansible may display deprecation warnings for language
# features that should no longer be used and will be removed in future versions.
# to disable these warnings, set the following value to False:
#deprecation_warnings = True 允许在ansible-playbook输出结果中禁用“不建议使用”警告

# (as of 1.8), Ansible can optionally warn when usage of the shell and
# command module appear to be simplified by using a default Ansible module
# instead. These warnings can be silenced by adjusting the following
# setting or adding warn=yes or warn=no to the end of the command line
# parameter string. This will for example suggest using the git module
# instead of shelling out to the git command.
# command_warnings = False 当shell和命令行模块被默认模块简化的时,Ansible 将默认发出警告


# set plugin path directories here, separate with colons
action_plugins = /usr/share/ansible_plugins/action_plugins
callback_plugins = /usr/share/ansible_plugins/callback_plugins
connection_plugins = /usr/share/ansible_plugins/connection_plugins
lookup_plugins = /usr/share/ansible_plugins/lookup_plugins
vars_plugins = /usr/share/ansible_plugins/vars_plugins
filter_plugins = /usr/share/ansible_plugins/filter_plugins

# by default callbacks are not loaded for /bin/ansible, enable this if you
# want, for example, a notification or logging callback to also apply to
# /bin/ansible runs
#bin_ansible_callbacks = False 用来控制callback插件是否在运行 /usr/bin/ansible 的时候被加载. 这个模块将用于命令行的日志系统,发出通知等特性


# don't like cows? that's unfortunate.
# set to 1 if you don't want cowsay support or export ANSIBLE_NOCOWS=1
#nocows = 1 默认ansible可以调用一些cowsay的特性 开启/禁用:0/1

# don't like colors either?
# set to 1 if you don't want colors, or export ANSIBLE_NOCOLOR=1
#nocolor = 1 输出带上颜色区别, 开启/关闭:0/1

# the CA certificate path used for validating SSL certs. This path
# should exist on the controlling node, not the target nodes
# common locations:
# RHEL/CentOS: /etc/pki/tls/certs/ca-bundle.crt
# Fedora : /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
# Ubuntu : /usr/share/ca-certificates/cacert.org/cacert.org.crt
#ca_file_path =

# the http user-agent string to use when fetching urls. Some web server
# operators block the default urllib user agent as it is frequently used
# by malicious attacks/scripts, so we set it to something unique to
# avoid issues.
#http_user_agent = ansible-agent

# if set to a persistent type (not 'memory', for example 'redis') fact values
# from previous runs in Ansible will be stored. This may be useful when
# wanting to use, for example, IP information from one group of servers
# without having to talk to them in the same playbook run to get their
# current IP information.
fact_caching = memory


# retry files
#retry_files_enabled = False
#retry_files_save_path = ~/.ansible-retry

[privilege_escalation]
#become=True
#become_method=sudo
#become_user=root
#become_ask_pass=False

[paramiko_connection]

# uncomment this line to cause the paramiko connection plugin to not record new host
# keys encountered. Increases performance on new host additions. Setting works independently of the
# host key checking setting above.
#record_host_keys=False

# by default, Ansible requests a pseudo-terminal for commands executed under sudo. Uncomment this
# line to disable this behaviour.
#pty=False

[ssh_connection]

# ssh arguments to use
# Leaving off ControlPersist will result in poor performance, so use
# paramiko on older platforms rather than removing it
#ssh_args = -o ControlMaster=auto -o ControlPersist=60s

# The path to use for the ControlPath sockets. This defaults to
# "%(directory)s/ansible-ssh-%%h-%%p-%%r", however on some systems with
# very long hostnames or very long path names (caused by long user names or
# deeply nested home directories) this can exceed the character limit on
# file socket names (108 characters for most platforms). In that case, you
# may wish to shorten the string below.
#
# Example:
# control_path = %(directory)s/%%h-%%r
#control_path = %(directory)s/ansible-ssh-%%h-%%p-%%r

# Enabling pipelining reduces the number of SSH operations required to
# execute a module on the remote server. This can result in a significant
# performance improvement when enabled, however when using "sudo:" you must
# first disable 'requiretty' in /etc/sudoers
#
# By default, this option is disabled to preserve compatibility with
# sudoers configurations that have requiretty (the default on many distros).
#
#pipelining = False

# if True, make ansible use scp if the connection type is ssh
# (default is sftp)
#scp_if_ssh = True

[accelerate]
accelerate_port = 5099
accelerate_timeout = 30
accelerate_connect_timeout = 5.0

# The daemon timeout is measured in minutes. This time is measured
# from the last activity to the accelerate daemon.
accelerate_daemon_timeout = 30

# If set to yes, accelerate_multi_key will allow multiple
# private keys to be uploaded to it, though each user must
# have access to the system via SSH to add a new key. The default
# is "no".
#accelerate_multi_key = yes

[selinux]
# file systems that require special treatment when dealing with security context
# the default behaviour that copies the existing context or uses the user default
# needs to be changed to use the file system dependant context.
#special_context_filesystems=nfs,vboxsf,fuse



ansible基础概念
inventory 主机源
playbooks 一组运行任务的命令集合
roles 角色
tasks 运行任务列表
handlers 运行任务后的触发动作
variables 定义的变量
ansible目录结构
使用Role组织任务,可以将复杂的Playbook剧本进行拆分,达到缩小文件,任务重用的作用。如下图目录结构可供参考。



Inventory
ansible可管理的主机源。

inventory目录包含:

hosts 主机及主机组列表
host_vars 主机变量,目录里包含以组名命名的yaml文件
group_vars 主机组变量,目录里包含以组名命名的yaml文件
inventory.py 动态主机列表脚本
如下图: host_vars

# cat /etc/ansible/inventory/hosts_vars/127.0.0.1
---
myname: wangpeng
address: beijing
1
2
3
4
若多个环境有不同的inventory源,可创建多个目录来区分,目录结构一致。比如将测试环境、生产环境区分开来。

Playbooks
执行playbook的统一入口。

在入口文件里指定目标主机、对应角色。

# cat /etc/ansible/playbooks/epel.yaml
---
- hosts: host1 # 定义主机组
gather_facts: false

roles: # 使用角色
- epel
1
2
3
4
5
6
7
Roles
定义的角色。角色目录中通常存放着tasks,handler,vars,templates,meta子目录,这些子目录并不是必须的,如果没用到某个目录(比如没有用到模板templates),可以为空目录,或者不创建。基于这样的目录结构,role会自动加载到目录内的tasks,vars及handlers。

在Role里编写具体的tasks、handlers、变量。

Tasks
play中运行的任务命令,也就是执行的哪些ansible模块,如command,shell,service,yum等。

# cat /etc/ansible/roles/epel/tasks/main.yaml
---

- name: install epel-release repo
remote_user: root
yum: name=epel-release state=installed
notify: make yum cache
1
2
3
4
5
6
7
目录下要有一个main.yaml文件,其他文件用Include引用到main中

Handlers
任务执行改变后触发的动作。handler也是task,但只task notify通知后才会触发,且多个task同时调用handler,只会触发一次。

# cat /etc/ansible/roles/epel/handlers/main.yaml
---

- name: make yum cache
shell: yum clean all && yum makecache
1
2
3
4
5
目录下要有一个main.yaml文件,其他文件用Include引用到main中

Vars
定义的主机变量和主机组变量。若group_vars,host_vars,role/vars目录中定义了相同变量名,优先级group_vars < host_vars < vars。

# cat /etc/ansible/roles/epel/vars/main.yaml
---
myname: wangpeng
address: beijing
1
2
3
4
目录下要有一个main.yaml文件,其他文件用Include引用到main中

Templates
使用template模板渲染功能时,所需的模块文件存放在这个目录。

运行

1
2
ansible all -m ping
ansible all -m shell -a "uptime"

playbook

  • shell –> 命令
  • playbook –> ansible命令

tower

1
wget http://releases.ansible.com/ansible-tower/setup/ansible-tower-setup-latest.tar.gz

模块

ansible本身是没有部署能力的,它只是个框架,它的模块才有真正的部署能力。

1
ansible -i hosts all -m ping

它就是用的ansible命令行,-i 表示使用当前目录下的hosts文件,all表示Host文件内声明的所有服务器,-m ping 表示使用module名为ping的module,这个module没有参数,所以就这样调用就行了。

Command

command 模块用于运行系统命令,比如echo hello, 你安装在系统里的python,或者make 一类。大家能领悟就行了。

常用参数:

parameter required default choices comments
chdir no 运行command命令前先cd到这个目录
creates no 如果这个参数对应的文件存在,就不运行command
executable no 将shell切换为command执行,这里的所有命令需要使用绝对路径
removes no 如果这个参数对应的文件不存在,就不运行command

案例

1
2
#ansible 命令调用command:
ansible -i hosts all -m command -a "uptime"

ansible命令行调用-m command模块 -a表示使用参数 “”内的为执行的command命令。
那么对应的节点都会执行关机。

1
2
# Run the command if the specified file does not exist.
ansible -i hosts all -m command -a "/usr/bin/make_database.sh arg1 arg2 creates=/path/to/database"

利用creates参数,判断/path/to/database这个文件是否存在,存在就跳过command命令,不存在就执行command命令。

shell

这个是一个很神奇的模块,它也是ansible的核心模块之一。它跟command模块一样负责在被ansible控制的节点(服务器)执行命令行。它与command模块有着相似的地方,也有不同的地方,看完这篇文章将告诉你答案。

常用参数

parameter required default choices comments
chdir no 跟command一样的,运行shell之前cd到某个目录
creates no 跟command一样的,如果某个文件存在则不运行shell
removes no 跟command一样的,如果某个文件不存在则不运行shell

案例

让所有节点运行somescript.sh并把log输出到somelog.txt。

1
$ ansible -i hosts all -m shell -a "sh somescript.sh >> somelog.txt"

先进入somedir/ ,再在somedir/目录下让所有节点运行somescript.sh并把log输出到somelog.txt。

1
$ ansible -i hosts all -m shell -a "somescript.sh >> somelog.txt" chdir=somedir/

体验shell和command的区别,先cd到某个需要编译的目录,执行condifgure然后,编译,然后安装。

1
$ ansible -i hosts all -m shell -a "./configure && make && make insatll" chdir=/xxx/yyy/

yum

用于包管理

常用参数

参数名 是否必须 默认值 选项值 参数说明
conf_file 设定远程yum执行时所依赖的yum配置文件
disable_gpg_check No Yes/No 在安装包前检查包,只会影响state参数为present或者latest的时候
list No 只能由ansible调用,不支持playbook,这个干啥的大家都懂
name Yes 你需要安装的包的名字,也能如此使用name=python=2.7安装python2.7
state no present present/latest/absent 用于描述安装包最终状态,present/latest用于安装包,absent用于remove安装包
update_cache no no yes/no 用于安装包前执行更新list,只会影响state参数为present/latest的时候

案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- name: 安装最新版本的apache
yum: name=httpd state=latest

- name: 移除apache
yum: name=httpd state=absent

- name: 安装一个特殊版本的apache
yum: name=httpd-2.2.29-1.4.amzn1 state=present

- name: 升级所有的软件包
yum: name=* state=latest

- name: 从一个远程yum仓库安装nginx
yum: name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present

- name: 从本地仓库安装nginx
yum: name=/usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present

- name: 安装整个Development tools相关的软件包
yum: name="@Development tools" state=present
1
2
3
4
5
6
7
8
- name: Install Base Require Software
yum:
name: "{{ item }}"
state: present
with_items:
- gcc
- fping
ignore_errors: yes

apt

这个模块是ubuntu作为远端节点的OS的时候,用的最多的。Apt是啥就不多说了,ubuntu/debian的包管理工具。

常用参数

参数名 是否必须 默认值 选项值 参数说明
cache_valid_time no 如果update_cache参数起作用的时候,这个参数才会起作用。其用来控制update_cache的整体有效时间
deb no 这个用于安装远程机器上的.deb后缀的软件包
default_release no 等同于apt命令的-t选项,这里就不多说了
force no no yes/no 强制执行apt install/remove
install_recommends no Ture yes/no 这个参数可以控制远程电脑上是否只是下载软件包,还是下载后安装,默认参数为true,设置为false的时候光下载软件包,不安装
name no apt要下载的软件包名字,支持name=git=1.6 这种制定版本的模式
purge no yes/no 如果state参数值为absent,这个参数为yes的时候,将会强行干净的卸载
state no present latest/absent/present 定义软件包的最终状态,latest时为安装最新软件
update_cache no yes/no 当这个参数为yes的时候等于apt-get update
upgrade no yes yes/safe/full/dist 如果参数为yes或者safe,等同于apt-get upgrade.如果是full就是完整更新。如果是dist等于apt-get dist-upgrade。

案例

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
# 在安装foo软件包前更新然后安装foo
- apt: name=foo update_cache=yes

# 移除foo软件包
- apt: name=foo state=absent

# 安装foo软件包
- apt: name=foo state=present

# 安装foo 1.0软件包
- apt: name=foo=1.00 state=present

# 安装nginx最新的名字为squeeze-backport发布包,并且安装前执行更新
- apt: name=nginx state=latest default_release=squeeze-backports update_cache=yes

# 只下载openjdk-6-jdk最新的软件包,不安装
- apt: name=openjdk-6-jdk state=latest install_recommends=no

# 安装所有软件包到最新版本
- apt: upgrade=dist

# 更新apt-get的list
- apt: update_cache=yes

# 3600秒后停止update_cache
- apt: update_cache=yes cache_valid_time=3600


# 安装远程节点上的/tmp/mypackage.deb软件包
- apt: deb=/tmp/mypackage.deb

fetch

copy

copy模块在ansible里的角色就是把ansible执行机器上的文件拷贝到远程节点上。
与fetch模块相反的操作。

常用参数

参数名 是否必须 默认值 选项值 参数说明
src no 用于定位ansible执行的机器上的文件,需要绝对路径。如果拷贝的是文件夹,那么文件夹会整体拷贝,如果结尾是”/”,那么只有文件夹内的东西被考过去。一切的感觉很像rsync
content no 用来替代src,用于将指定文件的内容,拷贝到远程文件内
dest yes 用于定位远程节点上的文件,需要绝对路径。如果src指向的是文件夹,这个参数也必须是指向文件夹
backup no no yes/no 备份远程节点上的原始文件,在拷贝之前。如果发生什么意外,原始文件还能使用。
directory_mode no 这个参数只能用于拷贝文件夹时候,这个设定后,文件夹内新建的文件会被拷贝。而老旧的不会被拷贝
follow no no yes/no 当拷贝的文件夹内有link存在的时候,那么拷贝过去的也会有link
force no yes yes/no 默认为yes,会覆盖远程的内容不一样的文件(可能文件名一样)。如果是no,就不会拷贝文件,如果远程有这个文件
group no 设定一个群组拥有拷贝到远程节点的文件权限
mode no 等同于chmod,参数可以为“u+rwx or u=rw,g=r,o=r”
owner no 设定一个用户拥有拷贝到远程节点的文件权限

案例

1
2
3
4
5
6
7
8
9
10
11
# 把/srv/myfiles/foo.conf文件拷贝到远程节点/etc/foo.conf,并且它的拥有者是foo,拥有它的群组是foo,权限是0644
- copy: src=/srv/myfiles/foo.conf dest=/etc/foo.conf owner=foo group=foo mode=0644

# 跟上面的案例一样,不一样的只是权限的写法
- copy: src=/srv/myfiles/foo.conf dest=/etc/foo.conf owner=foo group=foo mode="u=rw,g=r,o=r"

# 另外一个权限的写法
- copy: src=/srv/myfiles/foo.conf dest=/etc/foo.conf owner=foo group=foo mode="u+rw,g-wx,o-rwx"

# 拷贝/mine/ntp.conf到远程节点/etc/ntp.conf,并且备份远程节点的/etc/ntp.conf。
- copy: src=/mine/ntp.conf dest=/etc/ntp.conf owner=root group=root mode=644 backup=yes

常用参数返回值

参数名 参数说明 返回值 返回值类型 样例
src 位于ansible执行机上的位置 changed string /home/httpd/.ansible/tmp/ansible-tmp-1423796390.97-147729857856000/source
backup_file 将原文件备份 changed and if backup=yes string /path/to/file.txt.2015-02-12@22:09~
uid 在执行后,拥有者的ID success int 100
dest 远程节点的目标目录或文件 success string /path/to/file.txt
checksum 拷贝文件后的checksum值 success string 6e642bb8dd5c2e027bf21dd923337cbb4214f827
md5sum 拷贝文件后的md5 checksum值 when supported string 2a5aeecc61dc98c4d780b14b330e3282
state 执行后的状态 success string file
gid 执行后拥有文件夹、文件的群组ID success int 100
mode 执行后文件的权限 success string 0644
owner 执行后文件所有者的名字 success string httpd
group 执行后文件所有群组的名字 success string httpd
size 执行后文件大小 success int 1220

file

在之前ansible命令行的时候有copy模块,在playbook的时代自然也有一个模块专门负责文件的拷贝,当然这个时代它不仅仅是文件拷贝那么简单。

来自官方的解释:

file模块它包含了文件、文件夹、超级链接类的创立、拷贝、移动、删除操作。

常用参数

参数名 是否必须 默认值 选项 说明
follow no no yes/no 如果原来的文件是link,拷贝后依旧是link
force no no yes/no 强制执行,没说的
group no 设定一个群组拥有拷贝到远程节点的文件权限
mode no 等同于chmod,参数可以为“u+rwx or u=rw,g=r,o=r”
owner no 设定一个用户拥有拷贝到远程节点的文件权限
path yes 目标路径,也可以用dest,name代替
src yes 待拷贝文件/文件夹的原始位置。
state no file file/link/directory/
hard/touch/absent
file代表拷贝后是文件;
link代表最终是个软链接;
directory代表文件夹;
hard代表硬链接;
touch代表生成一个空文件;
absent代表删除

例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 修改文件的所有组、人、权限。
- file: path=/etc/foo.conf owner=foo group=foo mode=0644
# 操作链接的案例
- file: src=/file/to/link/to dest=/path/to/symlink owner=foo group=foo state=link
#参数化案例
- file: src=/tmp/{{ item.path }} dest={{ item.dest }} state=link
with_items:
- { path: 'x', dest: 'y' }
- { path: 'z', dest: 'k' }

# 使用touch来创建一个空文件并定义权限
- file: path=/etc/foo.conf state=touch mode="u=rw,g=r,o=r"

# touch一个空文件,并且修改权限
- file: path=/etc/foo.conf state=touch mode="u+rw,g-wx,o-rwx"

- name: link Zabbix Agent Link
#shell: ln -s {{ install_dir }}/zabbix-{{ zabbix_version }} {{ zabbix_dir }}
file:
src: "{{ install_dir }}/zabbix-{{ zabbix_version }}"
dest: "{{ zabbix_dir }}"
owner: root
group: root
state: link

template

template使用了Jinjia2格式作为文件模版,进行文档内变量的替换的模块。它的每次使用都会被ansible标记为”changed”状态。

常用参数

参数名 是否必须 默认值 选项值 参数说明
backup no no yes/no 建立个包括timestamp在内的文件备份,以备不时之需.
dest yes 远程节点上的绝对路径,用于放置template文件。
group no 设置远程节点上的的template文件的所属用户组
mode no 设置远程节点上的template文件权限。类似Linux中chmod的用法
owner no 设置远程节点上的template文件所属用户
src yes 本地Jinjia2模版的template文件位置。

案例

1
2
3
4
5
# 把/mytemplates/foo.j2文件经过填写参数后,复制到远程节点的/etc/file.conf,文件权限相关略过
- template: src=/mytemplates/foo.j2 dest=/etc/file.conf owner=bin group=wheel mode=0644

# 跟上面一样的效果,不一样的文件权限设置方式
- template: src=/mytemplates/foo.j2 dest=/etc/file.conf owner=bin group=wheel mode="u=rw,g=r,o=r"

service

service模块说白了,就是Linux下的service命令。但是它更简单。这个是playbook中用的非常多的模块。

常用参数

参数名 是否必须 默认值 选项值 参数说明
enabled no yes/no 启动os后启动对应service的选项。使用service模块的时候,enabled和state至少要有一个被定义
name yes 需要进行操作的service名字
state no stared/stoped/restarted/reloaded service最终操作后的状态。

案例

1
2
3
4
5
6
7
8
9
10
11
12
# 不管当前什么情况,启动apache
- service: name=httpd state=started

# 不管当前什么情况,停止apache
- service: name=httpd state=stopped

# 不管当前什么情况,重启apache
- service: name=httpd state=restarted


# 系统重启后,启动apache
- service: name=httpd enabled=yes

wait_for

当你利用service 启动tomcat,或数据库后,他们真的启来了么?这个你是否想确认下?
wait_for模块就是干这个的。等待一个事情发生,然后继续。它可以等待某个端口被占用,然后再做下面的事情,也可以在一定时间超时后做另外的事。

在playbook的执行过程中,等待某些操作完成以后再进行后续操作

常用参数

参数名 是否必须 默认值 选项值 参数说明
connect_timeout no 5 在下一个事情发生前等待链接的时间,单位是秒
delay no 延时,大家都懂,在做下一个事情前延时多少秒
host no 127.0.0.1 执行这个模块的host
path no 当一个文件存在于文件系统中,下一步才继续。
port no 端口号,如8080
state no started present/started/
stopped/absent
对象是端口的时候start状态会确保端口是打开的,
stoped状态会确认端口是关闭的;
对象是文件的时候,present或者started会确认文件是存在的,
而absent会确认文件是不存在的。
timeout no 300 wait_for的等待的超时时间

案例

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
# 10秒后在当前主机开始检查8000端口,直到端口启动后返回
- wait_for: port=8000 delay=10

# 检查path=/tmp/foo直到文件存在后继续
- wait_for: path=/tmp/foo

# 直到/var/lock/file.lock移除后继续
- wait_for: path=/var/lock/file.lock state=absent

# 直到/proc/3466/status移除后继续
- wait_for: path=/proc/3466/status state=absent

# 等待8080端口已正常监听,才开始下一个任务,直到超时
- wait_for: port=8080 state=started

# 等待8000端口正常监听,每隔10s检查一次,直至等待超时
- wait_for: port=8000 delay=10

# 等待8000端口直至有连接建立
- wait_for: host=0.0.0.0 port=8000 delay=10 state=drained

# 等待8000端口有连接建立,如果连接来自10.2.1.2或者10.2.1.3,则忽略。
- wait_for: host=0.0.0.0 port=8000 state=drained exclude_hosts=10.2.1.2,10.2.1.3

# 等待/tmp/foo文件已创建
- wait_for: path=/tmp/foo

# 等待/tmp/foo文件已创建,而且该文件中需要包含completed字符串
- wait_for: path=/tmp/foo search_regex=completed

# 等待/var/lock/file.lock被删除
- wait_for: path=/var/lock/file.lock state=absent

# 等待指定的进程被销毁
- wait_for: path=/proc/3466/status state=absent

# 等待openssh启动,10s检查一次
- local_action: wait_for port=22 host="{{ ansible_ssh_host | default(inventory_hostname) }}" search_regex=OpenSSH delay=10

unarchive

用于解压文件,模块包含如下选项:

  • copy:在解压文件之前,是否先将文件复制到远程主机,默认为yes。若为no,则要求目标主机上压缩包必须存在
  • creates:指定一个文件名,当该文件存在时,则解压指令不执行
  • dest:远程主机上的一个路径,即文件解压的路径
  • grop:解压后的目录或文件的属组
  • list_files:如果为yes,则会列出压缩包里的文件,默认为no,2.0版本新增的选项
  • mode:解决后文件的权限
  • src:如果copy为yes,则需要指定压缩文件的源路径
  • owner:解压后文件或目录的属主

示例如下

1
2
3
4
5
- unarchive: src=foo.tgz dest=/var/lib/foo

- unarchive: src=/tmp/foo.zip dest=/usr/local/bin copy=no

- unarchive: src=https://example.com/example.zip dest=/usr/local/bin copy=no

location_action

register

with_items

tags

pause

在playbook执行的过程中暂停一定时间或者提示用户进行某些操作

常用参数:

  • minutes:暂停多少分钟
  • seconds:暂停多少秒
  • prompt:打印一串信息提示用户操作

示例

1
2
3
4
5
 - name: wait on user input
pause: prompt="Warning! Detected slight issue. ENTER to continue CTRL-C a to quit"

- name: timed wait
pause: seconds=30

add_host

在playbook执行的过程中,动态的添加主机到指定的主机组中

常用参数

  • groups:添加主机至指定的组
  • name:要添加的主机名或IP地址

###示例

1
2
3
4
- name: add a host to group webservers
hosts: webservers
tasks:
- add_host name={{ ip_from_ec2 }} group=webservers foo=42 #添加主机到webservers组中,主机的变量foo的值为42

group_by

在playbook执行的过程中,动态的创建主机组

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 在playbook中设置一个新的主机组
- name: Create operating system group
hosts: all
tasks:
- group_by: key=os_{{ ansible_distribution }}

- name: Run on CentOS hosts only
hosts: os_CentOS
tasks:
- name: Install Apache
yum: name=httpd state=latest

- name: Run on Ubuntu hosts only
hosts: os_Ubuntu
tasks:
- name: Install Apache
apt: pkg=apache2 state=latest

fail

用于终止当前playbook的执行,通常与条件语句组合使用,当满足条件时,终止当前play的运行。可以直接由failed_when取代。

选项只有一个:

  • msg:终止前打印出信息

示例:

1
2
- fail: msg="The system may not be provisioned according to the CMDB status."
when: cmdb_status != "to-be-staged"