自动化运维工具 Ansible

Ansible 基础

Ansible 介绍

Ansible 是一个自动化运维工具,基于Python开发,集合了众多运维工具(puppet、cfengine、chef、 func、fabric)的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能。

Ansible 的名称来自科幻小说《安德的游戏》中跨越时空的即时通信工具,它可以在相距数光年的距离,远程实时控制前线的舰队战斗。

Ansible 的功能和特点

Ansible 的主要功能

  • 批量执行远程命令,可以对远程的多台主机同时进行命令的执行

  • 批量安装和配置软件服务,可以对远程的多台主机进行自动化的方式配置和管理各种服务

  • 编排高级的企业级复杂的IT架构任务,Ansible 的 Playbook 和 role 可以轻松实现大型的IT复杂架构

  • 提供自动化运维工具的开发 API, 有很多运维工具,如 jumpserver 就是基于 ansible 实现自动化 管理功能

Ansible 的主要优点

  • 部署简单方便,在对多机进行批量管量时,只需要在主控机上部署 Ansible 服务,被管理的机器不 用部署;

  • 默认通过 SSH 协议进行通信,只要保证主控端和被控机 ssh 通道畅通,就能保证服务可用;

  • 配置简单,上手快,功能强大;

  • 用 python 开发,打开源文件,所见即所得,对二次开发的支持非常友好;

  • 大量常规运维操作己经内置; 对于较复杂的需求,可以通过 playbook 功能和 role 功能来实现;

  • 还提供了操作方便,功能强大的的 web 管理界面;

  • 是一个己经商业化很久的项目了,生态成熟,社区活跃,文档完善

Ansible 的不足

  • 在管理的主机数量较多时,性能略差,执行效率不如 saltstack 高

  • 不支持事务回滚

Ansible 工作原理

执行流程

  1. 加载配置文件,读取配置;

  2. 加载对应的模块文件;

  3. 根据命令或模块,生成一个临时的 py 文件,再将该文件传送至对应的被管理的机器上 ($HOME/.ansible/tmp/ansible-tmp-xxx/xx.py)

  4. 给远程的 py 文件加可执行权限

  5. 执行该文件,并将结果抓取回当前的主机显示;

  6. 删除远端的临时 py 文件

Ansible 命令执行来源

  • 系统用户直接执行:系统用户登录终端后直接在命令行下执行单条命令

  • 在 playbooks 中间接执行,playbook中编写多条 ansible 命令,ansible 根据playbook文件的内容 依次执行

  • 在 web 管理界面上执行

  • 使用 API 调用执行:配置API接口,让第三方应用或程序调用接口执行 ansible 命令

使用注意事项

  • 执行ansible的主机一般称为管理端, 主控端,中控,master 或堡垒机

  • 主控端Python版本需要2.6或以上

  • 被控端Python版本小于2.4,需要安装python-simplejson

  • 被控端如开启SELinux需要安装libselinux-python

  • windows 不能做为主控端,只能做为被控制端

Ansible 安装和基本使用

Ansible 安装

bash 复制代码
#在Rocky中安装 ansible
#需要先安装 epel 源
[root@Rocky-9 ~]# yum install -y epel-release
[root@Rocky-9 ~]# yum install -y ansible


#在 Ubuntu 中安装 ansible
#用 pip 安装
[root@ubuntu24 ~]# pip3.10 install -i https://pypi.tuna.tsinghua.edu.cn/simple ansible

#直接安装
[root@ubuntu24 ~]# apt install ansible

ansible 和 ansible-core

ansible-core 包中仅包含核心功能和核心模块,ansible 包中除了核心功能之外还包含大量外围功能模块。

Ansible 配置文件

查看 ansible 配置文件
bash 复制代码
[root@ubuntu24 ~]# ansible --version
ansible [core 2.16.3]		#版本号
  config file = None		#配置文件
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']	#第三方插件目录
  ansible python module location = /usr/lib/python3/dist-packages/ansible					#官方模块目录
  ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections	
  executable location = /usr/bin/ansible				#可执行程序
  python version = 3.12.3 (main, Sep 11 2024, 14:17:37) [GCC 13.2.0] (/usr/bin/python3)		#python环境
  jinja version = 3.1.2			#jinja模板引擎版本
  libyaml = True				#是否己安装libyaml
  
  
  
  
#rocky中的配置文件
[root@Rocky-9 ~]# tree /etc/ansible/
/etc/ansible/
├── ansible.cfg
├── hosts
└── roles

1 directory, 2 files
[root@Rocky-9 ~]# cat /etc/ansible/ansible.cfg
# Since Ansible 2.12 (core):
# To generate an example config file (a "disabled" one with all default settings, commented out):
#               $ ansible-config init --disabled > ansible.cfg
#
# Also you can now have a more complete file by including existing plugins:
# ansible-config init --disabled -t all > ansible.cfg

# For previous versions of Ansible you can check for examples in the 'stable' branches of each version
# Note that this file was always incomplete  and lagging changes to configuration settings

# for example, for 2.9: https://github.com/ansible/ansible/blob/stable-2.9/examples/ansible.cfg




#如果要在 ubuntu 中使用,可以在 ansible-core 包中生成配置文件或从其它系统中 copy 文件到当前系统,或者从github上获取
https://github.com/ansible/ansible/blob/stable-2.10/examples/ansible.cfg

#创建目录
[root@ubuntu24 ~]# mkdir -pv /etc/ansible/roles
mkdir: created directory '/etc/ansible'
mkdir: created directory '/etc/ansible/roles'

[root@ubuntu24 ~]# touch /etc/ansible/hosts

#生成配置文件
[root@ubuntu24 ~]# ansible-config init -t all --disabled > /etc/ansible/ansible.cfg、

[root@ubuntu24 ~]# tree /etc/ansible/
/etc/ansible/
├── ansible.cfg	#主配置文件,配置ansible工作特性,也可以在项目的目录中创建此文件,当前目录下如果也有ansible.cfg,则当前目录的中的配置文件优先于此文件
├── hosts		#主机清单,在此文件中定义要管理的主机
└── roles		#目录,存放角色文件

2 directories, 2 files
主配置文件

Ansible 的主配置文件可以有多个,分别存放于不同目录,其优先级如下

bash 复制代码
ANSIBLE_CONFIG #环境变量,此变量中指向的文件必须存在才生效,指向的文件要以.cfg 结尾

./ansible.cfg #当前目录下的ansible.cfg,一般一个项目对应一个专用配置文件,推荐使用

~/.ansible.cfg #当前用户家目录下的.ansible.cfg

/etc/ansible/ansible.cfg #ansible默认配置文件,主配置文件

主配置文件中又间接定义了其它的配置项,在使用时,可以为不同的项目建立不同的配置文件放到不同的目录中,再去到该目录下执行 ansible,或者用变量指定不同的配置文件用来区分不同的项目配置,对于不同用户的配置,可以写在相应的家目录中。

主配置文件中的主要配置项

bash 复制代码
[root@ubuntu ~]# cat /etc/ansible/ansible.cfg

[defaults]
inventory      = /etc/ansible/hosts 		#远程主机清单
remote_tmp     = ~/.ansible/tmp 			#远程主机临时文件目录
local_tmp      = ~/.ansible/tmp 			#本地主机临时文件目录
keep_remote_files=False 					#是否保留远程主机上的py脚本文件,默认不保留
executable=/bin/sh 							#生成shell命令时用指定的bash执行
forks          = 5 							#并发数
ask_pass       = False 						#连接远程主机时,询问是否需要输入密码,默认不询问,走ssh key校验
host_key_checking = True 					#是否需要每次询问要不要添加HostKey,默认是true,每次询问
log_path = 									#日志文件地址,为空表示禁用日志
module_name = command 						#默认模块
gathering = smart|implicit|explicit 		#smart表示如果有缓存则使用缓存, implicit每次收集,explicit不收集,除非指定
fact_caching_timeout = 86400 				#远程主机信息缓存时长,默认 86400
fact_caching = memeory|jsonfile|redis 		#默认缓存到内存,可以写文件和redis
fact_caching_connection = /path/to/cachedir #如果写json 文件,此处写保存路径,如果是redis此处写redis连接地址
interpreter_python=auto 					#指定远程主机python版本和路径

