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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With