Ansible自动化运维工具及其常用模块
一、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
copy | [root@ansible ~]# yum install -y epel-release.noarch |
| [root@ansible ~]# yum install -y ansible |
3. ansible目录结构
copy | [root@ansible ~]# yum install -y ansible |
| [root@ansible ~]# tree /etc/ansible |
| /etc/ansible |
| ├── ansible.cfg |
| ├── hosts |
| └── roles |
● ansible.cfg
ansible的配置文件,一般无需修改
● hosts
ansible的主机清单,用于存储需要管理的远程主机的相关信息
● roles
公共角色目录
4. 配置主机清单
copy | [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 生成密钥对
copy | [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 |
| +---[RSA 2048]----+ |
| | ooo.... . o| |
| | +...+ = ..| |
| | + O B ...| |
| | . B E o .o| |
| | S * + . .| |
| | . o o = | |
| | + + o | |
| | =.=. .| |
| | .=O=+oo| |
| +----[SHA256]-----+ |
5.2 复制公钥至node1并验证
copy | [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 |
| #输入密码 |
| 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 |
| 192.168.122.11 |
| [root@node1 ~]# echo $(ifconfig ens33 | awk |
| 192.168.122.11 |
| [root@node1 ~]# exit |
| 登出 |
5.3 复制公钥至node2并验证
copy | [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 |
| 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 |
| |
| 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 |
| 192.168.122.12 |
| [root@node2 ~]# echo $(ifconfig ens33 | awk |
| 192.168.122.12 |
| #实现免密登录 |
| [root@node2 ~]# exit |
| 登出 |
三、Ansible命令行模块
命令格式:ansible <组名> -m <模块> -a <参数列表>
● ansible-doc -l
列出所有已安装的模块,按q退出
copy | [root@ansible ansible]# ansible-doc -l |
| fortios_router_community_list Configure community lists in Fortinet |
| 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 |
| 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 |
| 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
copy | [root@ansible ansible] |
| - name: Execute commands on targets |
| command: |
| argv: |
| 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: |
| cmd: |
| creates: |
| free_form: |
| form'. |
| removes: |
| stdin: |
| stdin_add_newline: |
| strip_empty_ends: |
| warn: |
1.2 指定ip执行date
● ansible 192.168.122.11 -m command -a 'date'
copy | [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'
copy | [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'
copy | [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 /'
copy | [root@ansible ansible] |
| 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:判断指定文件是否存在,如果存在,执行后面的操作
copy | [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运行命令(支持管段符号等功能)
copy | [root@ansible ansible] |
| - name: Execute shell commands on targets |
| shell: |
| chdir: |
| cmd: |
| creates: |
| executable: |
| free_form: |
| 'free form'. See the examples on how to use this module. |
| removes: |
| stdin: |
| stdin_add_newline: |
| warn: |
2.1 创建用户/更改密码
● ansible webservers -m shell -a 'useradd test'
● ansible webservers -m shell -a 'echo 123456 | passwd --stdin test'
copy | [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}"'
copy | [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'
copy | [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
copy | [root@ansible ansible] |
| - name: Manage cron.d and crontab entries |
| cron: |
| backup: |
| returned in the `backup_file' variable by this module. |
| cron_file: |
| 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: |
| disabled: |
| env: |
| `name' and `value' parameters are the name and the value of |
| environment variable. |
| hour: |
| insertafter: |
| the declaration of specified environment variable. |
| insertbefore: |
| before the declaration of specified environment variable. |
| job: |
| not contain line breaks. Required if `state=present'. |
| minute: |
| month: |
| name: |
| `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"'
copy | [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'
copy | [root@ansible ansible] |
| 192.168.122.11 | CHANGED | rc=0 >> |
| |
| */1 * * * * /bin/echo helloworld |
3.4 移除计划任务
● ansible webservers -m cron -a 'name="test crontab" state=absent'
copy | [root@ansible ansible] |
| 192.168.122.11 | CHANGED => { |
| "ansible_facts": { |
| "discovered_interpreter_python": "/usr/bin/python" |
| }, |
| "changed": true, |
| "envs": [], |
| "jobs": [] |
| } |
| [root@ansible ansible] |
| 192.168.122.11 | CHANGED | rc=0 >> |
移除计划任务,若该计划任务没有取名字,name=None即可。
若有多个计划任务没有取名字,name=None将批量删除所有未取名任务。
4. user模块
用户管理的模块
4.1 列出指定模块的描述信息和操作动作
● ansible-doc -s user
copy | [root@ansible ansible]# ansible-doc -s user |
| - name: Manage user accounts |
| user: |
| append: # If `yes |
| the groups specified in `groups |
| 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= |
| Illumos/Solaris. |
| comment: # Optionally sets the description (aka `GECOS |
| create_home: # Unless set to `no |
| the home directory does not exist. Changed from `createhome |
| `create_home |
| 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 |
| supported platforms. The behavior is the same as `userdel --force |
| check the man page for `userdel |
| support. When used with `generate_ssh_key=yes |
| 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 |
| groups: # List of groups user will be added to. When set to an empty string ` |
| 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"'
copy | [root@ansible ansible] |
| 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'
copy | [root@ansible ansible] |
| 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'
copy | [root@ansible ansible] |
| 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] |
| 192.168.122.12 | CHANGED | rc=0 >> |
| nginx:x:1001:1001::/home/nginx:/sbin/nologin |
5. group模块
用户组管理的模块
5.1 列出指定模块的描述信息和操作动作
● ansible-doc -s group
copy | [root@ansible ansible]# ansible-doc -s group |
| - name: Add or remove groups |
| group: |
| gid: # Optional `GID |
| 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 |
| `groupadd |
| 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 |
| macOS or BusyBox distributions. |
| state: # Whether the group should be present or not on the remote host. |
| system: # If `yes |
5.2 用户组管理
创建mysql组
● ansible dbservers -m group -a 'name=mysql gid=2222 system=yes'
copy | [root@ansible ansible] |
| 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'
copy | [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'
copy | [root@ansible ansible] |
| 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'
copy | [root@ansible ansible] |
| 192.168.122.12 | CHANGED | rc=0 >> |
| test01:x:2222:2222::/home/test01:/bin/bash |
● ansible dbservers -a 'id test01'
copy | [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
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 |
| the attributes in the same order as the one displayed by `lsattr |
| The `= |
| 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 |
| only when `dest |
| For advanced formatting or if `content |
| 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 |
| must be a directory too. If `dest |
| either `dest |
| created. If `dest |
| determined by the remote host. If `src |
| parent directory of `dest |
| 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'
copy | [root@ansible ansible] |
| 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'
copy | [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 |
| -rw-r |
| drwxrwxr-x 18 123456 123456 4096 10月 17 02:22 php-7.1.10 |
| -rw-r |
| drwxr-xr-x. 2 root root 6 3月 26 2015 rh |
● ansible dbservers -a 'cat /opt/fstab.bak'
copy | [root@ansible ansible] |
| 192.168.122.12 | CHANGED | rc=0 >> |
| |
| |
| |
| |
| |
| |
| |
| |
| 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'
copy | [root@ansible ansible] |
| 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'
copy | [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
copy | [root@ansible ansible]# ansible-doc -s file |
| |
| - name: Manage files and file properties |
| file: |
| access_time: # This parameter indicates the time the file |
| when no modification is required, `YYYYMMDDHHMM.SS |
| default time format, or `now |
| `preserve |
| and `now |
| access_time_format: # When used with `access_time |
| 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 |
| the attributes in the same order as the one displayed by `lsattr |
| The `= |
| 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 |
| 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 |
| 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 |
| number (like `0644 |
| ` |
| 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'
copy | [root@ansible ansible] |
| 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'
copy | [root@ansible ansible] |
| 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"
copy | [root@ansible ansible] |
| 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"
copy | [root@ansible ansible] |
| 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"
copy | [root@ansible ansible] |
| 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
copy | [root@ansible ansible] |
| 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
copy | [root@ansible ansible]# ansible-doc -s yum |
| - name: Manages packages with the `yum |
| 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 |
| dependencies of user-installed packages but which are no longer |
| required by any such package. Should be used alone or when state is |
| `absent |
| bugfix: # If set to `yes |
| 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 |
| to `main |
| to `repoid |
| disable_gpg_check: # Whether to disable the GPG checking of signatures of packages being installed. Has an effect only |
| if state is `present |
| disable_plugin: # `Plugin |
| beyond the transaction. |
| disablerepo: # `Repoid |
| beyond the transaction. When specifying multiple repos, separate |
| them with a `"," |
| list instead of `"," |
安装服务
● ansible webservers -m yum -a 'name=httpd'
copy | [root@ansible ansible] |
| 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'
copy | [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
copy | [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 |
| 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 |
| 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 |
| `restarted |
| 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 |
| 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 |
| 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'
copy | [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'
copy | [root@ansible ~] |
| 192.168.122.11 | CHANGED => { |
| ······ |
12. script 模块
实现远程批量运行本地的 shell 脚本
● ansible-doc -s script
copy | [root@ansible ~] |
| - name: Runs a local script on a remote node after transferring it |
| script: |
| chdir: |
| cmd: |
| creates: |
| decrypt: |
| executable: |
| free_form: |
| removes: |
12.1 准备脚本
copy | [root@ansible ~] |
| |
| |
| echo "hello ansible from script" > /opt/script.txt |
12.2 script执行脚本
● ansible webservers -m script -a 'test.sh'
copy | [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
copy | [root@ansible ~]# ansible-doc -s setup |
| - name: Gathers facts about remote hosts |
| setup: |
| fact_path: # Path used for local ansible facts (`*.fact |
| their results be added to `ansible_local |
| 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 |
| 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 |
| specify a list of values to specify a larger subset. Values can |
| also be used with an initial `! |
| subset should not be collected. For instance: |
| `!hardware,!network,!virtual,!ohai,!facter |
| then only the min subset is collected. To avoid collecting even the |
| min subset, specify `!all,!min |
| use `!all,!min |
| 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
copy | [root@ansible ~] |
| 192.168.122.11 | SUCCESS => { |
| "ansible_facts": { |
| ····· |
13.2 过滤获取指定主机的指定facts信息
使用filter可以筛选指定的facts信息
● ansible dbservers -m setup -a 'filter=*ipv4'
copy | [root@ansible ~] |
| 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. 列表表示
如果是名称类似的主机,可以使用列表的方式标识各个主机。
copy | [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 主机变量
copy | [root@ansible ~]# vim /etc/ansible/hosts |
| |
| [webservers] |
| 192.168.122.11 ansible_port=22 ansible_user=root ansible_password=123456 |
3.2 组变量
copy | [webservers:vars] |
| |
| ansible_user=root |
| ansible_password=123456 |
| |
| [all:vars] |
| |
| ansible_port=22 |
3.3 组嵌套
copy | [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 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现