Error converting yaml to json yaml did not find expected key

I just created a new Helm chart but when I run helm install --dry-run --debug I get: Error: YAML parse error on multi-camera-tracking/templates/multi-camera-tracking.yaml: error converting YAML to ...

I just created a new Helm chart but when I run helm install --dry-run --debug I get:

Error: YAML parse error on multi-camera-tracking/templates/multi-camera-tracking.yaml: error converting YAML to JSON: yaml: line 30: did not find expected key

And this is my Yaml file:

---
# apiVersion: apps/v1beta1
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: multi-camera-tracking
  annotations:
    Process: multi-camera-tracking
  labels:
    io.kompose.service: multi-camera-tracking
spec:
  serviceName: multi-camera-tracking
  replicas: 1
  selector:
    matchLabels:
      io.kompose.service: multi-camera-tracking
  podManagementPolicy: "Parallel"
  template:
    metadata:
      labels:
        io.kompose.service: multi-camera-tracking
    spec:
      containers:
      - name: multi-camera-tracking
        env:
        - name: MCT_PUB_PORT
          value: {{ .Values.MCT_PUB_PORT | quote }}
        - name: SCT_IP_ADDR_CSV
          value: {{ .Values.SCT_IP_ADDR_CSV | quote }}
        - name: SCT_PUB_PORT_CSV
          value: {{ .Values.SCT_PUB_PORT1 | quote }}, {{ .Values.SCT_PUB_PORT2 | quote }}
        image: {{ .Values.image_multi_camera_tracking }}
        ports:
        - containerPort: {{ .Values.MCT_PUB_PORT }}
        resources:
          requests:
            cpu: 0.1
            memory: 250Mi
          limits:
            cpu: 4
            memory: 10Gi
        readinessProbe:
          exec:
            command:
            - ls
            - /tmp
          initialDelaySeconds: 5
          periodSeconds: 60
      restartPolicy: Always
---
apiVersion: v1
kind: Service
metadata:
  annotations:
    Process: multi-camera-tracking
  creationTimestamp: null
  labels:
    io.kompose.service: multi-camera-tracking
  name: multi-camera-tracking
spec:
  ports:
  - name: "MCT_PUB_PORT"
    port: {{ .Values.MCT_PUB_PORT }}
    targetPort: {{ .Values.MCT_PUB_PORT }}
  selector:
    io.kompose.service: multi-camera-tracking
status:
  loadBalancer: {}

The strange thing is I have created multiple other helm charted and they all are very similar to this but this one doesn’t work and produces error.

Matt Seymour's user avatar

Matt Seymour

8,6827 gold badges60 silver badges101 bronze badges

asked Nov 14, 2019 at 16:53

AVarf's user avatar

I found the reason why it is not working. First of all, it is allowed to have comma-separated values but the problematic part was the quotations.

This is the wrong syntax:

value: {{ .Values.SCT_PUB_PORT1 | quote }}, {{ .Values.SCT_PUB_PORT2 | quote }}

And this is the correct one:

value: {{ .Values.SCT_PUB_PORT1 }}, {{ .Values.SCT_PUB_PORT2 }}

answered Nov 15, 2019 at 9:46

AVarf's user avatar

AVarfAVarf

4,1747 gold badges44 silver badges71 bronze badges

In my case, I had written

name: { { template "cp-kafka.fullname" . } }-jaas-configmap

due to that giving error.

Right would be

name: {{ template "cp-kafka.fullname" . }}-jaas-configmap

The difference is space between curly brackets.

answered Mar 24, 2021 at 11:58

NIrav Modi's user avatar

NIrav ModiNIrav Modi

5,4447 gold badges30 silver badges45 bronze badges

0

I think the template command with --debug is the expected debug route for this kind of issue, e.g:

helm template  ./yourchart/ -f your-overrides.yaml -n your-ns --debug

Here helm will do its best to try and produce the YAML, and allow you to inspect and see whether you can see errors more clearly.

