读取Lineup文件遇重复键时,如何终止程序并抛出错误?
Absolutely, you can force Ansible to terminate with an error when duplicate keys are detected in your YAML files—no more letting warnings slide and ending up with unexpected overwritten values! Here are two straightforward, reliable approaches:
1. Update your global Ansible configuration (ansible.cfg)
Head to the [defaults] section of your ansible.cfg file and set the yaml_dup_key parameter to error:
[defaults] yaml_dup_key = error
By default, this setting is set to warn—which is exactly why you’re seeing that duplicate key warning. Switching it to error will make Ansible immediately fail any task that hits duplicate keys in YAML files, including your include_vars task.
2. Apply the setting per-playbook or at runtime
If you don’t want to adjust your global config, you can override this behavior for specific playbooks or runs:
- Per-playbook: Add the variable directly in your play definition:
- name: Your Target Play hosts: all vars: ansible_yaml_dup_key: error tasks: - name: Read in Lineup File include_vars: file: "{{ lineup_file }}" name: lineup - Runtime environment variable: Launch your playbook with this variable set temporarily:
ANSIBLE_YAML_DUP_KEY=error ansible-playbook your-playbook.yml
What changes after setting this?
Instead of only showing this warning when duplicate keys exist:
[WARNING]: While constructing a mapping from True, line 1, column 1, found a duplicate dict key (release). Using last defined value only.
Ansible will throw a fatal error and halt execution right away. This ensures you catch duplicate key issues before they lead to unintended behavior in your playbook.
内容的提问来源于stack exchange,提问作者Saurabh Batra

