<!--
  canonical-url: https://www.avonture.be/blog/ssh-config-tips
  published:     2026-10-01
  This is a static plain-Markdown mirror generated at build time.
  Visit the canonical URL above for the fully rendered page, with images and interactive components.
-->

# SSH Config Generator: Wildcard Stanzas, Aliases, and Automated Logins

> Generate your SSH config in seconds — then understand how it works: one wildcard eliminates every repeated ProxyJump and IdentityFile, domain stanzas set usernames for FQDNs, short aliases need their own User line, and RemoteCommand lands you directly as the application user.

---
![SSH Config Generator: Wildcard Stanzas, Aliases, and Automated Logins](/img/v2/ssh.webp)

**TL;DR**

SSH reads every matching stanza top-to-bottom, first value wins per directive — that's what makes `Host * !bastion` powerful: one stanza covers every server at once, no more repeating `ProxyJump` and `IdentityFile`. Domain stanzas layer in the right `User` for FQDN connections; short aliases must repeat it explicitly, because SSH matches on what you type, not the resolved hostname. Three directives — `ServerAliveInterval`, `ControlMaster`, `ConnectTimeout` — harden the global defaults without changing their logic. For machines mixing corporate and personal SSH, `Include` splits the two cleanly. `RemoteCommand` turns a `sudo su` + `cd` sequence into a single alias.

Every server in my environment is only reachable through my own Windows VM acting as a bastion. The [ProxyJump and DevContainers article](/blog/vscode-remote-ssh-proxyjump-devcontainer) shows a config with one alias. Add a second server and the config doubles. Add ten and it becomes a maintenance problem: change the bastion hostname once and you rewrite ten stanzas, each carrying the same `ProxyJump` and `IdentityFile` lines.

The config below covers any number of servers with no repetition.

## The Config

Both connection paths work out of the box — a short alias and a full FQDN, no flags needed:

```bash
$ ssh project_prod "whoami && hostname"
user-b
server-prod
$ ssh server-test.cloud.project-a.internal "whoami && hostname"
user-a
server-test
```

No `ProxyJump` flag, no explicit key — the config handles both transparently. Create `C:\Users\your_laptop_user\.ssh\config` (Windows; WSL included) or `~/.ssh/config` (Linux/macOS) with the following:

```txt
# 1. Bastion — no ProxyJump, no IdentityFile
Host windows-vm-ip
    User vm-user

# 2. Domain defaults — in effect when connecting via full FQDN only
Host *.cloud.project-a.internal
    User user-a

Host *.cloud.corp.example
    User user-b

Host *.office.corp.example
    User user-b

# 3. Short aliases — HostName + User
#    (domain defaults above do not apply to aliases — see article)
Host project_test
    HostName server-test.cloud.project-a.internal
    User user-a

Host project_prod
    HostName server-prod.office.corp.example
    User user-b

# 4. Explicit exceptions — bypass the bastion for specific hosts
#    Must come BEFORE "Host *" — SSH uses first-value-wins per directive
Host github.com
    ProxyJump none

# 5. Global defaults — fallback for every host except the bastion
Host * !windows-vm-ip
    ProxyJump vm-user@windows-vm-ip
    IdentityFile ~/.ssh/id_ed25519
```

## How SSH Reads a Config File

Three rules explain why the stanzas compose without conflict:

* **Multiple stanzas can match.** Running `ssh project_prod` causes SSH to scan the file top-to-bottom and collect settings from *every* `Host` stanza that matches `project_prod`, not just the first one.
* **First value wins per setting — the opposite of what most tools do.** In CSS, `.env` files, or most config systems, the last declaration overrides earlier ones. SSH does the reverse: the first value encountered is kept, and later stanzas can only fill in settings not yet defined. Put the most specific stanza first; the wildcard fallback last.
* **Patterns match on the command-line argument, not on the resolved hostname.** `Host *.office.corp.example` matches `ssh server-prod.office.corp.example`. It does **not** match `ssh project_prod`, even though `project_prod`'s `HostName` resolves to `server-prod.office.corp.example`.

## The Five Sections

The config snippet above is split into five numbered sections — here is what each one does and why it is placed in that order.