answered Feb 24, 2022 at 9:19

AntonOfTheWoods's user avatar

1

I suspect it’s the value following the key in line 30 that’s the issue; it contains a , and this makes it an invalid value.

{{ .Values.SCT_PUB_PORT1 | quote }}, {{ .Values.SCT_PUB_PORT2 | quote }}

answered Nov 14, 2019 at 17:02

DazWilkin's user avatar

DazWilkinDazWilkin

30.5k5 gold badges42 silver badges82 bronze badges

1

i had the similar issue, after all the debugging i found out that the issue was with the identation of one of the file, i was referring to in the configmap.yaml

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-conf
  labels:
    {{- include "mytemp.labels" . | nindent 4 }}
data:
{{ (tpl (.Files.Glob "configs/MyJobConf.conf").AsConfig . ) | nindent 4 }}

Identation issue was not in the configmap.yaml but MyJobConf.conf (helm is parsing it as yaml)

After correcting it, it solved my issue

maow's user avatar

maow

2,5771 gold badge10 silver badges24 bronze badges

answered Jun 20, 2022 at 9:01

Abhishek Paweria's user avatar

One way to debug this problem is to do a dry-run and render the template to see what is causing the issue on the offending line.

helm install [Chart] [flags] --dry-run --debug

This would allow you to see which keys are not indented well as this issue is sometimes caused by the wrong indentation.

answered Mar 26, 2020 at 8:54

Margach Chris's user avatar

5

Had a similar error with rendering an xml.
in values.yaml I had:

xml: >
  <md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" entityID="http://www.sso.com/diohadohad">
  <md:IDPSSODescriptor WantAuthnRequestsSigned="false" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
  <md:KeyDescriptor use="signing">
  <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
  <ds:X509Data>
  <ds:X509Certificate>JJDHDHASDAIDSFHDSGERGSERGISJDFGSERIGSERGRSG TEImxWRRX87Xj1MZyxjiBQ+ilySMD9OsskTSwVysTwWK+eFM40gVXFWBeAuoQvkb2rvZ2+8rJySQ rYC+dMIfKE6EEwnD6+XzwcKpTjs7TChviMZ6LxNbMJO6ybJPxoJt0zV0Aago9UEAF2U3NVuRTmsE TUOk9mbI14ULcZM03ltjSZqi</ds:X509Certificate>
  </ds:X509Data>
  </ds:KeyInfo>
  </md:KeyDescriptor>
  <md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified</md:NameIDFormat>
  <md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</md:NameIDFormat>
  <md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://mycompany.sso.com/app/asdfasdf/sso/saml"/>
  <md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://mycompany.sso.com/app/asdfasdfsdf/sso/saml"/>
  </md:IDPSSODescriptor>
  </md:EntityDescriptor>

And for some reason I couldn’t render this value. I was looking for character that was causing me trouble, and found out it was the double-quote " char.
Since it’s an xml, the quick fix for me was to change this character to a single-quote ' instead:

xml: >
  <md:EntityDescriptor xmlns:md='urn:oasis:names:tc:SAML:2.0:metadata' entityID='http://www.sso.com/diohadohad'>
  <md:IDPSSODescriptor WantAuthnRequestsSigned='false' protocolSupportEnumeration='urn:oasis:names:tc:SAML:2.0:protocol'>
  <md:KeyDescriptor use='signing'>
  <ds:KeyInfo xmlns:ds='http://www.w3.org/2000/09/xmldsig#'>
  <ds:X509Data>
  <ds:X509Certificate>JJDHDHASDAIDSFHDSGERGSERGISJDFGSERIGSERGRSG TEImxWRRX87Xj1MZyxjiBQ+ilySMD9OsskTSwVysTwWK+eFM40gVXFWBeAuoQvkb2rvZ2+8rJySQ rYC+dMIfKE6EEwnD6+XzwcKpTjs7TChviMZ6LxNbMJO6ybJPxoJt0zV0Aago9UEAF2U3NVuRTmsE TUOk9mbI14ULcZM03ltjSZqi</ds:X509Certificate>
  </ds:X509Data>
  </ds:KeyInfo>
  </md:KeyDescriptor>
  <md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified</md:NameIDFormat>
  <md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</md:NameIDFormat>
  <md:SingleSignOnService Binding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST' Location='https://mycompany.sso.com/app/asdfasdf/sso/saml'/>
  <md:SingleSignOnService Binding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect' Location='https://mycompany.sso.com/app/asdfasdfsdf/sso/saml'/>
  </md:IDPSSODescriptor>
  </md:EntityDescriptor>

