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

如何通过Ansible条件判断仅为存在公钥文件的用户部署SSH密钥

解决方案

要实现仅在公钥文件存在时才部署SSH密钥,你可以通过以下两种方式修改任务:

方法一:使用stat模块检查文件状态(推荐)

先通过stat模块检查每个用户对应的公钥文件是否存在,再根据检查结果决定是否执行密钥部署任务:

---
# /tasks/main.yml

- name: 添加用户
  user:
    name: "{{ item.name }}"
    uid: "{{ item.uid }}"
    groups: "{{ item.groups }}"
    shell: "{{ item.shell | d('/bin/bash') }}"
    password: "{{ item.userpass }}"
    state: present
  with_items: "{{ users }}"

- name: 检查用户SSH公钥文件是否存在
  stat:
    path: "{{ role_path }}/files/{{ item.name }}.pub"
  register: user_key_stats
  with_items: "{{ users }}"

- name: Deploy Users Public SSH-Key
  authorized_key:
    user: "{{ item.item.name }}"
    key: "{{ lookup('file', role_path ~ '/files/' ~ item.item.name ~ '.pub') }}"
  with_items: "{{ user_key_stats.results }}"
  when: item.stat.exists

说明:

  1. stat模块会在控制节点检查指定路径的文件状态,role_path变量自动指向当前角色的根目录,避免相对路径出错。
  2. 检查结果会被注册到user_key_stats变量中,后续任务遍历该结果,仅当item.stat.exists为true时执行密钥部署。

方法二:直接通过lookup忽略错误并判断内容长度

这种方式无需额外的stat任务,直接在when条件中用lookup获取文件内容(不存在时返回空),通过判断内容长度来决定是否执行:

---
# /tasks/main.yml

- name: 添加用户
  user:
    name: "{{ item.name }}"
    uid: "{{ item.uid }}"
    groups: "{{ item.groups }}"
    shell: "{{ item.shell | d('/bin/bash') }}"
    password: "{{ item.userpass }}"
    state: present
  with_items: "{{ users }}"

- name: Deploy Users Public SSH-Key
  authorized_key:
    user: "{{ item.name }}"
    key: "{{ lookup('file', role_path ~ '/files/' ~ item.name ~ '.pub') }}"
  with_items: "{{ users }}"
  when: lookup('file', role_path ~ '/files/' ~ item.name ~ '.pub', errors='ignore') | trim | length > 0

说明:

  • errors='ignore'参数让lookup在文件不存在时返回空字符串而非报错。
  • 通过trim去掉空白字符后判断长度,确保空文件也会被跳过(如果需要保留空文件部署的场景,可去掉trim)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 05:05:09