#连接持久化配置
[persistent_connection]
ansible_connection_path= #
command_timeout=30 #
connect_retry_timeout=15 		#超时重试时长
connect_timeout=30 				#连接
control_path_dir=~/.ansible/pc 	#socket 文件保存目录


#颜色配置
[colors]
changed=yellow
console_prompt=white
debug=dark gray
deprecate=purple
diff_add=green
diff_lines=cyan
diff_remove=red
error=red
highlight=white
ok=green
skip=cyan
unreachable=bright red
verbose=blue
warn=bright purple


#普通用户提权配置
[privilege_escalation] 
agnostic_become_prompt=True
become_allow_same_user=False
become=False
become_ask_pass=False 	#sudo 时是否提示输入密码
become_exe=
become_flags=
become_method=sudo 		#以 sudo 方式提权
become_user=root 		#默认 sudo 到 root
主机清单配置文件

ansible 的主要功用在于批量主机操作,为了便捷地使用其中的部分主机,可以在 inventory 主机清单文 件中将其分组组织

主机定义支持 ip 地址和主机名两种方式,写法多种多样

注意:

  • 生产建议在每个项目目录下创建项目独立的hosts文件

  • 通过项目目录下的ansible.cfg文件中的 inventory = ./hosts 实现

主机清单文件格式

inventory 文件遵循 INI 文件风格,中括号中的字符为组名。可以将同一个主机同时归并到多个不同的组 中,此外,当如若目标主机使用了非默认的SSH端口,还可以在主机名称之后使用冒号加端口号来标 明,如果主机名称遵循相似的命名模式,还可以使用列表的方式标识各主机

Inventory 参数说明

常用可定义的配置项

bash 复制代码
ansible_ssh_host=IP|hostname 		#指定远程主机,可用IP或主机名
ansible_ssh_port=PORT 				#指定SSH端口
ansible_ssh_user=UNAME 				#指定SSH用户名
ansible_ssh_pass=PWD 				#显式指定SSH密码
ansible_sudo_pass=PWD 				#显式指定SUDO密码
ansible_sudo_exe=/PATH/CMD 			#sudo 命令路径(适用于1.8及以上版本)
ansible_connection=local|ssh|paramiko|docker 	#与主机的连接类型
ansible_ssh_private_key_file=/PATH/FILE 		#SSH私钥文件
ansible_shell_type=sh|csh|fish 		#目标系统的shell类型.默认 sh
ansible_python_interpreter=/PATH/PYTHON 		#目标主机的python路径用于系统中有多个Python版本,或默认/usr/bin/python不存在

Ansible 工具

bash 复制代码
[root@ubuntu24 ansible]# ls /usr/bin/ansible*
/usr/bin/ansible           			#主程序,ad-hoc工作模式下执行单条命令
/usr/bin/ansible-config      		#配置管理工具
/usr/bin/ansible-console  			#互式命令行工具
/usr/bin/ansible-galaxy     		#线上role管理工具
/usr/bin/ansible-playbook  			#playbook 管理工具
/usr/bin/ansible-test				#Ansible的测试工具
/usr/bin/ansible-community  
/usr/bin/ansible-connection  		#连接插件管理工具
/usr/bin/ansible-doc      			#帮助手册,查看帮助文档
/usr/bin/ansible-inventory  		#用特定格式显示所有远程主机列表
/usr/bin/ansible-pull      			#playbook获取工具
/usr/bin/ansible-vault				#文档加密工具

ansible-doc命令用法

ansible-doc 工具用来查看 ansible 文档

bash 复制代码
ansible-doc [options] [module...]

#常用选项
-h|--help #显示帮助
--version #显示版本
-l|--list #列出所有可用模块
-t|--type #指定模块类型become|cache|callback|cliconf|connection|httpapi|inventory|lookup|netconf|shell|vars|module|strategy|role|keyword

-s|--snippet #显示指定模块的playbook片段
-j|--json #以 json 格式显示
-v|--verbose #显示详细信息,最多可以 -vvvvvv

ansible-console 命令用法

ansible-console 用来交互式执行命令,支持 tab 键补齐

bash 复制代码
ansible-console

#常用子命令
help|? 		#列出所子命令
cd 			#切换主机组
copy 		#
exit 		#退出
forks 		#设置并发执行数量
list 		#列出被管理的所有主机
ping 		#执行ping模块

#示例
[root@ubuntu24 ansible]# ansible-console
Welcome to the ansible console. Type help or ? to list commands.

root@all (3)[f:5]$ list
10.0.0.151
10.0.0.161
10.0.0.158
root@all (3)[f:5]$

ansible 命令用法

ansible 命令基础用法

ansible 工具一般用来执行单条命令,使用频率较高

bash 复制代码
ansible <host-pattern> [-m module_name] [-a args]

#常用选项
-h|--help 			#查看帮助
--version 			#显示版本
--list-hosts 		#列出远程主机,可以写成 --list
-m module 			#指定模块,默认模块为command,默认模块时,可省略不写
-a|--args 			#指定模块选项
-e|--extra-vars 	#指定执行选项
-C|--check 			#检测语句是否正确,并不立即执行
-k|--ask-pass 		#提示输入ssh密码,默认用sshkey验证
-T|--timeout N 		#设置命令超时时长,默认10S
-k|--ask-pass 		#提示输入ssh连接密码,默认Key验证
-u|--user=UNAME 	#执行远程执行的用户,默认root
-b|--become 		#代替旧版的sudo实现通过sudo机制实现提升权限
--become-user=USERNAME 	#指定sudo的runas用户,默认为root
-K|--ask-become-pass 	#提示输入sudo时的口令
-f|--forks N 		#指定并发同时执行ansible任务的主机数
-i|--inventory /PATH/FILE 	#指定主机清单文件
-v|vv|vvv|vvvv|vvvvv 	#显示详细执行过程

查看主机

bash 复制代码
#查看所有主机列表
[root@ubuntu24 ~]# ansible all --list-hosts
  hosts (3):
    10.0.0.151
    10.0.0.161
    10.0.0.153

#查看指定组主机列表
[root@ubuntu24 ~]# ansible ubuntu --list-hosts
  hosts (2):
    10.0.0.151
    10.0.0.161

自动添加主机到信任列表

bash 复制代码
[root@ubuntu ~]# ansible 10.0.0.161 -m ping -k
SSH password:
10.0.0.161
| FAILED! => {
    "msg": "Using a SSH password instead of a key is not possible because Host 
Key checking is enabled and sshpass does not support this. Please add this 
host's fingerprint to your known_hosts file to manage this host."
}
#修改配置文件,自动添加目标主机到信任主机列表
[root@ubuntu ~]# vim /etc/ansible/ansible.cfg
host_key_checking=False  #配置文件中一共有三处,需要修改在defaults中的

[root@ubuntu24 ~]# ansible 10.0.0.161 -m ping -k
SSH password:
10.0.0.161 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}

连接socket缓存

bash 复制代码
[root@ubuntu24 ~]# rm -rf .ansible

[root@ubuntu24 ~]# ansible 10.0.0.161 -m ping -k
SSH password:
10.0.0.161 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}
#生成一个 socket 文件
[root@ubuntu24 ~]# tree .ansible
.ansible
├── cp
│   └── 7eb12a22e7
└── tmp
    └── ansible-local-2681ak1w6fns

4 directories, 1 file

[root@ubuntu24 ~]# ll .ansible/cp/
total 8
drwx------ 2 root root 4096 Sep 28 09:31 ./
drwxr-xr-x 4 root root 4096 Sep 28 09:31 ../
srw------- 1 root root    0 Sep 28 09:31 7eb12a22e7=

#默认走 sshkey 验证,由于有缓存的 socket 文件,所以可以操作成功
[root@ubuntu24 ~]# ansible 10.0.0.161 -m ping
10.0.0.161 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}

