Ansible入门详解
目录
一、Ansible简介
1、什么是Ansible?
2、Ansible的特点
3、Ansible的架构
二、Ansible任务执行解析
ansible任务执行模式
ansible命令执行过程
三、Ansible配置解析
ansible的配置文件
ansible命令用法
ansible配置公私钥
添加主机清单
四、Ansible常用模块
主机连通性测试
command模块
shell模块
copy模块
fetch模块
script模块
一、Ansible简介
1、什么是Ansible?
-
ansible是新出现的自动化运维工具,基于python开发,集合了很多的运维工具(puppet、chef、func、fabric)的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能。
-
ansible是基于paramiko开发的,并且基于模块化工作,它本身没有批量部署的能力。真正具有批量部署的是ansible所运行的模块,ansible只是提供一种框架,ansible不需要在远程主机上安装client/agents,因为它们是基于ssh来和远程主机通讯的。ansible目前已经被红帽官方收购,是自动化运维工具认可度最高的。
2、Ansible的特点
-
部署简单,只需要在主控端部署Ansible环境,被控端无需做任何操作;
-
默认使用SSH协议对设备进行管理;
-
有大量的常规运维操作模块,可实现日常绝大部分的操作;
-
配置简单、功能强大、扩展性强;
-
支持API以及自定义模块,可以通过Python轻松扩展;
-
通过Playbooks来定制强大的配置、状态管理;
-
轻量级、无需在客户端安装agent,更新时,只需在操作机上进行一次更新即可;
-
提供一个功能强大、操作性强的web管理界面和REST API接口——AWX平台。
3、Ansible的架构
-
Ansible:Ansible的核心程序
-
HostInventory:记录有Ansible管理的主机信息,包括端口、密码、IP地址等
-
Playbooks:“剧本”YAML格式的文件,多个任务定义在一个文件中,定义主机需要调用哪些模块来完成的功能。
-
Core Modules:核心模块,主要操作是通过调用核心模块来完成管理任务
-
Custom Modules:自定义模块,完成核心模块无法完成的功能,支持多种语言。
-
Connection Plugins:连接插件,Ansible和Host通信使用
二、Ansible任务执行解析
ansible任务执行模式
-
ansible系统由控制主机被管节点的操作方式可以分为两类,即adhoc和playbook
-
ad-hoc模式(点对点模式)
使用单个模块,支持批量执行单条命令。ad-hoc命令是一种可以快速输入的命令,而且不需要保存起来的命令。就相当于bash中的一句话shell
-
playbook模式(剧本模式)
剧本模式是Ansible的主要管理方式,也是Ansible功能强大的关键所在。playbook通过多个task(任务)集合完成一类功能,比如web服务的安装部署、数据库服务的批量备份等。可以简单地把playbook理解为通过组合多条ad-hoc操作的配置文件
ansible命令执行过程
-
加载自己的配置文件,默认为/etc/ansible/ansible.cfg;
-
查找对应的主机配置文件,找到要执行的主机或者组;
-
加载自己对应的模块文件,如command;
-
通过ansible将模块或者命令生成对应的py文件(python脚本),并且将该文件传输到远程服务器;
-
对应执行用户的家目录.ansible/tmp/xxx/xxx.py文件;
-
给文件添加执行权限;
-
执行并且返回结果;
-
删除临时的py文件, sleep 0退出;
简单理解就是Ansible在运行时,首先读取ansible.cfg中的配置,根据规则获取Inventory中的管理主机列表,并行的在这些主机中执行配置的任务,最后等待执行返回结果。
三、Ansible配置解析
ansible的配置文件
常见参数如下:
[root@ansible ~]# cd /etc/ansible/
[root@ansible ansible]# ls
ansible.cfg hosts roles
[root@ansible ansible]# cat ansible.cfg
#inventory = /etc/ansible/hosts #指定 Ansible 管理的目标主机列表文件位置
#library = /usr/share/my_modules/ #指定 Ansible 自定义模块的存储目录
#module_utils = /usr/share/my_module_utils/ #指定模块工具函数的存放目录
#remote_tmp = ~/.ansible/tmp #指定 Ansible 在目标远程主机上存放临时文件(如模块脚本、执行结果)的路径
#local_tmp = ~/.ansible/tmp #指定 Ansible 在控制机(执行 ansible 命令的机器)上存放临时文件的路径
#plugin_filters_cfg = /etc/ansible/plugin_filters.yml #指定插件过滤规则配置文件的位置
#forks = 5 #设置 Ansible 同时操作的目标主机数量(并发数),默认值为 5
#poll_interval = 15 #对于异步执行的任务,Ansible 每隔指定秒数(默认 15 秒)检查一次远程主机的任务执行状态。
#sudo_user = root #默认 sudo 用户
#ask_sudo_pass = True #询问 sudo 密码
#ask_pass = True #询问登录密码
#transport = smart #指定 Ansible 与远程主机的通信方式
#remote_port = 22 #指定远程主机的 SSH 服务端口,默认值为 22
#module_lang = C #指定远程主机上执行模块时使用的语言环境,C 代表 POSIX 标准语言环境
#module_set_locale = False #控制是否为模块执行设置本地化环境(如字符编码、时区),默认值为 False
ansible命令用法
options:--ask-vault-pass ask for vault password--list-hosts outputs a list of matching hosts; does not execute anything else--playbook-dir BASEDIRSince this tool does not use playbooks, use this as a substitute playbook directory.This sets the relativepath for many features including roles/ group_vars/ etc.--syntax-check perform a syntax check on the playbook, but do not execute it--vault-id VAULT_IDS the vault identity to use--vault-password-file VAULT_PASSWORD_FILESvault password file--version show program's version number, config file location, configured module search path, module location,executable location and exit-B SECONDS, --background SECONDSrun asynchronously, failing after X seconds (default=N/A)-C, --check don't make any changes; instead, try to predict some of the changes that may occur-D, --diff when changing (small) files and templates, show the differences in those files; works great with --check-M MODULE_PATH, --module-path MODULE_PATHprepend colon-separated path(s) to module library(default=~/.ansible/plugins/modules:/usr/share/ansible/plugins/modules)-P POLL_INTERVAL, --poll POLL_INTERVALset the poll interval if using -B (default=15)-a MODULE_ARGS, --args MODULE_ARGSmodule arguments-e EXTRA_VARS, --extra-vars EXTRA_VARSset additional variables as key=value or YAML/JSON, if filename prepend with @-f FORKS, --forks FORKSspecify number of parallel processes to use (default=5)-h, --help show this help message and exit-i INVENTORY, --inventory INVENTORY, --inventory-file INVENTORYspecify inventory host path or comma separated host list. --inventory-file is deprecated-l SUBSET, --limit SUBSETfurther limit selected hosts to an additional pattern-m MODULE_NAME, --module-name MODULE_NAMEmodule name to execute (default=command)-o, --one-line condense output-t TREE, --tree TREE log output to this directory-v, --verbose verbose mode (-vvv for more, -vvvv to enable connection debugging)
ansible配置公私钥
[root@ansible ~]# ssh-keygen
Generating public/private ed25519 key pair.
Enter file in which to save the key (/root/.ssh/id_ed25519):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_ed25519
Your public key has been saved in /root/.ssh/id_ed25519.pub
The key fingerprint is:
SHA256:vXDNtT9DElC58tngVu6oam5a+hBsu2buRX/PIlsRMro root@ansible
The key's randomart image is:
+--[ED25519 256]--+
| .... |
| .. |
| o oo |
| . ..+o+oo |
| +Soo *oB. |
| . +oo. =++ |
| o E...ooo.|
| o*o .ooo.o|
| =**+.o+ .o |
+----[SHA256]-----+[root@ansible ~]# ssh-copy-id root@192.168.150.4
[root@ansible ~]# ssh-copy-id root@192.168.150.5
添加主机清单
[root@ansible ~]# cd /etc/ansible/
[root@ansible ansible]# ls
ansible.cfg hosts roles
[root@ansible ansible]# vim hosts #添加至文件最后
[webservers]
192.168.150.4
192.168.150.5
四、Ansible常用模块
用法:ansible 主机清单组名 -m 指定模块名 -a 指定模块参数
主机连通性测试
[root@ansible ~]# ansible webservers -m ping
[WARNING]: Platform linux on host 192.168.150.4 is using the discovered Python interpreter at /usr/bin/python3, but future
installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
192.168.150.4 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"},"changed": false,"ping": "pong"
}
[WARNING]: Platform linux on host 192.168.150.5 is using the discovered Python interpreter at /usr/bin/python3, but future
installation of another Python interpreter could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
192.168.150.5 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"},"changed": false,"ping": "pong"
}
command模块
command模块可以直接在远程主机上执行命令,并且结果返回打印出来,举例如下:
注意,command模块不支持 | 管道命令。
[root@ansible ~]# ansible webservers -m command -a "date"
192.168.150.5 | CHANGED | rc=0 >>
2025年 11月 12日 星期三 16:13:27 CST192.168.150.4 | CHANGED | rc=0 >>
2025年 11月 12日 星期三 16:13:28 CST
shell模块
-
shell模块可以在远程主机上调用shell解释器运行命令,支持shell的各种功能,例如管道等
-
只要是shell命令都可以在通过这个模块在远程主机里面运行
[root@ansible ~]# ansible webservers -m shell -a "ip a | grep ens160"
192.168.150.5 | CHANGED | rc=0 >>
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000inet 192.168.150.5/24 brd 192.168.150.255 scope global dynamic noprefixroute ens160192.168.150.4 | CHANGED | rc=0 >>
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000inet 192.168.150.4/24 brd 192.168.150.255 scope global dynamic noprefixroute ens160
copy模块
这个模块用于将文件复制到远程主机上,同时支持给定的内容生成文件和修改权限等
[root@ansible ~]# ansible webservers -m copy -a "src=/root/test.txt dest=/opt/ mode=0777"
192.168.150.4 | CHANGED => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"},"changed": true,"checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709","dest": "/opt/test.txt","gid": 0,"group": "root","md5sum": "d41d8cd98f00b204e9800998ecf8427e","mode": "0777","owner": "root","secontext": "system_u:object_r:usr_t:s0","size": 0,"src": "/root/.ansible/tmp/ansible-tmp-1762940702.6780243-54730-19246451320002/source","state": "file","uid": 0
}
192.168.150.5 | CHANGED => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python3"},"changed": true,"checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709","dest": "/opt/test.txt","gid": 0,"group": "root","md5sum": "d41d8cd98f00b204e9800998ecf8427e","mode": "0777","owner": "root","secontext": "system_u:object_r:usr_t:s0","size": 0,"src": "/root/.ansible/tmp/ansible-tmp-1762940702.690301-54732-165577350952488/source","state": "file","uid": 0
}
[root@web1 opt]# ls -l
总计 4
drwxr-xr-x. 4 root root 4096 8月26日 23:05 patch_workspace
-rwxrwxrwx. 1 root root 0 11月12日 17:44 test.txt
[root@web2 opt]# ls -l
总计 4
drwxr-xr-x. 4 root root 4096 8月26日 23:05 patch_workspace
-rwxrwxrwx. 1 root root 0 11月12日 17:44 test.txt
src:被复制到远程主机的本地文件。可以是绝对路径,也可以是相对路径。如果路径是一个目录,则会递归复制,用法类似于“rsync”。
dest:必选项,将源文件复制到远程主机的绝对路径。
mode:设置文件权限
fetch模块
fetch模块用于从远程某个主机获取(复制)文件到本地来
-
dest:用来存储文件的目录。
-
src:在远程拉取的文件,并且是一个file,不能是目录
[root@ansible ~]# ansible webservers -m fetch -a "src=/opt/test.txt dest=/opt/"
192.168.150.4 | CHANGED => {"changed": true,"checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709","dest": "/opt/192.168.150.4/opt/test.txt","md5sum": "d41d8cd98f00b204e9800998ecf8427e","remote_checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709","remote_md5sum": null
}
192.168.150.5 | CHANGED => {"changed": true,"checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709","dest": "/opt/192.168.150.5/opt/test.txt","md5sum": "d41d8cd98f00b204e9800998ecf8427e","remote_checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709","remote_md5sum": null
}
[root@ansible ~]# cd /opt
[root@ansible opt]# ls
192.168.150.4 192.168.150.5 patch_workspace
[root@ansible opt]# cd 192.168.150.4
[root@ansible 192.168.150.4]# ls
opt
[root@ansible 192.168.150.4]# cd opt/
[root@ansible opt]# ls
test.txt
script模块
script模块用于将本机的脚本在被管理端的机器上运行。该模块直接指定脚本的路径即可
先在ansible主机写一个脚本文件
[root@ansible ~]# vim test.sh
[root@ansible ~]# cat test.sh
#!/bin/bash
echo "Hello World!"
[root@ansible ~]# chmod +x test.sh
[root@ansible ~]# ./test.sh
Hello World!
运行这个脚本于被管理端
[root@ansible ~]# ansible webservers -m script -a "/root/test.sh"
192.168.150.4 | CHANGED => {"changed": true,"rc": 0,"stderr": "Shared connection to 192.168.150.4 closed.\r\n","stderr_lines": ["Shared connection to 192.168.150.4 closed."],"stdout": "Hello World!\r\n","stdout_lines": ["Hello World!"]
}
192.168.150.5 | CHANGED => {"changed": true,"rc": 0,"stderr": "Shared connection to 192.168.150.5 closed.\r\n","stderr_lines": ["Shared connection to 192.168.150.5 closed."],"stdout": "Hello World!\r\n","stdout_lines": ["Hello World!"]
}
更多常用模块正在持续更新.............
