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

如何在Ansible中遍历字典与列表,按需从私钥生成公钥?

Solution for Generating SSH Public Keys from Private Keys in Ansible

Let's fix your Ansible task step by step to achieve exactly what you need: generating a public key only when its corresponding file doesn't exist (i.e., when dict_pub_keys.value == false).

Correct Task Implementation

- name: "[CA_User] Generate public key from private key if public key doesn't exist"
  command: "ssh-keygen -y -f {{ item.key | regex_replace('\\.pub$', '') }} > {{ item.key }}"
  with_dict: "{{ dict_pub_keys }}"
  when:
    - not item.value
    - item.key | regex_replace('\\.pub$', '') in list_priv_keys

What Was Wrong with Your Original Code?

  1. Missing Private Key Path Logic:
    The {{ ????? }} placeholder needed a way to derive the private key path from the public key path in item.key. Using the regex_replace filter removes the .pub suffix from the public key path to get the matching private key path (e.g., ~/.ssh/id_rsa.pub becomes ~/.ssh/id_rsa).

  2. Redundant When Condition:
    The false in dict_pub_keys.values() condition was unnecessary and problematic. This would trigger the task for all items in dict_pub_keys if even one public key was missing, instead of only targeting the items where item.value == false. Removing this leaves us with the precise condition we need: not item.value.

  3. Optional: Validate Private Key Existence:
    I added an extra check item.key | regex_replace('\\.pub$', '') in list_priv_keys to ensure we only attempt to generate a public key if the corresponding private key exists in your list_priv_keys list. This prevents errors from trying to use a non-existent private key.

Bonus: Ensuring dict_pub_keys Has Accurate Existence Status

If you haven't already populated dict_pub_keys with the actual existence status of your public key files, you can do this first with the stat module:

- name: Check existence of public key files
  stat:
    path: "{{ item }}"
  loop: "{{ dict_pub_keys.keys() | list }}"
  register: pub_key_checks

- name: Create updated dict of public key existence
  set_fact:
    dict_pub_keys: "{{ dict(pub_key_checks.results | map(attribute='item') | zip(pub_key_checks.results | map(attribute='stat.exists'))) }}"

This ensures dict_pub_keys reflects the real state of your public key files before attempting to generate any missing ones.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:04:06