如何使用ansible.builtin.uri模块上传Ansible Vault加密文件并自动解密?
问题
我有一个存储在项目roles/the_role/files目录下、经Ansible Vault加密的许可证文件,想通过ansible.builtin.uri模块的POST/PUT操作上传,但发现上传的仍是加密状态,且无法使用copy模块。想咨询两个问题:
- 能否让
ansible.builtin.uri模块在POST/PUT时自动解密该加密文件? - 有没有安全的任务序列可以作为替代方案?
现有任务示例代码
- name: "Nexus Update License: Uploading new License file" ansible.builtin.uri: url: "http://{{ inventory_hostname }}:{{ nexus_default_port }}{{ nexus_default_context_path | regex_replace('\\/$', '')}}/service/rest/v1/system/license" user: "{{ nexus_admin_account }}" password: "{{ nexus_admin_password }}" headers: Content-Type: application/octet-stream method: POST force_basic_auth: yes status_code: 200,204 src: "license.lic.enc" # 上传的仍是加密后的文件...
回答
关于uri模块自动解密的可能性
不行,ansible.builtin.uri模块的src参数仅会读取文件的原始字节流,没有内置处理Ansible Vault加密文件的逻辑,所以直接传入加密文件路径时,上传的必然是加密状态的内容。
安全替代方案:控制节点解密后上传
可以借助slurp模块在控制节点完成解密读取,再将解密后的内容通过uri模块的body参数上传,全程不在目标节点生成明文文件,保障安全性:
- name: 解密读取Vault加密的许可证文件 ansible.builtin.slurp: src: "{{ role_path }}/files/license.lic.enc" register: encrypted_license - name: 上传解密后的许可证文件 ansible.builtin.uri: url: "http://{{ inventory_hostname }}:{{ nexus_default_port }}{{ nexus_default_context_path | regex_replace('\\/$', '')}}/service/rest/v1/system/license" user: "{{ nexus_admin_account }}" password: "{{ nexus_admin_password }}" headers: Content-Type: application/octet-stream method: POST force_basic_auth: yes status_code: 200,204 body: "{{ encrypted_license.content | b64decode }}"
方案细节说明:
slurp模块会自动识别Vault加密文件并完成解密,返回的内容是Base64编码格式(适配二进制文件读取需求)- 通过
b64decode过滤器将Base64内容还原为原始二进制,再通过body参数传递给uri模块,确保上传的是解密后的合法许可证 - 所有解密操作都在控制节点执行,目标节点不会留下任何明文文件痕迹,符合安全规范
内容的提问来源于stack exchange,提问作者Fabio
相关产品推荐
相关产品推荐