**Section 1 — Bastion definition.** Declares the jump host with its username. No `ProxyJump` here (it would loop back to itself) and no `IdentityFile` (the VM uses whatever auth you have configured for it separately).

**Section 2 — Domain defaults.** These match when you type a full FQDN like `ssh server-prod.office.corp.example`. SSH picks up the `User` from here, since no earlier stanza set it. Multiple domain stanzas with the same username are normal — one per domain suffix. These stanzas are also useful for scripts that construct hostnames programmatically or for `ssh-copy-id` calls.

**Section 3 — Short aliases.** Each alias declares `HostName` (the real FQDN) and `User`. Adding a new server alias is exactly two lines.

**Section 4 — Explicit exceptions.** Any host that must not go through the bastion — a Git hosting service, a CI runner, a SaaS API — gets `ProxyJump none` here. Position is load-bearing: this stanza must come *before* `Host *`.

**Section 5 — Global defaults.** The `!` prefix in `Host * !`windows-vm-ip means "all hosts *except* the bastion". Placed last, this stanza provides `ProxyJump` and `IdentityFile` as fallbacks for every preceding stanza that did not set them — which is all of them. Any stanza in sections 2, 3, or 4 can override these defaults simply by declaring the directive first, without touching section 5.

## Hardening Section 5 (optional)

Four directives extend the global defaults without changing their logic. Add whichever ones fit your environment — none are required for the config to work.

```txt
# 4. Explicit exceptions — bypass the bastion for specific hosts
#    Must come BEFORE "Host *" — SSH uses first-value-wins per directive
Host github.com
    ProxyJump none

# 5. Global defaults — fallback for every host except the bastion
Host * !windows-vm-ip
    ProxyJump vm-user@windows-vm-ip
    IdentityFile ~/.ssh/id_ed25519

    # Optional — prevent silently-dropped idle connections
    ServerAliveInterval 30
    ServerAliveCountMax 3

    # Optional — fail fast instead of waiting the default 2 minutes
    ConnectTimeout 5
```

* **`ServerAliveInterval 30` / `ServerAliveCountMax 3`** — SSH sends a keepalive packet every 30 seconds. After 3 unanswered packets (90 seconds of silence), the connection is dropped cleanly rather than hanging with a frozen prompt. Without these, an idle terminal on a corporate server often locks up with no error message.
* **`ConnectTimeout 5`** — fails after 5 seconds if the server is unreachable. On a corporate network with a reliable bastion, the default 2-minute timeout is pure noise.

> **ControlMaster does not work on Windows OpenSSH:**
>
> `ControlMaster auto` / `ControlPath` / `ControlPersist` enable SSH multiplexing: the first connection opens a Unix domain socket in `~/.ssh/`; subsequent connections reuse the tunnel instead of negotiating a new one through the bastion. On Linux and macOS this works well.
>
> On **Windows OpenSSH with ProxyJump**, these three directives silently break all connections — `ssh` hangs or exits with `Read from remote host: Unknown error` — because Windows's Unix socket implementation does not interoperate with ProxyJump's pipe-based stdio forwarding. The comment `# Optional` is not enough protection: the lines are copied and break things.
>
> Leave them out on Windows. If you connect from Linux or macOS, add them:
>
> ```text
>     ControlMaster auto
>     ControlPath ~/.ssh/cm_%C
>     ControlPersist 10m
> ```
>
> `%C` is a hash of the connection parameters — no colons, no special characters. Never use `%r@%h:%p`: the `:` is illegal in Windows filenames and silently corrupts the socket path even when ControlMaster itself is otherwise functional.

## Why Each Alias Needs Its Own `User` Line (skip if the config just works for you)

The domain stanzas in section 2 set `User` only when SSH matches them — and as noted above, SSH matches patterns on the command-line argument, not on the resolved hostname.

Running `ssh project_prod`:

1. Does **not** match `Host *.office.corp.example` (section 2) — `project_prod` is not a FQDN.
2. Matches `Host project_prod` (section 3) → applies `HostName server-prod.office.corp.example` and `User `user-b.
3. Does **not** match `Host github.com` (section 4) — `project_prod` is not in that list.
4. Matches `Host * !`windows-vm-ip (section 5) → applies `ProxyJump` and `IdentityFile`.

Without the `User` line in the alias stanza, SSH falls back to your local Windows username for that connection — which is almost certainly wrong.

