Giter VIP home page Giter VIP logo

kubetpl's Introduction

kubetpl Latest Version Build Status

Kubernetes templates made easy.
#keep-it-simple #no-server-component

Features:

  • Template flavor of your choice
  • Support for *.env (<VAR>=<VAL>) and YAML / JSON config files.
  • Fail-fast defaults (all variables must be given a value (unless explicitly marked optional)).
  • ConfigMap/Secret freezing for easier and less error-prone ConfigMap/Secret rollouts
    (something to consider if when you hit kubernetes/kubernetes#22368).
  • ConfigMap/Secret "data-from-file" injection when kubectl create configmap ... --from-file=... --from-file=... --from-file=... ... feels like too much typing.
  • image:tag -> image@digest pinning with the help of dockry
    (e.g. kubetpl render -s IMAGE=$(dockry digest --fq user/image:master) ... to force redeployment of the new build published under the same tag).

Installation

macOS / Linux

curl -sSL https://github.com/shyiko/kubetpl/releases/download/0.9.0/kubetpl-0.9.0-$(
    bash -c '[[ $OSTYPE == darwin* ]] && echo darwin || echo linux'
  )-amd64 -o kubetpl && chmod a+x kubetpl && sudo mv kubetpl /usr/local/bin/

Verify PGP signature (optional but recommended):

curl -sSL https://github.com/shyiko/kubetpl/releases/download/0.9.0/kubetpl-0.9.0-$(
    bash -c '[[ $OSTYPE == darwin* ]] && echo darwin || echo linux'
  )-amd64.asc -o kubetpl.asc
curl -sS https://keybase.io/shyiko/pgp_keys.asc | gpg --import
gpg --verify kubetpl.asc /usr/local/bin/kubetpl

macOS: gpg can be installed with brew install gnupg

Windows

Download executable from the Releases page.

Usage

# create template
echo $'
# kubetpl:syntax:$

apiVersion: v1
kind: Pod
metadata:
  name: $NAME-pod
spec:
  containers:
  - name: $NAME-container
    image: $IMAGE
    env:
    - name: ENV_KEY
      value: $ENV_KEY
' > template.yml 

# create config file (.env, .yml/.yaml or .json) (optional)
# (you'll probably have a different config file for each cluster/namespace/etc)
echo $'
NAME=sample-app
ENV_KEY=value
' > staging.env
# you might not need a config file if there are only a handful of variables (like in this case)
# -s/--set key=value might be enough

# render template
kubetpl render template.yml -i staging.env -s IMAGE=nginx 

# to apply, pipe "render"ed output through kubectl    
kubetpl render template.yml -i staging.env -s IMAGE=nginx | 
  kubectl apply -f -
  
# you can also apply remote template(s) 
kubetpl render https://rawgit.com/shyiko/kubetpl/master/example/nginx.sh.yml \
  -s NAME=kubetpl-example-nginx -s MESSAGE="hello $(whoami)" | 
  kubectl apply -f -

(for more examples see Template flavors)

Tab completion

# bash
source <(kubetpl completion bash)

# zsh
source <(kubetpl completion zsh)

ConfigMap/Secret freezing

When kubetpl render --freeze ... is used, kubetpl rewrites ConfigMap/Secret's name to include hash of the content and then updates all the references (in Pods / DaemonSets / Deployments / Jobs / ReplicaSets / ReplicationControllers / StatefulSets / CronJobs) with a new value.

For example, executing kubetpl render --freeze example/nginx-with-data-from-file.yml -s NAME=app -s MESSAGE=msg should produce example/nginx-with-data-from-file.rendered+frozen.yml.

NOTE: this feature can be used regardless of the Template flavor choice (or lack thereof (i.e. on its own)).

ConfigMap/Secret "data-from-file" injection

[email protected]+ also supports kubetpl/data-from-env-file.

Optionally, ConfigMap/Secret|s can be extended with kubetpl/data-from-file to load "data" from a list of files (relative to a template unless a different -c/--chroot is specified), e.g.

kind: ConfigMap
kubetpl/data-from-file: 
  - file 
  - path/to/another-file
  - custom-key=yet-another-file
data:
  key: value
...

