接上一节

常用模块

hostname主机名

1
#只有一个参数name,用于指定主机名

cron定时任务

支持:分时日月周(minute,hour,day,month,weekday)

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
OPTIONS (= is mandatory):

- backup
If set, create a backup of the crontab before it is modified. The location of the backup is returned in the
`backup_file' variable by this module.
[Default: False]
type: bool

- cron_file
If specified, uses this file instead of an individual user's crontab.
If this is a relative path, it is interpreted with respect to `/etc/cron.d'.
If it is absolute, it will typically be `/etc/crontab'.
Many linux distros expect (and some require) the filename portion to consist solely of upper- and lower-case letters,
digits, underscores, and hyphens.
To use the `cron_file' parameter you must specify the `user' as well.
[Default: (null)]
type: str

- day
Day of the month the job should run ( 1-31, *, */2, etc )
(Aliases: dom)[Default: *]
type: str

- disabled
If the job should be disabled (commented out) in the crontab.
Only has effect if `state=present'.
[Default: False]
type: bool
version_added: 2.0

- env
If set, manages a crontab's environment variable.
New variables are added on top of crontab.
`name' and `value' parameters are the name and the value of environment variable.
[Default: False]
type: bool
version_added: 2.1

- hour
Hour when the job should run ( 0-23, *, */2, etc )
[Default: *]
type: str

- insertafter
Used with `state=present' and `env'.
If specified, the environment variable will be inserted after the declaration of specified environment variable.
[Default: (null)]
type: str
version_added: 2.1

- insertbefore
Used with `state=present' and `env'.
If specified, the environment variable will be inserted before the declaration of specified environment variable.
[Default: (null)]
type: str
version_added: 2.1

- job
The command to execute or, if env is set, the value of environment variable.
The command should not contain line breaks.
Required if `state=present'.
(Aliases: value)[Default: (null)]
type: str

- minute
Minute when the job should run ( 0-59, *, */2, etc )
[Default: *]
type: str

- month
Month of the year the job should run ( 1-12, *, */2, etc )
[Default: *]
type: str

- name
Description of a crontab entry or, if env is set, the name of environment variable.
Required if `state=absent'.
Note that if name is not set and `state=present', then a new crontab entry will always be created, regardless of
existing ones.
This parameter will always be required in future releases.
[Default: (null)]
type: str

- reboot
If the job should be run at reboot. This option is deprecated. Users should use special_time.
[Default: False]
type: bool
version_added: 1.0

- special_time
Special time specification nickname.
(Choices: annually, daily, hourly, monthly, reboot, weekly, yearly)[Default: (null)]
type: str
version_added: 1.3

- state
Whether to ensure the job or environment variable is present or absent.
(Choices: absent, present)[Default: present]
type: str

- user
The specific user whose crontab should be modified.
When unset, this parameter defaults to using `root'.
[Default: (null)]
type: str

- weekday
Day of the week that the job should run ( 0-6 for Sunday-Saturday, *, etc )
(Aliases: dow)[Default: *]
type: str

创建一个定时任务

1
ansible host -m cron -a ''minute=*/5 job=/path/to/job/'

yum包管理