answered Sep 15, 2022 at 7:55

Alex Weitz's user avatar

Alex WeitzAlex Weitz

3,1074 gold badges33 silver badges53 bronze badges

$ cat templates/config-map.yaml


apiVersion: v1
kind: ConfigMap
metadata:
  name: my-schooltest-app
data:
  config_dev.json: |-
{{ .Files.Get "conf/config_dev.json" | indent 4}}
  config_qa.json: |-
{{ .Files.Get "conf/config_qa.json" | indent 4}}    

config_dev.json (same as config_qa.json)

{
  "students": [
    {
      "name": "test1",
      "proffesion": "Engineer",
      "subjectCodes": [
        "SOCIAL",
        "SCIENCE",
        "MATHS"
      ]
    },
    {
      "name": "test2",
      "proffesion": "Engineer",
      "subjectCodes": [
        "ENGLISH",
        "TAMIL"
      ]
    }
  ],
  "allowedSubjects": [
    "SOCIAL",
    "SCIENCE",
    "MATHS",
    "ENGLISH",
	"TAMIL"
  ],
  "school": "trm",
  "headmaster": [
    "Test5"
  ]
}

I am having an issue in update the config file using the below command

kubectl apply -f helm/templates/config-map.yaml -n $NAMESPACE

**

error: error parsing helm/templates/config-map.yaml: error converting YAML to JSON: yaml: line 8: could not find expected ‘:’

**

Note: When I do the helm install deployment, it works fine. But my requirement is update the configmap without restarting the pod
Tried : is outdented to the same level as the data key as well

The simple pod example YAML for Kubernetes shows that the ‘metadata’ and ‘spec’ elements required are at the top level of the definition. The kubectl command is most likely failing because it cannot find the ‘spec’ element, which defines the specification of the pod.

You seem to be testing the image pull configuration, and you have specified that you simply want to run echo SUCCESS inside the container. Considering both these conditions, it would be preferable to pull down bash image instead of the mysql image.

The following alternate YAML should work for your needs:

---
apiVersion: v1
kind: Pod
metadata:
  name: testing-for-image-pull
spec:
  containers:
  - name: bash
    image: bash
    imagePullPolicy: Always
    command: ["echo"]
    args: ["SUCCESS"]

The following changes have been made from the original YAML file: 1) The kind element has been corrected to the value Pod. 2) The name of the pod has been changed to fit Kubernetes requirements (lowercase DNS-like name). 3) The image and name elements have been modified to use the bash image. 4) The command definition has been changed to use the command and args keys instead.

Note that YAML uses spaces instead of tabs for indentation, and the suggested syntax for YAML is to use two spaces per level of indentation instead of the traditional four spaces.

For more example YAML files, refer to the Kubernetes website repository on GitHub.

Following higuita‘s answer you can lint your yaml and check for errors without installing a module in your machine using npx. I prefer this approach for commands that I do not intend to use often. NPX downloads the package, executes the command and remove the package when finishes.

npx yaml-lint yamllint file_name

I got that error while creating a yaml file for an Ingress using Helm. I had something like this as my Ingress specification

spec:
  tls:
  - hosts:
    - {{ .Values.ingress.host }}

and in the values.yaml

