最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

sprig template functions - Can write an if-statement checking if current datetime is between to given values using Helm? - Stack

programmeradmin0浏览0评论

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"

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"

Share Improve this question edited Feb 3 at 16:07 David Maze 160k45 gold badges245 silver badges288 bronze badges asked Feb 3 at 14:49 Viktor ErikssonViktor Eriksson 6,2513 gold badges22 silver badges25 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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.)

发布评论

评论列表(0)

  1. 暂无评论