Ansible apt_repository模块validate_certs参数为何失效?
我有一个用于添加Apt仓库的Ansible playbook,仓库部署在自有服务器上,通过HTTPS访问(使用自签名证书)。
手动将仓库添加到主机sources.list后,执行apt update会报错:
Certificate verification failed: The certificate is NOT trusted. The certificate issuer is unknown. The name in the certificate does not match the expected.
确认是自签名证书问题后,执行apt -o "Acquire::https::Verify-Peer=false" update禁用校验即可正常更新。
尝试用Ansible处理,playbook配置如下:
- name: add my repo and update cache apt_repository: repo: deb https://myserver/debian bullseye main filename: myrepo validate_certs: false state: present
但无论是否设置validate_certs: false,执行均失败,错误信息:
FAILED! => {"changed": false, "msg": "Failed to update apt cache: unknown reason"}
将仓库改为HTTP访问,或者在主机apt-config中设置Acquire::https::Verify-Peer "false";,均可正常运行。想知道为什么validate_certs参数无法生效?
环境信息:
debian 11.6 ansible 2.10.8 python 3.9.2
原因分析
apt_repository模块的validate_certs参数只作用于模块自身访问仓库源时的证书校验(比如拉取仓库的Release文件等操作),完全不控制系统apt update命令执行时的证书校验逻辑。
当模块执行到更新apt缓存的步骤时,本质是调用系统原生的apt update命令,这个命令的证书校验规则由系统apt配置决定,和Ansible模块的validate_certs参数没有关联——这就是你设置了参数依然报错的核心原因。
解决办法
方法1:临时带参数执行apt update
添加仓库后,单独用模块执行带禁用校验参数的apt update:
- name: add my repo apt_repository: repo: deb https://myserver/debian bullseye main filename: myrepo state: present - name: update apt cache with disabled cert verification apt: update_cache: yes environment: APT_OPTIONS: "-o Acquire::https::Verify-Peer=false"
或者直接用command模块:
- name: update apt cache command: apt -o "Acquire::https::Verify-Peer=false" update changed_when: false
方法2:永久配置apt跳过特定仓库校验
创建apt配置文件,针对目标仓库单独禁用校验,后续所有apt update都无需额外参数:
- name: add apt config to skip cert verification for myrepo copy: content: | Acquire::https::myserver::Verify-Peer "false"; dest: /etc/apt/apt.conf.d/99-myrepo-no-verify mode: 0644 - name: add my repo and update cache apt_repository: repo: deb https://myserver/debian bullseye main filename: myrepo state: present
方法3:导入自签名证书到系统信任库(推荐)
如果条件允许,将自签名证书导入主机的系统信任证书库,从根源解决证书信任问题,既不用禁用校验,也能保证安全性:
- name: copy self-signed cert to server copy: src: /path/to/your/cert.pem dest: /usr/local/share/ca-certificates/myrepo.crt mode: 0644 - name: update ca-certificates command: update-ca-certificates
内容的提问来源于stack exchange,提问作者chris01