Upon kubetpl render the content of file, another-file and yet-another-file (using custom-key as a key) will be added to the object's "data" (kubetpl/data-from-file is automatically striped away).

For example, executing kubetpl render --allow-fs-access example/nginx-with-data-from-file.yml -s NAME=app should produce example/nginx-with-data-from-file.rendered.yml.

NOTE #1: for security reasons, kubetpl/data-form-file is not allowed to read files unless --allow-fs-access or -c/--chroot=<root dir> is specified (see kubetpl render --help for more).

NOTE #2: this feature can be used regardless of the Template flavor choice (or lack thereof (i.e. on its own)).

Template flavors

Template syntax is determined by first checking template for # kubetpl:syntax:<$|go-template|template-kind> comment and then, if not found, --syntax=<$|go-template|template-kind> command line option. In the absence of both, kubetpl assumes that template is a regular resource definition file.

$ (shell)

A type of template where all instances of $VAR / ${VAR} are replaced with corresponding values. If, for some variable, no value is given - an error will be raised.

Use $$ when you need a literal dollar sign ($$v is interpreted as $v string and not '$' + <value_of_v>).

Example

Let's say we have the following (click to expand):

<project_dir>/k8s/staging.env
NAME=sample-app
REPLICAS=1
<project_dir>/k8s/template.yml
# kubetpl:syntax:$

apiVersion: v1
kind: Service
metadata:
  name: $NAME-service
spec:
  selector:
    app: $NAME
  ports:
  - protocol: TCP
    port: 80
---
apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: $NAME-deployment
spec:
  replicas: $REPLICAS
  template: 
    metadata:
      labels:
        app: $NAME
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80

kubetpl render k8s/template.yml -i k8s/staging.env -s REPLICAS=3 should then yield

(click to expand)
apiVersion: v1
kind: Service
metadata:
  name: sample-app-service
spec:
  selector:
    app: sample-app
  ports:
  - protocol: TCP
    port: 80
---
apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: sample-app-deployment
spec:
  replicas: 3
  template: 
    metadata:
      labels:
        app: sample-app
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80

[email protected]+ default values can be specified via # kubetpl:set:KEY=VALUE directive(s), e.g.

# kubetpl:syntax:$
# kubetpl:set:NAME=nginx
# kubetpl:set:REPLICAS=1

apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: $NAME
  annotations:
    version: $VERSION
spec:
  replicas: $REPLICAS
...  

go-template

All functions provided by sprig are available
(with the exception of env and expandenv).

A good overview of go-template|s can be found here. You might also want to check official documentation.

