大网数据广告活动
服务器运维问答

How to prevent empty subelement list error in Ansible loop?

· 52CE 我爱测

When I try to loop (with Ansible 2.6 loop) with subelements through all public keys of a list of users and encounter a user which has no public keys defined: - authorized_key: user: "{{ item.0.username }}" state: present key: "{{…

问题原文

原帖链接 · willemdh · CC BY-SA 4.0

When I try to loop (with Ansible 2.6 loop) with subelements through all public keys of a list of users and encounter a user which has no public keys defined:

- 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 }}"

I'm getting the following error: the key 'ssh_pub_keys' should point to a list, got None

When I try to use skip_missing like this:

- 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 }}"

I get this error: 'list object' has no attribute 'username'

This could be the users list:

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

How can I make the loop with subelements to go to the next user without throwing an error when a user is encountered which has no ssh_pub_keys list?

已采纳解答

原帖链接 · Vladimir Botka · CC BY-SA 4.0

Q: "Error: the key 'ssh_pub_keys' should point to a list, got None."

A: You might want to use lookup and set 'skip_missing': True.

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

Q: "Error: 'list object' has no attribute 'username'"

A: The index is missing. Fix it.

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

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2019-01-13)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。