一、Ansible简介
1. Ansible概述
Ansible是一个基于Python开发的配置管理和应用部署工具,现在也在自动化管理领域大放异彩。它融合了众多老牌运维工具的优点,Puppet和Saltstack能实现的功能,Ansible基本上都可以实现。
2. Ansible作用
Ansible能批量配置、部署、管理上千台主机。比如以前需要切换到每个主机上执行的一或多个操作,使用Ansible只需在固定的一台Ansible控制节点上去完成所有主机的操作。
3. Ansible的工作模块
Ansible是基于模块工作的,它只是提供了一种运行框架,它本身没有完成任务的能力,真正执行操作的是Ansible的模块, 比如copy模块用于拷贝文件到远程主机上,service模块用于管理服务的启动、停止、重启等。
4. 常用的自动化运维工具及区别
5. Ansible的主要特点
Ansible其中一个比较鲜明的特性是Agentless,即无Agent的存在,它就像普通命令一样,并非C/S软件,也只需在某个作为控制节点的主机上安装一次Ansible即可,通常它基于ssh连接来控制远程主机,远程主机上不需要安装Ansible或其它额外的服务。 Ansible的另一个比较鲜明的特性是它的绝大多数模块都具备幂等性(idempotence)。所谓幂等性,指的是多次操作或多次执行对系统资源的影响是一致的。比如执行 systemctl stop xxx 命令来停止服务,当发现要停止的目标服务已经处于停止状态, 它什么也不会做,所以多次停止的结果仍然是停止,不会改变结果,它是幂等的,而 systemctl restart xxx 是非幂等的。 Ansible的很多模块在执行时都会先判断目标节点是否要执行任务,所以,可以放心大胆地让Ansible去执行任务,重复执行某个任务绝大多数时候不会产生任何副作用。
6. Ansible的工作机制
使用者在使用时,在服务器终端输入命令或者playbooks,会通过预定好的规则将playbook拆解为play,再组织成ansible可以识别的任务,调用模块和插件,根据主机清单通过SSH将临时文件发给远程的客户端执行并返回结果,执行结束后自动删除
二、Ansible部署
1. Ansible环境安装部署
服务器 | IP地址 | 主机名 | 主要软件 |
管理端 | 192.168.122.10 | ansible | ansible |
被管理端 | 192.168.122.11 | node1 | - |
被管理端 | 192.168.122.12 | node2 | - |
被管理端 | 192.168.122.13 | node3 | - |
2. 管理端安装ansible
[root@ansible ~]# yum install -y epel-release.noarch
[root@ansible ~]# yum install -y ansible
3. ansible目录结构
[root@ansible ~]# yum install -y ansible
[root@ansible ~]# tree /etc/ansible
/etc/ansible
├── ansible.cfg
├── hosts
└── roles
● ansible.cfg ansible的配置文件,一般无需修改 ● hosts ansible的主机清单,用于存储需要管理的远程主机的相关信息 ● roles 公共角色目录
4. 配置主机清单
[root@ansible ~]# cd /etc/ansible/
[root@ansible ansible]# vim hosts
##配置组名
[webservers]
#组里面包含的被管理的主机IP地址或主机名
#使用主机名需要先修改/etc/hosts文件,更新ip映射
192.168.122.11
[dbservers]
192.168.122.12
5. 配置密钥对验证
5.1 生成密钥对
[root@ansible ansible]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
#回车
Enter passphrase (empty for no passphrase):
#回车
Enter same passphrase again:
#回车
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:Rnc5ypBw0tT11X4pzu6p9vu3Yro5TESazT+LIRldKbw root@ansible
The key's randomart image is:
+---[RSA 2048]----+
| ooo.... . o|
| +...+ = ..|
| + O B ...|
| . B E o .o|
| S * + . .|
| . o o = |
| + + o |
| =.=. .|
| .=O=+oo|
+----[SHA256]-----+
5.2 复制公钥至node1并验证
[root@ansible ansible]# ssh-copy-id root@192.168.122.11
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.122.11's password:
#输入密码
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.122.11'"
and check to make sure that only the key(s) you wanted were added.
[root@ansible ansible]# ssh root@192.168.122.11
Last login: Thu Oct 21 16:24:17 2021
[root@node1 ~]#
#实现免密登录
[root@node1 ~]# ifconfig ens33 | awk "NR==2 {print \$2}"
192.168.122.11
[root@node1 ~]# ifconfig ens33 | awk 'NR==2 {print $2}'
192.168.122.11
[root@node1 ~]# echo $(ifconfig ens33 | awk 'NR==2 {print $2}' | cut -d " " -f 2)
192.168.122.11
[root@node1 ~]# exit
登出
5.3 复制公钥至node2并验证
[root@ansible ansible]# ssh-copy-id root@192.168.122.12
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.122.12 (192.168.122.12)' can't be established.
ECDSA key fingerprint is SHA256:VZGGMMTK4KF/0n10SPQZ5+gjbPWA+2INFv05R3MSlog.
ECDSA key fingerprint is MD5:fa:3c:f3:ee:f1:b2:91:06:95:94:f2:94:04:d3:69:5c.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.122.12's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.122.12'"
and check to make sure that only the key(s) you wanted were added.
[root@ansible ansible]# ssh root@192.168.122.12
Last login: Thu Oct 21 16:24:38 2021
[root@node2 ~]# ifconfig ens33 | awk "NR==2 {print \$2}"
192.168.122.12
[root@node2 ~]# ifconfig ens33 | awk 'NR==2 {print $2}'
192.168.122.12
[root@node2 ~]# echo $(ifconfig ens33 | awk 'NR==2 {print $2}' | cut -d " " -f 2)
192.168.122.12
#实现免密登录
[root@node2 ~]# exit
登出
三、Ansible命令行模块
命令格式:ansible <组名> -m <模块> -a <参数列表> ● ansible-doc -l 列出所有已安装的模块,按q退出
[root@ansible ansible]# ansible-doc -l
fortios_router_community_list Configure community lists in Fortinet's FortiOS and FortiGate
azure_rm_devtestlab_info Get Azure DevTest Lab facts
ecs_taskdefinition register a task definition in ecs
avi_alertscriptconfig Module for setup of AlertScriptConfig Avi RESTful Object
tower_receive Receive assets from Ansible Tower
netapp_e_iscsi_target NetApp E-Series manage iSCSI target configuration
azure_rm_acs Manage an Azure Container Service(ACS) instance
fortios_log_syslogd2_filter Filters for remote system server in Fortinet's FortiOS and Fort...
junos_rpc Runs an arbitrary RPC over NetConf on an Juniper JUNOS device
na_elementsw_vlan NetApp Element Software Manage VLAN
pn_ospf CLI command to add/remove ospf protocol to a vRouter
pn_snmp_vacm CLI command to create/modify/delete snmp-vacm
cp_mgmt_service_sctp Manages service-sctp objects on Check Point over Web Services A...
onyx_ospf Manage OSPF protocol on Mellanox ONYX network devices
icx_command Run arbitrary commands on remote Ruckus ICX 7000 series switche...
cs_snapshot_policy Manages volume snapshot policies on Apache CloudStack based clo...
nxos_install_os Set boot options like boot, kickstart image and issu
cnos_static_route Manage static IP routes on Lenovo CNOS network devices
win_eventlog Manage Windows event logs
vmware_category Manage VMware categories
vmware_host_feature_info Gathers info about an ESXi host's feature capability informatio...
avi_cluster Module for setup of Cluster Avi RESTful Object
na_ontap_user NetApp ONTAP user configuration and management
aci_l3out Manage Layer 3 Outside (L3Out) objects (l3ext:Out)
memset_server_info Retrieve server information
gcp_compute_subnetwork_info Gather info for GCP Subnetwork
azure_rm_virtualmachinescalesetextension Manage Azure Virtual Machine Scale Set (VMSS) extensions
1. command模块
在远程主机执行命令,不支持管道,重定向等shell的特性。
1.1 列出指定模块的描述信息和操作动作
● ansible-doc -s command
[root@ansible ansible]# ansible-doc -s command
- name: Execute commands on targets
command:
argv: # Passes the command as a list rather than a string. Use `argv' to avoid quoting values that would
otherwise be interpreted incorrectly (for example "user name").
Only the string or the list form can be provided, not both. One or
the other must be provided.
chdir: # Change into this directory before running the command.
cmd: # The command to run.
creates: # A filename or (since 2.0) glob pattern. If it already exists, this step *won't* be run.
free_form: # The command module takes a free form command to run. There is no actual parameter named 'free
form'.
removes: # A filename or (since 2.0) glob pattern. If it already exists, this step *will* be run.
stdin: # Set the stdin of the command directly to the specified value.
stdin_add_newline: # If set to `yes', append a newline to stdin data.
strip_empty_ends: # Strip empty lines from the end of stdout/stderr in result.
warn: # Enable or disable task warnings.
1.2 指定ip执行date
● ansible 192.168.122.11 -m command -a 'date'
[root@ansible ansible]# ansible 192.168.122.11 -m command -a 'date'
192.168.122.11 | CHANGED | rc=0 >>
2021年 10月 21日 星期四 17:21:39 CST
1.3 指定组执行date
● ansible webservers -m command -a 'date' ● ansible dbservers -m command -a 'date'
[root@ansible ansible]# ansible webservers -m command -a 'date'
192.168.122.11 | CHANGED | rc=0 >>
2021年 10月 21日 星期四 17:36:45 CST
[root@ansible ansible]# ansible dbservers -m command -a 'date'
192.168.122.12 | CHANGED | rc=0 >>
2021年 10月 21日 星期四 17:36:50 CST
1.4 all代表所有hosts主机
● ansible all -m command -a 'date'
[root@ansible ansible]# ansible all -m command -a 'date'
192.168.122.11 | CHANGED | rc=0 >>
2021年 10月 21日 星期四 17:38:10 CST
192.168.122.12 | CHANGED | rc=0 >>
2021年 10月 21日 星期四 17:38:10 CST
1.5 如省略-m模块,则默认运行command模块
● ansible all -a 'ls /'
[root@ansible ansible]# ansible all -a 'ls /'
192.168.122.12 | CHANGED | rc=0 >>
bin
boot
dev
etc
home
lib
lib64
media
mnt
opt
proc
root
run
sbin
share
srv
sys
tmp
usr
var
192.168.122.11 | CHANGED | rc=0 >>
bin
boot
dev
etc
home
lib
lib64
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
1.6 常用的参数
chdir:在远程主机上运行命令前提前进入目录 creates:判断指定文件是否存在,如果存在,不执行后面的操作 removes:判断指定文件是否存在,如果存在,执行后面的操作
[21:53:07 root@c7-5 ~]#ansible all -m command -a "chdir=/home ls ./"
192.168.10.101 | CHANGED | rc=0 >>
mysql
syhj
192.168.10.70 | CHANGED | rc=0 >>
mysql
syhj
192.168.10.100 | CHANGED | rc=0 >>
syhj
2. shell模块
在远程主机执行命令,相当于调用远程主机的shell进程,然后在该shell下打开有一个子shell运行命令(支持管段符号等功能)
[root@ansible ansible]# ansible-doc -s shell
- name: Execute shell commands on targets
shell:
chdir: # Change into this directory before running the command.
cmd: # The command to run followed by optional arguments.
creates: # A filename, when it already exists, this step will *not* be run.
executable: # Change the shell used to execute the command. This expects an absolute path to the executable.
free_form: # The shell module takes a free form command to run, as a string. There is no actual parameter named
'free form'. See the examples on how to use this module.
removes: # A filename, when it does not exist, this step will *not* be run.
stdin: # Set the stdin of the command directly to the specified value.
stdin_add_newline: # Whether to append a newline to stdin data.
warn: # Whether to enable task warnings.
2.1 创建用户/更改密码
● ansible webservers -m shell -a 'useradd test' ● ansible webservers -m shell -a 'echo 123456 | passwd --stdin test'
[root@ansible ansible]# ansible webservers -m shell -a 'useradd test'
192.168.122.11 | CHANGED | rc=0 >>
[root@ansible ansible]# ansible webservers -m shell -a 'echo 123456 | passwd --stdin test'
192.168.122.11 | CHANGED | rc=0 >>
更改用户 test 的密码 。
passwd:所有的身份验证令牌已经成功更新。
2.2 查看ip
● ansible webservers -m shell -a 'ifconfig ens33 | awk "NR==2 {print \$2}"'
[root@ansible ansible]# ansible webservers -m shell -a 'ifconfig ens33 | awk "NR==2 {print \$2}"'
192.168.122.11 | CHANGED | rc=0 >>
192.168.122.11
● ansible webservers -m shell -a 'echo $(ifconfig ens33 | awk "NR==2 {print}") | cut -d " " -f 2'
[root@ansible ansible]# ansible webservers -m shell -a 'echo $(ifconfig ens33 | awk "NR==2 {print}") | cut -d " " -f 2'
192.168.122.11 | CHANGED | rc=0 >>
192.168.122.11
3. cron模块
在远程主机定义任务计划。其中有两种状态(state):present表示添加(默认,可省略),absent表示移除
3.1 列出指定模块的描述信息和操作动作
● ansible-doc -s cron
[root@ansible ansible]# ansible-doc -s cron
- name: Manage cron.d and crontab entries
cron:
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.
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.
day: # Day of the month the job should run ( 1-31, *, */2, etc )
disabled: # If the job should be disabled (commented out) in the crontab. Only has effect if `state=present'.
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.
hour: # Hour when the job should run ( 0-23, *, */2, etc )
insertafter: # Used with `state=present' and `env'. If specified, the environment variable will be inserted after
the declaration of specified environment variable.
insertbefore: # Used with `state=present' and `env'. If specified, the environment variable will be inserted
before the declaration of specified environment variable.
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'.
minute: # Minute when the job should run ( 0-59, *, */2, etc )
month: # Month of the year the job should run ( 1-12, *, */2, etc )
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
3.1 常用的参数
minute/hour/day/month/weekday:分/时/日/月/周 job:任务计划要执行的命令 name:任务计划的名称
3.2 设置计划任务
● ansible webservers -m cron -a 'minute="*/1" job="/bin/echo helloworld" name="test crontab"'
[root@ansible ansible]# ansible webservers -m cron -a 'minute="*/1" job="/bin/echo helloworld" name="test crontab"'
192.168.122.11 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": [
"test crontab"
]
}
3.3 查看计划任务
● ansible webservers -a 'crontab -l'
[root@ansible ansible]# ansible webservers -a 'crontab -l'
192.168.122.11 | CHANGED | rc=0 >>
#Ansible: test crontab*/1 * * * * /bin/echo helloworld
3.4 移除计划任务
● ansible webservers -m cron -a 'name="test crontab" state=absent'
[root@ansible ansible]# ansible webservers -m cron -a 'name="test crontab" state=absent'
192.168.122.11 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": []
}
[root@ansible ansible]# ansible webservers -a 'crontab -l'
192.168.122.11 | CHANGED | rc=0 >>
移除计划任务,若该计划任务没有取名字,name=None即可。 若有多个计划任务没有取名字,name=None将批量删除所有未取名任务。
4. user模块
用户管理的模块
4.1 列出指定模块的描述信息和操作动作
● ansible-doc -s user
[root@ansible ansible]# ansible-doc -s user
- 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
4.2 常用参数
常用参数 | 说明 |
name | 用户名,必选参数 |
state=present/absent | 创建账号或者删除账号,present表示创建,absent表示删除 |
system=yes/no | 是否为系统账号 |
uid | 用户uid |
group | 用户基本组 |
shell | 默认使用的shell |
move_home=yse/no | 如果设置的家目录已经存在,是否将已经存在的家目录进行移动 |
password | 用户的密码,建议使用加密后的字符串 |
comment | 用户的注释信息 |
remove=yes/no | 当state=absent时,是否删除用户的家目录 |
4.3 用户控制
创建用户test01 ● ansible dbservers -m user -a 'name="test01"'
[root@ansible ansible]# ansible dbservers -m user -a 'name="test01"'
192.168.122.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"comment": "",
"create_home": true,
"group": 1002,
"home": "/home/test01",
"name": "test01",
"shell": "/bin/bash",
"state": "present",
"system": false,
"uid": 1002
}
查看passwd ● ansible dbservers -a 'tail -n 1 /etc/passwd'
[root@ansible ansible]# ansible dbservers -a 'tail -n 1 /etc/passwd'
192.168.122.12 | CHANGED | rc=0 >>
test01:x:1002:1002::/home/test01:/bin/bash
删除用户test1 ● ansible dbservers -m user -a 'name="test01" state=absent'
[root@ansible ansible]# ansible dbservers -m user -a 'name="test01" state=absent'
192.168.122.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"force": false,
"name": "test01",
"remove": false,
"state": "absent"
}
[root@ansible ansible]# ansible dbservers -a 'tail -n 1 /etc/passwd'
192.168.122.12 | CHANGED | rc=0 >>
nginx:x:1001:1001::/home/nginx:/sbin/nologin
5. group模块
用户组管理的模块
5.1 列出指定模块的描述信息和操作动作
● ansible-doc -s group
[root@ansible ansible]# ansible-doc -s group
- 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.
5.2 用户组管理
创建mysql组 ● ansible dbservers -m group -a 'name=mysql gid=2222 system=yes'
[root@ansible ansible]# ansible dbservers -m group -a 'name=mysql gid=2222 system=yes'
192.168.122.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 2222,
"name": "mysql",
"state": "present",
"system": true
}
● ansible dbservers -a 'tail -n 1 /etc/group'
[root@ansible ansible]# ansible dbservers -a 'tail -n 1 /etc/group'
192.168.122.12 | CHANGED | rc=0 >>
mysql:x:2222
将test01用户添加到mysql组中 ● ansible dbservers -m user -a 'name=test01 uid=2222 system=yes group=mysql'
[root@ansible ansible]# ansible dbservers -m user -a 'name=test01 uid=2222 system=yes group=mysql'
192.168.122.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"comment": "",
"create_home": true,
"group": 2222,
"home": "/home/test01",
"name": "test01",
"shell": "/bin/bash",
"state": "present",
"stderr": "useradd:警告:此主目录已经存在。\n不从 skel 目录里向其中复制任何文件。\n",
"stderr_lines": [
"useradd:警告:此主目录已经存在。",
"不从 skel 目录里向其中复制任何文件。"
],
"system": true,
"uid": 2222
}
● ansible dbservers -a 'tail -n 1 /etc/passwd'
[root@ansible ansible]# ansible dbservers -a 'tail -n 1 /etc/passwd'
192.168.122.12 | CHANGED | rc=0 >>
test01:x:2222:2222::/home/test01:/bin/bash
● ansible dbservers -a 'id test01'
[root@ansible ansible]# ansible dbservers -a 'id test01'
192.168.122.12 | CHANGED | rc=0 >>
uid=2222(test01) gid=2222(mysql) 组=2222(mysql)
6. copy模块
用于复制指定主机文件到远程主机
注意:复制管理机器(种子机)的文件到远程主机
● ansible-doc -s copy
[root@ansible ansible]# ansible-doc -s copy
- name: Copy files to remote locations
copy:
attributes: # The attributes the resulting file or directory should have. To get supported flags look at the man
page for `chattr' on the target system. This string should contain
the attributes in the same order as the one displayed by `lsattr'.
The `=' operator is assumed as default, otherwise `+' or `-'
operators need to be included in the string.
backup: # Create a backup file including the timestamp information so you can get the original file back if
you somehow clobbered it incorrectly.
checksum: # SHA1 checksum of the file being transferred. Used to validate that the copy of the file was
successful. If this is not provided, ansible will use the local
calculated checksum of the src file.
content: # When used instead of `src', sets the contents of a file directly to the specified value. Works
only when `dest' is a file. Creates the file if it does not exist.
For advanced formatting or if `content' contains a variable, use
the [template] module.
decrypt: # This option controls the autodecryption of source files using vault.
dest: # (required) Remote absolute path where the file should be copied to. If `src' is a directory, this
must be a directory too. If `dest' is a non-existent path and if
either `dest' ends with "/" or `src' is a directory, `dest' is
created. If `dest' is a relative path, the starting directory is
determined by the remote host. If `src' and `dest' are files, the
parent directory of `dest' is not created and the task fails if it
does not already exist.
directory_mode: # When doing a recursive copy set the mode for the directories. If this is not set we will use the
system defaults. The mode is only set on directories which are
newly created, and will not affect those that already existed.
6.1 常用参数
常用参数 | 说明 |
dest | 指出复制文件的目标及位置,使用绝对路径,如果是源目录,指目标也要是目录,如果目标文件已经存在会覆盖原有的内容 |
src | 指出源文件的路径,可以使用相对路径或绝对路径,支持直接指定目录,如果源是目录则目标也要是目录 |
mode | 指出复制时,目标文件的权限 |
owner | 指出复制时,目标文件的属主 |
group | 指出复制时,目标文件的属组 |
content | 指出复制到目标主机上的内容,不能与src一起使用 |
6.2 复制管理
● ansible dbservers -m copy -a 'src=/etc/fstab dest=/opt/fstab.bak owner=root mode=640'
[root@ansible ansible]# ansible dbservers -m copy -a 'src=/etc/fstab dest=/opt/fstab.bak owner=root mode=640'
192.168.122.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "f033278c56c47bf1856d94f85f80e01d9a6bf399",
"dest": "/opt/fstab.bak",
"gid": 0,
"group": "root",
"md5sum": "7b3dbae60210e8febb95ec755c16d7ed",
"mode": "0640",
"owner": "root",
"size": 501,
"src": "/root/.ansible/tmp/ansible-tmp-1634816703.21-12851-219551934743358/source",
"state": "file",
"uid": 0
}
● ansible dbservers -a 'ls -l /opt'
[root@ansible ansible]# ansible dbservers -a 'ls -l /opt'
192.168.122.12 | CHANGED | rc=0 >>
总用量 14724
drwxr-xr-x 2 root root 88 10月 20 19:17 consul
drwx--x--x 4 root root 28 10月 20 19:08 containerd
-rw-r----- 1 root root 501 10月 21 19:45 fstab.bak
drwxrwxr-x 18 123456 123456 4096 10月 17 02:22 php-7.1.10
-rw-r--r-- 1 root root 15069098 8月 4 2018 php-7.1.10.tar.bz2
drwxr-xr-x. 2 root root 6 3月 26 2015 rh
● ansible dbservers -a 'cat /opt/fstab.bak'
[root@ansible ansible]# ansible dbservers -a 'cat /opt/fstab.bak'
192.168.122.12 | CHANGED | rc=0 >>
#
# /etc/fstab
# Created by anaconda on Tue Jun 8 02:45:07 2021
#
# 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
#
UUID=a001f3da-084b-4086-a845-1d9841e4e273 / xfs defaults 0 0
UUID=3c126149-e941-45da-b7b2-295bbb9d9ba3 /boot xfs defaults 0 0
UUID=cf45ed0f-c177-44b9-9874-e56eab1fefdb swap swap defaults 0 0
将helloworld写入/opt/hello.txt文件中 ● ansible dbservers -m copy -a 'content="helloworld" dest=/opt/hello.txt'
[09:10:45 root@c7-5 ~]#ansible dbservers -m copy -a 'content="helloworld" dest=/opt/hello.txt'
192.168.10.100 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "6adfb183a4a2c94a2f92dab5ade762a47889a5a1",
"dest": "/opt/hello.txt",
"gid": 0,
"group": "root",
"md5sum": "fc5e038d38a57032085441e7fe7010b0",
"mode": "0644",
"owner": "root",
"size": 10,
"src": "/root/.ansible/tmp/ansible-tmp-1639012816.68-33683-16711400272948/source",
"state": "file",
"uid": 0
}
● ansible dbservers -a 'cat /opt/hello.txt'
[09:20:17 root@c7-5 ~]#ansible dbservers -a 'cat /opt/hello.txt'
192.168.10.100 | CHANGED | rc=0 >>
helloworld
7. file模块
设置文件属性
7.1 列出指定模块的描述信息和操作动作
● ansible-doc -s file
[09:20:40 root@c7-5 ~]#ansible-doc -s file
- name: Manage files and file properties
file:
access_time: # This parameter indicates the time the file's access time should be set to. Should be `preserve'
when no modification is required, `YYYYMMDDHHMM.SS' when using
default time format, or `now'. Default is `None' meaning that
`preserve' is the default for `state=[file,directory,link,hard]'
and `now' is default for `state=touch'.
access_time_format: # When used with `access_time', indicates the time format that must be used. Based on default
Python format (see time.strftime doc).
attributes: # The attributes the resulting file or directory should have. To get supported flags look at the
man page for `chattr' on the target system. This string should
contain the attributes in the same order as the one displayed by
`lsattr'. The `=' operator is assumed as default, otherwise `+'
or `-' operators need to be included in the string.
follow: # This flag indicates that filesystem links, if they exist, should be followed. Previous to
Ansible 2.5, this was `no' by default.
force: # Force the creation of the symlinks in two cases: the source file does not exist (but will
appear later); the destination exists and is a file (so, we need
to unlink the `path' file and create symlink to the `src' file
in place of it).
......
7.2 文件属性管理
修改文件的属主属组权限等 ● ansible dbservers -m file -a 'owner=test01 group=mysql mode=644 path=/opt/fstab.bak'
[09:35:05 root@c7-5 ~]#ansible dbservers -m file -a 'owner=test01 group=mysql mode=644 path=/opt/fstab.bak'
192.168.10.100 | FAILED! => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"msg": "file (/opt/fstab.bak) is absent, cannot continue",
"path": "/opt/fstab.bak",
"state": "absent"
}
设置/opt/fstab.link为/opt/fstab.bak的链接文件 ● ansible dbservers -m file -a 'path=/opt/fstab.link src=/opt/fstab.bak state=link'
[root@ansible ansible]# ansible dbservers -m file -a 'path=/opt/fstab.link src=/opt/fstab.bak state=link'
192.168.122.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dest": "/opt/fstab.link",
"gid": 0,
"group": "root",
"mode": "0777",
"owner": "root",
"size": 14,
"src": "/opt/fstab.bak",
"state": "link",
"uid": 0
}
创建一个文件 ● ansible dbservers -m file -a "path=/opt/abc.txt state=touch"
[root@ansible ansible]# ansible dbservers -m file -a "path=/opt/abc.txt state=touch"
192.168.122.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dest": "/opt/abc.txt",
"gid": 0,
"group": "root",
"mode": "0644",
"owner": "root",
"size": 0,
"state": "file",
"uid": 0
}
删除一个文件 ● ansible dbservers -m file -a "path=/opt/abc.txt state=absent"
[root@ansible ansible]# ansible dbservers -m file -a "path=/opt/abc.txt state=absent"
192.168.122.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"path": "/opt/abc.txt",
"state": "absent"
}
8. hostname模块
用于管理远程主机上的主机名 ● ansible dbservers -m hostname -a "name=mysql01"
[root@ansible ansible]# ansible dbservers -m hostname -a "name=mysql01"
192.168.122.12 | CHANGED => {
"ansible_facts": {
"ansible_domain": "",
"ansible_fqdn": "mysql01",
"ansible_hostname": "mysql01",
"ansible_nodename": "mysql01",
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"name": "mysql01"
}
9. ping模块
检测远程主机的连通性 ● ansible all -m ping
[root@ansible ansible]# ansible all -m ping
192.168.122.12 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
192.168.122.11 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
10. yum模块
● ansible-doc -s yum
[09:35:11 root@c7-5 ~]#ansible-doc -s yum
- name: Manages packages with the `yum' package manager
yum:
allow_downgrade: # Specify if the named package and version is allowed to downgrade a maybe already installed
higher version of that package. Note that setting
allow_downgrade=True can make this module behave in a non-
idempotent way. The task could end up with a set of packages
that does not match the complete list of specified packages to
install (because dependencies between the downgraded package and
others can cause changes to the packages which were in the
earlier transaction).
autoremove: # If `yes', removes all "leaf" packages from the system that were originally installed as
dependencies of user-installed packages but which are no longer
required by any such package. Should be used alone or when state
is `absent' NOTE: This feature requires yum >= 3.4.3
(RHEL/CentOS 7+)
bugfix: # If set to `yes', and `state=latest' then only installs updates that have been marked bugfix
related.
conf_file: # The remote yum configuration file to use for the transaction.
disable_excludes: # Disable the excludes defined in YUM config files. If set to `all', disables all excludes. If
set to `main', disable excludes defined in [main] in yum.conf.
If set to `repoid', disable excludes defined for given repo id.
disable_gpg_check: # Whether to disable the GPG checking of signatures of packages being installed. Has an effect
only if state is `prese
......
安装服务 ● ansible webservers -m yum -a 'name=httpd'
[root@ansible ansible]# ansible webservers -m yum -a 'name=httpd'
192.168.122.11 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"msg": "",
"rc": 0,
"results": [
"httpd-2.4.6-67.el7.centos.x86_64 providing httpd is already installed"
]
}
卸载服务 ● ansible webservers -m yum -a 'name=httpd state=absent'
[root@ansible ansible]# ansible webservers -m yum -a 'name=httpd state=absent'
192.168.122.11 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"removed": [
"httpd"
]
},
"msg": "",
"rc": 0,
"results": [
"已加载插件:fastestmirror, langpacks\n正在解决依赖关系\n--> 正在检查事务\n---> 软件包 httpd.x86_64.0.2.4.6-67.el7.centos 将被 删除\n--> 解决依赖关系完成\n\n依赖关系解决\n\n================================================================================\n Package 架构 版本 源 大小\n================================================================================\n正在删除:\n httpd x86_64 2.4.6-67.el7.centos @local 9.4 M\n\n事务概要\n================================================================================\n移除 1 软件包\n\n安装大小:9.4 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n 正在删除 : httpd-2.4.6-67.el7.centos.x86_64 1/1 \n 验证中 : httpd-2.4.6-67.el7.centos.x86_64 1/1 \n\n删除:\n httpd.x86_64 0:2.4.6-67.el7.centos \n\n完毕!\n"
]
}
11. service/systemd 模块
用于管理远程主机上的管理服务的运行状态 ● ansible-doc -s service
[root@ansible ansible]# ansible-doc -s service
- name: Manage services
service:
arguments: # Additional arguments provided on the command line.
enabled: # Whether the service should start on boot. *At least one of state and enabled are required.*
name: # (required) Name of the service.
pattern: # If the service does not respond to the status command, name a substring to look for as would be
found in the output of the `ps' command as a stand-in for a status
result. If the string is found, the service will be assumed to be
started.
runlevel: # For OpenRC init scripts (e.g. Gentoo) only. The runlevel that this service belongs to.
sleep: # If the service is being `restarted' then sleep this many seconds between the stop and start
command. This helps to work around badly-behaving init scripts that
exit immediately after signaling a process to stop. Not all service
managers support sleep, i.e when using systemd this setting will be
ignored.
state: # `started'/`stopped' are idempotent actions that will not run commands unless necessary.
`restarted' will always bounce the service. `reloaded' will always
reload. *At least one of state and enabled are required.* Note that
reloaded will start the service if it is not already started, even
if your chosen init system wouldn't normally.
use: # The service module actually uses system specific modules, normally through auto detection, this
setting can force a specific module. Normally it uses the value of
the 'ansible_service_mgr' fact and falls back to the old 'service'
module when none matching is found.
11.1 常用参数
常用参数 | 说明 |
name | 被管理的服务名称 |
state=started\stopped\restarted | 动作包含启动关闭或者重启 |
enabled=yes\no | 表示是否设置该服务开机自启 |
runlevel | 如果设定了enabled开机自启去,则要定义在哪些运行目标下自启动 |
11.2 服务管理
查看web服务器httpd运行状态 ● ansible webservers -a 'systemctl status httpd'
[root@ansible ansible]# ansible webservers -m yum -a 'name=httpd'
[root@ansible ansible]# ansible webservers -a 'systemctl status httpd'
192.168.122.11 | FAILED | rc=3 >>
● httpd.service - The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
Active: inactive (dead)
Docs: man:httpd(8)
man:apachectl(8)
10月 21 13:36:01 client systemd[1]: Unit httpd.service cannot be reloaded because it is inactive.non-zero return code
启动httpd服务 ● ansible webservers -m service -a 'enabled=true name=httpd state=started'
[root@ansible ~]# ansible webservers -m service -a 'enabled=true name=httpd state=started'
192.168.122.11 | CHANGED => {
······
12. script 模块
实现远程批量运行本地的 shell 脚本 ● ansible-doc -s script
[root@ansible ~]# ansible-doc -s script
- name: Runs a local script on a remote node after transferring it
script:
chdir: # Change into this directory on the remote node before running the script.
cmd: # Path to the local script to run followed by optional arguments.
creates: # A filename on the remote node, when it already exists, this step will *not* be run.
decrypt: # This option controls the autodecryption of source files using vault.
executable: # Name or path of a executable to invoke the script with.
free_form: # Path to the local script file followed by optional arguments.
removes: # A filename on the remote node, when it does not exist, this step will *not* be run.
12.1 准备脚本
[root@ansible ~]# vim test.sh
#!/bin/bash
echo "hello ansible from script" > /opt/script.txt
12.2 script执行脚本
● ansible webservers -m script -a 'test.sh'
[root@ansible ~]# chmod +x test.sh
[root@ansible ~]# ansible webservers -m script -a 'test.sh'
192.168.122.11 | CHANGED => {
"changed": true,
"rc": 0,
"stderr": "Shared connection to 192.168.122.11 closed.\r\n",
"stderr_lines": [
"Shared connection to 192.168.122.11 closed."
],
"stdout": "",
"stdout_lines": []
}
[root@ansible ~]# ansible webservers -a 'cat /opt/script.txt'
192.168.122.11 | CHANGED | rc=0 >>
hello ansible from script
13. setup 模块
获取指定主机的facts信息 facts组件是用来收集被管理节点信息的,使用 setup 模块可以获取这些信息 ● ansible-doc -s setup
[root@ansible ~]# ansible-doc -s setup
- name: Gathers facts about remote hosts
setup:
fact_path: # Path used for local ansible facts (`*.fact') - files in this dir will be run (if executable) and
their results be added to `ansible_local' facts if a file is not
executable it is read. Check notes for Windows options. (from 2.1
on) File/results format can be JSON or INI-format. The default
`fact_path' can be specified in `ansible.cfg' for when setup is
automatically called as part of `gather_facts'.
filter: # If supplied, only return facts that match this shell-style (fnmatch) wildcard.
gather_subset: # If supplied, restrict the additional facts collected to the given subset. Possible values: `all',
`min', `hardware', `network', `virtual', `ohai', and `facter'. Can
specify a list of values to specify a larger subset. Values can
also be used with an initial `!' to specify that that specific
subset should not be collected. For instance:
`!hardware,!network,!virtual,!ohai,!facter'. If `!all' is specified
then only the min subset is collected. To avoid collecting even the
min subset, specify `!all,!min'. To collect only specific facts,
use `!all,!min', and specify the particular fact subsets. Use the
filter parameter if you do not want to display some collected
facts.
gather_timeout: # Set the default timeout in seconds for individual fact gathering.
13.1 获取指定主机的facts信息
● ansible webservers -m setup
[root@ansible ~]# ansible webservers -m setup
192.168.122.11 | SUCCESS => {
"ansible_facts": {
·····
13.2 过滤获取指定主机的指定facts信息
使用filter可以筛选指定的facts信息 ● ansible dbservers -m setup -a 'filter=*ipv4'
[root@ansible ~]# ansible dbservers -m setup -a 'filter=*ipv4'
192.168.122.12 | SUCCESS => {
"ansible_facts": {
"ansible_default_ipv4": {
"address": "192.168.122.12",
"alias": "ens33",
"broadcast": "192.168.122.255",
"gateway": "192.168.122.2",
"interface": "ens33",
"macaddress": "00:0c:29:55:18:bd",
"mtu": 1500,
"netmask": "255.255.255.0",
"network": "192.168.122.0",
"type": "ether"
},
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}
四、inventory 主机清单
Inventory支持对主机进行分组,每个组内可以定义多个主机,每个主机都可以定义在任何一个或多个主机组内。
1. 列表表示
如果是名称类似的主机,可以使用列表的方式标识各个主机。
[root@ansible ~]# vim /etc/ansible/hosts
[webservers]
192.168.122.11:2222
#冒号后定义远程连接端口,默认是 ssh 的 22 端口
192.168.122.1[2:5]
[dbservers]
db-[a:f].example.org
#支持匹配 a~f
2. inventory 中的变量
Inventory变量名 | 含义 |
ansible_host | ansible连接节点时的IP地址 |
ansible_port | 连接对方的端口号,ssh连接时默认为22 |
ansible_user | 连接对方主机时使用的主机名。不指定时,将使用执行ansible或ansible-playbook命令的用户 |
ansible_password | 连接时的用户的ssh密码,仅在未使用密钥对验证的情况下有效 |
ansible_ssh_private_key_file | 指定密钥认证ssh连接时的私钥文件 |
ansible_ssh_common_args | 提供给ssh、sftp、scp命令的额外参数 |
ansible_become | 允许进行权限提升 |
ansible_become_method | 指定提升权限的方式,例如可使用sudo/su/runas等方式 |
ansible_become_user | 提升为哪个用户的权限,默认提升为root |
ansible_become_password | 提升为指定用户权限时的密码 |
3. 变量
3.1 主机变量
[root@ansible ~]# vim /etc/ansible/hosts
[webservers]
192.168.122.11 ansible_port=22 ansible_user=root ansible_password=123456
3.2 组变量
[webservers:vars]
#表示为 webservers 组内所有主机定义变量
ansible_user=root
ansible_password=123456
[all:vars]
#表示为所有组内的所有主机定义变量
ansible_port=22
3.3 组嵌套
[nginx]
192.168.122.11
192.168.122.12
192.168.122.13
[apache]
192.168.122.3[0:3]
[webs:children]
#表示为 webs 主机组中包含了 nginx 组和 apache 组内的所有主机
nginx
apache
五、role 模块
1. role模块的作用
Ansible为了层次化、结构化地组织Playbook,使用了角色(roles),roles可以根据层次型结构自动装载变量文件、task以及handlers等。简单来讲,roles就是通过分别将变量、文件、任务、模块及处理器放置于单独的目录中,并可以便捷地include它们。roles一般用于基于主机构建服务的场景中,但也可以用于构建守护进程等场景中。
2. roles的目录结构
[root@ansible ansible]# tree /etc/ansible/roles/
/etc/ansible/roles/
├── mysql
│ ├── defaults
│ │ └── main.yml
│ ├── files
│ ├── handlers
│ │ └── main.yml
│ ├── meta
│ │ └── main.yml
│ ├── tasks
│ │ └── main.yml
│ ├── templates
│ └── vars
│ └── main.yml
├── nginx
│ ├── defaults
│ │ └── main.yml
│ ├── files
│ │ ├── default.conf
│ │ ├── index.php
│ │ ├── mysql.php
│ │ └── nginx.repo
│ ├── handlers
│ │ └── main.yml
│ ├── meta
│ │ └── main.yml
│ ├── tasks
│ │ └── main.yml
│ ├── templates
│ └── vars
│ └── main.yml
└── php
├── defaults
│ └── main.yml
├── files
│ ├── php-ini
│ └── www.conf
├── handlers
│ └── main.yml
├── meta
│ └── main.yml
├── tasks
│ └── main.yml
├── templates
└── vars
└── main.yml
3. roles内各个目录含义解释
●files 用来存放由 copy 模块或 script 模块调用的文件。
●templates 用来存放 jinjia2 模板,template 模块会自动在此目录中寻找 jinjia2 模板文件。
●tasks 此目录应当包含一个 main.yml 文件,用于定义此角色的任务列表,此文件可以使用 include 包含其它的位于此目录的 task 文件。
●handlers 此目录应当包含一个 main.yml 文件,用于定义此角色中触发条件时执行的动作。
●vars 此目录应当包含一个 main.yml 文件,用于定义此角色用到的变量。
●defaults 此目录应当包含一个 main.yml 文件,用于为当前角色设定默认变量。
●meta 此目录应当包含一个 main.yml 文件,用于定义此角色的特殊设定及其依赖关系。
4. roles创建lamp
4.1 创建以roles命名的目录
yum装完默认已创建
[root@ansible ansible]# ls
ansible.cfg hosts roles
[root@ansible ansible]# pwd
/etc/ansible
[root@ansible ansible]# cd roles
[root@ansible roles]# ll
总用量 0
4.2 创建全局变量目录
[root@ansible roles]# mkdir -p /etc/ansible/group_vars/
[root@ansible roles]# touch /etc/ansible/group_vars/all
#文件名自己定义,使用的时候需注意
4.3 在roles目录中分别创建以个角色名称命令的目录
[root@ansible roles]# mkdir /etc/ansible/roles/nginx
[root@ansible roles]# mkdir /etc/ansible/roles/mysql
[root@ansible roles]# mkdir /etc/ansible/roles/php
4.4 在每个角色命令的目录中创建工作目录
在每个角色命令的目录中分别创建files、handlers、tasks、templates、meta、defaults和vars目录,用不到的目录可以创建为空目录,也可以不创建
[root@ansible roles]# mkdir /etc/ansible/roles/nginx/{files,templates,tasks,handlers,vars,defaults,meta}
[root@ansible roles]# mkdir /etc/ansible/roles/mysql/{files,templates,tasks,handlers,vars,defaults,meta}
[root@ansible roles]# mkdir /etc/ansible/roles/php/{files,templates,tasks,handlers,vars,defaults,meta}
4.5 创建main.yml文件
在每个角色的 handlers、tasks、meta、defaults、vars 目录下创建 main.yml 文件,千万不能自定义文件名
[root@ansible roles]# touch /etc/ansible/roles/nginx/{defaults,vars,tasks,meta,handlers}/main.yml
[root@ansible roles]# touch /etc/ansible/roles/mysql/{defaults,vars,tasks,meta,handlers}/main.yml
[root@ansible roles]# touch /etc/ansible/roles/php/{defaults,vars,tasks,meta,handlers}/main.yml
4.6 修改site.yml文件,针对不用主机去调用不同的角色
[root@ansible roles]# vim /etc/ansible/site.yml
---
- hosts: webservers
remote_user: root
roles:
- nginx
- hosts: dbservers
remote_user: root
roles:
- mysql
- hosts: phpservers
remote_user: root
roles:
- php
4.7 修改主机清单
[webservers]
192.168.122.11
[dbservers]
192.168.122.12
[phpservers]
192.168.122.13
4.8 nginx模块
4.8.1 编写任务脚本
[root@ansible ansible]# vim /etc/ansible/roles/nginx/tasks/main.yml
---
- name: create nginx_yum
copy: src=/etc/ansible/roles/nginx/files/nginx.repo dest=/etc/yum.repos.d/nginx.repo
- name: install apache
yum: name={{pkg}} state=latest
- name: modify configuration file
copy: src=/etc/ansible/roles/nginx/files/default.conf dest=/etc/nginx/conf.d/default.conf
- name: start apache
service: enabled=true name={{svc}} state=started
- name: create php_test web
copy: src=/etc/ansible/roles/nginx/files/index.php dest=/usr/share/nginx/html/index.php
- name: create mysql_test web
copy: src=/etc/ansible/roles/nginx/files/mysql.php dest=/usr/share/nginx/html/mysql.php
- name: install nfs
yum: name=nfs-utils state=present
- name: nfs_share
copy: content="/usr/share/nginx/html/ 192.168.122.0/24(rw)" dest=/etc/exports
- name: start nfs
service: name=nfs state=restarted enabled=yes
4.8.2 定义变量
可以定义在全局变量中,也可以定义在roles角色变量中,一般定义在角色变量中
[root@ansible ansible]# vim /etc/ansible/roles/nginx/vars/main.yml
pkg: nginx
svc: nginx
4.8.3 准备nginx.repo文件
[root@ansible files]# vim /etc/ansible/roles/nginx/files/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1
4.8.4 准备nginx配置文件default.conf
取消location ~ .php$域的注释,
修改fastcgi_pass为php的IP和端口
修改fastcgi_param为SCRIPT_FILENAME/usr/share/nginx/html$fastcgi_script_name;
[root@ansible files]# egrep -v ^' '*# /etc/ansible/roles/nginx/files/default.conf | grep -v '^$'
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
location ~ \.php$ {
root html;
fastcgi_pass 192.168.122.13:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html$fastcgi_script_name;
include fastcgi_params;
}
}
4.8.5 准备测试网页index.php
index.php(用于测试php与nginx的连接)
[root@ansible files]# vim /etc/ansible/roles/nginx/files/index.php
<?php
phpinfo();
?>
mysql.php(用于测试php与mysql的连接)
[root@ansible files]# vim /etc/ansible/roles/nginx/files/mysql.php
<?php
$link=mysqli_connect('192.168.122.12','root','Admin@123');
if($link) echo "<h1>Success!!</h1>";
else echo "Fail!!";
?>
4.9 mysql模块
编写任务脚本
[root@ansible ansible]# vim /etc/ansible/roles/mysql/tasks/main.yml
---
- name: clean mariadb
yum: name=mariadb state=absent
- name: get mysql download source
command: wget -i -c http://dev.mysql.com/get/mysql57-community-release-el7-10.noarch.rpm
#get_url: url=http://dev.mysql.com/get/mysql57-community-release-el7-10.noarch.rpm dest=/etc/yum.repos.d/mysql57-community-release-el7-10.noarch.rpm
- name: install mysql5.7
yum: name=mysql57-community-release-el7-10.noarch.rpm
- name: install mysql-community-server
yum: name=mysql-community-server state=latest
- name: start mysql
service: enabled=true name=mysqld state=started
- name: change passwd
shell: mysqladmin -u root -p"$(grep "password" /var/log/mysqld.log | awk 'NR==1{print $NF}')" password 'Admin@123'
ignore_errors: yes
- name: grant pribileges
command: mysql -uroot -p"Admin@123" -e 'grant all privileges on *.* to root@"%" identified by "Admin@123" with grant option;'
- name: flush privileges
command: mysql -uroot -p"Admin@123" -e 'flush privileges;'
- name: stop auto-update
yum: name=mysql57-community-release-el7-10.noarch state=absent
- name: install nfs
yum: name=nfs-utils state=present
- name: nfs_share
copy: content="/var/lib/mysql/ 192.168.122.0/24(rw)" dest=/etc/exports
- name: start nfs
service: name=nfs state=restarted enabled=yes
4.10 php模块
4.10.1 编写任务脚本
[root@ansible ansible]# vim /etc/ansible/roles/php/tasks/main.yml
---
- name: get epel download source
command: rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
- name: get webtatic download source
command: rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
- name: install php7.2
command: yum -y install php72w php72w-cli php72w-common php72w-devel php72w-embedded php72w-gd php72w-mbstring php72w-pdo php72w-xml php72w-fpm php72w-mysqlnd php72w-opcache php72w-redis
- name: modify www.conf
copy: src=/etc/ansible/roles/php/files/www.conf dest=/etc/php-fpm.d/www.conf
- name: modify php.ini
copy: src=/etc/ansible/roles/php/files/php-ini dest=/etc/php.ini
- name: create nginx directory
file: path=/usr/share/nginx/html/ state=directory mode=777 recurse=yes
- name: create mysql directory
file: path=/var/lib/mysql/ state=directory mode=777 recurse=yes
- name: mount nginx
mount: src=192.168.122.11:/usr/share/nginx/html/ path=/usr/share/nginx/html/ fstype=nfs state=mounted
- name: mounnt mysql
mount: src=192.168.122.12:/var/lib/mysql/ path=/var/lib/mysql/ fstype=nfs state=mounted
- name: start php
service: name=php-fpm enabled=true state=started
4.10.2 准备www.conf文件
修改listen监听IP和端口为0.0.0.0:9000 修改listen.allowed_clients = 192.168.122.11,设置为nginx的IP地址
[root@ansible files]# egrep -v "^;|^$" /etc/ansible/roles/php/files/www.conf
[www]
user = apache
group = apache
listen = 0.0.0.0:9000
listen.allowed_clients = 192.168.122.11
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
slowlog = /var/log/php-fpm/www-slow.log
php_admin_value[error_log] = /var/log/php-fpm/www-error.log
php_admin_flag[log_errors] = on
php_value[session.save_handler] = files
php_value[session.save_path] = /var/lib/php/session
php_value[soap.wsdl_cache_dir] = /var/lib/php/wsdlcache
4.10.3 准备php.ini文件
877行,修改date.timezone = Asia/Shanghai 1097行,修改mysqli.default_socket = /var/lib/mysql/mysql.sock
[root@ansible files]# egrep -v "^;|^$" /etc/ansible/roles/php/files/php-ini
[PHP]
engine = On
short_open_tag = Off
precision = 14
output_buffering = 4096
zlib.output_compression = Off
implicit_flush = Off
unserialize_callback_func =
serialize_precision = 17
disable_functions =
disable_classes =
zend.enable_gc = On
expose_php = On
max_execution_time = 30
max_input_time = 60
memory_limit = 128M
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
display_errors = Off
display_startup_errors = Off
log_errors = On
log_errors_max_len = 1024
ignore_repeated_errors = Off
ignore_repeated_source = Off
report_memleaks = On
track_errors = Off
html_errors = On
variables_order = "GPCS"
request_order = "GP"
register_argc_argv = Off
auto_globals_jit = On
post_max_size = 8M
auto_prepend_file =
auto_append_file =
default_mimetype = "text/html"
default_charset = "UTF-8"
doc_root =
user_dir =
enable_dl = Off
file_uploads = On
upload_max_filesize = 2M
max_file_uploads = 20
allow_url_fopen = On
allow_url_include = Off
default_socket_timeout = 60
[CLI Server]
cli_server.color = On
[Date]
date.timezone = Asia/Shanghai
[filter]
[iconv]
[intl]
[sqlite]
[sqlite3]
[Pcre]
[Pdo]
[Pdo_mysql]
pdo_mysql.cache_size = 2000
pdo_mysql.default_socket=
[Phar]
[mail function]
sendmail_path = /usr/sbin/sendmail -t -i
mail.add_x_header = On
[SQL]
sql.safe_mode = Off
[ODBC]
odbc.allow_persistent = On
odbc.check_persistent = On
odbc.max_persistent = -1
odbc.max_links = -1
odbc.defaultlrl = 4096
odbc.defaultbinmode = 1
[Interbase]
ibase.allow_persistent = 1
ibase.max_persistent = -1
ibase.max_links = -1
ibase.timestampformat = "%Y-%m-%d %H:%M:%S"
ibase.dateformat = "%Y-%m-%d"
ibase.timeformat = "%H:%M:%S"
[MySQLi]
mysqli.max_persistent = -1
mysqli.allow_persistent = On
mysqli.max_links = -1
mysqli.cache_size = 2000
mysqli.default_port = 3306
mysqli.default_socket = /var/lib/mysql/mysql.sock
mysqli.default_host =
mysqli.default_user =
mysqli.default_pw =
mysqli.reconnect = Off
[mysqlnd]
mysqlnd.collect_statistics = On
mysqlnd.collect_memory_statistics = Off
[OCI8]
[PostgreSQL]
pgsql.allow_persistent = On
pgsql.auto_reset_persistent = Off
pgsql.max_persistent = -1
pgsql.max_links = -1
pgsql.ignore_notice = 0
pgsql.log_notice = 0
[bcmath]
bcmath.scale = 0
[browscap]
[Session]
session.save_handler = files
session.use_strict_mode = 0
session.use_cookies = 1
session.use_only_cookies = 1
session.name = PHPSESSID
session.auto_start = 0
session.cookie_lifetime = 0
session.cookie_path = /
session.cookie_domain =
session.cookie_httponly =
session.serialize_handler = php
session.gc_probability = 1
session.gc_divisor = 1000
session.gc_maxlifetime = 1440
session.referer_check =
session.cache_limiter = nocache
session.cache_expire = 180
session.use_trans_sid = 0
session.hash_function = 0
session.hash_bits_per_character = 5
url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=fakeentry"
[Assertion]
zend.assertions = -1
[mbstring]
[gd]
[exif]
[Tidy]
tidy.clean_output = Off
[soap]
soap.wsdl_cache_enabled=1
soap.wsdl_cache_dir="/tmp"
soap.wsdl_cache_ttl=86400
soap.wsdl_cache_limit = 5
[sysvshm]
[ldap]
ldap.max_links = -1
[mcrypt]
[dba]
[curl]
[openssl]
4.11 执行site.yml脚本
[root@ansible roles]# cd /etc/ansible
[root@ansible ansible]# ansible-playbook site.yml
4.12 访问测试网页
访问192.168.122.11/index.php,测试php与nginx的接连
访问192.168.122.11/mysql.php,测试php与mysql的连接
六、ansible-playbook
1. playbook的组成
playbooks 本身由以下各部分组成 (1)Tasks:任务,即通过 task 调用 ansible 的模板将多个操作组织在一个 playbook 中运行 (2)Variables:变量 (3)Templates:模板 (4)Handlers:处理器,当changed状态条件满足时,(notify)触发执行的操作 (5)Roles:角色
2. 剧本示例test1
2.1 剧本制作
[root@ansible ansible]# vim test1.yaml
---
#yaml文件以---开头,以表明这是一个yaml文件,可省略
- name: first test
#定义一个play的名称,可省略
gather_facts: false
#设置不进行facts信息收集,这可以加快执行速度,可省略
hosts: webservers
#指定要执行任务的被管理主机组,如多个主机组用冒号分隔
remote_user: root
#指定被管理主机上执行任务的用户
tasks:
#定义任务列表,任务列表中的各任务按次序逐个在hosts中指定的主机上执行
- name: test connection
#自定义任务名称
ping:
#使用 module: [options] 格式来定义一个任务
- name: disable selinux
command: '/sbin/setenforce 0'
#command模块和shell模块无需使用key=value格式
ignore_errors: True
#如执行命令的返回值不为0,就会报错,tasks停止,可使用ignore_errors忽略失败的任务
- name: disable firewalld
service: name=firewalld state=stopped
#使用 module: options 格式来定义任务,option使用key=value格式
- name: install httpd
yum: name=httpd state=latest
- name: install configuration file for httpd
copy: src=/root/ansible/httpd.conf dest=/etc/httpd/conf/httpd.conf
#这里需要一个事先准备好的/opt/httpd.conf文件
notify: "restart httpd"
#如以上操作后为changed的状态时,会通过notify指定的名称触发对应名称的handlers操作
- name: start httpd service
service: enabled=true name=httpd state=started
handlers:
#handlers中定义的就是任务,此处handlers中的任务使用的是service模块
- name: restart httpd
#notify和handlers中任务的名称必须一致
service: name=httpd state=restarted
无注释
---
- name: first test
gather_facts: false
hosts: webservers
remote_user: root
tasks:
- name: test connection
ping:
- name: disable selinux
command: '/sbin/setenforce 0'
ignore_errors: True
- name: disable firewalld
service: name=firewalld state=stopped
- name: install httpd
yum: name=httpd state=latest
- name: install configuration file for httpd
copy: src=/root/ansible/httpd.conf dest=/etc/httpd/conf/httpd.conf
notify: "restart httpd"
- name: start httpd service
service: enabled=true name=httpd state=started
handlers:
- name: restart httpd
service: name=httpd state=restarted
Ansible在执行完某个任务之后并不会立即去执行对应的handler,而是在当前play中所有普通任务都执行完后再去执行handler,这样的好处是可以多次触发notify(通知),但最后只执行一次对应的handler,从而避免多次重启。
2.2 准备http.conf
[root@ansible ansible]# vim httpd.conf
#42行,指定端口
Listen 8080
#95行,指定域名
ServerName www.test.com:8080
2.3 运行剧本
ansible-playbook test1.yaml
[root@ansible ansible]# ansible-playbook test1.yaml
PLAY [first test] ****************************************************************************************************************
TASK [test connection] ***********************************************************************************************************
ok: [192.168.122.11]
TASK [disable selinux] ***********************************************************************************************************
fatal: [192.168.122.11]: FAILED! => {"changed": true, "cmd": ["/sbin/setenforce", "0"], "delta": "0:00:00.001853", "end": "2021-10-22 16:10:22.925768", "msg": "non-zero return code", "rc": 1, "start": "2021-10-22 16:10:22.923915", "stderr": "/sbin/setenforce: SELinux is disabled", "stderr_lines": ["/sbin/setenforce: SELinux is disabled"], "stdout": "", "stdout_lines": []}
...ignoring
TASK [disable firewalld] *********************************************************************************************************
ok: [192.168.122.11]
TASK [install httpd] *************************************************************************************************************
ok: [192.168.122.11]
TASK [install configuration file for httpd] **************************************************************************************
changed: [192.168.122.11]
TASK [start httpd service] *******************************************************************************************************
changed: [192.168.122.11]
RUNNING HANDLER [restart httpd] **************************************************************************************************
changed: [192.168.122.11]
PLAY RECAP ***********************************************************************************************************************
192.168.122.11 : ok=7 changed=4 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1
2.4 查看webserbers服务器
[root@ansible ansible]# ansible webservers -m shell -a 'netstat -natp | grep httpd'
192.168.122.11 | CHANGED | rc=0 >>
tcp6 0 0 :::8080 :::* LISTEN 26582/httpd
2.5 补充参数
-k(-ask-pass):用来交互输入ssh密码 -K(-ask-become-pass):用来交互输入sudo密码 -u:指定用户 ansible-playbook test1.yaml --syntax-check 检查yaml文件的语法是否正确
[root@ansible ansible]# ansible-playbook test1.yaml --syntax-check
playbook: test1.yaml
ansible-playbook test1.yaml --list-task 检查tasks任务
[root@ansible ansible]# ansible-playbook test1.yaml --list-task
playbook: test1.yaml
play #1 (webservers): first test TAGS: []
tasks:
test connection TAGS: []
disable selinux TAGS: []
disable firewalld TAGS: []
install httpd TAGS: []
install configuration file for httpd TAGS: []
start httpd service TAGS: []
ansible-playbook test1.yaml --list-hosts 检查生效的主机
[root@ansible ansible]# ansible-playbook test1.yaml --list-hosts
playbook: test1.yaml
play #1 (webservers): first play TAGS: []
pattern: [u'webservers']
hosts (1):
192.168.122.11
ansible-playbook test1.yaml --start-at-task='install httpd' 指定从某个task开始运行
[root@ansible ansible]# ansible-playbook test1.yaml --start-at-task='install httpd'
PLAY [first test] ****************************************************************************************************************
TASK [install httpd] *************************************************************************************************************
changed: [192.168.122.11]
TASK [install configuration file for httpd] **************************************************************************************
changed: [192.168.122.11]
TASK [start httpd service] *******************************************************************************************************
changed: [192.168.122.11]
RUNNING HANDLER [restart httpd] **************************************************************************************************
changed: [192.168.122.11]
PLAY RECAP ***********************************************************************************************************************
192.168.122.11 : ok=4 changed=4 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
3. 剧本示例test2--定义、引用变量
3.1 剧本制作
[root@ansible ansible]# vim test2.yaml
---
- name: second test
hosts: dbservers
remote_user: root
vars:
#定义变量
- groupname: mysql
#格式为 key: value
- username: nginx
tasks:
- name: create group
group: name={{groupname}} system=yes gid=306
#使用 {{key}} 引用变量的值
- name: create user
user: name={{username}} uid=306 group={{groupname}}
- name: copy file
copy: content="{{ansible_default_ipv4}}" dest=/opt/vars.txt
#在setup模块中可以获取facts变量信息
3.2 运行剧本
[root@ansible ansible]# ansible-playbook test2.yaml
PLAY [second play] ***************************************************************************************************************
TASK [Gathering Facts] ***********************************************************************************************************
ok: [192.168.122.12]
TASK [create group] **************************************************************************************************************
changed: [192.168.122.12]
TASK [create user] ***************************************************************************************************************
changed: [192.168.122.12]
TASK [copy file] *****************************************************************************************************************
changed: [192.168.122.12]
PLAY RECAP ***********************************************************************************************************************
192.168.122.12 : ok=4 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
3.3 查看dbservers服务器
[root@ansible ansible]# ansible dbservers -a 'grep "mysql" /etc/group'
192.168.122.12 | CHANGED | rc=0 >>
mysql:x:306:
[root@ansible ansible]# ansible dbservers -a 'grep "nginx" /etc/passwd'
192.168.122.12 | CHANGED | rc=0 >>
nginx:x:306:306::/home/nginx:/sbin/nologin
[root@ansible ansible]# ansible dbservers -a 'cat /opt/vars.txt'
192.168.122.12 | CHANGED | rc=0 >>
{"macaddress": "00:0c:29:55:18:bd", "network": "192.168.122.0", "mtu": 1500, "broadcast": "192.168.122.255", "alias": "ens33", "netmask": "255.255.255.0", "address": "192.168.122.12", "interface": "ens33", "type": "ether", "gateway": "192.168.122.2"}
3.4 修改剧本中的变量设定
删除dbservers中的mysql组和nginx用户以及/opt/var.txt
[root@ansible ansible]# ansible dbservers -a 'userdel -r nginx'
192.168.122.12 | CHANGED | rc=0 >>
userdel:组“nginx”没有移除,因为它不是用户 nginx 的主组
[root@ansible ansible]# ansible dbservers -a 'groupdel mysql'
192.168.122.12 | CHANGED | rc=0 >>
[root@ansible ansible]# ansible dbservers -a 'rm -rf /opt/vars.txt'
[WARNING]: Consider using the file module with state=absent rather than running 'rm'. 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.122.12 | CHANGED | rc=0 >>
确认用户、组以及文件已删除
[root@ansible ansible]# ansible dbservers -a 'grep "nginx" /etc/passwd'
192.168.122.12 | FAILED | rc=1 >>
non-zero return code
[root@ansible ansible]# ansible dbservers -a 'grep "mysql" /etc/group'
192.168.122.12 | FAILED | rc=1 >>
non-zero return code
[root@ansible ansible]# ansible dbservers -a 'cat /opt/vars.txt'
192.168.122.12 | FAILED | rc=1 >>
cat: /opt/vars.txt: 没有那个文件或目录non-zero return code
删除/注释“- username: nginx”变量
[root@ansible ansible]# vim test2.yaml
---
- name: second test
hosts: dbservers
remote_user: root
vars:
- groupname: mysql
# - username: nginx
#删除或注释username变量
tasks:
- name: create group
group: name={{groupname}} system=yes gid=306
- name: create user
user: name={{username}} uid=306 group={{groupname}}
- name: copy file
copy: content="{{ansible_default_ipv4}}" dest=/opt/vars.txt
3.5 在命令行定义变量运行剧本
[root@ansible ansible]# ansible-playbook test2.yaml -e "username=nginx"
PLAY [second play] ***************************************************************************************************************
TASK [Gathering Facts] ***********************************************************************************************************
ok: [192.168.122.12]
TASK [create group] **************************************************************************************************************
changed: [192.168.122.12]
TASK [create user] ***************************************************************************************************************
changed: [192.168.122.12]
TASK [copy file] *****************************************************************************************************************
changed: [192.168.122.12]
PLAY RECAP ***********************************************************************************************************************
192.168.122.12 : ok=4 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
3.6 查看dbservers服务器
[root@ansible ansible]# ansible dbservers -a 'grep "nginx" /etc/passwd'
192.168.122.12 | CHANGED | rc=0 >>
nginx:x:306:306::/home/nginx:/bin/bash
[root@ansible ansible]# ansible dbservers -a 'grep "mysql" /etc/group'
192.168.122.12 | CHANGED | rc=0 >>
mysql:x:306:
[root@ansible ansible]# ansible dbservers -a 'cat /opt/vars.txt'
192.168.122.12 | CHANGED | rc=0 >>
{"macaddress": "00:0c:29:55:18:bd", "network": "192.168.122.0", "mtu": 1500, "broadcast": "192.168.122.255", "alias": "ens33", "netmask": "255.255.255.0", "address": "192.168.122.12", "interface": "ens33", "type": "ether", "gateway": "192.168.122.2"}
4. 剧本示例test3--指定远程主机sudo切换用户
[root@ansible ansible]# vim test3.yaml
---
- hosts: dbservers
remote_user: zhangsan
become: yes
#2.6版本以后的参数,之前是sudo,意思为切换用户运行
become_user: root
#指定sudo用户为root
执行playbook时:ansible-playbook test3.yaml -K <密码>
5. 剧本示例test4--when条件判断
在Ansible中,提供的唯一一个通用的条件判断是when指令,当when指令的值为true时,则该任务执行,否则不执行该任务。 when一个比较常见的应用场景是实现跳过某个主机不执行任务或者只有满足条件的主机执行任务
[root@ansible ansible]# vim test4.yaml
---
- hosts: all
remote_user: root
tasks:
- name: shutdown host
command: /sbin/shutdown -r now
when: ansible_default_ipv4.address == "192.168.122.12"
#when指令中的变量名不需要手动加上{{}}
#或者使用
# when: inventory_hostname == "<主机名>"
执行
[root@ansible ansible]# ansible-playbook test4.yaml
PLAY [all] ***********************************************************************************************************************
TASK [Gathering Facts] ***********************************************************************************************************
ok: [192.168.122.11]
ok: [192.168.122.12]
TASK [shutdown host] *************************************************************************************************************
skipping: [192.168.122.11]
fatal: [192.168.122.12]: FAILED! => {"msg": "Failed to connect to the host via ssh: ssh_exchange_identification: read: Connection reset by peer"}
PLAY RECAP ***********************************************************************************************************************
192.168.122.11 : ok=1 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0
192.168.122.12 : ok=1 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
执行后,仅有指定主机重启,执行ping模块查看
[root@ansible ansible]# ansible all -m ping
192.168.122.11 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
192.168.122.12 | UNREACHABLE! => {
"changed": false,
"msg": "Failed to connect to the host via ssh: ssh: connect to host 192.168.122.12 port 22: Connection timed out",
"unreachable": true
}
6. 剧本示例test5--迭代
Ansible提供了很多种循环结构,一般都命名为with_items,作用等同于 loop 循环。
[root@ansible ansible]# vim test5.yaml
---
- name: test5
hosts: all
gather_facts: false
tasks:
- name: create directories
file:
path: "{{item}}"
state: directory
with_items:
#等同于 loop:
- /test/test1
- /test/test2
- name: add users
user: name={{item.name}} state=present groups={{item.groups}}
with_items:
- name: test1
groups: test
- name: test2
groups: root
#或使用以下格式
# with_items:
# - {name:'test1', groups:'test'}
# - {name:'test2', groups:'root'}
执行
[root@ansible ansible]# ansible-playbook test5.yaml
PLAY [test5] *********************************************************************************************************************
TASK [create directories] ********************************************************************************************************
changed: [192.168.122.12] => (item=/test/test1)
changed: [192.168.122.11] => (item=/test/test1)
changed: [192.168.122.12] => (item=/test/test2)
changed: [192.168.122.11] => (item=/test/test2)
TASK [add users] *****************************************************************************************************************
changed: [192.168.122.12] => (item={u'name': u'test1', u'groups': u'test'})
changed: [192.168.122.11] => (item={u'name': u'test1', u'groups': u'test'})
ok: [192.168.122.12] => (item={u'name': u'test2', u'groups': u'root'})
changed: [192.168.122.11] => (item={u'name': u'test2', u'groups': u'root'})
PLAY RECAP ***********************************************************************************************************************
192.168.122.11 : ok=2 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
192.168.122.12 : ok=2 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
查看验证
[root@ansible ansible]# ansible all -a "ls -l /test/"
192.168.122.12 | CHANGED | rc=0 >>
总用量 0
drwxr-xr-x 2 root root 6 10月 24 15:54 test1
drwxr-xr-x 2 root root 6 10月 24 15:54 test2
192.168.122.11 | CHANGED | rc=0 >>
总用量 0
drwxr-xr-x 2 root root 6 10月 24 15:54 test1
drwxr-xr-x 2 root root 6 10月 24 15:54 test2
[root@ansible ansible]# ansible all -m shell -a "id test1"
192.168.122.11 | CHANGED | rc=0 >>
uid=1002(test1) gid=1002(test1) 组=1002(test1),1001(test)
192.168.122.12 | CHANGED | rc=0 >>
uid=1001(test1) gid=1002(test1) 组=1002(test1),1004(test)
[root@ansible ansible]# ansible all -m shell -a "id test2"
192.168.122.12 | CHANGED | rc=0 >>
uid=1002(test2) gid=1003(test2) 组=1003(test2),0(root)
192.168.122.11 | CHANGED | rc=0 >>
uid=1003(test2) gid=1003(test2) 组=1003(test2),0(root)
7. Template模块
Jinja是基于Python的模块引擎。Template类是Jinja的一个重要组件,可以看做是一个编译过的模板文件,用来产生目标文本,传递Python的变量给模板去替换模板中的标记。
7.1 准备template模板文件
先准备一个以.j2为后缀的template模板文件,设置引用的变量 模板文件使用test1曾用的httpd.conf配置文件
[root@ansible ansible]# cp httpd.conf httpd.conf.j2
[root@ansible ansible]# vim httpd.conf.j2
##42行,修改
Listen {{http_port}}
##95行,修改
ServerName {{server_name}}
##119行,修改
DocumentRoot "{{root_dir}}"
##124行,修改
<Directory "{{root_dir}}">
7.2 修改主机清单文件
修改主机清单文件,使用主机变量定义一个变量名相同,而值不同的变量
[root@ansible ansible]# vim /etc/ansible/hosts
[webservers]
192.168.122.11 http_port=192.168.122.11:80 server_name=www.test1.com:80 root_dir=/etc/httpd/htdocs
[dbservers]
192.168.122.12 http_port=192.168.122.12:80 server_name=www.test2.com:80 root_dir=/etc/httpd/htdocs
7.3 编写playbook
[root@ansible ansible]# vim test6.yaml
---
- hosts: all
remote_user: root
vars:
- package: httpd
- service: httpd
tasks:
- name: install httpd package
yum: name={{package}} state=latest
- name: install configure file
template: src=/root/ansible/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
#使用template模板
notify:
- restart httpd
- name: create root dir
file: path=/etc/httpd/htdocs state=directory
- name: start httpd server
service: name={{service}} enabled=true state=started
handlers:
- name: restart httpd
service: name={{service}} state=restarted
7.4 执行playbook
[root@ansible ansible]# ansible-playbook test6.yaml
PLAY [all] ***********************************************************************************************************************
TASK [Gathering Facts] ***********************************************************************************************************
ok: [192.168.122.11]
ok: [192.168.122.12]
TASK [install httpd package] *****************************************************************************************************
ok: [192.168.122.11]
ok: [192.168.122.12]
TASK [install configure file] ****************************************************************************************************
changed: [192.168.122.12]
changed: [192.168.122.11]
TASK [create root dir] ***********************************************************************************************************
changed: [192.168.122.12]
changed: [192.168.122.11]
TASK [start httpd server] ********************************************************************************************************
ok: [192.168.122.11]
changed: [192.168.122.12]
RUNNING HANDLER [restart httpd] **************************************************************************************************
changed: [192.168.122.12]
changed: [192.168.122.11]
PLAY RECAP ***********************************************************************************************************************
192.168.122.11 : ok=6 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
192.168.122.12 : ok=6 changed=4 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
7.5 制作测试网页
[root@ansible ansible]# ansible 192.168.122.11 -m shell -a "echo 'this is test1 template test' > /etc/httpd/htdocs/index.html"
192.168.122.11 | CHANGED | rc=0 >>
[root@ansible ansible]# ansible 192.168.122.12 -m shell -a "echo 'this is test2 template test' > /etc/httpd/htdocs/index.html"
192.168.122.12 | CHANGED | rc=0 >>
7.6 访问测试
[root@ansible ansible]# curl 192.168.122.11
this is test1 template test
[root@ansible ansible]# curl 192.168.122.12
this is test2 template test
[root@ansible ansible]# echo '192.168.122.11 www.test1.com' >> /etc/hosts
[root@ansible ansible]# echo '192.168.122.11 www.test2.com' >> /etc/hosts
[root@ansible ansible]# curl www.test1.com
this is test1 template test
[root@ansible ansible]# curl www.test2.com
this is test2 template test
8. tags模块
可以在一个playbook中为某个或某些任务定义“标签”,在执行此playbook时通过ansible-playbook命令使用--tags选项能实现仅运行指定的tasks。 playbook还提供了一个特殊的tags为always。作用就是当使用always当tags的task时,无论执行哪一个tags时,定义有always的tags都会执行。
8.1 编写脚本
[root@ansible ansible]# vim test7.yaml
---
- hosts: webservers
remote_user: root
tasks:
- name: mkdir directory
file: path=/opt/test/ state=directory
tags:
- always
- name: touch file
file: path=/opt/test/testhost state=touch
tags:
- test1
- all
- name: copy hosts file
copy: src=/etc/hosts dest=/opt/test/hosts
tags:
- test2
- all
8.2 执行tags="test1"
[root@ansible ansible]# ansible-playbook test7.yaml --tags="test1"
PLAY [webservers] ****************************************************************************************************************
TASK [Gathering Facts] ***********************************************************************************************************
ok: [192.168.122.11]
TASK [mkdir directory] ***********************************************************************************************************
changed: [192.168.122.11]
TASK [touch file] ****************************************************************************************************************
changed: [192.168.122.11]
PLAY RECAP ***********************************************************************************************************************
192.168.122.11 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
验证
[root@ansible ansible]# ansible webservers -a "ls -l /opt/test/"
192.168.122.11 | CHANGED | rc=0 >>
总用量 0
-rw-r--r-- 1 root root 0 10月 25 12:14 testhost
8.3 执行tags="test2"
删除文件夹
[root@ansible ansible]# ansible webservers -m file -a "path=/opt/test/ state=absent"
192.168.122.11 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"path": "/opt/test/",
"state": "absent"
}
[root@ansible ansible]# ansible webservers -a "ls -l /opt/test/"
192.168.122.11 | FAILED | rc=2 >>
ls: 无法访问/opt/test/: 没有那个文件或目录non-zero return code
执行tags="test2"
[root@ansible ansible]# ansible-playbook test7.yaml --tags="test2"
PLAY [webservers] ****************************************************************************************************************
TASK [Gathering Facts] ***********************************************************************************************************
ok: [192.168.122.11]
TASK [mkdir directory] ***********************************************************************************************************
changed: [192.168.122.11]
TASK [copy hosts file] ***********************************************************************************************************
changed: [192.168.122.11]
PLAY RECAP ***********************************************************************************************************************
192.168.122.11 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
验证
[root@ansible ansible]# ansible webservers -a "ls -l /opt/test/"
192.168.122.11 | CHANGED | rc=0 >>
总用量 4
-rw-r--r-- 1 root root 233 10月 25 12:24 hosts
8.4 执行tags="all"
删除文件夹
[root@ansible ansible]# ansible webservers -m file -a "path=/opt/test/ state=absent"
192.168.122.11 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"path": "/opt/test/",
"state": "absent"
}
[root@ansible ansible]# ansible webservers -a "ls -l /opt/test/"
192.168.122.11 | FAILED | rc=2 >>
ls: 无法访问/opt/test/: 没有那个文件或目录non-zero return code
执行tags="all"
[root@ansible ansible]# ansible-playbook test7.yaml --tags="all"
PLAY [webservers] ****************************************************************************************************************
TASK [Gathering Facts] ***********************************************************************************************************
ok: [192.168.122.11]
TASK [mkdir directory] ***********************************************************************************************************
changed: [192.168.122.11]
TASK [touch file] ****************************************************************************************************************
changed: [192.168.122.11]
TASK [copy hosts file] ***********************************************************************************************************
changed: [192.168.122.11]
PLAY RECAP ***********************************************************************************************************************
192.168.122.11 : ok=4 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
验证
[root@ansible ansible]# ansible webservers -a "ls -l /opt/test/"
192.168.122.11 | CHANGED | rc=0 >>
总用量 4
-rw-r--r-- 1 root root 233 10月 25 12:27 hosts
-rw-r--r-- 1 root root 0 10月 25 12:27 testhost
https://www.cnblogs.com/dingcong1201/p/15456507.html
https://www.cnblogs.com/dingcong1201/p/15438653.html
https://www.cnblogs.com/keerya/p/7987886.html