需要机器支持yum包管理器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#常用参数
- name
- state
Whether to install (`present' or `installed', `latest'), or remove (`absent' or `removed') a package.
`present' and `installed' will simply ensure that a desired package is installed.
`latest' will update the specified package if it's not of the latest available version.
`absent' and `removed' will remove the specified package.
Default is `None', however in effect the default action is `present' unless the `autoremove' option is enabled for
this module, then `absent' is inferred.
(Choices: absent, installed, latest, present, removed)[Default: (null)]
- list
Package name to run the equivalent of yum list --show-duplicates <package> against. In addition to listing packages,
use can also list the following: `installed', `updates', `available' and `repos'.
This parameter is mutually exclusive with `name'.
[Default: (null)]
-...

service服务管理

1
2
3
4
5
6
7
8
# 常用参数
- name: # 介绍功能
service:
name: # 服务名
state: # 状态,可选参数started、restarted、reloaded、stopped
enable: # bool型,是否开启开机自启
## commandline
ansible host -m service -a 'name=<...> state=<...> enable=<true|false>'

user管理用户

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
- name: Manage user accounts
user:
append: # If `yes', add the user to the groups specified in `groups'. If `no', user will only be added to the groups specified in `groups', removing them from all other groups. Mutually exclusive with `local'
authorization: # Sets the authorization of the user. Does nothing when used with other platforms. Can set multiple authorizations using comma separation. To delete all authorizations, use `authorization='''. Currently supported on Illumos/Solaris.
comment: # 描述信息# Optionally sets the description (aka `GECOS') of user account.
create_home: # Unless set to `no', a home directory will be made for the user when the account is created or if the home directory does not
exist. Changed from `createhome' to `create_home' in Ansible 2.5.
expires: # 设置账号有效期 # An expiry time for the user in epoch, it will be ignored on platforms that do not support this. Currently supported on GNU/Linux, FreeBSD, and DragonFlyBSD. Since Ansible 2.6 you can remove the expiry time specify a negative value. Currently supported on GNU/Linux and FreeBSD.
force: # This only affects `state=absent', it forces removal of the user and associated directories on supported platforms. The behavior is the same as `userdel --force', check the man page for `userdel' on your system for details and support. When used with `generate_ssh_key=yes' this forces an existing key to be overwritten.
generate_ssh_key: # Whether to generate a SSH key for the user in question. This will *not* overwrite an existing SSH key unless used with `force=yes'.
group: # 设置主组 # Optionally sets the user's primary group (takes a group name).
groups: # 设置附加组 # List of groups user will be added to. When set to an empty string `''', the user is removed from all groups except the primary group. Before Ansible 2.3, the only input format allowed was a comma separated string. Mutually exclusive with `local'
hidden: # macOS only, optionally hide the user from the login window and system preferences. The default will be `yes' if the `system' option is used.
home: # 指定用户家目录 # Optionally set the user's home directory.
local: # Forces the use of "local" command alternatives on platforms that implement it. This is useful in environments that use centralized authentification when you want to manipulate the local users (i.e. it uses `luseradd' instead of `useradd'). This will check `/etc/passwd' for an existing account before invoking commands. If the local account database exists somewhere other than `/etc/passwd', this setting will not work properly. This requires that the above commands as well as `/etc/passwd' must exist on the target host, otherwise it will be a fatal error. Mutually exclusive with `groups' and `append'
login_class: # Optionally sets the user's login class, a feature of most BSD OSs.
move_home: # If set to `yes' when used with `home: ', attempt to move the user's old home directory to the specified directory if it isn't there already and the old home exists.
name: # 设置用户名 # (required) Name of the user to create, remove or modify.
non_unique: # Optionally when used with the -u option, this option allows to change the user ID to a non-unique value.
password: # 设置用户的密码 # Optionally set the user's password to this crypted value. On macOS systems, this value has to be cleartext. Beware of security issues. To create a disabled account on Linux systems, set this to `'!'' or `'*''. To create a disabled account on OpenBSD, set this to `'*************''. See https://docs.ansible.com/ansible/faq.html#how-do-i-generate-encrypted-passwords-for-the-user-module for details on various ways to generate these password values.
password_lock: # Lock the password (`usermod -L', `usermod -U', `pw lock'). Implementation differs by platform. This option does not always mean the user cannot login using other methods. This option does not disable the user, only lock the password. This must be set to `False' in order to unlock a currently locked password. The absence of this parameter will not unlock a password. Currently supported on Linux, FreeBSD, DragonFlyBSD, NetBSD, OpenBSD.
profile: # Sets the profile of the user. Does nothing when used with other platforms. Can set multiple profiles using comma separation. To delete all the profiles, use `profile='''. Currently supported on Illumos/Solaris.
remove: #是否在删除用户的同时删除家目录 # This only affects `state=absent', it attempts to remove directories associated with the user. The behavior is the same as `userdel --remove', check the man page for details and support.
role: # Sets the role of the user. Does nothing when used with other platforms. Can set multiple roles using comma separation. To delete all roles, use `role='''. Currently supported on Illumos/Solaris.
seuser: # Optionally sets the seuser type (user_u) on selinux enabled systems.
shell: # Optionally set the user's shell. On macOS, before Ansible 2.5, the default shell for non-system users was `/usr/bin/false'. Since Ansible 2.5, the default shell for non-system users on macOS is `/bin/bash'. On other operating systems, the default shell is determined by the underlying tool being used. See Notes for details.
skeleton: # Optionally set a home skeleton directory. Requires `create_home' option!
ssh_key_bits: # Optionally specify number of bits in SSH key to create.
ssh_key_comment: # Optionally define the comment for the SSH key.
ssh_key_file: # Optionally specify the SSH key filename. If this is a relative filename then it will be relative to the user's home directory. This parameter defaults to `.ssh/id_rsa'.
ssh_key_passphrase: # Set a passphrase for the SSH key. If no passphrase is provided, the SSH key will default to having no passphrase.
ssh_key_type: # Optionally specify the type of SSH key to generate. Available SSH key types will depend on implementation present on target host.
state: # 对用户进行的操作(删除absent,默认present创建) # Whether the account should exist or not, taking action if the state is different from what is stated.
system: # 是否设置用户为系统用户 # When creating an account `state=present', setting this to `yes' makes the user a system account. This setting cannot be
changed on existing users.
uid: # 手动设置用户的uid # Optionally sets the `UID' of the user.
update_password: # 更行用户密码 # `always' will update passwords if they differ. `on_create' will only set the password for newly created users.

group管理组

1
2
3
4
5
6
7
8
- name: Add or remove groups
group:
gid: # Optional `GID' to set for the group.
local: # Forces the use of "local" command alternatives on platforms that implement it. This is useful in environments that use centralized authentication when you want to manipulate the local groups. (e.g. it uses `lgroupadd' instead of `groupadd'). This requires that these commands exist on the targeted host, otherwise it will be a fatal error.
name: # (required) Name of the group to manage.
non_unique: # This option allows to change the group ID to a non-unique value. Requires `gid'. Not supported on macOS or BusyBox distributions.
state: # Whether the group should be present or not on the remote host.
system: # If `yes', indicates that the group created is a system group.

ansible-galaxy命令

连接https://galaxy.ansible.com下载相应的roles。

列出roles

1
ansible-galaxy list

下载roles

1
ansible-galaxy install <>

删除roles

1
ansible-galaxy remove <>

ansible-playbook命令

剧本

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
optional arguments:
--ask-vault-pass ask for vault password
--flush-cache clear the fact cache for every host in inventory
--force-handlers run handlers even if a task fails
# 列出主机
--list-hosts outputs a list of matching hosts; does not execute
anything else
# 列出所有标签
--list-tags list all available tags
# 列出所有任务
--list-tasks list all tasks that would be executed
--skip-tags SKIP_TAGS
only run plays and tasks whose tags do not match these
values
--start-at-task START_AT_TASK
start the playbook at the task matching this name
--step one-step-at-a-time: confirm each task before running
--syntax-check perform a syntax check on the playbook, but do not
execute it
--vault-id VAULT_IDS the vault identity to use
--vault-password-file VAULT_PASSWORD_FILES
vault password file
--version show program's version number, config file location,
configured module search path, module location,
executable location and exit
# 运行测试,并不会做修改
-C, --check don't make any changes; instead, try to predict some
of the changes that may occur
-D, --diff when changing (small) files and templates, show the
differences in those files; works great with --check
-M MODULE_PATH, --module-path MODULE_PATH
prepend colon-separated path(s) to module library (def
ault=~/.ansible/plugins/modules:/usr/share/ansible/plu
gins/modules)
-e EXTRA_VARS, --extra-vars EXTRA_VARS
set additional variables as key=value or YAML/JSON, if
filename prepend with @
# 修改并发数目,默认为5
-f FORKS, --forks FORKS
specify number of parallel processes to use
(default=5)
-h, --help show this help message and exit
-i INVENTORY, --inventory INVENTORY, --inventory-file INVENTORY
specify inventory host path or comma separated host
list. --inventory-file is deprecated
-l SUBSET, --limit SUBSET
further limit selected hosts to an additional pattern
-t TAGS, --tags TAGS only run plays and tasks tagged with these values
-v, --verbose verbose mode (-vvv for more, -vvvv to enable
connection debugging)
Privilege Escalation Options:
control how and which user you become as on target hosts

--become-method BECOME_METHOD
privilege escalation method to use (default=sudo), use
`ansible-doc -t become -l` to list valid choices.
--become-user BECOME_USER
run operations as this user (default=root)
-K, --ask-become-pass
ask for privilege escalation password
-b, --become run operations with become (does not imply password
prompting)

ansible-vault命令

对yml剧本文件进行加密解密

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
positional arguments:
{create,decrypt,edit,view,encrypt,encrypt_string,rekey}
create Create new vault encrypted file
decrypt Decrypt vault encrypted file
edit Edit vault encrypted file
view View vault encrypted file
encrypt Encrypt YAML file
encrypt_string Encrypt a string
rekey Re-key a vault encrypted file

optional arguments:
--version show program's version number, config file location,
configured module search path, module location,
executable location and exit
-h, --help show this help message and exit
-v, --verbose verbose mode (-vvv for more, -vvvv to enable
connection debugging)

加密/解密

1
ansible-vault encrypt/decrypt <>

剧本yaml文件语法

结合ansible做简单介绍

1
2
3
4
5
6
7
8
9
10
--- #开头三个连接符表示档案的开始,可以不写,这只是一个习惯
- hosts: #指定主机,类似ansible后的第一个参数
remote_user: #指定登录的用户

tasks:
- name: #任务模块,描述信息,一个name对应一个模块
<module>: #模块名和参数的键值对(这是最常用的形式)
- name:
action: <module> <argues> #这是第二种形式(不常用)
... #表示结尾,可以不写

tasks,handlers和tags

tasks中的任务是依次执行的,当出现前一个任务修改了配置文件,后一个任务是启动服务的情况时,tasks无法让服务重启使新的配置生效。

handlers

handlers触发器,可以用来解决上述问题。

handlers

与tasks平级,需要使用notify绑定事件

以nginx服务为例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
---
- hosts: centos
remote_user: root

tasks:
# - name: install nginx
# yum: name=nginx
- name: config
copy: src=/etc/nginx/nginx.conf dest=/etc/nginx/
notify:
- restart nginx
- check nginx process
tags: copy_config
- name: start nginx service
service: name=nginx state=started enabled=yes

handlers:
- name: restart nginx
service: name=nginx state=restarted
- name: check nginx process
shell: killall -0 nginx > /tmp/nginx.log

tags

使用标签,可以用于特定执行某些动作。

1
2
3
4
5
6
7
8
# ...
- name: config
copy: src=/etc/nginx/nginx.conf dest=/etc/nginx/
notify:
- restart nginx
- check nginx process
tags: copy_config
# ...
1
2
#使用-t参数可以指定标签
ansible-playbook nginx.yml -t copy_config