How to Set Host-Specific Environment Variables in SSH Using ssh_config


1 views

While SendEnv in SSH config allows exporting local environment variables to remote hosts, it doesn't provide host-specific value assignment. This becomes problematic when you need different variable values for different hosts.

The most effective solution is to combine LocalCommand with environment variable assignment in your ~/.ssh/config:

Host example.com
  HostName example.com
  User myuser
  LocalCommand FOO=bar ssh -o SendEnv=FOO %r@%h
  PermitLocalCommand yes

For more complex scenarios, create a wrapper script:

#!/bin/bash
# save as ~/bin/ssh_foobar
export FOO=bar
ssh -o SendEnv=FOO "$@"

Then configure your SSH host with:

Host example.com
  HostName example.com
  ProxyCommand ~/bin/ssh_foobar %h %p

Remember that environment variables are visible to all processes on the remote host. For sensitive data, consider using:

  • SSH certificates with embedded metadata
  • Remote configuration files (e.g., ~/.profile)
  • Configuration management tools like Ansible

Here's how you might set different AWS profiles for different hosts:

Host production-server
  HostName prod.example.com
  LocalCommand AWS_PROFILE=production ssh -o SendEnv=AWS_PROFILE %r@%h
  PermitLocalCommand yes

Host staging-server
  HostName stage.example.com
  LocalCommand AWS_PROFILE=staging ssh -o SendEnv=AWS_PROFILE %r@%h
  PermitLocalCommand yes

While SendEnv in SSH client configuration allows exporting environment variables to remote hosts, it has a critical limitation: it can only send variables that already exist in your local environment. There's no native way to define host-specific variable values directly in ssh_config.

Method 1: Local Shell Wrapper

Create a shell function that sets variables before SSH connection:

function ssh_example() {
    FOO=bar ssh example.com
}

Method 2: Using ProxyCommand

A more advanced solution using ProxyCommand:

Host example.com
    ProxyCommand sh -c "FOO=bar exec nc %h %p"

Method 3: Remote Configuration

On the server side, modify sshd_config:

AcceptEnv FOO
Match Host example.com
    SetEnv FOO=bar

For maximum flexibility, create a wrapper script:

#!/bin/bash

declare -A host_vars=(
    ["example.com"]="FOO=bar"
    ["test.server"]="FOO=baz"
)

host=$1
if [[ -n "${host_vars[$host]}" ]]; then
    env ${host_vars[$host]} ssh "$@"
else
    ssh "$@"
fi

Remember that environment variables are visible to all processes on the remote host. For sensitive data:

  • Use SSH certificates instead of variables
  • Consider SSH Agent forwarding for credentials
  • Restrict variable acceptance in sshd_config