ingress:
  host: "[NAMESPACE]-example.com"

Turned out that the brackets where causing the error.

The issue could be fixed by putting quotes on the value using the quote function.

- {{ .Values.ingress.host | quote }}

This is also what the Helm doc recommends

The easiest way to avoid type conversion errors is to be explicit about strings, and implicit about everything else. Or, in short, quote all strings.

and here

When you are working with string data, you are always safer quoting the strings than leaving them as bare words:

yamllint package is useful to debug and find this kind of errors, just do yamllint filename and it will list the possible problems it finds. Install via your distro package manager (usually recommended if available) or via the below npm install command (it will install globally)

npm install -g yaml-lint

Thanks to Kyle VG for the npm command

The overall file looks good.
There are some issues with indentation.

YAML file

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
    spec:
      volumes:
      - name: nginx-config
        configMap:
          name: nginx-config
      - name: php-config
        configMap:
          name: php-config
      containers:
      - image: php-fpm:7.2
        name: php
        ports:
        - containerPort: 9000
        volumeMounts:
        - name: persistent-storage
            # looks like indentation issue here                 
            mountPath: /var/www/data 
        - name: php-config
            # looks like indentation issue here                 
            mountPath: /usr/local/etc/php-fpm.d/www.conf
            subPath: www.conf
      - image: nginx:latest
        name: nginx
        - containerPort: 80
        volumeMounts:
        - name: persistent-storage
            mountPath: /var/www/data
        - name: nginx-config
            mountPath: /etc/nginx/nginx.conf
            subPath: nginx.conf
      volumes:
        - name: persistent-storage
          persistentVolumeClaim:
            claimName: nfs-pvc

Tags:

Yaml

Kubernetes

Related

I just created a new Helm chart but when I run helm install --dry-run --debug I get:

Error: YAML parse error on multi-camera-tracking/templates/multi-camera-tracking.yaml: error converting YAML to JSON: yaml: line 30: did not find expected key

And this is my Yaml file:

---
# apiVersion: apps/v1beta1
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: multi-camera-tracking
  annotations:
    Process: multi-camera-tracking
  labels:
    io.kompose.service: multi-camera-tracking
spec:
  serviceName: multi-camera-tracking
  replicas: 1
  selector:
    matchLabels:
      io.kompose.service: multi-camera-tracking
  podManagementPolicy: "Parallel"
  template:
    metadata:
      labels:
        io.kompose.service: multi-camera-tracking
    spec:
      containers:
      - name: multi-camera-tracking
        env:
        - name: MCT_PUB_PORT
          value: {{ .Values.MCT_PUB_PORT | quote }}
        - name: SCT_IP_ADDR_CSV
          value: {{ .Values.SCT_IP_ADDR_CSV | quote }}
        - name: SCT_PUB_PORT_CSV
          value: {{ .Values.SCT_PUB_PORT1 | quote }}, {{ .Values.SCT_PUB_PORT2 | quote }}
        image: {{ .Values.image_multi_camera_tracking }}
        #name: multi-camera-tracking
        ports:
        - containerPort: {{ .Values.MCT_PUB_PORT }}
        resources:
          requests:
            cpu: 0.1
            memory: 250Mi
          limits:
            cpu: 4
            memory: 10Gi
        readinessProbe:
          exec:
            command:
            - ls
            - /tmp
          initialDelaySeconds: 5
          periodSeconds: 60
      restartPolicy: Always
      #imagePullSecrets:
      #- name: wwssecret
---
apiVersion: v1
kind: Service
metadata:
  annotations:
    Process: multi-camera-tracking
  creationTimestamp: null
  labels:
    io.kompose.service: multi-camera-tracking
  name: multi-camera-tracking
spec:
  ports:
  - name: "MCT_PUB_PORT"
    port: {{ .Values.MCT_PUB_PORT }}
    targetPort: {{ .Values.MCT_PUB_PORT }}
  selector:
    io.kompose.service: multi-camera-tracking
