How to make a Spinnaker SpEL reference to a context attribute that does not exist return null (or None or '')?

Viewed 498

According to Spinnaker Doc, a context value for attribute X can be referenced as ${#stage("Deploy to Prod")["X"]}. In my case, X may not exist. The value returned when X does not exist is the SpEL expression itself "${#stage("Deploy to Prod")["X"]}". I was expecting to get a null or empty string. Is there a way to get the SpEL expression return None or '' when the attribute does not exist in the context map?

1 Answers

Try the Elvis operator:

${ #stage("Deploy to Prod")["X"]?:"defaultValue" }

The Elvis operator ?: can be used to get a value if exists - in the example: #stage("Deploy to Prod")["X"] -, else get the default value - in the example: "defaultValue". Explanation from SpEL docs, section "6.5.14 The Elvis Operator":

The Elvis operator is a shortening of the ternary operator syntax and is used in the Groovy language. With the ternary operator syntax you usually have to repeat a variable twice, for example:

String name = "Elvis Presley";
String displayName = name != null ? name : "Unknown";
Related