Ansible自动化运维工具及其常用模块
阅读原文时间:2023年07月08日阅读:6

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将临时文件发给远程的客户端执行并返回结果,执行结束后自动删除

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 <组名> -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:判断指定文件是否存在,如果存在,执行后面的操作

[root@ansible ansible]# ansible all -m command -a "chdir=/home ls ./"
123456
192.168.122.12 | CHANGED | rc=0 >>
123456

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
[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 -n 1 'tail /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'

[root@ansible ansible]# ansible dbservers -m copy -a 'content="helloworld" dest=/opt/hello.txt'
192.168.122.12 | 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-1634816859.21-12943-32638067870190/source",
    "state": "file",
    "uid": 0
}

● ansible dbservers -a 'cat /opt/hello.txt'

[root@ansible ansible]# ansible dbservers -a 'cat /opt/hello.txt'
192.168.122.12 | CHANGED | rc=0 >>
helloworld

7. file模块

设置文件属性

7.1 列出指定模块的描述信息和操作动作

● ansible-doc -s file

[root@ansible ansible]# 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).
      group:                 # Name of the group that should own the file/directory, as would be fed to `chown'.
      mode:                  # The permissions the resulting file or directory should have. For those used to `/usr/bin/chmod'
                               remember that modes are actually octal numbers. You must either add
                               a leading zero so that Ansible's YAML parser knows it is an octal
                               number (like `0644' or `01777') or quote it (like `'644'' or
                               `'1777'') so Ansible receives a string and can do its own
                               conversion from string into number. Giving Ansible a number without
                               following one of these rules will end up with a decimal number

7.2 文件属性管理

修改文件的属主属组权限等

● ansible dbservers -m file -a 'owner=test01 group=mysql mode=644 path=/opt/fstab.bak'

[root@ansible ansible]# ansible dbservers -m file -a 'owner=test01 group=mysql mode=644 path=/opt/fstab.bak'
192.168.122.12 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "gid": 2222,
    "group": "mysql",
    "mode": "0644",
    "owner": "test01",
    "path": "/opt/fstab.bak",
    "size": 501,
    "state": "file",
    "uid": 2222
}

设置/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

[root@ansible ansible]# 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 `present' or `latest'.
      disable_plugin:        # `Plugin' name to disable for the install/update operation. The disabled plugins will not persist
                               beyond the transaction.
      disablerepo:           # `Repoid' of repositories to disable for the install/update operation. These repos will not persist
                               beyond the transaction. When specifying multiple repos, separate
                               them with a `","'. As of Ansible 2.7, this can alternatively be a
                               list instead of `","' separated string

安装服务

● 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支持对主机进行分组,每个组内可以定义多个主机,每个主机都可以定义在任何一个或多个主机组内。

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