status:
  loadBalancer: {}

The strange thing is I have created multiple other helm charted and they all are very similar to this but this one doesn’t work and produces error.

4 Answers

I found the reason why it is not working. First of all, it is allowed to have comma-separated values but the problematic part was the quotations.

This is the wrong syntax:

value: {{ .Values.SCT_PUB_PORT1 | quote }}, {{ .Values.SCT_PUB_PORT2 | quote }}

And this is the correct one:

value: {{ .Values.SCT_PUB_PORT1 }}, {{ .Values.SCT_PUB_PORT2 }}

I suspect it’s the value following the key in line 30 that’s the issue; it contains a , and this makes it an invalid value.

{{ .Values.SCT_PUB_PORT1 | quote }}, {{ .Values.SCT_PUB_PORT2 | quote }}

In my case, I had written

name: { { template "cp-kafka.fullname" . } }-jaas-configmap

due to that giving error.

Right would be

name: {{ template "cp-kafka.fullname" . }}-jaas-configmap

The difference is space between curly brackets.

One way to debug this problem is to do a dry-run and render the template to see what is causing the issue on the offending line.

helm install [Chart] [flags] --dry-run --debug

This would allow you to see which keys are not indented well as this issue is sometimes caused by the wrong indentation.

Я делаю лабораторную работу по kubernetes в облаке Google..
Я создал файл YAML, но когда я пытаюсь его развернуть, оболочка показывает мне эту ошибку:

error converting YAML to JSON: yaml: line 34: did not find expected key

YAML-файл:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
    spec:
      volumes:
      - name: nginx-config
        configMap:
          name: nginx-config
      - name: php-config
        configMap:
          name: php-config
      containers:
      - image: php-fpm:7.2
        name: php
        ports:
        - containerPort: 9000
        volumeMounts:
        - name: persistent-storage
          mountPath: /var/www/data
        - name: php-config
          mountPath: /usr/local/etc/php-fpm.d/www.conf
          subPath: www.conf
      - image: nginx:latest
        name: nginx
        - containerPort: 80
        volumeMounts:
        - name: persistent-storage
          mountPath: /var/www/data
        - name: nginx-config
          mountPath: /etc/nginx/nginx.conf
          subPath: nginx.conf
      volumes:
        - name: persistent-storage
          persistentVolumeClaim:
            claimName: nfs-pvc

Перейти к ответу
Данный вопрос помечен как решенный


Ответы
7

В целом файл выглядит хорошо.
Есть некоторые проблемы с отступами.

YAML-файл

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
    spec:
      volumes:
      - name: nginx-config
        configMap:
          name: nginx-config
      - name: php-config
        configMap:
          name: php-config
      containers:
      - image: php-fpm:7.2
        name: php
        ports:
        - containerPort: 9000
        volumeMounts:
        - name: persistent-storage
            # looks like indentation issue here                 
            mountPath: /var/www/data 
        - name: php-config
            # looks like indentation issue here                 
            mountPath: /usr/local/etc/php-fpm.d/www.conf
            subPath: www.conf
      - image: nginx:latest
        name: nginx
        - containerPort: 80
        volumeMounts:
        - name: persistent-storage
            mountPath: /var/www/data
        - name: nginx-config
            mountPath: /etc/nginx/nginx.conf
            subPath: nginx.conf
      volumes:
        - name: persistent-storage
          persistentVolumeClaim:
            claimName: nfs-pvc

Пакет yamlint полезен для отладки и поиска таких ошибок, просто выполните yamllint filename, и он перечислит возможные проблемы, которые он найдет. Установите через диспетчер пакетов вашего дистрибутива (обычно рекомендуется, если он доступен) или с помощью приведенной ниже команды установки npm (она будет установлена ​​глобально)

Npm install -g yaml-lint

Спасибо Kyle VG за команду npm