#但该文件有生命周期,默认1分钟
#上次连接的缓存失效后,如果没有 -k 选项,默认走 sshkey 验证,会失败

指定主机和用户

bash 复制代码
#指定用户要使用该用户密码
[root@ubuntu24 ~]# ansible 10.0.0.161 -m ping -u tom -k
SSH password:
10.0.0.161 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}

#以 sudo 身份执行
#修改目标主机10.0.0.161
[root@ubuntu24 ~]# vim /etc/sudoers
tom ALL=(root) NOPASSWD: ALL

#测试
# -m command 可以省略不写
[root@ubuntu24 ~]# ansible 10.0.0.161 -m command -a "sudo ls /root" -u tom -k
SSH password:
10.0.0.161 | CHANGED | rc=0 >>
apache-tomcat-9.0.95.tar.gz
app1
dira
jpress
nexus-3.67.1-01-java11-unix.tar.gz
nginx-1.24.0
nginx-1.24.0.tar.gz
nginx-1.26.2
nginx-1.26.2.tar.gz
sonatype-work
spring-boot-helloworld

#另一种写法,-b 指定 sudo 执行 -K指定 sudo 密码
[root@ubuntu24 ~]# ansible 10.0.0.161 -m command -a "ls /root " -u tom -k -b -K
SSH password:
BECOME password[defaults to SSH password]:
10.0.0.161 | CHANGED | rc=0 >>
apache-tomcat-9.0.95.tar.gz
app1
dira
jpress
nexus-3.67.1-01-java11-unix.tar.gz
nginx-1.24.0
nginx-1.24.0.tar.gz
nginx-1.26.2
nginx-1.26.2.tar.gz
sonatype-work
spring-boot-helloworld

并发控制

bash 复制代码
#并发数为1 ,每次执行一台机,总共需要4S
[root@ubuntu24 ~]# ansible ubuntu -a "sleep 2" -f1 -k
SSH password:
10.0.0.151 | CHANGED | rc=0 >>

10.0.0.161 | CHANGED | rc=0 >>

#可以将密码添加到/etc/ansible/hosts文件中就不用每次都输入,还可以添加其他参数,例如指定ssh用户名,默认是root
[root@ubuntu24 ~]# cat /etc/ansible/hosts
[ubuntu:vars]
ansible_ssh_password=123456

#并发改为2后变为2s
[root@ubuntu24 ~]# time ansible ubuntu -a "sleep 2" -f2
10.0.0.151 | CHANGED | rc=0 >>

10.0.0.161 | CHANGED | rc=0 >>


real	0m2.859s
user	0m0.486s
sys	0m0.312s
host-pattern 规则

host-pattern 用于匹配被管理的主机列表

bash 复制代码
#所有主机
[root@ubuntu24 ansible]# ansible all --list-hosts
  hosts (6):
    10.0.0.150
    10.0.0.157
    10.0.0.184
    node1.linux-baidu.com
    node2.linux-baidu.com
    node3.linux-baidu.com

#指定组
[root@ubuntu24 ansible]# ansible test1 --list-hosts
  hosts (2):
    10.0.0.150
    10.0.0.157
    
    
#直接指定主机
[root@ubuntu24 ansible]# ansible "10.0.0.184 10.0.0.150" --list-hosts
  hosts (2):
    10.0.0.184
    10.0.0.150


##用通配符表示所有主机
[root@ubuntu24 ansible]# ansible "*" --list-hosts
  hosts (6):
    10.0.0.150
    10.0.0.157
    10.0.0.184
    node1.linux-baidu.com
    node2.linux-baidu.com
    node3.linux-baidu.com

#指定开头
[root@ubuntu24 ansible]# ansible "10.0.0.15*" --list-hosts
  hosts (2):
    10.0.0.150
    10.0.0.157
    
#指定结尾
[root@ubuntu24 ansible]# ansible "*com" --list-hosts
  hosts (3):
    node1.linux-baidu.com
    node2.linux-baidu.com
    node3.linux-baidu.com
    
    
#逻辑或(并集)
[root@ubuntu24 ansible]# ansible "test1:test2" --list-hosts
  hosts (3):
    10.0.0.150
    10.0.0.157
    10.0.0.184
    
#默认就是逻辑或

#逻辑与(交集即同时在两个组中出现)
[root@ubuntu24 ansible]# ansible "test1:&test2" --list-hosts
  hosts (1):
    10.0.0.157

#逻辑非(在 test1不在 test2 中的主机)
[root@ubuntu24 ansible]# ansible "test1:!test2" --list-hosts	#需要单引号
-bash: !test2: event not found
[root@ubuntu24 ansible]# ansible 'test1:&test2' --list-hosts
  hosts (1):
    10.0.0.157
 
 #所有不在 test1,test2中的主机
[root@ubuntu24 ansible]# ansible 'all:!test1:!test2' --list-hosts
  hosts (3):
    node1.linux-baidu.com
    node2.linux-baidu.com
    node3.linux-baidu.com
    
    
    
#支持正则表达式
#node 开头
[root@ubuntu24 ansible]# ansible "~node" --list-hosts
  hosts (3):
    node1.linux-baidu.com
    node2.linux-baidu.com
    node3.linux-baidu.com

#以com 结尾
[root@ubuntu24 ansible]# ansible "~.*com$" --list-hosts
  hosts (3):
    node1.linux-baidu.com
    node2.linux-baidu.com
    node3.linux-baidu.com
执行结果状态说明
  • 绿色 执行成功,此次执行远程主机没有写行为发生(修改文件,删除文件,新增文件等)

  • 黄色 执行成功,有发生变改

  • 红色 执行失败

Ansible 常用模块

command 模块

此模块为 ansible 默认模块,可以省略 -m 选项,该模块用来在远程主机上执行 shell 命令,但有些操作 不支持,比如管道,重定向,通配符等,如果要实现这些功能,可以用 shell 模块实现。

此模块不具有幂等性

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s command

#常用选项
chdir=dir #执行命令前,先切换至目录dir
creates=file #当file不存在时才会执行
removes=file #当file存在时才会执行



#创建文件当/root/test/abc 不存在时执行
[root@ubuntu24 ansible]# ansible 10.0.0.161 -m command -a "chdir=/root/test creates=/root/test/abc touch abc"
10.0.0.161 | CHANGED | rc=0 >>

[root@ubuntu24 test]# ls -l
total 0
-rw-r--r-- 1 root root 0 Sep 28 10:40 abc

#再次执行,文件己存在,提示 skipped
[root@ubuntu24 ansible]# ansible 10.0.0.161 -m command -a "chdir=/root/test creates=/root/test/abc touch abc"
10.0.0.161 | SUCCESS | rc=0 >>
skipped, since /root/test/abc existsDid not run command since '/root/test/abc' exists

#重定向无法执行成功
[root@ubuntu24 ansible]# ansible 10.0.0.161 -m command -a "echo 123 > /root/test/abc"
10.0.0.161 | CHANGED | rc=0 >>
123 > /root/test/abc

#文件为空
[root@ubuntu24 test]# ls -l
total 0
-rw-r--r-- 1 root root 0 Sep 28 10:40 abc

#管道符也无法使用
#不支持多条命令

shell 模块

此模块用法和 command 模块类似,都是用来执行 shell 命令,但功能比 command 模块强大,对于在 command 模块中不支持的功能,此处均可使用。此模块也不具有幂等性。

在调用shell模块执行命令时,复杂的命令也有可能会执行失败,类似于包含多重管道,正则表达式这些,这种情况下,我们需要写成 shell 脚本,用 copy 模块直接推送到远程执行。

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s shell

#常用选项
chdir=dir #执行命令前,先切换至目录dir
creates=file #当file不存在时才会执行
removes=file #当file存在时才会执行


#支持管道
[root@ubuntu24 ansible]# ansible 10.0.0.161 -m shell -a "echo 1+2|bc"
10.0.0.161 | CHANGED | rc=0 >>
3

