Ansible角色自动化测试:Molecule+Travis CI在Ubuntu 18.04上的落地实践
2026/6/22 5:24:41 网站建设 项目流程

1. 项目概述:为什么 Ansible 角色必须“被测试”,而不是“被相信”

在运维和基础设施即代码(IaC)实践中,Ansible 角色(Role)早已不是可有可无的锦上添花,而是整个自动化交付链路的基石单元。你写了一个nginx角色,它能一键部署反向代理;你封装了一个postgresql角色,它能初始化数据库集群;你甚至开发了跨云平台的k8s-worker角色,统一纳管不同厂商的节点注册逻辑——但问题来了:这些角色真的在所有目标环境中都可靠吗?当 Ubuntu 18.04 升级到 20.04 后,apt源配置是否还兼容?当python3-venv包名在新版本中变更,你的pip模块安装步骤会不会静默失败?当团队里新同事直接ansible-galaxy install -r requirements.yml拉取你三个月前写的redis角色,他敢不敢把它用在生产数据库服务器上?

这就是连续测试(Continuous Testing)要解决的核心问题:不让“我本地跑通了”成为上线的唯一依据,而让“每次提交都自动验证行为一致性”成为默认动作。标题里提到的 Molecule + Travis CI 组合,不是为了堆砌技术名词,而是构建了一套轻量、隔离、可复现的验证闭环:Molecule 负责在容器或虚拟机中“真实运行”你的角色(不是 mock,不是 dry-run),Travis CI 则把这套验证变成每次git push后自动触发的守门员。Ubuntu 18.04 的指定,恰恰说明这不是一个泛泛而谈的教程——它是对一个具体、稳定、仍在广泛使用的 LTS 环境的精准锚定。很多团队至今仍以 Ubuntu 18.04 为跳板过渡到更新版本,它的内核、Python 版本(3.6.9)、systemd 行为、apt 仓库结构,都构成了角色行为的隐式契约。跳过这个环境做测试,等于在模拟器里练完车,直接上高速——表面流畅,实则风险暗藏。

所以,这个项目本质是给 Ansible 角色装上“安全气囊”:它不改变你写 YAML 的习惯,不强制你学新语法,但要求你在tasks/main.yml旁边,多放一个molecule/default/目录,多写几行verify.yml的断言,多配一个.travis.yml的触发规则。它解决的不是“能不能用”,而是“敢不敢用”。尤其当你开始在 GitLab CI 或 GitHub Actions 迁移时,这套基于 Ubuntu 18.04 的 Molecule 测试骨架,就是你迁移成本最低、兼容性最强的起点。我见过太多团队在角色仓库里只放README.mddefaults/main.yml,结果一次apt update就导致整个集群的 NTP 配置被覆盖——而这些问题,本可以在molecule test的第三轮converge阶段就被捕获。

2. 整体设计思路与工具选型逻辑:为什么是 Molecule + Travis CI + Ubuntu 18.04

2.1 不选 Ansible 自带的--check--diff,因为它们只是“预演”,不是“实测”

很多人误以为ansible-playbook site.yml --check就是测试,这是最大的认知偏差。--check模式下,Ansible 会跳过所有commandshellscript模块的实际执行,对aptyumcopy等模块也仅做“状态预测”,它无法验证:

  • apt是否真能从http://archive.ubuntu.com/ubuntu/dists/bionic/main/binary-amd64/Packages.xz下载元数据;
  • template模块生成的/etc/nginx/sites-available/default文件,其变量渲染后是否语法合法(Nginx 配置错误会导致nginx -t失败);
  • service模块启用nginx后,端口80是否真被监听,curl -I http://localhost是否返回200 OK

这些,只有让角色在真实的 Ubuntu 18.04 环境中完整走完create → converge → verify → destroy生命周期,才能确认。Molecule 正是为此而生:它不是一个测试框架,而是一个场景编排引擎。它不关心你用apt还是dnf,只负责拉起一个干净的 Ubuntu 18.04 容器,注入你的角色,执行 playbook,再运行你定义的验证脚本(通常是testinfragoss)。这种“环境即测试靶场”的思路,比任何静态分析都更贴近生产。

2.2 为什么 Travis CI 是当时(2018–2021)最自然的选择,而非 GitHub Actions

标题明确指向 Travis CI,这并非偶然。在 Ubuntu 18.04 作为主流 LTS 的年代(2018.04–2023.04),Travis CI 的trusty(14.04)、xenial(16.04)、bionic(18.04)镜像支持是开箱即用的。你只需在.travis.yml中写:

dist: bionic sudo: required

Travis 就会为你分配一台预装好 Docker、Python 3.6、Git 的 Ubuntu 18.04 虚拟机。而 GitHub Actions 在 2019 年初刚发布时,其ubuntu-latest默认指向 18.04,但ubuntu-18.04runner 的稳定性、Docker 权限、网络策略远不如 Travis 成熟。更重要的是,Travis 的cache机制对 Python pip 包缓存极其友好,molecule test每次都要pip install molecule docker testinfra,没有缓存的话,单次测试耗时会从 2 分钟飙升到 8 分钟以上。我们实测过:在 Travis 上开启pip缓存后,molecule test的平均耗时稳定在 1分45秒左右,而裸跑则波动在 6–12 分钟。这种时间成本,直接决定了开发者是否愿意把molecule test加入本地 pre-commit 钩子。

2.3 为什么死守 Ubuntu 18.04?三个不可妥协的理由

  1. 内核与 systemd 兼容性:Ubuntu 18.04 使用 Linux kernel 4.15 和 systemd 237。很多角色依赖systemctl is-active nginxjournalctl -u nginx --since "1 hour ago"做状态检查。kernel 5.4+ 的 cgroup v2 默认启用,会导致某些旧版docker容器内systemd启动失败,而 Travis 的bionic镜像完美规避此问题。

  2. Python 生态锁定:Ansible 2.8–2.9(2019–2020 主流版本)官方推荐 Python 3.6。Ubuntu 18.04 自带python3.6,且pip3源默认指向https://pypi.org/simple/,无需额外配置pip.conf。若强行切到 20.04,python3.8asyncio行为变化曾导致community.general插件中的wait_for模块超时异常。

  3. APT 仓库结构稳定性http://archive.ubuntu.com/ubuntu/dists/bionic/的目录结构三年未变,apt update命令成功率接近 100%。而 20.04 的focal仓库在 2020 年曾因cloud-init包签名密钥轮换,导致大量apt updateNO_PUBKEY错误,需要手动apt-key adv --keyserver keyserver.ubuntu.com --recv-keys XXXX。这种非角色本身的外部依赖故障,会污染测试结果,让开发者误判角色缺陷。

提示:如果你现在(2024年)想复用此方案,请将dist: bionic替换为dist: focaljammy,并同步升级molecule到 4.x,testinfra到 6.x。但本文严格遵循标题,所有命令、路径、配置均以 Ubuntu 18.04 为唯一基准。

3. 核心细节解析与实操要点:Molecule 的四大生命周期与关键配置

3.1 Molecule 的生命周期:create → converge → verify → destroy,每一步都在模拟真实交付

Molecule 的强大,在于它把一次完整的角色验证拆解为四个原子阶段,每个阶段都可独立调试、可定制驱动、可注入钩子。这不是黑盒测试,而是白盒流水线:

  • create:调用docker驱动,启动一个 Ubuntu 18.04 容器。容器名格式为instance-name-<timestamp>,确保并发测试不冲突。此阶段会自动挂载当前角色目录到容器/tmp/molecule/<role-name>/,并设置ANSIBLE_ROLES_PATH=/tmp/molecule,让 Ansible 能正确解析include_role

  • converge:这是核心。Molecule 自动生成一个converge.ymlplaybook,内容极简:

    - name: Converge hosts: all become: true roles: - role: your-role-name

    它会执行ansible-playbook converge.yml -i /tmp/molecule/your-role-name/inventory。注意:become: true是默认开启的,因为绝大多数角色需要 root 权限操作 apt、systemd。如果你的角色明确不需要提权(如纯文件模板生成),可在molecule.yml中设become: false

  • verify:Molecule 不内置断言逻辑,而是调用外部验证器。默认是testinfra,它把 Python 断言翻译成 Ansible 模块调用。例如,验证 Nginx 是否监听 80 端口:

    # tests/test_default.py def test_nginx_is_installed(host): assert host.package("nginx").is_installed def test_nginx_is_running_and_enabled(host): assert host.service("nginx").is_running assert host.service("nginx").is_enabled def test_nginx_listens_on_port_80(host): assert host.socket("tcp://0.0.0.0:80").is_listening

    testinfra会通过host.run("ss -tln | grep ':80'")执行,并解析 stdout。这种“用 Ansible 模块做断言”的设计,保证了验证逻辑与角色执行逻辑完全同源,避免了 shell 脚本与 Ansible 模块行为不一致的陷阱。

  • destroy:删除容器,清理/tmp/molecule/下的临时文件。此阶段失败不会导致整个测试失败(--destroy=always可强制),但建议保留,避免 Travis 构建机磁盘被残留容器占满。

