YAML error: duplicated mapping key

The YAML specification requires keys in a mapping to be unique. Strict parsers (js-yaml, the yaml package, Go’s yaml.v3, kubectl) reject a repeated key; lenient ones such as PyYAML keep the last value without a warning. Either way, one of the two values was written for a reason and is now ignored, so decide which one is correct and remove the other.

Seen as:

  • YAMLException: duplicated mapping key (5:3)
  • Map keys must be unique at line 5, column 3
  • yaml: unmarshal errors: line 5: mapping key "image" already defined at line 2
  • error converting YAML to JSON: yaml: unmarshal errors: line 5: key "image" already set in map

Input

Settings

History

Load from URL

Common causes

1. A setting added again lower in the block

Long service definitions make it easy to add image: again instead of editing the existing line. Keep one key with the value you want.

Before
web:
  image: nginx:1.25
  ports:
    - "80:80"
  image: nginx:1.27
After
web:
  image: nginx:1.27
  ports:
    - "80:80"

2. Two blocks for the same list

Writing env: twice, once for each group of variables, defines the key twice instead of extending the list. Merge the items under one key.

Before
env:
  - name: LOG_LEVEL
    value: info
env:
  - name: REGION
    value: eu-west-1
After
env:
  - name: LOG_LEVEL
    value: info
  - name: REGION
    value: eu-west-1

3. Keys that look different but are the same

Quoting does not change a key: "port" and port are identical. Keys are case-sensitive, though, so Port and port are different keys and will not be reported.

Before
port: 8080
"port": 9090
After
port: 9090

4. Templated keys colliding with literal ones

A Helm {{- toYaml .Values.labels | nindent 4 }} that also emits app: collides with an app: written in the template. Remove the literal key or the value from the values file.

Before
labels:
  app: web
  app: web-canary
  tier: frontend
After
labels:
  app: web-canary
  tier: frontend

Frequently asked questions

Why does my file load fine in Python?

PyYAML does not check for duplicate keys and silently keeps the last value. The same file fails in kubectl, Helm, GitHub Actions or any tool built on a strict parser.

Is the merge key <<: allowed to repeat keys?

Yes. Keys pulled in with <<: *anchor can be overridden by keys written directly in the mapping; that is how merge keys are meant to work and is not a duplicate.

How do I find every duplicate in a large file?

Paste it into PasteKit: every repeated key is reported with its line and column. yamllint’s key-duplicates rule does the same in CI.

Related