1

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.

3

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

  • Oh my. You're right. Thanks for pointing that out! – imlepid Jul 26 '16 at 7:19
4

For posterity:

Along with the mistake pointed out by "linuxdynasty" regarding with_items, there was a further error in the way I was referencing the key file.

I tried to use the following syntax:

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

But that won't work in this case because authroized_key expects a file. One must either use "with_files" or Lookups to get this.

To make it work in my situation, I had to concatenate multiple variables together, which I did with the help of this StackOverflow post. The final syntax I came up with was:

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

and it worked fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.