Running `ssh server-prod.office.corp.example` directly:

1. Matches `Host *.office.corp.example` (section 2) → `User `user-b.
2. Does **not** match `Host github.com` (section 4) — not in that list.
3. Matches `Host * !`windows-vm-ip (section 5) → `ProxyJump`, `IdentityFile`.

Both paths land on the right user. They just need different stanzas to get there.

> **ZSH users: autocomplete your aliases:**
>
> The [zsh-ssh-config-suggestions plugin](/blog/zsh-plugin-ssh-config-suggestions) reads `~/.ssh/config` and offers completions on `ssh <Tab>`. Every alias in section 3 becomes a suggestion — the longer your alias list, the more useful it is.

## One Caveat: The Wildcard Is Truly Universal (skip if this machine is corporate-only)

`Host * !`windows-vm-ip applies to **every** SSH connection from this machine — including `ssh github.com` or `ssh localhost`. Connections to external hosts will attempt a `ProxyJump` through the VM and fail if the VM is not reachable.

> **Devcontainers: declare exceptions before Host \*:**
>
> When the SSH config is bind-mounted into a devcontainer, the bastion hostname may not resolve inside the container network. Any SSH connection from the container — `git push`, `scp`, `rsync` — hits `Host *`, attempts a `ProxyJump` through the bastion, fails to resolve it, and exits with:
>
> ```text
> ssh: Could not resolve hostname your-bastion: Name or service not known
> ```
>
> Hosts that must bypass the bastion need an explicit `ProxyJump none` stanza **before** `Host *`. SSH applies first-value-wins per directive: a `ProxyJump none` placed after `Host *` is silently ignored. Section 4 in the config above exists precisely for this — add any host that connects directly (Git hosting, CI runners, third-party APIs) to that stanza.

Three options if that matters:

* **Replace `Host *` with an explicit domain list:** `Host *.project-a.internal *.cloud.corp.example *.office.corp.example`. Connections to anything outside that list skip the bastion entirely.
* **Keep `Host *`** if this machine uses SSH exclusively for servers inside your corporate network. In a dedicated work machine, the wildcard is fine.
* **Override specific hosts above section 4.** Because the global defaults are last, any stanza placed before them wins. Add an exemption anywhere above section 4 — position within sections 1–3 does not matter:

```text
# Anywhere above section 4 — fits naturally in section 3 alongside the other aliases
Host github.com gitlab.com
    ProxyJump none
    IdentityFile ~/.ssh/id_ed25519_personal

# Section 4 — global defaults (last, unchanged)
Host * !windows-vm-ip
    ProxyJump ...
```

* **Split the config with `Include`** — the cleanest solution for a machine used for both corporate and personal SSH:

```text
# ~/.ssh/config
Include ~/.ssh/config.d/work
Include ~/.ssh/config.d/personal
```

`~/.ssh/config.d/work` holds the full corporate config (bastion, domain stanzas, aliases, global defaults last). `~/.ssh/config.d/personal` holds a clean config with no bastion routing. The `Include` directives are processed top-to-bottom before any `Host` block in the main file — OpenSSH 7.3+ required.

## Bonus: Log In Directly as Another User

Some servers require you to connect with your own account and then switch to an application user — `sudo su app_user` followed by `cd /opt/project`. The `RemoteCommand` directive automates the entire sequence from the alias.

The generator below produces **two aliases per server**: a plain alias for VSCode Remote Explorer (no `RemoteCommand`) and a `_app` variant for terminal sessions that lands you directly as the application user.

## Generate Your Complete Config

Fill in your values once and copy the result directly into `~/.ssh/config`. For a second project, copy-paste only the Section 3 aliases and change the project name — the bastion and global defaults are already in place.

> **Test your bastion connection first:**
>
> Before testing a full alias, verify the bastion itself is reachable and accepts your key:
>
> ```bash
> $ ssh vm-user@windows-vm-ip "echo bastion-ok"
> bastion-ok
> ```
>
> `echo bastion-ok` is a non-interactive command — it exits immediately after printing, leaving no open session. If the output appears, section 1 and section 4 are wired correctly. If it hangs or fails, the problem is between your machine and the bastion, independently of any server alias.

