Authorized_keys and with_items in Ansible

ansiblessh-keys

I'm trying to create new users and populate their ~/.ssh/authorized_keys file using Ansible. Here's my task:

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

and my variables file looks like this:

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

I've setup the various user's public ssh keys into a publickeys directory which I put in the variable named "sshkey_path". There is one public key file for each user (e.g. jdoe.pub).

When I run the playbook, the user account creation goes fine, but the authorized_keys part says:

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

Any ideas what could be going wrong? In principle, it should work as there are similar examples found online. I've played with the format but cannot get it to work. Your pointers are appreciated.

Best Answer

The reason it is failing, is because the actual plugin is called with_items and not with_item. You forgot the s.

Related Topic