如何用Ansible的apt_repository模块正确配置Ubuntu的deb822仓库?
在各Ubuntu版本中用Ansible正确配置APT仓库的方案
问题背景
- Ubuntu 20.04中,Ansible的
apt_repository模块会将仓库密钥写入已弃用的/etc/apt/trusted.gpg,而系统原生add-apt-repository工具会将密钥存入合规的/etc/apt/trusted.gpg.d/ - Ubuntu 22.04仍沿用
trusted.gpg.d/存储密钥,而非部分文档建议的/etc/apt/keyring - Ubuntu 24.04中,
add-apt-repository会直接将密钥嵌入/etc/apt/sources.list.d/下的对应.sources文件,但Ansible的apt_repository模块仍依赖已弃用的apt-key工具尝试写入/etc/apt/trusted.gpg,触发权限错误
解决方案
方法1:调用原生add-apt-repository命令(跨版本兼容)
直接调用系统原生工具,自动适配不同Ubuntu版本的密钥存储逻辑,是最省心的跨版本方案:
- name: 添加Ondrej PHP PPA仓库 become: true command: add-apt-repository -y ppa:ondrej/php args: creates: /etc/apt/sources.list.d/ondrej-ubuntu-php-{{ ansible_distribution_release }}.list
creates参数确保仅当仓库未添加时执行,避免重复操作
方法2:优化apt_repository模块用法(适配新版APT规范)
针对不同Ubuntu版本,显式指定密钥存储路径,彻底规避apt-key的弃用问题:
适配Ubuntu 20.04/22.04
- name: 添加Ondrej PHP PPA仓库(20.04/22.04) become: true apt_repository: repo: ppa:ondrej/php state: present keyring: /etc/apt/trusted.gpg.d/ondrej-php.gpg
适配Ubuntu 24.04
Ubuntu 24.04支持将密钥嵌入.sources文件,可先导入密钥到合规目录,再定义完整仓库源:
- name: 获取Ondrej PHP PPA密钥 become: true get_url: url: https://keyserver.ubuntu.com/pks/lookup?op=get&search=0xB8DC7E53946656EFBCE4C1DD71DAEAAB4AD4CAB6 dest: /etc/apt/trusted.gpg.d/ondrej-php.gpg mode: '0644' - name: 添加Ondrej PHP PPA仓库(24.04) become: true apt_repository: repo: "deb [signed-by=/etc/apt/trusted.gpg.d/ondrej-php.gpg] http://ppa.launchpad.net/ondrej/php/ubuntu {{ ansible_distribution_release }} main" state: present filename: ondrej-php
额外注意事项
- 所有操作必须加上
become: true获取root权限,否则会触发权限错误 - 对于非PPA的第三方仓库,需手动获取密钥的公开URL,通过
get_url模块导入到/etc/apt/trusted.gpg.d/目录(Ansible 2.10+已弃用apt_key模块,不建议使用) - 仓库配置完成后,建议执行APT缓存更新:
- name: 更新APT缓存 become: true apt: update_cache: true
内容的提问来源于stack exchange,提问作者JohnRDOrazio
相关产品推荐
相关产品推荐

