Search code examples
kubernetes-helmsprig-template-functions

Can write an if-statement checking if current date/time is between to given values using Helm?


I want to schedule a deployment. I have the following values:

- namespace: test-dind-1
  name: dev-container-gpu
  startDate: 1738105200
  endDate: 1738191600

And my deployment manifest:

{{- if and (gt (now | unixEpoch) .startDate) (lt (now | unixEpoch) .endDate) }}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ .name }}
  namespace: {{ .namespace }}

So I want the deployment to only be activated within the timeslot. I'm using Fleet(similar to ArgoCD) for deployment.

How can I write that comparison? The error with the solution above is: " incompatible types for comparison"


Solution

  • unixEpoch returns a string!

    {{/* Running `helm template` over this shows "string" twice */}}
    kind: '{{ now | unixEpoch | kindOf }}'
    type: '{{ now | unixEpoch | typeOf }}'
    

    That means you need to convert that string back to a number before you compare it. You can do similar introspection on the Helm value and discover that it's a float. Helm has a set of type-conversion functions, and in particular float64 will turn anything into a float.

    I might break this into a variable, but fundamentally, converting now | unixEpoch | float64 should make the comparison work.

    {{- $now := now | unixEpoch | float64 -}}
    {{- if and (gt $now .startDate) (lt $now .endDate) }}
    ...
    {{- end }}
    

    (unixEpoch, along with most of the other Helm extension functions, comes from the Sprig extension library. In its source, you can see an explicit strconv.FormatInt() call. Also see Masterminds/sprig#372 which asks about more generic time comparisons, and includes a conversion like what I show here.)