#支持重定向
[root@ubuntu24 ansible]# ansible 10.0.0.161 -m shell -a "echo 123 > /root/test/abc"
10.0.0.161 | CHANGED | rc=0 >>

[root@ubuntu24 test]# ls -l
total 4
-rw-r--r-- 1 root root 4 Sep 28 10:47 abc

#支持多条命令

[root@ubuntu24 ansible]# ansible 10.0.0.161 -m shell -a "id;id;id"
10.0.0.161 | CHANGED | rc=0 >>
uid=0(root) gid=0(root) groups=0(root)
uid=0(root) gid=0(root) groups=0(root)
uid=0(root) gid=0(root) groups=0(root)


#Ansible 工作原理
#开始执行
[root@ubuntu24 ansible]# ansible 10.0.0.161 -m shell -a "sleep 50;echo 123"
10.0.0.161 | CHANGED | rc=0 >>
123

#远程主机
[root@ubuntu24 ~]# tree .ansible/
.ansible/
└── tmp
    └── ansible-tmp-1727492350.816154-4145-80036210466863
        └── AnsiballZ_command.py

3 directories, 1 file

#当命令执行完成后,临时脚本会被删除
#或者可以开启配置文件的中配置项,保留远程主机上的脚本,也可以观察

keep_remote_files=True

script 模块

script 模块可以在远程主机上运行 ansible 机器上的脚本(而且脚本文件可以没有执行权限),这里的脚本 并不仅仅只是 shell脚本,只要远程主机上能执行的,都可以,包括但不限于 php, sh, py 等。

此模块不具有幂等性。

bash 复制代码
#查看脚本
[root@ubuntu ~]# cat test.sh 
#!/bin/bash
hostname -I >/tmp/ansible-script.log
hostname -I

#可以不需要x权限
[root@ubuntu24 ~]# ll test.sh
-rw-r--r-- 1 root root 391 Sep 28 11:02 test.sh

#测试
[root@ubuntu24 ~]# ansible ubuntu -m script -a "./test.sh"
10.0.0.161 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 10.0.0.161 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 10.0.0.161 closed."
    ],
    "stdout": "10.0.0.161 \r\n",
    "stdout_lines": [
        "10.0.0.161 "
    ]
}
10.0.0.151 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 10.0.0.151 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 10.0.0.151 closed."
    ],
    "stdout": "10.0.0.151 \r\n",
    "stdout_lines": [
        "10.0.0.151 "
    ]
}

#在远程主机上查看log
[root@ubuntu24 ~]# cat /tmp/ansible-script.log
10.0.0.161
[root@ubuntu22:~]# cat /tmp/ansible-script.log
10.0.0.151

copy 模块

copy 模块将 ansible 主机上的文件复制到远程主机,此模块具有幂等性。

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s copy

#常用选项
src=/path/file 		#ansible主机文件路径
dest=/path/file 	#远程主机文件路径
owner=UNAME 		#新文件属主
group=GNAME 		#新文件属组
mode=777 			#新文件权限
backup=yes|no 		#是否备份,默认no
content=str 		#使用str生成新文件
remote_src=yes|no 	#no是默认值,表示src文件在ansible主机,yes表示src文件在远程主机


#将 ansible 主机上的文件 copy 到远程主机
[root@ubuntu24 ~]# ansible 10.0.0.161 -m copy -a "src=/root/1.txt dest=/root/"
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "checksum": "82b790a77d66d9cc277ece5a0e151254c7d5bf00",
    "dest": "/root/1.txt",
    "gid": 0,
    "group": "root",
    "md5sum": "2f3c52c1fe6b14b8db23f929e169579a",
    "mode": "0644",
    "owner": "root",
    "size": 45,
    "src": "/root/.ansible/tmp/ansible-tmp-1727493154.2193365-4884-186491211459164/source",
    "state": "file",
    "uid": 0
}

[root@ubuntu24 ~]# cat 1.txt
123
12312
1312
3123

31231
3123


10.0.0.157

#修改文件
[root@ubuntu24 ~]# echo 10.0.0.157 > 1.txt

#备份,指定属主属组,指定权限
[root@ubuntu24 ~]# ansible 10.0.0.161 -m copy -a "src=/root/1.txt  dest=/root/ backup=yes owner=tom group=tom mode=400 "
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "backup_file": "/root/1.txt.4569.2024-09-28@11:17:19~",
    "changed": true,
    "checksum": "72513039d276cab39ec7eb057ca4307f9ca9cfb1",
    "dest": "/root/1.txt",
    "gid": 1001,
    "group": "tom",
    "md5sum": "ff9b9b668bf961efd80dd186d13582ab",
    "mode": "0400",
    "owner": "tom",
    "size": 11,
    "src": "/root/.ansible/tmp/ansible-tmp-1727493437.1678395-4970-2182778319449/source",
    "state": "file",
    "uid": 1001
}

[root@ubuntu24 ~]# ls -l 1.*
-r-------- 1 tom  tom  11 Sep 28 11:17 1.txt
-rw-r--r-- 1 root root 45 Sep 28 11:12 1.txt.4569.2024-09-28@11:17:19~

#使用remote_src=yes可以实现在源和目标都在远程主机上进行文件复制


#幂等性验证
#从指定内容中生成文件
[root@ubuntu24 ~]# ansible 10.0.0.161 -m copy -a 'content=#!/usr/bin/python3\nprint("123") dest=/tmp/test.py'
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "checksum": "2f357684cc033c7e43e351feed22506d2a953eb1",
    "dest": "/tmp/test.py",
    "gid": 0,
    "group": "root",
    "md5sum": "1fc953b4dbf2b024f2a0cbafd8ec717c",
    "mode": "0644",
    "owner": "root",
    "size": 32,
    "src": "/root/.ansible/tmp/ansible-tmp-1727493937.620777-5030-47056363093670/source",
    "state": "file",
    "uid": 0
}
[root@ubuntu24 tmp]# ls -l test.py
-rw-r--r-- 1 root root 32 Sep 28 11:27 test.py

#再次执行,绿色,提示成功
[root@ubuntu24 ~]# ansible 10.0.0.161 -m copy -a 'content=#!/usr/bin/python3\nprint("123") dest=/tmp/test.py'
10.0.0.161 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "checksum": "2f357684cc033c7e43e351feed22506d2a953eb1",
    "dest": "/tmp/test.py",
    "gid": 0,
    "group": "root",
    "mode": "0644",
    "owner": "root",
    "path": "/tmp/test.py",
    "size": 32,
    "state": "file",
    "uid": 0
}

#远程主机上的文件时间戳没有发生变化
[root@ubuntu24 tmp]# ls -l test.py
-rw-r--r-- 1 root root 32 Sep 28 11:27 test.py

get_url 模块

该模块可以将网络上的资源下载到指定主机,支持 http,https,ftp 协议

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s get_url

#常用选项
url=http://www.a.com/b.txt 	#下载文件URL
dest=/tmp/c.txt 			#保存文件路径(绝对路径)
owner=UNAME 				#指定属主
group=GNAME 				#指定属组
mode=777 					#指定权限
force=yes|no 				#默认yes,如果目标文件存在,则覆盖, no 表示只有目标不存在才下载
checksum="algorithm:str" 	#指定目标文件摘要值,下载完成后算出文件摘要再对比,确认文件是否完整
 
#checksum="md5:2741cb83a6840e01a22544bddc4b0d1e"
 
#checksum="sha256:http://example.com/path/sha256sum.txt"

url_username=UNAME 		#http 认证用户名
url_password=PWD 		#http 认证密码
validate_certs=yes|no 	#no表示不验证SSL证书合法性
timeout=10 				#URL请求的超时时间,默认10S

fetch 模块

从远程主机提取文件至 ansible 的主控端,copy 相反,不支持目录

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s fetch

#常用选项
src=/path/file 			#远程主机上的文件路径
fail_on_missing=yes|no 	#默认yes,无法获取远程主机文件时,显示失败
dest=/path 				#ansible主机上的保存路径,不存在会自动创建

