Tim Spurling

finding out promptly how much damage typing badly might do

As Tom mentioned in a previous post, it’s nice having the purpose of a machine reflected in the shell prompt: for example, a hint of red when working on a production machine, or a less threatening yellow in the case of a staging server.

Recently, as the result of no one particularly objecting, we changed everyone’s default shell on all our servers to be zsh. This had the side effect of breaking the mechanism by which the prompt hackery was done. So, here is some explanation of how it works now:

where am i?

First, it needs to be possible to find out the purpose of a machine. Luckily, we use puppet on everything, and happen to use an environment string to control certain aspects of its behaviour. For example, the same .jar might be started with different parameters (defined through hiera) based on whether it is running in ‘stage’ or ‘prod’.

So, all we really need to do is take this information that Puppet has, and make it available to the users’ shells. This is pretty easy—we just use a template to inject our own special variables into /etc/zsh/zshenv, one of several files available for zsh’s system-wide configuration. For example:

MBST_ENV=stage
MBST_ENV_COLOR=yellow

Where did ‘yellow’ come from? We just do this mapping to standard colours directly at the templating stage, to keep things simple and make it easier to use them later in a prompt. A switch statement in the zshenv template is the easiest way:

environmentColor = case environment
  when 'dev' then 'green'
  when 'stage' then 'yellow'
  when 'prod' then 'red'
  else 'cyan'
end

choice

At this point, anyone can modify their own rc file (~/.zshrc) to use these variables which we provide globally (through /etc/zsh/zshenv) and easily show the relevant colour in their own preferred way.

As a dead simple example, here’s a prompt that just shows the hostname (%m) with the system colour as a background:

export PROMPT="%K{$MBST_ENV_COLOR}%m%k "

Note zsh’s delightful %K and %k operations to push/pop background colours onto/off-from a stack.

blog comments powered by Disqus