> **Eliminate password prompts — push your public key to a server:**
>
> Once the config is in place, authorize your key on any server with this PowerShell one-liner. Replace `project_test` with the alias or hostname you want to reach:
>
> ```bash
> $ Get-Content $env:USERPROFILE\.ssh\id_ed25519.pub | ssh project_test "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
> ```
>
> You will be prompted for the server password once. After that, `ssh project_test` connects silently. On Linux and macOS, `ssh-copy-id project_test` does the same thing.

> **VSCode Remote Explorer does not work with RemoteCommand:**
>
> VSCode Remote SSH injects its own server process during login. `RemoteCommand` replaces the remote shell before that injection can happen — the connection closes before VSCode gets a foothold. Use the plain `project_test` / `project_prod` aliases for Remote Explorer; navigate to the application directory from within VSCode once connected.

The `_app` variant's `RemoteCommand` chains two things: `cd` to the application directory and `exec bash -l` to start a login shell as the application user. `RequestTTY yes` allocates a pseudo-terminal — without it, the session closes immediately after the command instead of giving you an interactive shell.

```bash
$ ssh project_test_app
mass_upload@server-test:/opt/folder_devcontainer$
```

```bash
$ ssh project_prod_app
app-user@server-prod:/opt/project$
```

All four aliases get the global `ProxyJump` from section 4 automatically.

> **sudo must be passwordless — or use su instead:**
>
> `sudo -u `app-user in a `RemoteCommand` works silently only when the sudoers file grants your account `NOPASSWD` for that specific user. If it does not, the connection will block waiting for a password that SSH cannot deliver before the TTY is fully established.
>
> If passwordless sudo is not configured, use `sudo su - `app-user instead — with `RequestTTY yes` the TTY is allocated before the command runs, so the password prompt appears normally:
>
> ```text
> RemoteCommand sudo su - app-user -c "cd /opt/project && exec bash -l"
> ```
>
> You will see the sudo password prompt once, then land in the shell.

## Production Environment Warning

A `RemoteCommand` banner is visible only to whoever has that SSH alias set up. The right place for a production warning is the **server itself** — so it reaches every user, whatever client they use.

Drop a script in `/etc/profile.d/` on the server. Every interactive shell sources that directory on login:

```bash title="/etc/profile.d/env-banner.sh (on the server)"
#!/usr/bin/env bash
case "$(hostname -s)" in
  *prod*|*prd*)
    printf '\033[38;5;88;48;5;224m  ⚠  Production server — be careful!  \033[0m\n\n'
    export PS1='\[\033[38;5;88;48;5;224m\] ⚠ PROD \[\033[0m\] \u@\h:\w\$ '
    ;;
esac
```

The color pair `38;5;88` (dark maroon) on `48;5;224` (pale rose) is clearly visible without being aggressive — a reminder, not a warning sign.

```bash
$ ssh project_prod_app
  ⚠  Production server — be careful!

app-user@server-prod:/opt/project$
```

Because `exec bash -l` in the `RemoteCommand` starts a login shell, the profile scripts run and the banner appears on every `_app` connection as well. No change to the SSH config needed.

> **hostname-based detection vs. an explicit file:**
>
> `hostname -s` matching `*prod*` is convenient but fragile — a host named `deployments-node` would match nothing. An explicit marker file is more reliable:
>
> ```bash
> if [[ -f /etc/env-type ]] && grep -qx "production" /etc/env-type; then
> ```
>
> Create `/etc/env-type` with the content `production` when provisioning a server. The check is unambiguous regardless of the hostname.

## Conclusion

One wildcard stanza eliminates the per-alias repetition of `ProxyJump` and `IdentityFile`. Domain stanzas layer in usernames for direct FQDN access. Short aliases repeat `User` explicitly — because SSH matches on what you type, not on what the alias resolves to.

Adding a new server means two lines: `HostName` and `User`. The routing is already handled. When a server requires a specific user and directory, `RemoteCommand` turns that sequence into a single alias. And when a production server needs a clear visual warning for everyone, `/etc/profile.d/` is the right place — not the SSH config.

If you need to [generate or manage your SSH keys](/blog/github-connect-using-ssh), that article covers `ed25519` key generation and GitHub authorization from scratch — the same key used in the `IdentityFile` line above.