Я получил эту ошибку при создании файла yaml для Ingress с помощью Helm. У меня было что-то подобное в качестве моей спецификации Ingress

spec:
  tls:
  - hosts:
    - {{ .Values.ingress.host }}

И в значениях.yaml

ingress:
  host: "[NAMESPACE]-example.com"

Выяснилось, что скобки вызывают ошибку.

Проблему можно решить, заключив значение в кавычки с помощью функции quote.

- {{ .Values.ingress.host | quote }}

Это также то, что рекомендует Хелм документ

The easiest way to avoid type conversion errors is to be explicit about strings, and implicit about everything else. Or, in short, quote all strings.

И здесь

When you are working with string data, you are always safer quoting the strings than leaving them as bare words:

Следуя ответу higuita, вы можете проверить свой yaml и проверить наличие ошибок, не устанавливая модуль на свой компьютер, используя npx. Я предпочитаю этот подход для команд, которые я не собираюсь использовать часто. NPX загружает пакет, выполняет команду и удаляет пакет по завершении.

npx yaml-lint yamllint file_name

Хотя приведенный выше файл yaml выглядел нормально, проблема заключалась в отступе (который едва заметен при просмотре файла). Другая проблема, которая может вызвать эту ошибку, связана с проблемой с файлом, например, с отсутствующим именем поля или столбцом.

У меня была такая же проблема, но я решил скопировать ссылку на файл RAW Github и установить его на kubectl

kubectl create -f https://raw.githubusercontent.com/user/project/master/file.yml

Убедитесь, что у вас нет невидимых символов, которые вызывают у вас проблемы.

Эта ошибка:

error converting YAML to JSON: yaml: line 96: could not find expected '':''

Был из-за невидимого разрыва между : и С в этой строке:

- name: CERT_ALIAS

Другие вопросы по теме

#postgresql #kubernetes #yaml #kubernetes-helm #kubernetes-statefulset

Вопрос:

Получение ошибки при развертывании postgres для службы приводит к сбою. Проверил yaml с помощью yamllint, и он действителен, но все равно появляется ошибка. Файл развертывания содержит ServiceAccount , Службу и набор состояний.

 install.go:158: [debug] Original chart version: ""
install.go:175: [debug] CHART PATH: /builds/xxx/xyxy/xyxyxy/xx/xxyy/src/main/helm
Error: YAML parse error on postgresdeployment.yaml: error converting YAML to JSON: yaml: line 24: did not find expected key
helm.go:75: [debug] error converting YAML to JSON: yaml: line 24: did not find expected key
YAML parse error on postgresdeployment.yaml
helm.sh/helm/v3/pkg/releaseutil.(*manifestFile).sort
    /home/circleci/helm.sh/helm/pkg/releaseutil/manifest_sorter.go:146
helm.sh/helm/v3/pkg/releaseutil.SortManifests
    /home/circleci/helm.sh/helm/pkg/releaseutil/manifest_sorter.go:106
helm.sh/helm/v3/pkg/action.(*Configuration).renderResources
    /home/circleci/helm.sh/helm/pkg/action/install.go:489
helm.sh/helm/v3/pkg/action.(*Install).Run
    /home/circleci/helm.sh/helm/pkg/action/install.go:230
main.runInstall
    /home/circleci/helm.sh/helm/cmd/helm/install.go:223
main.newUpgradeCmd.func1
    /home/circleci/helm.sh/helm/cmd/helm/upgrade.go:113
github.com/spf13/cobra.(*Command).execute
    /go/pkg/mod/github.com/spf13/cobra@v0.0.5/command.go:826
github.com/spf13/cobra.(*Command).ExecuteC
    /go/pkg/mod/github.com/spf13/cobra@v0.0.5/command.go:914
github.com/spf13/cobra.(*Command).Execute
    /go/pkg/mod/github.com/spf13/cobra@v0.0.5/command.go:864
main.main
    /home/circleci/helm.sh/helm/cmd/helm/helm.go:74
