codingenious
codingenious

Reputation: 8653

Exit if duplicate keys are while reading from Lineup file

I am getting the below warning while reading the lineup file

[WARNING]: While constructing a mapping from True, line 1, column 1, found a duplicate dict key (release). Using last defined value only.

Code piece is:

 - name: Read in Lineup File
   include_vars:
     file: "{{ lineup_file }}"
     name: lineup

What I want to do is exit with an error instead of warning if duplicate keys are found in YAML file.

Is there any way to do that?

Upvotes: 2

Views: 240

Answers (1)

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68269

IFAIK there's no configuration setting or something like this.

But you can teach Ansible to do whatever you want with a plugins.

Drop this into project/callback_plugins/catch_dup.py:

from ansible.plugins.callback import CallbackBase
from ansible.errors import AnsibleError

try:
    from __main__ import display
except ImportError:
    display = None


class CallbackModule(CallbackBase):

    def __init__(self, *args, **kwargs):

        def catch_dup(msg, formatted=False):
            display.warn_original(msg, formatted=False)
            if 'found a duplicate dict key' in msg:
                raise AnsibleError("FATAL ERROR: Duplicate key!")

        display.warn_original = display.warning
        display.warning = catch_dup

This plugin overrides display.warning method with catch_dup one, where we check for specific warning message and fail if duplicate key warning is there.

Upvotes: 1

Related Questions