Ribeye
Ribeye

Reputation: 2177

Ansible authorized_key cant find key file

I am starting to use Ansible to automate the creation of users. The following code creates the user and the /home/test_user_003/.ssh/id_rsa.pub file.

But the authorized_key step gives error "could not find file in lookup". Its there, I can see it.

  ---
   - hosts: test
     become: true
     tasks:
     - name: create user
       user:
         name: test_user_003
         generate_ssh_key: yes
         group: sudo
         ssh_key_passphrase: xyz
     - name: Set authorized key
       authorized_key:
         user: test_user_003
         state: present
         key: "{{ lookup('file', '/home/test_user_003/.ssh/id_rsa.pub') }}"

(I would be interested to know why "key" uses lookup, but thats for education only)

Upvotes: 1

Views: 2624

Answers (1)

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68269

You create user on remote host but try to lookup generated key on local host (all lookups in ansible are executed locally).

You may want to capture (register) result of user task and use it's fields:

 - name: create user
   user:
     name: test_user_003
     generate_ssh_key: yes
     group: sudo
     ssh_key_passphrase: xyz
   register: new_user
 - name: Set authorized key
   authorized_key:
     user: test_user_003
     state: present
     key: "{{ new_user.ssh_public_key }}"

Upvotes: 6

Related Questions