Ansible下载远程文件:如何实现带密码的加密传输?
如何用Ansible实现加密形式的文件下载?
你说得对,Ansible的fetch和synchronize模块确实没有内置的带密码加密功能,但我们可以通过几个变通方案来实现加密下载远程配置文件的需求,下面给你几个靠谱的实现方式:
方法一:远程加密 → 下载 → 本地解密
这是最直观的思路:先在远程主机把目标文件加密,再用fetch下载加密后的文件,最后在本地解密得到原文件。
示例Playbook:
- name: 加密并下载远程配置文件 hosts: your_remote_host vars: # 建议用Ansible Vault加密这个密码,避免明文泄露 encryption_password: "your_secure_password" remote_config_path: "/etc/nginx/nginx.conf" remote_encrypted_path: "/tmp/nginx.conf.enc" local_dest_path: "/local/path/to/save/" tasks: - name: 在远程主机加密配置文件 command: openssl enc -aes-256-cbc -salt -in {{ remote_config_path }} -out {{ remote_encrypted_path }} -k "{{ encryption_password }}" args: creates: "{{ remote_encrypted_path }}" # 避免重复加密 - name: 下载加密后的文件到本地 fetch: src: "{{ remote_encrypted_path }}" dest: "{{ local_dest_path }}" flat: yes # 直接保存到指定路径,不创建主机名子目录 - name: 本地解密文件 local_action: module: command cmd: openssl enc -d -aes-256-cbc -in {{ local_dest_path }}/nginx.conf.enc -out {{ local_dest_path }}/nginx.conf -k "{{ encryption_password }}" args: creates: "{{ local_dest_path }}/nginx.conf" # 避免重复解密 - name: 清理远程主机的加密临时文件 file: path: "{{ remote_encrypted_path }}" state: absent
关键提示:
- 密码安全:绝对不要明文写密码!用
ansible-vault encrypt_string加密密码变量,运行Playbook时加上--ask-vault-pass或指定Vault密码文件。 - 加密算法:这里用的是AES-256-CBC,你也可以根据需求换成其他openssl支持的加密算法。
方法二:通过SSH管道直接加密传输
如果不想在远程生成临时文件,可以直接通过SSH管道把加密后的内容传输到本地,全程不落地加密文件:
- name: 管道加密下载远程配置文件 hosts: your_remote_host vars: encryption_password: "your_secure_password" remote_config_path: "/etc/nginx/nginx.conf" local_encrypted_path: "/local/path/nginx.conf.enc" tasks: - name: 通过SSH管道加密下载 local_action: module: shell cmd: ssh {{ ansible_user }}@{{ inventory_hostname }} "openssl enc -aes-256-cbc -salt -in {{ remote_config_path }} -k '{{ encryption_password }}'" > {{ local_encrypted_path }}
之后你可以在本地手动解密,或者再加一个本地解密的任务,和方法一类似。
额外说明:传输过程的加密
如果你担心的是传输过程的加密,其实Ansible默认是通过SSH连接远程主机的,SSH本身就提供了端到端的加密传输,fetch和synchronize的传输过程已经是加密的。但如果你的需求是文件本身加密存储(下载到本地后也是加密状态,需要密码才能查看),上面的两种方法就完全适用了。
内容的提问来源于stack exchange,提问作者Ikrom
相关产品推荐
相关产品推荐