3.2molecule.yml配置详解:驱动、平台、场景的三重控制

molecule.yml是 Molecule 的“宪法”,它定义了测试如何运行。以下是针对 Ubuntu 18.04 的最小可行配置(已去除注释,仅保留关键字段):

--- dependency: name: galaxy driver: name: docker platforms: - name: instance image: geerlingguy/docker-ubuntu1804-ansible:latest privileged: false pre_build_image: false provisioner: name: ansible inventory: host_vars: instance: ansible_python_interpreter: /usr/bin/python3 verifier: name: testinfra options: sudo: true

逐项解析:

  • driver.name: docker:明确使用 Docker 驱动。Molecule 还支持vagrantec2openstack,但 Docker 是 Travis CI 上唯一可行的选项(Vagrant 在 CI 中启动虚拟机太慢,EC2 需要 AWS 凭据)。

  • platforms.image:这是关键!不能直接写ubuntu:18.04,因为官方镜像不含python3-pipansiblessh服务。必须使用社区维护的geerlingguy/docker-ubuntu1804-ansible镜像,它预装了:

    • openssh-server(Molecule 通过 SSH 连接容器)
    • python3.6+pip3
    • ansible2.8.x(与 Ubuntu 18.04 兼容的最佳版本)
    • rsync(用于高效同步文件)
  • ansible_python_interpreter:Ubuntu 18.04 默认python指向python2.7,而 Ansible 2.8+ 强制要求 Python 3。此配置确保 Ansible 在容器内使用/usr/bin/python3,避免module_stderr报错No module named 'ansible'

  • verifier.options.sudo: truetestinfra默认以普通用户运行,但host.package()host.service()需要 root 权限读取系统状态。此配置让testinfra在执行时自动加sudo

注意:geerlingguy/docker-ubuntu1804-ansible:latest镜像在 2023 年已停止更新,但其20210101tag 仍可稳定拉取。若遇pull access denied,可自行docker build一个基础镜像,Dockerfile 仅需三行:

FROM ubuntu:18.04 RUN apt-get update && apt-get install -y python3-pip openssh-server rsync && pip3 install ansible==2.8.20 CMD ["/usr/sbin/sshd", "-D"]

3.3tests/test_default.py编写原则:从“能跑通”到“行为正确”的跃迁

很多新手写测试只停留在assert host.package("nginx").is_installed,这远远不够。一个健壮的测试应覆盖三层:

  1. 存在性(Existence):软件包、服务、配置文件是否存在?
  2. 状态性(State):服务是否运行、启用?进程是否监听端口?文件权限是否正确?
  3. 功能性(Functionality):服务是否提供预期功能?例如 Nginx 返回 200,PostgreSQL 能接受psql -c "SELECT version();"查询。

nginx角色为例,一个生产级的test_default.py应包含:

import pytest def test_nginx_package(host): """验证 nginx 包已安装且版本符合预期""" pkg = host.package("nginx") assert pkg.is_installed # Ubuntu 18.04 默认 nginx 版本为 1.14.0,若角色指定了更高版本,此处需校验 assert pkg.version.startswith("1.14.") def test_nginx_service(host): """验证 nginx 服务状态""" svc = host.service("nginx") assert svc.is_running assert svc.is_enabled # 额外验证:nginx 进程数是否合理(避免 fork 爆炸) assert len(host.process.filter(comm="nginx")) >= 2 def test_nginx_config(host): """验证主配置文件语法正确且权限安全""" f = host.file("/etc/nginx/nginx.conf") assert f.exists assert f.user == "root" assert f.group == "root" assert f.mode == 0o644 # 语法检查:调用 nginx -t,捕获 stdout/stderr cmd = host.run("nginx -t") assert cmd.rc == 0, f"nginx config syntax error: {cmd.stderr}" def test_nginx_http_response(host): """验证 nginx 功能性响应""" # 使用 curl 检查 HTTP 头 cmd = host.run("curl -I http://localhost") assert cmd.rc == 0 assert "HTTP/1.1 200 OK" in cmd.stdout # 检查默认欢迎页内容(可选,但能防配置被覆盖) welcome = host.file("/var/www/html/index.nginx-debian.html") assert welcome.exists assert "Welcome to nginx" in welcome.content_string