#将远程主机上的文件 fetch 到ansible 主机
[root@ubuntu24 ~]# ansible 10.0.0.161 -m fetch -a "src=/tmp/test.py dest=/root/"
10.0.0.161 | CHANGED => {
    "changed": true,
    "checksum": "7370224080f49dc413b0ca54829f26b5c12aea70",
    "dest": "/root/10.0.0.161/tmp/test.py",
    "md5sum": "d5d3e53f5da5d10fe08ba23425d32623",
    "remote_checksum": "7370224080f49dc413b0ca54829f26b5c12aea70",
    "remote_md5sum": null
}

[root@ubuntu24 ~]# tree 10.0.0.161/
10.0.0.161/
└── tmp
    └── test.py

2 directories, 1 file

file 模块

file 模块主要提供文件管理功能,比如创建文件和目录,修改文件和目录,设置文件权限和属性,设置 链接等

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s file

#常用选项
path=/path/file 	#目标文件路径
owner=USER 			#属主
group=GROUP 		#属组
mode=777 			#权限
state=file|touch|directory|link|hard|absent 	#具体操作,如果是 link,源用 src指定
recurse=yes|no 		#yes表示递归操作,仅在 state=directory 时生效


#在远程主机上递归创建文件夹
[root@ubuntu24 ~]# ansible 10.0.0.161 -m file -a "path=/tmp/dira/dir1/dir2 state=directory owner=tom group=root recurse=yes"
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "gid": 0,
    "group": "root",
    "mode": "0755",
    "owner": "tom",
    "path": "/tmp/dira/dir1/dir2",
    "size": 4096,
    "state": "directory",
    "uid": 1001
}

#获取文件信息
[root@ubuntu24 ~]# ansible 10.0.0.161 -m file -a "path=/root/1.txt state=file"
10.0.0.161 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "gid": 1001,
    "group": "tom",
    "mode": "0400",
    "owner": "tom",
    "path": "/root/1.txt",
    "size": 11,
    "state": "file",
    "uid": 1001
}


#创建链接
[root@ubuntu24 ~]# ansible 10.0.0.161 -m file -a "src=/root/1.txt dest=/tmp/1.txt.link state=link"
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "dest": "/tmp/1.txt.link",
    "gid": 0,
    "group": "root",
    "mode": "0777",
    "owner": "root",
    "size": 11,
    "src": "/root/1.txt",
    "state": "link",
    "uid": 0
}

#删除文件
[root@ubuntu24 ~]# ansible 10.0.0.161 -m file -a "path=/root/1.txt state=absent"
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "path": "/root/1.txt",
    "state": "absent"
}

stat 模块

stat 模块用来获取目标文件的状态,对于 windows 主机,要使用 win_stat 模块

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s stat

#常用选项
path=/path/file 		#指定目标文件路径
follow=true|false 		#是否跟随链接,默认 false,不跟随


#查看目录文件
[root@ubuntu24 ~]# ansible 10.0.0.161 -m stat -a "path=/root/test"
10.0.0.161 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "stat": {
        "atime": 1727491242.2433984,
        "attr_flags": "e",
        "attributes": [
            "extents"
        ],
        "block_size": 4096,
        "blocks": 8,
        "charset": "binary",
        "ctime": 1727491226.1313975,
        "dev": 64512,
        "device_type": 0,
        "executable": true,
        "exists": true,
        "gid": 0,
        "gr_name": "root",
        "inode": 4476048,
        "isblk": false,
        "ischr": false,
        "isdir": true,
        "isfifo": false,
        "isgid": false,
        "islnk": false,
        "isreg": false,
        "issock": false,
        "isuid": false,
        "mimetype": "inode/directory",
        "mode": "0755",
        "mtime": 1727491226.1313975,
        "nlink": 2,
        "path": "/root/test",
        "pw_name": "root",
        "readable": true,
        "rgrp": true,
        "roth": true,
        "rusr": true,
        "size": 4096,
        "uid": 0,
        "version": "1145341742",
        "wgrp": false,
        "woth": false,
        "writeable": true,
        "wusr": true,
        "xgrp": true,
        "xoth": true,
        "xusr": true
    }
}

#文件不存在
[root@ubuntu24 ~]# ansible 10.0.0.161 -m stat -a "path=/root/tt"
10.0.0.161 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "stat": {
        "exists": false
    }
}

unarchive 模块

unarchive 模块主要用来解压缩或解包,将 ansible 主机或其它主机上的压缩包复制到指定主机,再解压到某个目录

在使用此模块时,要保证远程主机能解压对应的压缩包(现在应该也并不是必须的)

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s unarchive
#常用选项

src=/path/file 		#包文件路径,可以是ansible主机上的包文件,也可以是远程主机上的文件(也可以是第三方主机)
dest=/pth/dir 		#目标路径
remote_src=yes|no #yes表示包文件在远程主机或第三方主机上,no表示包文件在ansible主机
上,默认值为no
copy=yes|no #yes表示包文件在ansible主机上,no表示包文件在远程主机或第三方主机
上,己废弃
creates=/path/file #此文件不存在才执行
mode=777 #设置目标权限
owner=USER #设置目标属主
group=GROUP #设置目标属组

#压缩并打包
[root@ubuntu24 ~]# tar zcvf dira.tar.gz ./

#将ansible主机上的压缩包解压至远程主机,远程目录必须存在
[root@ubuntu24 ~]# ansible 10.0.0.161 -m unarchive -a "src=/root/dira.tar.gz dest=/tmp/dira"
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "dest": "/tmp/dira",
    "extract_results": {
        "cmd": [
            "/usr/bin/tar",
            "--extract",
            "-C",
            "/tmp/dira",
            "-z",
            "-f",
            "/root/.ansible/tmp/ansible-tmp-1727505116.3163786-5773-224657750341971/source"
        ],
        "err": "",
        "out": "",
        "rc": 0
    },
    "gid": 0,
    "group": "root",
    "handler": "TgzArchive",
    "mode": "0700",
    "owner": "root",
    "size": 4096,
    "src": "/root/.ansible/tmp/ansible-tmp-1727505116.3163786-5773-224657750341971/source",
    "state": "directory",
    "uid": 0
}

#在远程主机上查看
[root@ubuntu24 ~]# ls /tmp/dira/
10.0.0.161  1.txt  dir1  dir2  mbox  passwd  passwdE  test.csr  test.key  test.sh

archive 模块

archive 模块在远程主机上执行压缩打包命令,此模块的源和目标都在远程主机上

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s archive

#常用选项
path=/path/dir 		#源目录或文件路径
dest=/pth/file 		#目标的文件路径
remove=false|true 	#是否删除源文件,默认 false
mode=777 			#设置目标权限
owner=USER 			#设置目标属主
group=GROUP 		#设置目标属组
format=bz2|gz|tar|xz|zip 	#指定压缩算法,默认 gz


[root@ubuntu24 ~]# ansible 10.0.0.161 -m archive -a "path=/root/* dest=/tmp/dirb/dira.bz2 format=bz2 "
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "archived": [
        "/root/1.txt.4569.2024-09-28@11:17:19~",
        "/root/apache-tomcat-9.0.95.tar.gz",
        "/root/app1/dir1",
        "/root/app1/index.html",
        "/root/app1/dir1/test.jsp",
        "/root/dira/index.html",
        "/root/dira/test.jsp",
        "/root/jpress/jpress-addons",
        "/root/jpress/docker",
        ....
         ],
    "arcroot": "/root/",
    "changed": true,
    "dest": "/tmp/dirb/dira.bz2",
    "dest_state": "archive",
    "expanded_exclude_paths": [],
    "expanded_paths": [
        "/root/dirb",
        "/root/dira",
        "/root/nginx-1.24.0",
        "/root/nginx-1.26.2",
        "/root/app1",
        "/root/sonatype-work",
        "/root/1.txt.4569.2024-09-28@11:17:19~",
        "/root/nexus-3.67.1-01-java11-unix.tar.gz",
        "/root/nginx-1.24.0.tar.gz",
        "/root/jpress",
        "/root/test",
        "/root/nginx-1.26.2.tar.gz",
        "/root/spring-boot-helloworld",
        "/root/apache-tomcat-9.0.95.tar.gz"
    ],
    "gid": 0,
    "group": "root",
    "missing": [],
    "mode": "0644",
    "owner": "root",
    "size": 1070759055,
    "state": "file",
    "uid": 0
}

