如何在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?
Missing Private Key Path Logic:
The{{ ????? }}placeholder needed a way to derive the private key path from the public key path initem.key. Using theregex_replacefilter removes the.pubsuffix from the public key path to get the matching private key path (e.g.,~/.ssh/id_rsa.pubbecomes~/.ssh/id_rsa).Redundant When Condition:
Thefalse in dict_pub_keys.values()condition was unnecessary and problematic. This would trigger the task for all items indict_pub_keysif even one public key was missing, instead of only targeting the items whereitem.value == false. Removing this leaves us with the precise condition we need:not item.value.Optional: Validate Private Key Existence:
I added an extra checkitem.key | regex_replace('\\.pub$', '') in list_priv_keysto ensure we only attempt to generate a public key if the corresponding private key exists in yourlist_priv_keyslist. 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

