iTerm 2 Automatic Profile Switching

Posted on Apr 19, 2018

A couple of months ago I decided to set it up so my iTerm 2 terminal changed to a different colour when I am ssh’d into either one of our Production or Staging servers when I am working at Disco.

I’ve found it really useful as it allows me to quickly recognise which terminal window I need to be in, and helps prevent me from accidentally running a command on Production that I, in fact, wanted to run on Staging. This all conforms to my general philosophy of “Make it really hard to do the wrong thing.”

Here is an example of what my final setup looks like.

Default Environment

Iterm Default Theme

Production

Iterm Production Theme

Staging

Iterm Staging Theme

Pretty sweet, eh? The process to set it up is as follows. This is a bit involved, but worth the effort, so strap in.

What we are looking to do is detect when we are in certain environments in the shell and change the terminal profile so we can visually see what environment we are in.

We are going to go through the steps of setting up automatic profile switching when you are in production, but the principle holds for other types of switching. The below instructions presume that your command prompt is in the format user@server. If you have a different style of command prompt, you can change the regex that you are using to grab the data.

  1. Go to preferences and then profiles
  2. Go to your default profile and go to the ‘Advanced’ tab
  3. Hit the ‘Edit’ button under Triggers
  4. Put in the regular expression ^(\w+)@([\w.-]+), the action ‘Report User & Host’ and the parameters as \1@\2 and make sure the instant box is checked.
  5. Select your default profile, go to ‘Other Actions’ at the bottom and duplicate.
  6. Select your new profile and navigate back to the ‘General’ tab. Name it ‘Production’.
  7. Go to the ‘Colours’ tab and change the colour scheme to something visually recognisable - I have selected a red background for production.
  8. Go to Advanced. Under Automatic Profile Switching create a new rule for user@server*

You are good to go!

Now, when you ssh into the production server, it should automatically switch the profile.

For more information you can see the iTerm2 documentation on it here