iTerm2: Automatic Profile Switching

devops Jan 08, 2020

As devops engineers, we spend a lot of time SSHing into different hosts (e.g. CI, staging, production). But juggling multiple hosts at the same time can sometimes get confusing.

Am I on production or staging?

You certainly don't want to accidentally type a command into production, thinking that you were somewhere else. If you make this mistake, you could be in for a very, very bad time.

Fortunately, our tools can help us. Using automatic profile switching in iTerm2, we can switch our terminal profile every time we connect to a different host. Profiles allow you to have completely different settings, like colours, fonts, background images, etc.

No more wondering which host you're on — production can be a scary red, staging a calming blue, and CI can be a soothing green, or whatever floats your boat.

I Want It Now!

There's a few things you need to do to get this working properly, but don't worry, it's not too complicated.

First, you need to install shell integration. You can also do this manually, if you don't trust iTerm running a command for you.

Next, we need to set up a trigger to automatically detect a terminal prompt. The hosts I'm connecting to all have prompts like this:

josh@staging:~$

Using a trigger, we can notify iTerm when a new user and host is detected. This trigger must be created in our Default profile (the one that is automatically used when you open a new terminal):

Create a new trigger with the following settings:

  • Regular Expression: ^(\w+)@([\w.-]+):.+\$
  • Action: Report User & Host
  • Parameters: \1@\2
  • Instant: ✅

Now that you have created the trigger, iTerm will be notified whenever it detects a user and host.

Next, we need to duplicate the default profile. To do this, select the default profile, click the 'Other Actions' drop-down, and then select 'Duplicate Profile':

Name your duplicated profile (mine is called 'Staging'), and optionally give it a tag (I tagged mine with 'ssh'):

Select your new profile and make it visually different to your default profile. I just changed the background colour, but obviously you could tweak whatever settings you like:

Finally, add a rule for automatic profile switching. This profile will be used whenever this rule is matched. In my case, if the user and host match josh@staging, then the Staging profile will be used:

Enjoy!

Tags

Josh Bassett

Hello. I'm a software developer living in Byron Bay, Australia.