[root@ubuntu24 ~]# ls -l /tmp/dirb/
total 1045668
-rw-r--r-- 1 root root 1070759055 Sep 28 14:55 dira.bz2

hostname 模块

此模块主要用于修改远程主机的主机名,修改后永久生效

bash 复制代码
[root@ubuntu24 ~]# ansible 10.0.0.161 -m hostname -a "name=test-1"
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "ansible_domain": "compute-1.amazonaws.com",
        "ansible_fqdn": "ec2-18-235-170-27.compute-1.amazonaws.com",
        "ansible_hostname": "test-1",
        "ansible_nodename": "test-1",
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "name": "test-1"
}

#远程主机查看
[root@ubuntu24 ~]# hostname
test-1

cron 模块

cron 模块用于管理远程主机上的 crontab 定时任务

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s cron

#常用选项
name=str 				#任务名称
job=/path/cmd args 		#具体任务命令
disabled=yes|no 		#是否禁用,默认 false
state=absent|present 	#absent 删除,默认present 
env=yes|no 				#yes设置环境变量,no 设置定时任务,默认 no
special_time=annually|daily|hourly|monthly|reboot|weekly|yearly 	#指定特殊时间
user=UNAME 				#指定任务用户
minute= 				#指定分钟参数
hour= 					#小时参数
day= 					#自然天参数
month= 					#自然月参数 
weekday= 				#星期参数


[root@ubuntu24 ~]# ansible 10.0.0.161 -m cron -a 'job="/usr/bin/wall test-crontab2" name=test-crontab'
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "envs": [],
    "jobs": [
        "test-crontab"
    ]
}

[root@ubuntu24 ~]# crontab -l
#Ansible: test-crontab
* * * * * /usr/bin/wall test-crontab2

#修改定时任务
[root@ubuntu24 ~]# ansible 10.0.0.161 -m cron -a 'job="/usr/bin/wall test-crontab222" minute=*/5 name=test-crontab'
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "envs": [],
    "jobs": [
        "test-crontab"
    ]
}

[root@ubuntu24 ~]# crontab -l
#Ansible: test-crontab
*/5 * * * * /usr/bin/wall test-crontab222

#禁用
[root@ubuntu24 ~]# ansible 10.0.0.161 -m cron -a 'job="/usr/bin/wall test-crontab" name=test-crontab disabled=yes'
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "envs": [],
    "jobs": [
        "test-crontab"
    ]
}

[root@ubuntu24 ~]# crontab -l
#Ansible: test-crontab
#* * * * * /usr/bin/wall test-crontab


#删除
[root@ubuntu24 ~]# ansible 10.0.0.161 -m cron -a 'job="/usr/bin/wall test-cron111" name=test-crontab state=absent'
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "envs": [],
    "jobs": []
}

yum 模块和 apt 模块

yum 模块和 apt 模块用于在远程主机上管理软件包,yum 模块适用于 redhat 系列,apt 适用于 debian 系列

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s yum

#常用选项
name=packagename 		#指定包名 name1,name2
state=absent|installed|latest|present|removed 		#absent|removed 删除,installed|present 安装,latest 升级到最新版
list=packagename|installed|updates|available|repos 	#此选项与name选项互斥,
 #写具体包名是相当于执行 yum list --showduplicates packagename


download_dir=/path 		#指定下载目录
download_only=yes|no 	#只下载不安装,默认 no
update_only=yes|no 		#yes 仅更新,默认no
use_backend=auto|yum|yum4|dnf 	#指定真实执行的命令,默认 auto
autoremove=yes|no 		#卸载依赖,仅在卸载时生效,默认no
disablerepo=repoid 		#排除某些仓库 repoid1,repoid2
enablerepo=repoid 		#从指定仓库中安装 repoid1,repoid2
validate_certs=yes|no 	#是否对包进行校验,默认yes
disable_gpg_check=yes|no 	#是否不对包进行校验,默认no
update_only=yes|no 	#只更新不安装,默认no


#列出指定软件包,相当于 yum list --showduplicates nginx
[root@ubuntu24 ~]# ansible rocky -m yum -a 'list=nginx'
10.0.0.153 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "msg": "",
    "results": [
        {
            "arch": "x86_64",
            "envra": "1:nginx-1.20.1-16.el9_4.1.x86_64",
            "epoch": "1",
            "name": "nginx",
            "nevra": "1:nginx-1.20.1-16.el9_4.1.x86_64",
            "release": "16.el9_4.1",
            "repo": "ali-appstraem",
            "version": "1.20.1",
            "yumstate": "available"
        },
        {
            "arch": "x86_64",
            "envra": "1:nginx-1.20.1-16.el9_4.1.x86_64",
            "epoch": "1",
            "name": "nginx",
            "nevra": "1:nginx-1.20.1-16.el9_4.1.x86_64",
            "release": "16.el9_4.1",
            "repo": "appstream",
            "version": "1.20.1",
            "yumstate": "available"
        }
    ]
}

#列出所有 repo
[root@ubuntu24 ~]# ansible rocky -m yum -a "list=repos"
10.0.0.153 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "msg": "",
    "results": [
        {
            "repoid": "ali-appstraem",
            "state": "enabled"
        },
        {
            "repoid": "nju-baseos",
            "state": "enabled"
        },
        {
            "repoid": "nju-extras",
            "state": "enabled"
        },
        {
            "repoid": "baseos",
            "state": "enabled"
        },
        {
            "repoid": "appstream",
            "state": "enabled"
        },
        {
            "repoid": "extras",
            "state": "enabled"
        }
    ]
}


#从指定源安装
[root@ubuntu24 ~]# ansible 10.0.0.153 -m yum -a 'name=nginx enablerepo=ali-appstraem'
10.0.0.153 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "msg": "",
    "rc": 0,
    "results": [
        "Installed: nginx-filesystem-1:1.20.1-16.el9_4.1.noarch",
        "Installed: nginx-1:1.20.1-16.el9_4.1.x86_64",
        "Installed: nginx-core-1:1.20.1-16.el9_4.1.x86_64"
    ]
}
#远程客户端
[root@Rocky-9 ~]# systemctl status nginx
○ nginx.service - The nginx HTTP and reverse proxy server
     Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; preset: disabled)
     Active: inactive (dead)
     
#卸载  
[root@ubuntu24 ~]# ansible 10.0.0.153 -m yum -a "name=nginx state=removed"
10.0.0.153 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "msg": "",
    "rc": 0,
    "results": [
        "Removed: nginx-1:1.20.1-16.el9_4.1.x86_64"
    ]
}

[root@Rocky-9 ~]# systemctl status nginx
Unit nginx.service could not be found.

apt 模块

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s apt

#常用选项
name=packagename 		#指定包名,可用通配符
autoclean=yes|no 		#清除本地安装包,只删除己卸载的软件的 deb包
deb=/path/file.deb 		#指定deb包,可以是本地的,也可以是网络的
autoremove=yes|no 		#卸载依赖包,默认no
only_upgrade=yes|no 	#仅更新,不安装
state=absent|build-dep|latest|present|fixed 	#absent 卸载,build-dep 安装依赖包, latest 安装或升级到最新版
 #present 安装,fixed 修复
update_cache=yes|no 	#更新索引

yum_repository 模块

此模块用来对远程主机上的 yum 仓库配置进行管理

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s yum_repository

#常用选项
name=repoid 		#repoid
description=desc 	#描述信息
baseurl=url 		#仓库地址
enabled=yes|no 		#是否启用
gpgcheck=yes|no 	#是否启用gpgcheck,没有默认值,默认跟随 /etc/yum.conf 中的全局配置
gpgkey=/path/key 	#gpgkey路径
state=absent|present 	#absent删除, present安装,默认present
timeout=30 			#超时时长,默认30s

apt_repository 模块