runtime.main
    /usr/local/go/src/runtime/proc.go:203
runtime.goexit
    /usr/local/go/src/runtime/asm_amd64.s:1357
    
 

после развертывания.yaml

  1. Существует ли какой-либо недопустимый синтаксис yaml?
  2. Какой-нибудь отступ отсутствует ?
  3. Какой узел здесь отсутствует?
 {{- if contains "-dev" .Values.istio.suffix }}
# Postgre ServiceAccount
apiVersion: v1
kind: ServiceAccount
metadata:
  name: postgres
---
# PostgreSQL StatefulSet Service
apiVersion: v1
kind: Service
metadata:
  name: postgres
  labels:
    app: postgres
spec:
  selector:
    app: postgres
  ports:
    - port: 5432
      targetPort: 5432
---
# Postgre StatefulSet
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: postgres
spec:
  selector:
    matchLabels:
      app: postgres
  replicas: {{ .Values.replicaCount }}
  template:
    metadata:
      labels:
        app: postgres
    spec:
        serviceAccountName: postgres
        securityContext:
          {{- toYaml .Values.securityContext | nindent 8 }}
        terminationGracePeriodSeconds: {{ default 60 .Values.terminationGracePeriodSeconds }}
        volumes:
        {{ include "xxx.volumes.logs.spec" . | indent 8 }}
        - emptyDir: { }
            name: postgres-disk
        containers:
          - name: postgres
            image: "{{ template "xxx.dockerRegistry.hostport" . }}/postgres:latest"
            imagePullPolicy: {{ .Values.image.pullPolicy }}
            ports:
              - name: postgres
                containerPort: 5432
            livenessProbe:
              tcpSocket:
                port: 5432
              failureThreshold: 3
              initialDelaySeconds: 240
              periodSeconds: 45
              timeoutSeconds: 5
            readinessProbe:
              tcpSocket:
                port: 5432
              failureThreshold: 2
              initialDelaySeconds: 180
              periodSeconds: 5
              timeoutSeconds: 20
            resources:
              {{ if .Values.lowResourceMode }}
                {{- toYaml .Values.resources.low | nindent 12 }}
                {{ else }}
                {{- toYaml .Values.resources.high | nindent 12 }}
                {{ end }}
            env:
              - name: PGDATA
                value: /var/lib/postgresql/data/pgdata
            volumeMounts:
              - name: postgres-disk
                mountPath: /var/lib/postgresql/data
{{- end }}
 

Ответ №1:

Шаблонные усы в helm (и его одноранговый текст/шаблон golang) должны быть одним маркером, иначе yaml считает, что { открывает диктант, а затем { пытается открыть дочерний диктант, и, как и в JSON, это недопустимая структура

Так что вы захотите:

         serviceAccountName: postgres
        securityContext:
          {{- toYaml .Values.securityContext | nindent 8 }}
 

Комментарии:

1. Да , это работает, но теперь я получаю еще одну ошибку «helm.go:75: [отладка] ошибка преобразования YAML в JSON: yaml: строка 24: не найден ожидаемый ключ»

2. Слушай, мне жаль, что YAML это так ново для вас, но - emptyDir: { }nname: postgres-disk это неверный, слишком; это не какие-то тонкости «кто мог знать» различные, не говоря уже о том, что вы не включили какой строке 24 есть на самом деле, я был просто в состоянии заметить эту очевидную ошибку-не может быть другим, основываясь на values.yaml том, что вы и не пост

3. Знак минус непосредственно внутри двойных фигурных скобок {{- ... }} -это сигнал движку Go text/template удалить пробелы перед блоком шаблона; его не примут за словарь YAML.

Понравилась статья? Поделить с друзьями:
  • Error converting value to type system
  • Error converting to execution character set invalid or incomplete multibyte or wide character
  • Error converting to execution character set illegal byte sequence
  • Error converting one or more entries
  • Error converting data type varchar to float перевод