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, ruamel.yaml) 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
  • ruamel.yaml.constructor.DuplicateKeyError: found duplicate key "image" with value "nginx:1.27" (original value: "nginx:1.25")

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. A merge that kept both sides of a conflict produces exactly the same result.

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. Render the chart with helm template to see the real output, then 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

5. The merge key written twice

Pulling in two anchors with two <<: lines repeats the key << itself. js-yaml happens to allow it, but the yaml package rejects it. A list of anchors is the correct form and works in both.

Before
defaults: &defaults
  retries: 3
limits: &limits
  cpu: 2
job:
  <<: *defaults
  <<: *limits
After
defaults: &defaults
  retries: 3
limits: &limits
  cpu: 2
job:
  <<: [*defaults, *limits]

Which parsers reject it and which keep a value

Section 3.2.1.1 of the YAML 1.2 specification says each key in a mapping must be unique, but what a parser does about a violation varies. These were checked against the sample at the top of this page:

  • js-yaml: rejects it. With the json: true option the last value wins.
  • yaml (npm): rejects it unless you pass uniqueKeys: false, and then the last value wins.
  • PyYAML: accepts it silently, last value wins, with both the Python and C loaders.
  • ruamel.yaml: rejects it. With allow_duplicate_keys = True the first value wins.
  • Go yaml.v3: rejects it.
  • Go yaml.v2: Unmarshal accepts it; UnmarshalStrict rejects it.
  • sigs.k8s.io/yaml: YAMLToJSON accepts it; YAMLToJSONStrict rejects it.

Go tools built on these libraries therefore differ, depending on the function they call. GitHub Actions has its own check and reports 'with' is already defined for a workflow. Test with the program that will actually consume the file, and be wary of a file that “worked” until now: it may have been running with the value you did not expect.

Deciding which value is correct

Deleting one line is easy; deleting the right one takes a minute of checking:

  1. Find out which value has been in effect. Under a last-wins parser such as PyYAML, the lower line is the one running today.
  2. Look at the history with git log -L 2,5:deploy.yaml, or git blame, to see when each line appeared and why.
  3. If the two lines came from a merge, read both branches. Each side may have intended something the other did not.
  4. Keep one key. For lists and nested maps, the answer is often to combine the entries rather than choose between them.

Quoted keys and keys that only look alike deserve a second look: "port" and port are the same key, while a key with a trailing space inside quotes is not.

Enforcing unique keys in CI and in Python

yamllint turns this on by default and reports each repeat as duplication of key "image" in mapping (key-duplicates), which works for every file in a repository regardless of what reads it later.

If your application uses PyYAML, a small loader adds the check at load time. The merge-key test keeps << working:

class UniqueKeyLoader(yaml.SafeLoader):
    def construct_mapping(self, node, deep=False):
        seen = set()
        for key_node, _ in node.value:
            if key_node.tag == "tag:yaml.org,2002:merge":
                continue
            key = self.construct_object(key_node, deep=deep)
            if key in seen:
                line = key_node.start_mark.line + 1
                raise ValueError(f"duplicate key {key!r} on line {line}")
            seen.add(key)
        return super().construct_mapping(node, deep)

config = yaml.load(text, Loader=UniqueKeyLoader)

When you only need the file checked once, PasteKit lists every repeated key in a single pass rather than stopping at the first, each with its line and column. The YAML common mistakes guide covers the related traps.

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 js-yaml, in Go’s yaml.v3 and in anything else 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.

Are duplicate keys allowed in JSON?

RFC 8259 only says names should be unique, so most JSON parsers accept them and keep the last. YAML is stricter on paper. See duplicate keys in JSON for the details.

Does the order of keys matter once the duplicate is gone?

No. A YAML mapping is unordered, so moving a key does not change the meaning. Tools may print keys in a different order without the data being different.

Related