如何防止 Ansible 循环中出现空子元素列表错误?

如何防止 Ansible 循环中出现空子元素列表错误?

当我尝试使用子元素循环(使用 Ansible 2.6 循环)遍历用户列表的所有公钥并遇到没有定义公钥的用户时:

- authorized_key:
    user: "{{ item.0.username }}"
    state: present
    key: "{{ item.1.pub_key }}"
  loop: "{{ users | subelements('ssh_pub_keys') | default ([]) }}"
  loop_control:
    label: "{{ item.username }}"

我收到以下错误:the key 'ssh_pub_keys' should point to a list, got None

当我尝试像这样使用 skip_missing 时:

- authorized_key:
    user: "{{ item.0.username }}"
    state: present
    key: "{{ item.1.pub_key }}"
    loop: "{{ lookup('subelements', users, 'ssh_pub_keys', {'skip_missing': True})}}"
  loop_control:
    label: "{{ item.username }}"

我收到此错误:'list object' has no attribute 'username'

这可能是用户列表:

users:
  - username: usera
    ssh_pub_keys:
      - from: home
        pub_key: kdzadizajdiazjd
      - from: work
        pub_key: dzadadazdzadzad
  - username: userb
    ssh_pub_keys:
      - from: home
        pub_key: kdzadizajdiazjd
      - from: work
        pub_key: dzadadazdzadzad
  - username: userc
  - username: userd
    ssh_pub_keys:
      - from: home
        pub_key: kdzadizajdiazjd
      - from: work
        pub_key: dzadadazdzadzad

当遇到没有列表的用户时,如何使带有子元素的循环转到下一个用户而不会引发错误ssh_pub_keys

答案1

问:错误:密钥“ssh_pub_keys”应该指向一个列表,但却没有。

答:你可能需要使用抬头并设置‘skip_missing’:真

    loop: "{{ lookup('subelements',
                      users,
                      'ssh_pub_keys',
                      {'skip_missing': True}) }}"

问:错误:“列表对象”没有属性“用户名”

A:索引缺失。请修复它。

    label: "{{ item.0.username }}"

相关内容