Openshift/OKD template if/else condition

12/4/2018

Currently I have an OKD/openshift template which exposes port 1883 on a specific container:

ports:
 - name: 1883-tcp
   port: 1883
   containerPort: 1883
   protocol: TCP
   hostPort: ${MQTT-PORT}

Is it possible to have an if/else clause depending on parameters. For example:

ports:
 - name: 1883-tcp
   port: 1883
   containerPort: 1883
   protocol: TCP
   {{ if ${MQTT-PORT} != 0 }}
   hostPort: ${MQTT-PORT}
   {{ /if }}

By doing this, I can have the same template in all my environments (e.g.: development/testing/production) but based on the parameters given by creation, some ports are available for debugging or testing without having to forward them each time using the oc command.

-- Bob Claerhout
kubernetes
okd
openshift

1 Answer

12/4/2018

You can't do this kind of conditional processing at the template level.

But, to achieve your desired outcome, you can do one of 2 things.

Option 1 Pass all the parameters required for the condition to process at the template level, like MQTT-PORTand map the correct port number when building your service. This might be the correct approach as templates are designed to be as logic-less as possible, you do all the decision making at a much lower level.

Option 2 If you can relax the "same template" constraint, We could have 2 flavors of the same template, one with the specific port and another with the parameterized port. The only issue with this option is to change 2 templates every time you change your app/service specs, which violates the DRY principle.

Update

Using Helm with OpenShift might be the best option here. You can templatize your artifacts using Helm's conditionals and deploy a Helm app to OpenShift. Here's a repository which has a Helm chart tailored for OpenShift. Also, you need to point to the right namespace for Tiller to use Helm with OpenShift. You can find more details about it here.

-- Badri
Source: StackOverflow