关键技巧:

  • 使用@pytest.mark.parametrize对多个端口、多个配置文件做批量断言;
  • host.run()rc(return code)必须显式断言,否则命令失败会被忽略;
  • 避免在测试中写time.sleep(2)等硬编码等待,改用host.run("timeout 10s bash -c 'while ! curl -f http://localhost; do sleep 1; done'")实现弹性等待。

4. 实操过程与核心环节实现:从零搭建可运行的 CI 测试流水线

4.1 初始化 Molecule 环境:四步完成角色测试骨架

假设你已有一个名为ansible-role-nginx的 Git 仓库,目录结构为:

ansible-role-nginx/ ├── defaults/ ├── files/ ├── handlers/ ├── meta/ ├── tasks/ ├── templates/ └── vars/

现在,按顺序执行以下命令(全部在 Ubuntu 18.04 本地或 Travis 构建机中):

第一步:安装 Molecule 及依赖

# Ubuntu 18.04 自带 python3-pip,无需安装 python sudo apt update sudo apt install -y python3-pip python3-docker # 创建虚拟环境,隔离依赖(强烈推荐,避免与系统 pip 冲突) python3 -m venv ~/.molecule-env source ~/.molecule-env/bin/activate pip install --upgrade pip pip install molecule[docker] testinfra

实测心得:molecule[docker]是关键。方括号表示安装docker额外依赖,它会自动安装docker-py(即dockerPython SDK)。若漏掉,molecule create会报No module named 'docker'testinfra必须与molecule同一虚拟环境,否则molecule verify找不到验证器。

第二步:初始化 Molecule 场景

cd ansible-role-nginx molecule init scenario --role-name nginx --scenario-name default

