From 69491c9aa0e448feb7853a4ceb5c3523b113e133 Mon Sep 17 00:00:00 2001 From: Markus Pesch Date: Wed, 7 Jan 2026 10:28:13 +0100 Subject: [PATCH] feat: support environment variables in authorized_keys file --- README.md | 6 +++++- templates/authorized_keys.j2 | 25 +++++++++++++++++++++---- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 483b6ef..eed6743 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,11 @@ The SSH client directory `~/.ssh` can also be managed via the Ansible role. This `~/.ssh/config`, `~/.ssh/authorized_keys` as well as the maintenance of private and public SSH keys. The following example create two entries in `~/.ssh/authorized_keys`. One normal SSH access for `claire`. If `bob` -establish a SSH connection the command `/usr/local/bin/upload-file.sh` will be executed and exited. +establish a SSH connection the command `/usr/local/bin/upload-file.sh` will be executed and exited. Furthermore, +environment variables can be espcilitly defined, to consume it during execution of the command. + +> [!IMPORTANT] +> To allow consuming environment variables must be set `PermitUserEnvironment yes` in `/etc/ssh/sshd_config`. The private key `toor@toor-pc.ed25519.key` must be stored in `ssh/private_keys`. The public key will be automatically extracted from the private key. diff --git a/templates/authorized_keys.j2 b/templates/authorized_keys.j2 index ea1c91c..2383944 100644 --- a/templates/authorized_keys.j2 +++ b/templates/authorized_keys.j2 @@ -3,9 +3,26 @@ # {{ ansible_managed }} # {% for authorized_key in unix_user.value.ssh.authorized_keys %} -{% if authorized_key.command is defined and authorized_key.command | length > 0 %} -command="{{ authorized_key.command }}" {{ lookup('file', 'ssh/authorized_keys/' + authorized_key.filename ) }} -{% else %} + {% set _args = [] %} + {% if authorized_key.command is defined and authorized_key.command | length > 0 %} + {% set _args = _args + [ "command=\"" + authorized_key.command + "\"" ] %} + {% endif %} + {% if authorized_key.environments is defined %} + {% set ns = namespace(envs=[]) %} + {% for environment in authorized_key.environments %} + {% if environment.key is defined and environment.key | length > 0 and + environment.value is defined and environment.value | length > 0 + %} + {% set ns.envs = ns.envs + [ environment.key + "=" + environment.value ] %} + {% endif %} + {% endfor %} + {% if ns.envs | length > 0 %} + {% set _args = _args + [ "environment=\"" + (ns.envs | join(',')) + "\"" ] %} + {% endif %} + {% endif %} + {% if _args | length > 0 %} +{{ _args | join(',') }} {{ lookup('file', 'ssh/authorized_keys/' + authorized_key.filename ) }} + {% else %} {{ lookup('file', 'ssh/authorized_keys/' + authorized_key.filename ) }} -{% endif %} + {% endif %} {% endfor %}