Ansible 中的 authorized_keys 和 with_items

Ansible 中的 authorized_keys 和 with_items

我正在尝试使用 Ansible 创建新用户并填充他们的 ~/.ssh/authorized_keys 文件。这是我的任务:

- name: Create user account
  user: name="{{ item.username }}-ns" comment="{{ item.realname }}"
    groups=adm,sudo, append=yes
    password="{{ item.password }}"
  with_items: "{{ ssh_users }}"
- name: copy ssh keys to authorized_keys
  authorized_key:  user="{{ item.username }}-ns"
    key="{{ sshkey_path }}/{{ item.username }}.pub"
  with_item: "{{ ssh_users }}"

我的变量文件如下所示:

ssh_users:
  - username: "jdoe"
    realname: "jrow"
    password: "$6$FWhXrnkizCqwKJcM$y55ETlvthHA49NuzwYgKAmOTnsBDRzfXE1OiOuJ.HHwVuI4P/BQrR/eKgYOioevIrgYYw.HpeP/sxCR3M38SW/"
  - username: "jroe"
    realname: "Jane Roe"
    password: "$6$wQhvxq3C.egKzrGi$na0M4jn3bi1lM2dz2YvdbAvvJBvbg4iGH1K6j7sHnZZt7mZggexHPvxOT799pfaDKmU6xDrbtbrLsxviGyABA0"
  - username: "testuser"
    realname: "Test User"
    password: "$6$U24oz4dsfdYD/LZ$fuziBEkc2q/POHSEvfcuTaD6wFTF.49RbU8z8JLQk3oki/He87cYqpSZtL16A11EBaG6VdemXdy6\V/"

我已经将各个用户的公共 ssh 密钥设置到 publickeys 目录中,并将其放入名为“sshkey_path”的变量中。每个用户都有一个公钥文件(例如 jdoe.pub)。

当我运行剧本时,用户帐户创建顺利,但authorized_keys部分显示:

ERROR! 'with_item' is not a valid attribute for a Task

The error appears to have been in 'user-add.yaml': line 29, column 7, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:


    - name: copy ssh keys to authorized_keys
      ^ here

有什么想法可能会出错吗?原则上,它应该可以工作,因为有类似的例子在网上找到的。我尝试过这种格式,但无法让它工作。非常感谢您的指点。

答案1

失败的原因是因为实际的插件被称为with_items而不是 with_item。你忘了 s。

答案2

为了后代:

除了“linuxdynasty”指出的有关的错误之外with_items,我在引用密钥文件的方式上还存在另一个错误。

我尝试使用以下语法:

key="{{ sshkey_path }}/{{ item.username }}.pub"

但在这种情况下,这行不通,因为authroized_key需要一个文件。必须使用“with_files”或 Lookups 来获取它。

为了使它在我的环境中发挥作用,我必须将多个变量连接在一起,这是我在堆栈溢出帖子。我想到的最终语法是:

key="{{ lookup('file', sshkey_path+item.username+'.pub') }}"

并且运行良好。

相关内容