Some of the most commonly used expressions:

  • {{ .VAR }} - get the value of VAR;
  • {{ if isset "VAR" }} ... {{ end }} - render content between }} and {{ only if .VAR is set;
  • {{ get "VAR" "default" }} - get the value of VAR, return "default" if not set (e.g. {{ get "REPLICAS" 1 }});
  • {{ .VAR | quote }} - quote the value of VAR;
  • {{ .VAR | indent 4 }} - indent value of VAR with 4 spaces;
  • {{ .VAR | b64enc }} - base64-encode value of VAR.
Example

Let's say we have the following (click to expand):

<project_dir>/k8s/staging.env
NAME=sample-app
REPLICAS=1
<project_dir>/k8s/template.yml
# kubetpl:syntax:go-template

apiVersion: v1
kind: Service
metadata:
  name: {{ .NAME }}-service
spec:
  selector:
    app: {{ .NAME }}
  ports:
  - protocol: TCP
    port: 80
---
apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: {{ .NAME }}-deployment
spec:
  replicas: {{ .REPLICAS }}
  template: 
    metadata:
      labels:
        app: {{ .NAME }}
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80

kubetpl render k8s/template.yml -i k8s/staging.env -s REPLICAS=3 should then yield

(click to expand)
apiVersion: v1
kind: Service
metadata:
  name: sample-app-service
spec:
  selector:
    app: sample-app
  ports:
  - protocol: TCP
    port: 80
---
apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: sample-app-deployment
spec:
  replicas: 3
  template: 
    metadata:
      labels:
        app: sample-app
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80

template-kind

aka kind: Template.

As described in Templates + Parameterization proposal.

Example

Let's say we have the following (click to expand):

<project_dir>/k8s/staging.env
NAME=sample-app
<project_dir>/k8s/template.yml
# kubetpl:syntax:template-kind

kind: Template
apiVersion: v1
metadata:
  name: nginx-template
  annotations:
    description: nginx template
objects:
- apiVersion: v1
  kind: Service
  metadata:
    name: $(NAME)-service
  spec:
    selector:
      app: $(NAME)
    ports:
    - protocol: TCP
      port: 80
- apiVersion: apps/v1beta1
  kind: Deployment
  metadata:
    name: $(NAME)-deployment
  spec:
    replicas: $((REPLICAS))
    template: 
      metadata:
        labels:
          app: $(NAME)
      spec:
        containers:
        - name: nginx
          image: nginx:1.7.9
          ports:
          - containerPort: 80
parameters:
- name: NAME
  description: Application name
  required: true
  parameterType: string
- name: REPLICAS
  description: Number of replicas
  value: 1
  required: true
  parameterType: int

kubetpl render k8s/template.yml -i k8s/staging.env -s REPLICAS=3 should then yield

(click to expand)
apiVersion: v1
kind: Service
metadata:
  name: sample-app-service
spec:
  selector:
    app: sample-app
  ports:
  - protocol: TCP
    port: 80
---
apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: sample-app-deployment
spec:
  replicas: 3
  template: 
    metadata:
      labels:
        app: sample-app
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80

Development

PREREQUISITE: go1.9+.

git clone https://github.com/shyiko/kubetpl $GOPATH/src/github.com/shyiko/kubetpl 
cd $GOPATH/src/github.com/shyiko/kubetpl
make fetch

go run kubetpl.go

Legal

All code, unless specified otherwise, is licensed under the MIT license.
Copyright (c) 2018 Stanley Shyiko.

kubetpl's People

Contributors

67421 avatar conradirwin avatar shyiko avatar shyykoserhiy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

kubetpl's Issues

Yaml element ordering

kubetpl appears to reorder the yaml elements alphabetically.
Is this deliberate and is there a way to keep original order?
Cheers

gpg: can't open signed data `/usr/local/bin/kubetpl'

While running the verified installation, verification fails.

Error I am getting

gpg: can't open signed data `/usr/local/bin/kubetpl'
gpg: can't hash datafile: file open error

Previous steps are successful.

24:22: "REGISTRY" isn't set

Hello,
i am keep getting error

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  namespace: default
  name: $NAME
spec:
  replicas: $REPLICAS

  template:
    metadata:
      labels:
        app: $NAME-srv
    spec:
      containers:
        - name: $NAME
          command: [
            "/$NAME-srv",
            "--server_address=0.0.0.0:8080",
            "--broker_address=0.0.0.0:10001"
          ]
          image: microhq/$NAME-srv:kubernetes
          env:
            - name: MICRO_REGISTRY
              value: $REGISTRY
            - name: MICRO_TRANSPORT
              value: $TRANSPORT
            - name: MICRO_SELECTOR
              value: $SELECTOR
            - name: MICRO_REDIS_ADDRESS
              value: $REDIS_ADDRESS
            - name: MICRO_REDIS_PASSWORD
              value: $REDIS_PASSWORD
            - name: MICRO_REDIS_DATABASE
              value: $REDIS_DATABASE
          imagePullPolicy: Always
          ports:
          - containerPort: 8080
            name: $NAME-port
        - name: health
          command: [
            "/health",
            "--health_address=0.0.0.0:8081",
            "--server_name=$NAME",
            "--server_address=0.0.0.0:8080"
          ]
          image: microhq/health:kubernetes
          livenessProbe:
            httpGet:
              path: /health
              port: 8081
            initialDelaySeconds: 3
            periodSeconds: 3

env:

NAME=account
EXECUTABLE=account-srv
REPLICAS=1
BROKER=nats
REGISTRY=kubernetes
TRANSPORT=nats
SELECTOR=static
REDIS_ADDRESS=my-release-redis-master:6379
REDIS_PASSWORD=""
REDIS_DATABASE=0

kubetpl render deployment.tpl -i production.env --syntax=$

Add support for environment variables

kubetpl should be able to interpolate environment variables that appear in the source template, similarly to what envsubst does, possibly with an option like --with-env.

My use case is that I'm collecting secrets from AWS SecretsManager and storing them in environment variables in a Makefile. I would like to be able to write something like this:

fetch_secret = $(shell aws secretsmanager get-secret-value --secret-id '$(1)' --output text --query SecretString)

my_file_1.yaml: export SECRET1 = $(call fetch_secret, this_secret)
my_file_2.yaml: export SECRET2 = $(call fetch_secret, that_secret)

%.yaml: %.tpl
	kubetpl render $< -c . -i $(VALUES_FILE) --with-env -o $@

Values obtained this way would probably have the lowest priority, after -s and -i values.

using defaults for variables

Hi, in the README it's mentioned:

"Fail-fast defaults (all variables must be given a value (unless explicitly marked optional))."

How do I mark a variable optional? Can't find it in the docs.

messed up rendering

kubectl logs calc-fnc-5b7d48c9bb-dlwd9
Error from server (BadRequest): a container name must be specified for pod calc-fnc-5b7d48c9bb-dlwd9, choose one of: [calc-fnc health]

# kubetpl:syntax:$

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  namespace: default
  name: $NAME
spec:
  replicas: $REPLICAS

  template:
    metadata:
      labels:
        app: $EXECUTABLE
    spec:
      serviceAccountName: micro-services
      containers:
        - name: $NAME
          command: [
            "/$EXECUTABLE",
            "--server_address=0.0.0.0:8080",
            "--broker_address=0.0.0.0:10001"
          ]
          image: $IMAGE
          env:
            - name: MICRO_REGISTRY
              value: $REGISTRY
            - name: MICRO_TRANSPORT
              value: $TRANSPORT
            - name: MICRO_SELECTOR
              value: $SELECTOR
          imagePullPolicy: Always
          ports:
          - containerPort: 8080
            name: $NAME-port
        - name: health
          command: [
            "/health",
            "--health_address=0.0.0.0:8081",
            "--server_name=$NAME",
            "--server_address=0.0.0.0:8080"
          ]
          image: microhq/health:kubernetes
          livenessProbe:
            httpGet:
              path: /health
              port: 8081
            initialDelaySeconds: 3
            periodSeconds: 3
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: calc-fnc
  namespace: default
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: calculation-srv
    spec:
      containers:
      - command:
        - /calculation-srv
        - --server_address=0.0.0.0:8080
        - --broker_address=0.0.0.0:10001
        env:
        - name: MICRO_REGISTRY
          value: kubernetes
        - name: MICRO_TRANSPORT
          value: nats
        - name: MICRO_SELECTOR
          value: static
        image: cryptovalue/calculation-fnc:221f746
        imagePullPolicy: Always
        name: calc-fnc
        ports:
        - containerPort: 8080
          name: calc-fnc-port
      - command:
        - /health
        - --health_address=0.0.0.0:8081
        - --server_name=calc-fnc
        - --server_address=0.0.0.0:8080
        image: microhq/health:kubernetes
        livenessProbe:
          httpGet:
            path: /health
            port: 8081
          initialDelaySeconds: 3
          periodSeconds: 3
        name: health
      serviceAccountName: micro-services

Render multiple configs to single template

Maybe i've missed something but I'm looking for a way to do a rendering for multiple input files.

Example:
My template is deployment.yml. I have multiple config files in one directory config1.yml and config2.yml.

deployment.yml contains:

# kubetpl:syntax:go-template

apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ .NAME }}

