Hi. We have the need to update a possibly existing /etc/ansible/ansible.cfg file during the installation of an Ansible collection. Instead of replacing the file, we’d like to just get the updates in that we need (a few settings in the [defaults] section), in order to be tolerant to existing files.
I looked at the ansible-config command, but it only lists/views/dumps the effective config, combining all of its sources.
Is there a command line tool or a Python library that can update ansible.cfg files?
I don’t think there is an official Ansible command or built-in tool that “patches” an existing ansible.cfg.
You should try using an external parser, such as ConfigUpdater.
example of how you can use ConfigUpdater to update the [defaults] section in your ansible.cfg while preserving comments and formatting:
from configupdater import ConfigUpdater
config_path = '/etc/ansible/ansible.cfg'
# Create an updater instance and read the file
updater = ConfigUpdater()
updater.read(config_path)
# Ensure the [defaults] section exists; create it if missing
if 'defaults' not in updater.sections():
updater.add_section('defaults')
# Access the [defaults]
defaults = updater['defaults']
# Update specific settings; these will be added or overwritten
defaults['inventory'] = '/path/to/your/inventory'
defaults['host_key_checking'] = 'False'
# Optionally, add a comment to one of the settings
defaults['inventory'].comment = 'Updated inventory path'
# Write the updated configuration back to the file
with open(config_path, 'w') as config_file:
updater.write(config_file)
Obviously, since it’s an external script, I advise you to thoroughly test it before making any changes to the real ansible.cfg file.