Ansible playbook运行时启动带2FA的OpenVPN如何实时获取密码避免超时
解决方案
核心思路
你的需求本质是需要延迟密码输入的时机到OpenVPN启动任务执行前一刻,避开2FA密码的有效期限制,vars_prompt默认在Play启动时就提示输入,不适用该场景,推荐使用pause模块实现任务执行过程中的交互式密码获取。
具体实现代码
# 在原有OpenVPN启动任务前新增密码采集步骤 - name: 提示输入OpenVPN 2FA密码(PIN+动态令牌) ansible.builtin.pause: prompt: "请输入OpenVPN连接密码(PIN+动态令牌)" echo: no register: openvpn_2fa_pass no_log: true - name: 写入临时密码文件 ansible.builtin.copy: content: "{{ openvpn_2fa_pass.user_input }}" dest: /etc/openvpn/.2fa_tmp_pass mode: '0600' owner: root no_log: true # 若你使用的OpenVPN服务默认没有配置密码文件读取,新增服务配置覆盖 - name: 配置OpenVPN服务读取临时密码文件 ansible.builtin.lineinfile: path: /etc/systemd/system/{{ openvpn_service }}.d/override.conf line: "ExecStart=/usr/sbin/openvpn --config /etc/openvpn/%i.conf --askpass /etc/openvpn/.2fa_tmp_pass" regexp: '^ExecStart=' create: yes mode: '0644' - name: 重载systemd配置 ansible.builtin.systemd: daemon_reload: yes - name: 启动并启用OpenVPN服务 ansible.builtin.service: name: "{{ openvpn_service }}" state: started enabled: yes - name: 强制删除临时密码文件 ansible.builtin.file: path: /etc/openvpn/.2fa_tmp_pass state: absent always: yes no_log: true
安全注意事项
- 所有涉及密码处理的步骤都添加
no_log: true参数,禁止密码内容输出到Ansible日志 - 临时密码文件权限设置为0600,仅root用户可读写
- 通过
always参数保证无论OpenVPN启动成功或失败,都会删除临时密码文件,避免密码泄露 - 如果无需永久修改服务配置,也可以直接使用
command模块调用openvpn命令传入密码完成连接,无需修改systemd配置
内容的提问来源于stack exchange,提问作者Andrew Mclean
相关产品推荐
相关产品推荐