config1.yml contains:

NAME: a

config2.yml contains:

NAME: b

What I expect to happen:

$ kubetpl r templates/deployment.yml -i configs/*.yml

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: a
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: b

what actually happens:

$ kubetpl r templates/deployment.yml -i configs/*.yml

Resource "kind" is missing 

Is there any way to accomplish this scenario?

BUG: --freeze says 'Malformed object (missing/invalid kind)' with valid yaml and kubernetes resource

--freeze can't handle yaml files that start with yaml's ---, the c-document-start boundary marker. Without --freeze render handles the yaml with or without the boundary marker.

❯ cat configmap.template
# kubetpl:syntax:go-template
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .APP }}-config
  namespace: {{ .NAMESPACE }}
data:
  my-key: my-value

❯ ./kubetpl-0.9.0-linux-amd64 render configmap.template --freeze --set APP=my-app --set NAMESPACE=default
---
apiVersion: v1
data:
  my-key: my-value
kind: ConfigMap
metadata:
  name: my-app-config-3b45d2a
  namespace: default

❯ vi configmap.template #Add --- to the top of the yaml block

❯ cat configmap.template
# kubetpl:syntax:go-template
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .APP }}-config
  namespace: {{ .NAMESPACE }}
data:
  my-key: my-value

❯ ./kubetpl-0.9.0-linux-amd64 render configmap.template --freeze --set APP=my-app --set NAMESPACE=default
Malformed object (missing/invalid kind)

Support for interface in go template

Hi,

I want to do like Helm for complex properties

Example :

NODE_SELECTOR:
  agentpool: api
  {{- if .NODE_SELECTOR }}
{{ include "toYaml" .NODE_SELECTOR | indent 2 }}
  {{- end }}

Today it's not possible, can you integrate this feature ?

Thk you

go get github.com/shyiko/kubetpl fails in module mode

This module depends on github.com/Sirupsen/logrus, which has been renamed to github.com/sirupsen/logrus.

This causes installation to fail in go module mode with:

go: github.com/Sirupsen/[email protected]: parsing go.mod:
	module declares its path as: github.com/sirupsen/logrus
	        but was required as: github.com/Sirupsen/logrus

We can work around this by setting:

replace github.com/Sirupsen/logrus v1.6.0 => github.com/sirupsen/logrus v1.6.0

in our go.mod, but it would be better to update this library to reference the new name directly.

Ignore: "map has no entry for key"

Hi there,

There is a way to ignore helm templating ? like "{{ .Release.Name }}"

I use env.json to fill my values.

if i use # kubetpl:syntax:go-template, the --ignore-unset is not working.

If i use # kubetpl:syntax:template-kind, i have an error for my yaml map key => yaml: invalid map key: map[interface {}]interface {}{".components.batch.version":interface {}(nil)}

Thanks :)

Avoid `- null` values on templating.

I am not sure if the issue I will point is a minor bug or a feature request. Anyway I am using your Kind: Template way of templating, and in cases that I have non-required ENVs kubetpl adds - null value for the non-declared ENVs. This output cannot passed directly to kubectl as this output is not a valid input.
My simple workaround for this case was to add a sed pipe (sed '/- null/d') in the middle that deletes all lines that have - null value and this way I produce a valid input which can be passed to kubectl create -f -
Example to reproduce:

# kubetpl:syntax:template-kind

kind: Template
apiVersion: v1
metadata:
  name: dummy-yiic-template
  annotations:
    description: dummyyiic one off template
objects:
- apiVersion: batch/v1
  kind: Job
  metadata:
    name: dummyoneoff-$(COMMAND)
  spec:
   backoffLimit: 5
   activeDeadlineSeconds: 600
   template:
     metadata:
       name: dummyoneoff-$(COMMAND)
       # These are the labels that pods will be given when created via this Job
       labels:
        app: dummy
        tier: cli
        framework: yii
        version: $(BRANCH_AND_VERSION)
     spec:

       containers:
       - name: yiic
         image: dummy/dummy_fpm
         imagePullPolicy: IfNotPresent
         volumeMounts:
         - name: app-volume
           mountPath: /var/www/dummy
         resources:
           requests:
             cpu: $(CPU_REQUEST)
             memory: $(MEM_REQUEST)
           limits:
             cpu: $(CPU_LIMIT)
             memory: $(MEM_LIMIT)
         envFrom:
         - configMapRef:
             name: dummy
         - secretRef:
             name: dummy
         command: ["./yiic", $(COMMAND), $(ACTION), $(ARGS)]
       restartPolicy: Never
       volumes:
       - name: app-volume
         emptyDir: {}
parameters:
- name: BRANCH_AND_VERSION
  description: Branch and Version
  required: true
  parameterType: string
- name: REPLICAS
  description: Number of replicas
  value: 1
  required: true
  parameterType: int
- name: CPU_REQUEST
  description: CPU Request
  required: true
  value: "200m"
  parameterType: string
- name: CPU_LIMIT
  description: CPU Limit
  required: true
  value: 1
  parameterType: string
- name: MEM_REQUEST
  description: Memory Request
  required: true
  value: "256Mi"
  parameterType: string
- name: MEM_LIMIT
  description: Memory Limit
  required: true
  value: "1Gi"
  parameterType: string
- name: COMMAND
  description: Command
  parameterType: string
- name: ACTION
  description: Action
  parameterType: string
- name: ARGS
  description: Arguments
  parameterType: string

Fails:

kubetpl render dummy-oneoff-yiic-template.yml -s BRANCH_AND_VERSION=test.yolo -s COMMAND=devops -s ACTION=demo | kubectl create -f -
error: error validating "STDIN": error validating data: ValidationError(Job.spec.template.spec.containers[0].command): unknown object type "nil" in Job.spec.template.spec.containers[0].command[3]; if you choose to ignore these errors, turn validation off with --validate=false

Succeed:

kubetpl render dummy-oneoff-yiic-template.yml -s BRANCH_AND_VERSION=test.yolo -s COMMAND=devops -s ACTION=demo | sed '/- null/d' | kubectl create -f -
job.batch "dummyoneoff-devops" created

Use multiple input ("-i") files

Is it possible to use the --input flag multiple times? I've tried and none of the options I thought of worked fine.

kubetpl --debug r template.yaml --input i2.yaml i1.yaml
kubetpl --debug r template.yaml --input i2.yaml,i1.yaml
kubetpl --debug r template.yaml --input "i2.yaml i1.yaml"
kubetpl --debug r template.yaml --input i2.yaml --input i1.yaml

Any help will be highly appreciated! Thanks for the nice piece of software you're creating 👍

A more complex type of substitution.

Say I have the following env vars.

export APP_ENV='development'
export development_DB="dev.db.com"
export production_DB=prod.db.com

I want to render the following in my yaml file.

    env:
          - name: DB
             value: ${${APP_ENV}_DB}

I know the syntax is not valid bash but I hope you know what I mean.

Thanks.

Render error env on yaml

Hello,
Sorry for my English, I speak Spanish.
I get the following error. env depends on containers. But it should depend on image.

Result:

---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: java-app
  namespace: java-app
spec:
  replicas: 2
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      labels:
        app: java
        tipo: api-rest
    spec:
      containers:
      - env:
        - name: JAVA_OPTS
          value: -Dspring.profiles.active=staging
        - name: DB_USER
          valueFrom:
            secretKeyRef:
              key: spring.datasource.username
              name: java-app-secret
        - name: DB_PASSWORD
          valueFrom:
            secretKeyRef:
              key: spring.datasource.password
              name: java-app-secret
        image: docker.hub/java-app:1.0
        imagePullPolicy: IfNotPresent
        imagePullSecrets:
        - name: java-app-reg
        livenessProbe:
          failureThreshold: 12
          httpGet:
            path: /actuator/health
            port: 8080
          initialDelaySeconds: 60
          periodSeconds: 60
          successThreshold: 1
          timeoutSeconds: 5
        name: java-app
        ports:
        - containerPort: 8080
          name: http
        readinessProbe:
          failureThreshold: 5
          httpGet:
            path: /actuator/health
            port: 8080
          initialDelaySeconds: 120
          periodSeconds: 5
          successThreshold: 1
          timeoutSeconds: 5
        resources:
          limits:
            cpu: 250m
            memory: 1024Mi
          requests:
            cpu: 100m
            memory: 512Mi
        volumeMounts:
        - mountPath: /var/logs/
          name: logs-volume
      volumes:
      - emptyDir: {}
        name: logs-volume

template:

# kubetpl:syntax:go-template
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: {{ .APP_NAME }}
  namespace: {{ .NAMESPACE_NAME }}
spec:
  replicas: {{ get "REPLICAS" 1 }}
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      labels:
      {{ range $index, $value := .LABELS }}
        {{ $index | indent 8 }}: {{ $value }}
      {{ end }}
    spec:
      containers:
        - image: {{ .REGISTRY_IMAGE }}:{{ .IMAGE_VERSION }}
          name: {{ .APP_NAME }}
          imagePullPolicy: IfNotPresent
          volumeMounts:
            - mountPath: /var/logs/
              name: logs-volume
          env:
            - name: JAVA_OPTS
              value: -Dspring.profiles.active=staging
            - name: DB_USER
              valueFrom:
                secretKeyRef:
                  name: {{ .APP_NAME }}-secret
                  key: spring.datasource.username
            - name: DB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ .APP_NAME }}-secret
                  key: spring.datasource.password
          ports:
            - containerPort: 8080
              name: http
          livenessProbe:
            failureThreshold: 12
            httpGet:
              path: /actuator/health
              port: 8080
            initialDelaySeconds: 60
            periodSeconds: 60
            successThreshold: 1
            timeoutSeconds: 5
          readinessProbe:
            failureThreshold: 5
            httpGet:
              path: /actuator/health
              port: 8080
            initialDelaySeconds: 120
            periodSeconds: 5
            successThreshold: 1
            timeoutSeconds: 5
          resources:
            requests:
              cpu: 100m
              memory: 512Mi
            limits:
              cpu: 250m
              memory: "1024Mi"
          imagePullSecrets:
            - name: {{ .APP_NAME }}-reg
      volumes:
        - emptyDir: {}
          name: logs-volume

env.json:

{
  "APP_NAME": "java-app",
  "NAMESPACE_NAME": "java-app",
  "REPLICAS": "2",
  "REGISTRY_IMAGE": "docker.hub/java-app",
  "IMAGE_VERSION": "1.0",
  "REGISTRY_SECRET": "eyJhdXRocyI6eyJyZWdpcaljfsdmsdA3FdW3ecEFWdedwwedEFSFQwqdkewDEdWEDewDwed3RyeS5uZy5ibHVlbWl4Lm5ldCI6eyJ1c2VybmFtZSI6InRva2VuIiwicGFzc3dvcmQiOiJleUpoYkdjaU9pSklVekkxTmlJc0luUjVjQ0k2SWtwWFZDSjkuZXlKcWRHa2lPaUkwTldWaU5URm1aUzA0TVdReExUVXhPRE10T1RCa1ppMWlNakZsWWpOa01EZGhaRFVpTENKcGMzTWlPaUp5WldkcGMzUnllUzV1Wnk1aWJIVmxiV2w0TG01bGRDSjkudDJoNXI4SXJaZ3d0STFSYlVrQVJIWXdQemViSXZ2amVnZ1g0Sl8wakVZMCIsImVtYWlsIjoiZ2FicmllbC5tZWxpYW5Ac3VwZXJ2aWVsbGUuY29tLmFyIiwiYXV0aCI6ImRHOXJaVzQ2WlhsS2FHSkhZMmxQYVVwSlZYcEpNVTVwU1hOSmJsSTFZME5KTmtscmNGaFdRMG81TG1WNVNuRmtSMnRwVDJsSk1FNVhWbWxPVkVadFdsTXdORTFYVVhoTVZGVjRUMFJOZEU5VVFtdGFhVEZwVFdwR2JGbHFUbXROUkdSb1drUlZhVXhEU25Cak0wMXBUMmxLZVZwWFpIQmpNMUo1WlZNMWRWcDVOV2xpU0Zac1lsZHNORXh0Tld4a1EwbzVMblF5YURWeU9FbHlXbWQzZEVreFVtSlZhMEZTU0ZsM1VIcGxZa2wyZG1wbFoyZFlORXBmTUdwRldUQT0ifX19",
  "LABELS": {
    "app":"java",
    "tipo":"api-rest"
    }
  }

I do not detect anything erroneous in the config.
Best regards.

Kupetpl vs helm template command

I have recently discovered helm template command that renders the helm chart without need for tiller.

What are the reasons to stick with kubetpl vs helm template?

I'm happy with kubetpl, but wondering if consolidating down to one template tool makes sense in the long run.

Support for `data-from-env-file`

similar to the kubectl create configmap ... --from-file=... --from-file=... --from-file use case being replaced by kubetpl/data-from-file, I feel like there should be kubetpl/data-from-env-file for the equivalent kubectl create configmap ... --from-env-file=... --from-env-file=... --from-env-file use case

"isset" does not work inside ranges

The following template iterates over a range "entries" and inside each iteration checks if a value is set in the current iteration value:

# kubetpl:syntax:go-template

a-start: Here the YAML starts
{{- if isset "key" }}
msg: "Found value for key: {{ .key }}"
{{- else }}
error: "Key value is missing"
{{- end}}

an-output-entry:
{{ range $ig := .entries }}
  - the-name: {{ .name }}
    output: {{ .value }}
    {{- if isset "print" }}
    the-value-to-print: {{ .print }}
    {{- end }}
{{ end }}
z-end: The last entry

Sample values:

key: some value

entries:
  - name: one
    value: first value
    print: value to print
  - name: two
    value: the second
    print: another value
  - name: three
    value: the third

The actual result:

---
a-start: Here the YAML starts
an-output-entry:
- output: first value
  the-name: one
- output: the second
  the-name: two
- output: the third
  the-name: three
msg: 'Found value for key: some value'

The expected result:

---
a-start: Here the YAML starts
an-output-entry:
- output: first value
  the-name: one
  the-value-to-print: value to print
- output: the second
  the-name: two
  the-value-to-print: another value
- output: the third
  the-name: three
msg: 'Found value for key: some value'

The check {{- if isset "print" }} fails always inside the retries range.

How can I use hugo Scratch

My template like
{{ .Scratch.Set "greeting" "Hello" }}

when i render it, always got a error
at <.Scratch.Set>: map has no entry for key "Scratch"

Does kubetpl not suport hugo Scratch?

[Enhancement] include Ambassador Host tlsSecret in Secret freezing

We use Ambassador as our ingress controller and an automated CI deployment system for managing/pushing updates to the Kubernetes cluster. After a recent update to the TLS certs for Ambassador we found that it didn't pick up the new secret. It looks like this piece of config doesn't get picked up by kubetpl render as it uses a tlsSecret key to reference the secret rather than the normal secretName.

See https://www.getambassador.io/docs/edge-stack/latest/topics/running/host-crd/#tlssecret-enables-tls-termination

If this functionality could be added it would be great.

This key is not certified with a trusted signature

Probably not a big deal and maybe I did something wrong, but if I run the recommended PGP signature verification

curl -sSL https://github.com/shyiko/kubetpl/releases/download/0.9.0/kubetpl-0.9.0-$(
    bash -c '[[ $OSTYPE == darwin* ]] && echo darwin || echo linux'
  )-amd64.asc -o kubetpl.asc
curl -sS https://keybase.io/shyiko/pgp_keys.asc | gpg --import
gpg --verify kubetpl.asc /usr/local/bin/kubetpl

I get the following output

gpg: Signature made Thu Jan 17 07:42:35 2019 STD
gpg:                using RSA key 160A7A9CF46221A56B06AD64461A804F2609FD89
gpg: Good signature from "Stanley Shyiko <[email protected]>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg:          There is no indication that the signature belongs to the owner.
Primary key fingerprint: 160A 7A9C F462 21A5 6B06  AD64 461A 804F 2609 FD89

So the key doesn't seem to be certified with a trusted signature.

Resource with 'parameters' key and no syntax "cannot unmarshal !!map into []engine.TemplateKindTemplateParameter"

Issue type: Bug

Given a kubernetes resource file that has a top-level key parameters and no syntax definition as a comment nor command-line argument a fatal unmarshal error occurs.

Example resource.yml:

---
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
   name: rook-ceph-delete-bucket
provisioner: ceph.rook.io/bucket
reclaimPolicy: Delete
parameters:
  objectStoreName: ceph-object-store
  objectStoreNamespace: rook-ceph
$ kubetpl render resource.yml
yaml: unmarshal errors:
  line 8: cannot unmarshal !!map into []engine.TemplateKindTemplateParameter

According to the documentation, in the absence of a syntax declaration:

kubetpl assumes that template is a regular resource definition file

But it seems that it's maybe actually trying to render it as template-kind?

A workaround is to add # kubetpl:syntax:$ and, in this case, it renders as expected.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.