ansible role test测试

在 Ansible roles 目录结构中,tests/ 目录主要用于测试该角色是否可以正确运行,确保它能在不同环境中顺利执行。

tests/ 目录的内容

在你的 tests/ 目录下,有两个文件:

  1. 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:

  1. /opt/ansible/playbook/roles/roles/es_cluster/tests/roles
  2. /root/.ansible/roles
  3. /usr/share/ansible/roles
  4. /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
复制代码

 

posted @   不会跳舞的胖子  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示