Skip to content

case - Case statement for performing multiple conditional checks on a value

The case statement is perfect for performing multiple comparisons against a given value, and producing an output. The expressions must result in some boolean result.

NOTE: This case statement, like all case statements, will return the first matching value. This means the order of your clauses in your case statement are extremely important.

Syntax

case {
  condition1 -> value1,
  condition2 -> value2,
  ...
  conditionN -> valueN,
  _          -> <default-value>
}

Example - Mapping server IPs to a specific owner, based on their subnet ranges

It is common to include IP addresses in logs, especially of the servers that produced them. It is also very helpful to decorate logs with the owner of a given IP address, so that if a production incident occurs, the log contains the name of the person to which the issue must be escalated.

Consider the following log documents:

{
  server_ip: 10.0.0.1,
  ...
},
{
  server_ip: 165.0.0.1,
  ...
},
{
  server_ip: 333.4.5.6,
}

We have 3 different IP addresses here, and we can use the ipInSubnet function to work out which subnet they belong to. We can also include a default value to add a generic value, in case we are unable to match.

case {
  ipInSubnet(server_ip, '10.0.0.0/8')   -> 'Chris',
  ipInSubnet(server_ip, '165.0.0.0/8')  -> 'George',
  ipInSubnet(server_ip, '333.4.0.0/16') -> 'Maya',
  _                                     -> 'DevOps Team'
}

We can then save the output of this case statement into a new field, called server_owner.

create server_owner from 
  case {
    ipInSubnet(server_ip, '10.0.0.0/8')   -> 'Chris',
    ipInSubnet(server_ip, '165.0.0.0/8')  -> 'George',
    ipInSubnet(server_ip, '333.4.0.0/16') -> 'Maya',
    _                                     -> 'DevOps Team'
  }

Now, either we will match an IP address to a given subnet range and, therefore, an owner, or it will default to being owned by the DevOps Team.