如何修复从列表中获取值的错误

How To Fix An Error With Getting Values From A List

我正在尝试使用 ansible 创建用户。我创建了一个名为 users 的变量,其中包含用户列表和其他选项。这是:

users:
  - { user_name: "user1", sudo_type: "full", password: "pass", ssh_pub_key: "ssh-rsa AAAAB..." }
  - { user_name: "user2", sudo_type: "limited", password: "somepass", ssh_pub_key: "ssh-rsa AAAAB3..." }

然后我创建了以下任务:

- name: create local users
  local_action: user name={{ users.user_name }} createhome=yes state=present password={{ users.password }} shell=/bin/bash generate_ssh_key=yes ssh_key_type=rsa ssh_key_comment="{{ ansible_hostname }}-{{ users.user_name }}"

当我 运行 剧本时,它失败并出现以下错误:

fatal: [10.60.16.1]: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'list object' has no attribute 'user_name'\n\nThe error appears to have been in '/root/ansible-builds/roles/users/tasks/main.yml': line 11, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: create local users\n  ^ here\n"}

问题出在哪里?

users 是一个没有属性 user_name 的列表。它只有 items,每个 item 都有一个属性 user_name。您必须遍历 users 的列表。类似于:

vars:
  users:
    - { user_name: "user1", sudo_type: "full", password: "pass", ssh_pub_key: "ssh-rsa AAAAB..." }
    - { user_name: "user2", sudo_type: "limited", password: "somepass", ssh_pub_key: "ssh-rsa AAAAB3..." }

tasks:
  - name: create local users
    shell: echo {{ item.user_name }}
    with_items: "{{ users }}"

所以你的任务将是这样的:

  - name: create local users
    local_action: user name={{ item.user_name }} createhome=yes state=present password={{ item.password }} shell=/bin/bash generate_ssh_key=yes ssh_key_type=rsa ssh_key_comment="{{ ansible_hostname }}-{{ item.user_name }}"
    with_items: "{{ users }}"