此模块实现 apt 仓库的配置管理,仅于用 debian 系列的环境中

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s apt_repository

#常用选项
repo=str 				#具体源
filename=/path/file 	#具体文件名,默认加到 /etc/apt/sources.list 中
state=absent|present 	#absent 删除,present 新增,默认 present
update_cache=yes|no 	#yes 更新源,相当于执行 apt-get update

service 模块

service 模块主要用于对远程主机的服务进行管理

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s service

#常用选项
name=servicename 	#服务名
enabled=yes|no 		#是否是开机启动
state=reloaded|restarted|started|stopped 	#具体操作
args=val 			#参数

#启动服务
[root@ubuntu24 ~]# ansible 10.0.0.161 -m service -a "name=nginx state=started"
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "name": "nginx",
    "state": "started",
    "status": {
        "ActiveEnterTimestamp": "Sat 2024-09-28 09:04:26 CST",
        
        。。。
        
[root@ubuntu24 ~]# systemctl status nginx.service
● nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: enabled)
     Active: active (running) since Sat 2024-09-28 16:04:31 CST; 45s ago
     。。

user 模块

此模块用于对远程主机进行用户管理

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s user

#常用选项
name=USERNAME 			#指定用户名
comment=str 			#用户描述信息
create_home=yes|no 		#是否创建家目录,默认yes
group=GROUPNAME 		#指定私有组
groups=group1,group2... #指定附加组
home=/path 				#指定家目录路径
shell=SHELL 			#指定shell
password=str 			#设置密码,必须是加密后的字符串
state=absent|present 	#absent 删除用户,present 创建用户,默认 present 
system=yes|no 			#是否创建系统账号,默认 no
uid=UID 				#手动指定uid
umask=UMASK 			#指定umask
remove=yes|no 			#是否删除家目录,默认 no
generate_ssh_key=yes|no #是否创建私钥,默认 no
ssh_key_bits=2048 		#指定私钥位数
ssh_key_file=/path/file #指定文件位置,默认 .ssh/id_rsa


#创建用户user1,并指定uid
[root@ubuntu24 ~]# ansible 10.0.0.161 -m user -a 'name=user1 comment="ansible user" uid=2048'
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "comment": "ansible user",
    "create_home": true,
    "group": 2048,
    "home": "/home/user1",
    "name": "user1",
    "shell": "/bin/sh",
    "state": "present",
    "system": false,
    "uid": 2048
}

#远程主机查看
[root@ubuntu24 ~]# id user1
uid=2048(user1) gid=2048(user1) groups=2048(user1)

#删除用户
[root@ubuntu24 ~]# ansible 10.0.0.161 -m user -a "name=user1 remove=yes state=absent"
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "force": false,
    "name": "user1",
    "remove": true,
    "state": "absent",
    "stderr": "userdel: user1 mail spool (/var/mail/user1) not found\n",
    "stderr_lines": [
        "userdel: user1 mail spool (/var/mail/user1) not found"
    ]
}

group 模块

此模块用于对远程主机的组管理

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s group

#常用选项
name=GROUPNAME 	#指定组名
gid=GID 		#指定组ID
state=absent|present 	#absent 删除,present 创建,默认present
system=yes|no 	#是否是系统组,默认no

lineinfile 模块

lineinfile 模块主要用于修改远程主机上的文件。

ansible 提供了两个常用的文件修改模块,其中 lineinfile 主要对文件单行进行替换修改,replace 模块主要进行多行替换和修改。

如果使用 ansible 调用 sed 进行文件修改时,经常会遇到需要转义的情况,而且在对特殊符号进行替换 时,有可能会失败。

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s lineinfile

#常用选项
path=/path/file 	#远程主机文件路径
regexp= 			#正则,用来锚定要被修改的内容
insertafter= 		#正则,在指定内容后的新行中增加line里面的内容,与regex同时使用时,只有regex没匹配才生效
insertbefore= 		#正则,在指定内容前的新行中增加line里面的内容,与regex同时使用时,只有regex没匹配才生效
line=str 			#修改后的内容
state=absent|present #absent 删除,present 不存在先创建
backup=yes|no 		#修改前先备份,默认no
create=yes|no 		#不存在先创建,默认no
backrefs=yes|no 	#是否支持引用,默认no不支持
mode=666 			#设置权限
owner=USER 			#指定属主
group=GROUP 		#指定属组

#使用 regexp 配合正则表达式来锚定要被修改的内容时,如果有多行被匹配,则只有最后一行会被替换,如果删除,则匹配到的行都会被删除


#在远程主机上查看
[root@ubuntu24 ~]# cat 2.txt
10.0.0.157
123132123

#替换最后一行
[root@ubuntu24 ~]# ansible 10.0.0.161 -m lineinfile -a 'path=/root/2.txt regexp="^123" line="10.0.0.161"'
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "backup": "",
    "changed": true,
    "msg": "line replaced"
}

[root@ubuntu24 ~]# cat 2.txt
10.0.0.157
10.0.0.161

#新增内容
[root@ubuntu24 ~]# ansible 10.0.0.161 -m lineinfile -a 'path=/root/2.txt insertafter="157$" line="AAAAA"'
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "backup": "",
    "changed": true,
    "msg": "line added"
}
[root@ubuntu24 ~]# cat 2.txt
10.0.0.157
AAAAA
10.0.0.161

#删除行
[root@ubuntu24 ~]# ansible 10.0.0.161 -m lineinfile -a 'path=/root/2.txt regexp="^A" backup=yes state=absent'
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "backup": "/root/2.txt.8403.2024-09-28@16:36:03~",
    "changed": true,
    "found": 1,
    "msg": "1 line(s) removed"
}
[root@ubuntu24 ~]# cat 2.txt
10.0.0.157
10.0.0.161

#文件不存在,创建新文件
[root@ubuntu24 ~]# ansible 10.0.0.161 -m lineinfile -a 'path=/root/3.txt line="ABCD" create=yes owner=tom mode=777'
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "backup": "",
    "changed": true,
    "msg": "line added and ownership, perms or SE linux context changed"
}
[root@ubuntu24 ~]# ls -l 3.txt
-rwxrwxrwx 1 tom root 5 Sep 28 16:38 3.txt

replace 模块

该模块功能与 lineinfile 模块功能类似,也是基于正则匹配的模式来修改文件,但与 lineinfile 不同的是 replace 模块用于多行匹配和修改

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s replace

#常用选项
path=/path/file 	#远程主机文件路径
regexp= 			#正则,用来锚定要被修改的内容
replace=STR 		#用来替换的内容
after=STR 			#从STR之后开始处理
before=STR 			#处理到STR之前
backup=yes|no 		#修改前是否备份,默认 no
mode=666 			#设置权限
owner=USER 			#指定属主
group=GROUP 		#指定属组


#替换所有3个数字的行
[root@ubuntu24 ~]# ansible 10.0.0.161 -m replace -a "path=/root/2.txt regexp='^([0-9]{3})$' replace='\1----\1' backup=yes"
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "backup_file": "/root/2.txt.8617.2024-09-28@16:48:44~",
    "changed": true,
    "msg": "3 replacements made",
    "rc": 0
}

#只处理 10.0.0.161行到456行中间的内容
[root@ubuntu24 ~]# ansible 10.0.0.161 -m replace -a "path=/root/2.txt after='10.0.0.161' before='456' regexp='^(.+)$' replace='# \1'"
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "msg": "2 replacements made",
    "rc": 0
}

[root@ubuntu24 ~]# cat 2.txt
10.0.0.157
10.0.0.161
# 123----123
# 123----123
456----456
abcdefg
ABCDEFG
123root

selinux 模块

selinux 模块用作对远程主机的 selinux 机制进行管理

bash 复制代码
[root@ubuntu24 ~]# ansible-doc -s selinux

#常用选项
configfile=/path/file 			#selinux 配置文件路径,默认/etc/selinux/config
policy=targeted|minimum|mls 	#在state值不为 disabled 时必选
state=disabled|enforcing|permissive 	#具体设置

reboot 模块

