我在Travis CI上尝试了自己编写的Ansible模块的健全性测试
这是一篇关于使用Travis CI进行自行创建的Ansible模块的sanity测试的笔记。
Travis CI 是一个持续集成的工具。
如果使用私有仓库,请选择专业版。
Travis CI文档
关于模块测试
由于测试本身是在GitLab上进行的,所以我将以此为基础进行尝试。
使用的存储库
这次我将使用以下的仓库来进行测试。
考察对象
我将尝试对位于上述仓库的modules目录下的所有模块进行一次完整性测试。
CI正计算准备
在Travis CI中启用存储库。
在使用GitHub账户登录并关联Travis CI后,启用相关的代码仓库。

Docker 文件
使用Ansible模块进行测试时,会使用预先准备好的测试容器映像进行测试。
我创建了以下类似的Docker文件。
FROM quay.io/ansible/default-test-container:latest
RUN ln -sf /usr/share/zoneinfo/Asia/Tokyo /etc/localtime
RUN cd /opt && \
git clone https://github.com/ansible/ansible.git && \
cd ansible && \
mkdir lib/ansible/modules/salf_made/ && \
mkdir test/units/modules/salf_made
ADD ansible_module_test.sh /opt
ADD modules /opt/ansible/lib/ansible/modules/salf_made/
RUN chmod +x /opt/ansible_module_test.sh
RUN apt-get -y install man-db
测试脚本
这是一个在容器内执行的测试脚本。
#!/bin/sh
version=$1
module_dir='lib/ansible/modules/salf_made/'
cd /opt/ansible
. hacking/env-setup
for module in $(find $module_dir | grep "\.py$" | awk -F / '{print $(NF)}' | sed -e "s/\.py$//g" | grep -v "__init__" | sort) ; do
if [ $version = "2.6" ] ; then
ansible-test sanity --python $version --skip-test botmeta $module
elif [ $version = "3.8" ] ; then
ansible-test sanity --python $version --skip-test pylint $module
else
ansible-test sanity --python $version $module
fi
if [ $? -ne 0 ] ; then
exit 1
fi
done
在Python 2.6和3.8版本中,由于某些测试模块不兼容,会导致错误,因此我们选择跳过。
CI文件
我们使用以下的 Travis CI配置文件来执行以下操作:
根据存储库中的Docker文件构建镜像并启动容器,然后执行容器内的脚本。
language: python
services:
- docker
before_install:
- docker build -t ansible-ci:latest .
- docker run -d -it --name ansible-ci ansible-ci:latest
jobs:
include:
- stage: sanity test
name: python 2.6
script: docker exec ansible-ci /bin/sh -c '/opt/ansible_module_test.sh 2.6'
- name: python 2.7
script: docker exec ansible-ci /bin/sh -c '/opt/ansible_module_test.sh 2.7'
- name: python 3.5
script: docker exec ansible-ci /bin/sh -c '/opt/ansible_module_test.sh 3.5'
- name: python 3.6
script: docker exec ansible-ci /bin/sh -c '/opt/ansible_module_test.sh 3.6'
- name: python 3.7
script: docker exec ansible-ci /bin/sh -c '/opt/ansible_module_test.sh 3.7'
- name: python 3.8
script: docker exec ansible-ci /bin/sh -c '/opt/ansible_module_test.sh 3.8'
CI执行
以后,当将代码推送到存储库时,持续集成将会执行。
以下是示例结果。