Sub topic 6
Saving connection details in ~/.ssh/config
This chapter assumes you can already connect to an instance with ssh -i key.pem user@address, that you know which login user your AMI uses, and that you have a working key pair. Here you move those details into the OpenSSH client configuration file so that each connection needs one short command.
Why a config file
A typical EC2 connection command carries three values that rarely change: the address, the login user, and the private key path. Retyping them invites mistakes, such as using root instead of ec2-user or forgetting -i.
The OpenSSH client reads ~/.ssh/config before every connection. Each entry maps a short alias to a set of options. The same file is read by scp, sftp, rsync -e ssh, and by tools built on OpenSSH such as VS Code Remote-SSH and Ansible.
The file is plain text and lives only on your machine. It does not change anything on the instance.
A first entry
Host web1
HostName 203.0.113.25
User ec2-user
IdentityFile ~/.ssh/my-key.pemWith this entry saved, the following commands are equivalent.
ssh web1
ssh -i ~/.ssh/my-key.pem [email protected]The directives mean the following.
| Directive | Meaning |
|---|---|
| `Host` | The alias you type. It starts a block that lasts until the next `Host` line. |
| `HostName` | The real address or DNS name to connect to. Without it, the alias itself is used as the address. |
| `User` | The login user on the instance. |
| `IdentityFile` | The private key file to offer. |
Indentation is a convention for readability. It is not required by the parser.
Setting up the file correctly
If ~/.ssh/config does not exist, create it and restrict its permissions. OpenSSH refuses to use a config file that other users can write to, and it reports Bad owner or permissions.
mkdir -p ~/.ssh
chmod 700 ~/.ssh
touch ~/.ssh/config
chmod 600 ~/.ssh/configThe key file still needs chmod 400, as in the earlier chapters. The config file only points to the key. It does not store it.
How matching works
OpenSSH evaluates the file from top to bottom. For each option, the first value obtained wins. Later lines never override an earlier value for the same option. This has two practical consequences.
- Put specific
Hostblocks first and general ones, such asHost *, last. - A command-line option such as
-ior-ltakes precedence over the file.
The following file shows this layout.
Host web1
HostName 203.0.113.25
User ec2-user
IdentityFile ~/.ssh/my-key.pem
Host db1
HostName 10.0.2.40
User ubuntu
IdentityFile ~/.ssh/db-key.pem
Host *
ServerAliveInterval 60
ServerAliveCountMax 3
IdentitiesOnly yesThe Host * block applies to every connection. ServerAliveInterval 60 sends a keepalive message every 60 seconds, which stops idle sessions from being dropped by NAT devices or firewalls that discard quiet connections. ServerAliveCountMax 3 closes the connection after three unanswered keepalives, so a dead link fails instead of hanging.
Why IdentitiesOnly matters
If you run ssh-agent with several keys loaded, the client offers the agent's keys first. A server allows only a limited number of authentication attempts, six by default in MaxAuthTries. With many keys loaded, you can hit that limit before the correct key is tried and see Too many authentication failures.
IdentitiesOnly yes tells the client to offer only the keys named by IdentityFile entries (plus any given with -i). Use it when you keep more than a few keys in an agent.
Patterns and multiple hosts
Host accepts several aliases and wildcards.
Host web1 web2 web3
User ec2-user
IdentityFile ~/.ssh/my-key.pem
Host web1
HostName 203.0.113.25
Host web2
HostName 203.0.113.26
Host web3
HostName 203.0.113.27Because the first value wins and the blocks all match, ssh web1 combines the first and the second block. The first supplies User and IdentityFile. The second supplies HostName. This lets you share settings without repeating them.
Wildcards use * (any run of characters) and ? (one character). You can also negate a pattern with !.
Host ip-10-0-*.ec2.internal
User ec2-user
IdentityFile ~/.ssh/my-key.pemPublic addresses change
For an instance with an auto-assigned public IPv4 address, the address changes when you stop and start the instance. An Elastic IP address stays fixed. If your entries use the auto-assigned address, you must edit HostName after each stop and start.
Options for coping with this:
- Allocate an Elastic IP address for instances you reach often.
- Use the instance's public DNS name. It also changes with the public IP, so it does not help here.
- Use a DNS record you control that points at the instance.
- Use Session Manager, covered later in this tutorial, where the instance ID is the stable identifier.
Host key checking and moving addresses
The first time you connect to an address, SSH asks you to confirm the server's host key fingerprint and stores it in ~/.ssh/known_hosts. If a new instance later receives an address that an old instance used, SSH sees a different key for the same address and stops with WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!.
This is common with EC2 because addresses are reused. Remove the stale entry instead of disabling checking.
ssh-keygen -R 203.0.113.25You may see advice to set StrictHostKeyChecking no and UserKnownHostsFile /dev/null globally. That turns off protection against an attacker who impersonates the server. If you must relax checking, restrict it to a narrow pattern, such as short-lived test instances in one lab network.
Host lab-*
StrictHostKeyChecking accept-newaccept-new records the key for new hosts automatically but still refuses a changed key. It is a safer middle ground.
Verifying what SSH will do
Two commands help you debug a config file.
ssh -G web1
ssh -v web1ssh -G web1 prints the final, merged configuration for that alias without connecting. Look for the hostname, user, and identityfile lines. ssh -v web1 connects and prints which config file was read and which key was offered. These show immediately whether the wrong block matched or whether a key is being skipped.
Other useful directives
| Directive | Purpose |
|---|---|
| `Port` | Connect to a port other than 22. |
| `ForwardAgent` | Forward your agent to the instance. Enable only for hosts you trust, because root on that host can use your agent while you are connected. |
| `ProxyJump` | Reach a private instance through a bastion host in one command. |
| `LocalForward` | Forward a local port to a remote destination. |
| `Include` | Read additional config files, for example `Include ~/.ssh/config.d/*`. |
For a private instance behind a bastion, ProxyJump replaces a manual two-step login.
Host bastion
HostName 203.0.113.25
User ec2-user
IdentityFile ~/.ssh/my-key.pem
Host private-app
HostName 10.0.2.40
User ec2-user
IdentityFile ~/.ssh/my-key.pem
ProxyJump bastionRunning ssh private-app opens a connection to bastion and then to 10.0.2.40 through it. Your private key stays on your machine.
Preparing for Session Manager
A config entry can also run a command to create the connection, using ProxyCommand. A later chapter uses that to send SSH traffic through Session Manager with a pattern such as Host i-* mi-*. The matching rules from this chapter apply there unchanged. In particular, the pattern block must come before any Host * block that sets conflicting values.
Common mistakes
- Setting
Host *first with aUservalue, which then overrides every specific block below it. - Permissions on
~/.ssh/configthat are too open, givingBad owner or permissions. - A leftover
HostNameafter the instance's public IP changed, which causes a timeout. - Using
~inside quoted values in some tools that do not expand it. Use an absolute path there. - Forgetting that
-ion the command line is added to, not replacing,IdentityFileentries, unlessIdentitiesOnly yesis set.
Exercise
Your file has Host * with User admin at the top, followed by Host web1 with User ec2-user. Running ssh web1 logs in as admin and fails on an Amazon Linux instance. Why does this happen, and how do you fix it?
Show answer
OpenSSH uses the first value it finds for each option, and Host * matches web1 first, so User admin wins. Move the Host web1 block above Host *, or remove User from Host *. Confirm the result with ssh -G web1 and check that the user line shows ec2-user.
Exercise
After stopping and starting an instance, ssh web1 hangs and times out, although the config entry has not changed. What is the most likely cause, and what are two ways to prevent it?
Show answer
The instance had an auto-assigned public IPv4 address, which changes on stop and start, so HostName now points to an old address. Prevent it by associating an Elastic IP address with the instance, or by switching to Session Manager, which uses the instance ID instead of an IP address. Updating HostName fixes the immediate problem.