reboot 模块主要用于对远程主机进行重启操作

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s reboot

#常用选项
msg=str 			#广播重启提示消息,默认为空
test_command=str 	#重启后执行验证命令,默认 whoami
reboot_timeout=600 	#超时时长,默认600S
pre_reboot_delay=0 	#执行重启前等待时长,如果小于60S,此字段会被置0,也就是无效
post_reboot_delay=0 #重启后等待一个时长后再验证是否重启完成


#远程主机在重启过程中此进程会一直等待,直到超时
[root@ubuntu24 ~]# ansible 10.0.0.161 -m reboot -a 'pre_reboot_delay=65 msg="This is a msg"'
10.0.0.161 | CHANGED => {
    "changed": true,
    "elapsed": 83,
    "rebooted": true
}
#远程主机收到广播
This is a msg
The system will reboot at Sat 2024-09-28 17:00:05 CST!

mount 模块

mount 模块用于管理远程主机的挂载

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s mount

#常用选项
src=/path/device #要挂载的设备路径,可以是网络地址
path=/path/point #挂载点
state=absent|mounted|present|unmounted|remounted  
	# absent 取消挂载,并删除永久挂载中的配置
  	# mounted 永久挂载,立即生效,挂载点不存在会自动创建
  	# present 永久挂载,写配置文件,但不会立即生效
	# unmounted 临时取消挂载,不改变配置文件
	# remounted 重新挂载,但不会改变配置文件
fstab=/path/file 	#指定挂载配置文件路径,默认 /etc/fstab
fstype=str 			#设备文件系统 xfs|ext4|swap|iso9660...
opts=str 			#挂载选项


#挂载光盘,永久挂载,并立即生效
[root@ubuntu24 ~]# ansible 10.0.0.161 -m mount -a 'src=/dev/sr0 path=/mnt/ state=mounted fstype=iso9660'
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "backup_file": "",
    "boot": "yes",
    "changed": true,
    "dump": "0",
    "fstab": "/etc/fstab",
    "fstype": "iso9660",
    "name": "/mnt/",
    "opts": "defaults",
    "passno": "0",
    "src": "/dev/sr0"
}

[root@test-1 /]# ls -l mnt
total 45
dr-xr-xr-x 1 root root  2048 Feb 14  2024 boot
-r--r--r-- 1 root root  2048 Apr 23 20:46 boot.catalog
dr-xr-xr-x 1 root root  4096 Apr 23 20:45 casper
dr-xr-xr-x 1 root root  2048 Apr 23 20:44 dists
dr-xr-xr-x 1 root root  2048 Feb 14  2024 EFI
dr-xr-xr-x 1 root root  2048 Apr 23 20:44 install
-r--r--r-- 1 root root 29026 Apr 23 20:46 md5sum.txt
dr-xr-xr-x 1 root root  2048 Apr 23 20:44 pool
lr-xr-xr-x 1 root root     1 Apr 23 20:44 ubuntu -> .

#取消挂载,永久生效
[root@ubuntu24 ~]# ansible 10.0.0.161 -m mount -a 'src=/dev/sr0 path=/mnt/ state=absent'
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "backup_file": "",
    "boot": "yes",
    "changed": true,
    "dump": "0",
    "fstab": "/etc/fstab",
    "name": "/mnt/",
    "opts": "defaults",
    "passno": "0",
    "src": "/dev/sr0"
}

setup 模块

此模块主要用来从远程主机上收集相关信息在 ansible 主机上显示,由于需要收集的信息较多,此模块执行较慢。

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s setup

#常用选项
filter=filed1,filed2 	#只显示指定字段,可以用通配符,可以写多个,可以用 !取反
gather_timeout=10 		#超时时长,默认10S


#收集所有字段
[root@ubuntu24 ~]# ansible 10.0.0.161 -m setup
10.0.0.161 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "10.0.0.161"
        ],
        "ansible_all_ipv6_addresses": [
            "fe80::20c:29ff:fe4e:cc99"
        ],
        "ansible_apparmor": {
            "status": "enabled"
            。。。
            
#只显示主机名
[root@ubuntu24 ~]# ansible 10.0.0.161 -m setup -a 'filter=ansible_hostname'
10.0.0.161 | SUCCESS => {
    "ansible_facts": {
        "ansible_hostname": "test-1",
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false
}

debug 模块

此模块可以用于输出信息,并且通过 msg 定制输出的信息内容,功能类似于 echo 命令

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s debug

#常用选项
msg=str 			#输出消息内容,默认 Hello world!
var=val 			#指定变量名,和 msg 互斥
verbosity=0|1|2|3 	#指定调试级别,verbosity=2 则表示仅在 -vv|-vvv|-vvvv 的级别下显示


#默认消息
[root@ubuntu24 ~]# ansible 10.0.0.161 -m debug
10.0.0.161 | SUCCESS => {
    "msg": "Hello world!"
}

[root@ubuntu24 ~]# ansible 10.0.0.161 -m debug -a 'msg="this is test msg"'
10.0.0.161 | SUCCESS => {
    "msg": "this is test msg"
}

#设定了运行级别,当前跳过
[root@ubuntu24 ~]# ansible 10.0.0.161 -m debug -a 'msg="this is test msg" verbosity=2'
10.0.0.161 | SKIPPED

sysctl 模块

sysctl 模块用来修改远程主机上的内核参数

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s sysctl

#常用选项
name=str 		#参数名称
val=str 		#参数值
reload=yes|no 	#默认yes,调用 /sbin/sysctl -p 生效
state=present|absent 	#是否保存到文件,默认present
sysctl_file=/path/file 	#指定保存文件路径,默认 /etc/sysctl.conf
sysctl_set=yes|no 		#是否使用systctl -w 校验,默认no


#修改内核参数,并写文件
[root@ubuntu24 ~]# ansible 10.0.0.161 -m sysctl -a 'name=net.ipv4.ip_forward value=1'
10.0.0.161 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true
}

pam_limits 模块

此模块主要用于管理远程主机上的资源限制

bash 复制代码
#查看帮助
[root@rocky86 ~]# ansible-doc -s pam_limits

#常用选项
domain=username|@groupname|UID|GID 		#具体对象
limit_item=core|data|fsize|memlock|nofile|rss|stack|cpu|nproc|as|maxlogins|maxsyslogins|priority|locks|
sigpending|msgqueue|nice|rtprio|chroot 	#修改内容
limit_type=hard|soft|- 		#限定类型
value=str 			#具体值

apt_key 模块

此模块实现 apt 仓库的key 的配置管理,仅于用 debian 系列的环境中

bash 复制代码
#查看帮助
[root@ubuntu ~]# ansible-doc -s apt_key

#常用选项
url=URL 				#key文件路径
validate_certs=yes|no 	#是否校验https 的 ssl 证书,默认yes
state=absent|present 	#absent 删除,present 新增,默认 present

其它模块

除了上述模块之外,ansible 还提供了很多其它的模块,在我们需要使用时,可以再进行查询

bash 复制代码
ansible-doc -l | grep "模块关键字"
ansible-doc 模块名
相关推荐
雅欣-鱼子酱4 分钟前
什么是PD协议?握手过程是怎样的?
linux·运维·网络
小安运维日记32 分钟前
Linux云计算 |【第四阶段】RDBMS1-DAY5
linux·运维·服务器·数据库·mysql·云计算
黑马金牌编程1 小时前
nginx常用的性能优化
运维·服务器·nginx·性能优化
@游子1 小时前
Linux-基础篇文件权限和组的管理-练习实践(附答案)
linux·运维·服务器
西西o1 小时前
Linux服务安装node,npm与yarn
linux·运维·npm
熊明才2 小时前
How to install JetBrains ToolBox in Ubuntu 22.04 LTS?
linux·运维·ubuntu
pyliumy2 小时前
ansible 配置
大数据·ansible
青春不流名2 小时前
解决 GitHub 文件大小限制的问题
运维
傲娇的鲤鱼3 小时前
基于RustDesk自建远程桌面服务
java·运维·服务器·远程工作