ansible role test测试
在 Ansible roles 目录结构中,tests/
目录主要用于测试该角色是否可以正确运行,确保它能在不同环境中顺利执行。
tests/
目录的内容
在你的 tests/
目录下,有两个文件:
-
inventory
- 这个文件通常定义了测试环境中的主机(类似
hosts
文件)。
- 这个文件通常定义了测试环境中的主机(类似
[test_servers]
localhost ansible_connection=local
这个配置表示测试将在本机 (localhost
) 运行,不依赖远程主机。
test.yml
- 这是一个 playbook,用于测试这个 role 是否能正确执行。
---
- hosts: localhost
remote_user: root
gather_facts: yes
roles:
- es_cluster
这里 es_cluster
是当前目录下的 role 名称,Ansible 在执行这个 playbook 时会调用 es_cluster
角色,并应用它的任务。
运行测试 Playbook
ansible-playbook -i tests/inventory tests/test.yml
为什么需要 tests/
目录?
- 本地测试:可以先在
localhost
上验证 role 的正确性,避免直接在生产环境运行出现问题。
执行报错
[root@master-1 es_cluster]# ansible-playbook -i tests/inventory tests/test.yml ERROR! the role 'es_cluster' was not found in /opt/ansible/playbook/roles/roles/es_cluster/tests/roles:/root/.ansible/roles:/usr/share/ansible/roles:/etc/ansible/roles:/opt/ansible/playbook/roles/roles/es_cluster/tests The error appears to be in '/opt/ansible/playbook/roles/roles/es_cluster/tests/test.yml': line 6, column 7, but may be elsewhere in the file depending on the exact syntax problem. The offending line appears to be: roles: - es_cluster ^ here [root@master-1 es_cluster]# cat tests/test.yml --- - hosts: localhost remote_user: root gather_facts: yes roles: - es_cluster [root@master-1 es_cluster]# cat tests/ inventory test.yml [root@master-1 es_cluster]# cat tests/inventory localhost
原因是 Ansible 找不到 es_cluster
这个 role
问题分析
Ansible 在运行 tests/test.yml
时,会查找 es_cluster
角色的路径,但默认情况下,它会在以下路径中查找 role:
/opt/ansible/playbook/roles/roles/es_cluster/tests/roles
/root/.ansible/roles
/usr/share/ansible/roles
/etc/ansible/roles
然而,你的 es_cluster
role 目录位于 当前路径,但 Ansible 并不会自动在 tests/
的上一级目录查找 role。
解决方法
在 ansible.cfg
中指定 roles 目录
[defaults] #roles_path = /etc/ansible/roles roles_path = /opt/ansible/playbook/roles/roles [root@master-1 es_cluster]# ll /opt/ansible/playbook/roles/roles 总用量 0 drwxr-xr-x 11 root root 167 2月 21 13:21 es_cluster drwxr-xr-x 2 root root 6 2月 21 11:06 kafka drwxr-xr-x 10 root root 154 2月 21 11:39 my_role drwxr-xr-x 2 root root 6 2月 21 11:06 mysql drwxr-xr-x 10 root root 116 2月 21 11:07 nginx drwxr-xr-x 2 root root 6 2月 21 11:06 redis drwxr-xr-x 2 root root 6 2月 21 11:06 zk
越学越感到自己的无知
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现