You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible如何循环判断文件存在后执行公钥推送任务?

实现方法

首先明确一个容易踩的逻辑点:你当前使用的lookup('file', 路径)是在运行Ansible命令的控制节点本地读取文件,不会在被管理的远程目标节点上执行文件读取。根据公钥文件的存放位置,选对应方案即可:

方案1:最简实现(公钥存放在控制节点,90%场景适用)

不需要额外调用stat模块,直接给file lookup增加错误忽略参数,判断公钥内容非空时才执行添加操作,代码最简洁、执行效率最高:

- name: Add pubkeys for users with existing pubkey file
  ansible.posix.authorized_key:
    user: "{{ item.username }}"
    state: present
    key: "{{ user_pubkey_content }}"
  loop: "{{ userlist }}"
  vars:
    user_pubkey_content: "{{ lookup('file', '~/ap/ansible/sonderfiles/{{ item.username }}_pubkey.pub', errors='warn') }}"
  when: user_pubkey_content | length > 0

配置errors='warn'后,公钥文件不存在时lookup不会直接抛出致命错误终止任务,只会输出警告信息,配合when条件即可跳过没有对应公钥的用户。

方案2:基于stat模块检查(公钥存放在远程目标节点时使用)

如果你的公钥文件是存放在被管理的远程主机上,才需要用stat模块做远程文件存在性校验,实现逻辑是先批量遍历用户做文件检查、注册结果,再遍历检查结果列表,对存在文件的用户执行公钥添加:

# 第一步:批量检查远程主机上的公钥文件是否存在
- name: Check if pubkey file exists on remote host
  ansible.builtin.stat:
    path: "/your/remote/pubkey/path/{{ item.username }}_pubkey.pub" # 替换为远程主机上公钥的实际存放路径
  loop: "{{ userlist }}"
  register: pubkey_check_result

# 第二步:仅为存在公钥文件的用户推送公钥
- name: Add valid pubkeys to authorized_keys
  ansible.posix.authorized_key:
    user: "{{ check_item.item.username }}"
    state: present
    key: "{{ slurp_pubkey.content | b64decode }}" # 远程文件请先用slurp模块读取后解码,不要用控制节点本地的file lookup
  loop: "{{ pubkey_check_result.results }}"
  loop_control:
    loop_var: check_item
  when: check_item.stat.exists

注意:如果公钥存放在远程主机,不要用file lookup读取文件内容,需要先调用ansible.builtin.slurp模块读取远程文件内容做base64解码后再传给key参数,否则会因为读取控制节点本地不存在的文件报错。


内容的提问来源于stack exchange,提问作者Julian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 16:21:34