W3tTr3y's blog

A personal technology focused blog

SSH Config: Dynamically Appending Domain (Host -> Fqdn via .ssh/config))

I the ssh config file to set a number of options; for several years now I’ve known there had to be a way to dynamically add a domain name to a hostname but I ahven’t been able to figure out how to do it.

(As an aside) The TLDR version is the %h variable will hold the host value. HostName %h.example.com will append .example.com to a matched host

For example, the username configured on my laptop is different from our servers so I have rules in place that automatically set my user.

Host db99 User jdoe

In reality, we have a number of servers so I have a rule similar to: Host db? log?? web? User jdoe

My problem has been I have a bad habbit that while I’m at the office, I just use hostnames (e.g. ssh db1). When I VPN in from home, I must use fully qualified domain names (e.g. ssh db1.example.com). You can use the HostName setting to set the fully qualified domain name, but the only way I could find was to make a setting per server. For exsample:

Host db1 User jdoe HostName db1.example.com

Host db2 User jdoe HostName db2.example.com

They need not match

Host fred User jdoe HostName db99.example.com

As you can probably guess that’s great, but it really doesn’t scale. I wrote a bash script to loop over all over our settings and generate the configuratin, so its not completely unmanagable but I was convinced there was a better way. Unfortunately my searches turned up blank so I’ve suffered in pain for years.

Today I just happened to come across an askubuntu post (https://askubuntu.com/questions/281988/can-i-configure-ubuntu-to-append-a-domain-to-the-end-of-an-ssh-hostname-request/760686#760686?newreg=14a526c965824d93854059e1ed7e8988) asking this exact question and the answer is so simple, %h will return the hostname.

Thus I can go back to my previous entry, just with one line added: Host db? log?? web? User jdoe HostName %h.example.com

As a slight aside, in case I type the full qualified domain name I also have: Host *.example.com User jdoe

I feel really dumb that its 2016 and I just found this setting, but hopefully this helps others in a similar situation.