Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve "could not locate file in lookup" reading id_rsa.pub?

in an Ansible playbook, I'm trying to read the default public key into a variable to be used later.
Here's my yml:

- hosts: hostsGroup
  become: false
  vars:
    publicKey: "{{ lookup('file', lookup('env','HOME') + '/.ssh/id_rsa.pub') }}"

The script breaks with the following error:

fatal: [redacted-ip]: FAILED! => 
{"msg": "An unhandled exception occurred while templating '{{ lookup('file', lookup('env','HOME') + '/.ssh/id_rsa.pub') }}'. Error was a <class 'ansible.errors.AnsibleError'>, 
original message: An unhandled exception occurred while running the lookup plugin 'file'. Error was a <class 'ansible.errors.AnsibleError'>, 
original message: could not locate file in lookup: /root/.ssh/id_rsa.pub"}

The file is confirmed to exist in that location.

Is there a better way? or What am I doing wrong?

like image 203
Teaspoon Avatar asked Jan 02 '23 09:01

Teaspoon


1 Answers

Quoting the documentation:

Lookups occur on the local computer, not on the remote computer.

To get the content of the remote file, you can use a task like this:

- name: get remote file contents
  command: "cat {{ ansible_env.HOME }}/.ssh/id_rsa.pub"
  register: key

You can then access the contents like this:

- name: show key contents
  debug:
    var: key.stdout

But! Note that here I'm using ansible_env.HOME. This is populated by Ansible when gathering facts, and it will represent the value of the HOME environment variable from the perspective of whatever user Ansible used to authenticate. If you're using things like become_user, the value will not change to reflect the new user.

like image 59
larsks Avatar answered Mar 16 '23 00:03

larsks