I’m trying to use ansible’s template module to assemble and authorized_keys file, but it’s not working. I have a task:
- shell: ls sshkeys/*
register: keys
- template: src=authorized_keys.j2 dest=/tmp/authorized_keys
My authorized_keys.j2 looks like this:
{% for key in keys.stdout_lines %}
command=“/path/script” {% include ‘{{ key }}’ %}
{% endfor %}
This is failing with:
TASK: [template src=authorized_keys.j2 dest=/tmp/authorized_keys] ****************
fatal: [localhost] => {‘msg’: ‘{{ key }}’, ‘failed’: True}
fatal: [localhost] => {‘msg’: ‘{{ key }}’, ‘failed’: True}
I don’t understand this error. Any help would be appreciated.
Regards,
Anand
Hi Anand, Your first task:
- shell: ls sshkeys/*
register: keys
is running on the remote host, the ansible client. But your second task:
- template: src=authorized_keys.j2 dest=/tmp/authorized_keys
it running on the ansible “server”. So it’s not going to have access to the keys.
If you want the first command to run on the ansible server you could make it a “local_action” task.
I have a feelign you can probably use a lookup plugin to do this better though:
http://www.ansibleworks.com/docs/playbooks2.html#lookup-plugins-accessing-outside-data
Romeo
Hi Romeo,
Thank you for your reply. Actually, I am running this locally, with “ansible-playbook test.yml -c local”, so the keys are available.
In a different playbook, I am using the authorized_key module with the file lookup plugin to populate users’ files with their keys. However, I have this other use case where I need to assemble an authorized_keys file with the SSH command option before the key to restrict what some users are allowed to run. I don’t know if it can be done with lookup plugins, so if it’s possible with my example, I’d appreciate an example. And that’s why I was trying to use a template instead.
Anand
Ok guys, I figured this out eventually. Now I’m doing:
- authorized_key: user=blah key=“command="/path/to" {{ item }}”
with_file: keys.stdout_lines
It works No templates needed!