<%#
  kind: snippet
  name: remote_execution_ssh_keys
%>
# SSH keys setup snippet
#
# Parameters:
#
# remote_execution_ssh_keys: public keys to be put in ~/.ssh/authorized_keys
#
# remote_execution_ssh_user: user for which remote_execution_ssh_keys will be
#                            authorized
#
# This template sets up SSH keys in any host so that as long as your public
# SSH key is in remote_execution_ssh_keys, you can SSH into a host.

# A personal recomendation: create a global parameter remote_execution_ssh_keys
# and put your keys there, so that you can access any newly provisioned host
# without having to set up the parameter on every host or host group.


<% if !@host.params['remote_execution_ssh_keys'].blank? %>
<% ssh_user = @host.params['remote_execution_ssh_user'] || 'root' %>
<% ssh_path = "~#{ssh_user}/.ssh" %>

mkdir -p <%= ssh_path %>

cat << EOF >> <%= ssh_path %>/authorized_keys
<%= @host.params['remote_execution_ssh_keys'].join("\n") %>
EOF

chmod 700 <%= ssh_path %>
chmod 600 <%= ssh_path %>/authorized_keys
chown -R <%= "#{ssh_user}:" %> <%= ssh_path %>

# Restore SELinux context with restorecon, if it's available:
command -v restorecon && restorecon -RvF <%= ssh_path %> || true
<% end %>