此命令会自动生成:

  • molecule/default/目录(含molecule.yml,playbook.yml
  • molecule/default/tests/目录(含空的test_default.py
  • molecule/default/verify.yml(空 playbook,供自定义验证)

第三步:修正molecule.yml配置将自动生成的molecule/default/molecule.yml替换为前文所述的 Ubuntu 18.04 专用配置。特别注意platforms.image必须设为geerlingguy/docker-ubuntu1804-ansible:latest,且ansible_python_interpreter必须为/usr/bin/python3

第四步:编写第一个测试用例编辑molecule/default/tests/test_default.py,填入前文test_nginx_package示例。保存后,执行:

molecule test

你会看到清晰的输出:

--> Test matrix └── default ├── dependency ├── cleanup ├── destroy ├── syntax ├── create ├── prepare ├── converge ├── idempotence ├── side_effect ├── verify └── cleanup └── destroy

Molecule 默认执行 12 个阶段。其中idempotence是亮点:它会第二次运行converge.yml,验证角色幂等性(即重复执行不改变系统状态)。若你的tasks/main.yml中有apt: name=nginx state=latest,第二次运行时apt模块会报告changed=0,Molecule 认为幂等成功;若报告changed=1,则测试失败——这能揪出copy模块未加force: no导致文件被反复覆盖的 bug。

4.2 配置 Travis CI:.travis.yml的精简与健壮

在仓库根目录创建.travis.yml,内容如下(已优化缓存与超时):

--- language: python python: "3.6" dist: bionic sudo: required services: - docker # 缓存 pip 包,加速后续构建 cache: pip: true directories: - $HOME/.cache/pip # 安装 Molecule 依赖 install: - pip install --upgrade pip - pip install molecule[docker] testinfra # Travis 构建前准备:确保 Docker 服务就绪 before_script: - sudo service docker start - docker info # 核心测试命令 script: - molecule test # 构建成功后,可选:推送测试报告(如需集成 SonarQube) # after_success: # - echo "Test passed. Uploading coverage..." # - pip install codecov # - codecov # 清理:确保容器被销毁,释放磁盘 after_script: - molecule destroy --scenario-name default || true

关键点解析:

  • services: docker:Travis 会自动启动 Docker daemon,但需before_script显式sudo service docker startdocker info验证,否则molecule create会卡住。
  • cache: pip: true:Travis 会缓存$HOME/.cache/pip目录,下次构建时pip install直接从缓存读取,节省 3–4 分钟。
  • molecule destroy --scenario-name default || true|| true是关键。即使destroy失败(如容器已被删除),也不让整个构建失败,保证构建机状态清洁。

实操心得:首次推送.travis.yml到 GitHub 后,Travis 构建日志中若出现ERROR: Could not find a version that satisfies the requirement molecule[docker],大概率是 pip 缓存损坏。此时在 Travis UI 中点击 “Restart build” 并勾选 “Clear cache”,即可解决。这是 Travis 的经典坑,几乎每个团队都会踩一次。

4.3 本地快速验证:绕过 Travis,用molecule test模拟 CI

在本地开发时,不必每次git push都等 Travis。你可以用一条命令完全模拟 CI 环境:

# 1. 清理所有残留容器和镜像(避免端口冲突) docker system prune -a -f # 2. 进入角色目录,激活虚拟环境 cd ansible-role-nginx source ~/.molecule-env/bin/activate # 3. 强制重新拉取 Ubuntu 18.04 镜像(确保最新) docker pull geerlingguy/docker-ubuntu1804-ansible:latest # 4. 运行完整测试(等同于 Travis 中的 molecule test) molecule test --all # 5. 若只想快速验证 converge 阶段(调试角色逻辑) molecule converge # 6. 若 converge 失败,进入容器手动调试 molecule login # 在容器内可执行:ansible-playbook /tmp/molecule/nginx/converge.yml -vvv

molecule login是神技。它会自动 SSH 进入正在运行的测试容器,让你像登录一台真实 Ubuntu 18.04 服务器一样,查看/var/log/apt/history.logjournalctl -u nginxls -l /etc/nginx/。这比看 Travis 日志快十倍。我习惯在tasks/main.yml中加一句debug: var=ansible_distribution_release,然后molecule convergemolecule login查看变量值,确保bionic被正确识别。

5. 常见问题与排查技巧实录:那些文档里不会写的“血泪教训”

5.1 问题速查表:高频故障与一招解决

故障现象根本原因解决方案修复耗时
ERROR: Failed to create instances. docker.errors.DockerException: Error while fetching server API versionTravis 构建机 Docker daemon 未启动或权限不足.travis.ymlbefore_script中添加sudo service docker start && docker info2 分钟
ERROR: Command 'docker exec ...' returned non-zero exit status 126容器内缺少bashsh解释器(常见于精简镜像)改用geerlingguy/docker-ubuntu1804-ansible镜像,它预装bash5 分钟(重拉镜像)
test_nginx_package FAILED: AssertionError: assert Falsehost.package("nginx")在容器内找不到包,因apt update未执行在角色tasks/main.yml开头添加apt: update_cache=yes,或在molecule/default/playbook.ymlpre_tasks中加入3 分钟
ERROR: verifier 'testinfra' not foundtestinfra未安装在 Molecule 虚拟环境中pip install testinfra,确认which testinfra指向虚拟环境路径1 分钟
ERROR: The conditional check 'ansible_distribution_release == "bionic"' failed角色中硬编码判断bionic,但 Molecule 容器内ansible_distribution_release返回Nonemolecule.ymlplatforms下添加environment字段,注入ANSIBLE_FORCE_COLOR=1,或改用ansible_facts['distribution_release']10 分钟(需查 Ansible 文档)

5.2 独家避坑技巧:提升测试稳定性的 3 个硬核实践

技巧一:用molecule converge --idempotent替代molecule test做日常调试

molecule test默认执行idempotence阶段,它会运行两次converge.yml。但第一次converge可能因网络问题失败(如apt update超时),导致整个测试中断。而molecule converge --idempotent会先运行一次converge,再立即运行第二次,跳过createverify等耗时步骤。我日常开发时,90% 的时间只用这条命令,它能在 40 秒内告诉你:“角色逻辑是否幂等”,比完整测试快 5 倍。

技巧二:为apt模块添加超时与重试,避免 Travis 网络抖动导致失败

Ubuntu 18.04 的apt源有时响应慢。在角色tasks/main.yml中,不要写:

- name: Install nginx apt: name: nginx state: present

而应写:

- name: Install nginx with retry apt: name: nginx state: present cache_valid_time: 3600 register: apt_result until: apt_result is succeeded retries: 3 delay: 10

cache_valid_time: 3600表示apt update元数据缓存 1 小时,避免每次convergeapt updateuntil/retries/delay实现指数退避重试,彻底解决 Travis 构建机网络不稳定问题。

技巧三:用molecule listmolecule status掌握测试现场状态

在 Travis 构建失败时,日志只显示最后几行。此时,你可以在本地复现:

# 查看所有场景状态 molecule list # 输出: # Scenario Driver Name Provisioner Name Verifier Name Status Instances # default docker ansible testinfra idle 0 # 查看详细状态(包括容器 ID、IP、状态) molecule status # 输出: # default docker ansible testinfra created instance # instance docker ansible testinfra running 172.17.0.2

Statuscreated,说明create成功但converge失败,可立即molecule login进入容器;若为idle,说明容器已被销毁,需molecule create重建。这个命令比翻 Travis 日志快 10 倍。

5.3 性能优化:将单次molecule test从 8 分钟压到 1分50秒

我们团队实测的优化组合(基于 Ubuntu 18.04 + Travis):

  1. Docker 镜像层缓存:在.travis.yml中,install阶段前加:

    before_install: - docker pull geerlingguy/docker-ubuntu1804-ansible:latest || true

    利用 Travis 的 Docker 层缓存,避免每次molecule create都拉镜像。

  2. Molecule 并行测试:若角色有多个平台(如ubuntu1804centos7),用molecule test --all会串行执行。改为:

    molecule test --scenario-name ubuntu1804 & molecule test --scenario-name centos7 & wait

    利用 Travis 的双核 CPU 并行,总耗时减少 40%。

  3. 禁用非必要验证器molecule test默认运行idempotenceside_effect。若你的角色不修改全局状态(如不 touch/etc/hosts),可在molecule.yml中禁用:

    scenarios: - name: default test_sequence: - dependency - cleanup - destroy - syntax - create - prepare - converge - verify - cleanup - destroy

    移除idempotenceside_effect,节省 1 分钟。

最终,一个包含 5 个testinfra断言的nginx角色,在优化后molecule test平均耗时 1分48秒,标准差小于 5 秒,完全满足 CI 的快速反馈需求。

6. 后续演进与现实考量:当 Ubuntu 18.04 EOL 后,这套方案何去何从

Ubuntu 18.04 的标准支持已于 2023 年 4 月结束,扩展安全维护(ESM)将持续到 2028 年。这意味着,你今天在 Travis CI 上跑的bionic构建,明年依然能用,但新项目不应再以它为唯一目标。那么,这套 Molecule + CI 的测试范式,该如何平滑演进?

我的建议是“三步走”:

第一步:保持向后兼容,新增focal(20.04)场景
不删除bionic,而在molecule.yml中扩展platforms

platforms: - name: ubuntu1804 image: geerlingguy/docker-ubuntu1804-ansible:latest - name: ubuntu2004 image: geerlingguy/docker-ubuntu2004-ansible:latest

同时,tests/test_default.py中的断言需适配双版本,例如:

def test_nginx_version(host): pkg = host.package("nginx") if host.system_info.distribution == "ubuntu" and host.system_info.release == "18.04": assert pkg.version.startswith("1.14.") elif host.system_info.distribution == "ubuntu" and host.system_info.release == "20.04": assert pkg.version.startswith("1.18.")

这样,molecule test --all会自动在两个环境运行,确保角色行为一致性。

第二步:将 Travis CI 迁移至 GitHub Actions,但复用全部 Molecule 配置
GitHub Actions 的ubuntu-20.04runner 已非常成熟。.github/workflows/ci.yml可精简为:

name: CI on: [push, pull_request] jobs: test: runs-on: ubuntu-20.04 steps: - uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v4 with: python-version: '3.8' - name: Install dependencies run: pip install molecule[docker] testinfra - name: Run Molecule test run: molecule test

你会发现,除了 runner 名称和 Python 版本,其余molecule.ymltest_default.pyconverge.yml全部无需修改。Molecule 的抽象能力,正是它历经 CI 平台变迁而屹立不倒的原因。

第三步:引入molecule lintansible-lint,让测试前移
script阶段加入:

script: - ansible-lint - molecule lint

ansible-lint检查 YAML 语法、最佳实践(如禁止command模块代替apt);molecule lint检查molecule.yml格式。它们在converge之前执行,能在 10 秒内发现 80% 的低级错误,避免浪费 2 分钟去拉容器。

最后分享一个个人体会:我坚持为每个 Ansible 角色写 Molecule 测试已五年,累计覆盖 127 个角色。最大的收益不是“减少了线上故障”,而是“改变了团队的交付心智”。当新人提交 PR 时,第一反应不再是“我本地测试过了”,而是“CI 是否绿了”。当角色需要升级 Nginx 版本时,我们

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询