Ansible ini lookup插件无法处理键值中的%特殊字符问题求助
问题:Ansible读取含URL编码%的INI配置项报错
我运行以下Ansible Playbook任务,试图从INI文件中读取固件下载URL:
- name: Retrieve FW Files tags: fw_ssh, retrieve_fw_vars ansible.builtin.set_fact: fw_tstg_url: "{{ lookup('ansible.builtin.ini', 'fw_test_image_download_url', section='pytest', file='~/latestRelease.ini', interpolation=false) }}"
但目标配置项fw_test_image_download_url的值包含URL编码的%字符(例如site.com?date=2024-12-19T16%3A56Z),即使设置了interpolation=false,仍抛出以下错误:
TASK [Retrieve FW Files] **************************************************************************************************************************************** fatal: [parshall-pi]: FAILED! => {"msg": "An unhandled exception occurred while running the lookup plugin 'ansible.builtin.ini'. Error was a <class 'configparser.InterpolationSyntaxError'>, original message: '%' must be followed by '%' or '(', found: '%3A21%3A02Z&se=2025-12-20T18%3A21%3A00Z&sr=b&sp=r&sig=d0AMoAny8EVHasu4KARQeYy2KEx7XaS8Vhd39GdFBv8%3D'. '%' must be followed by '%' or '(', found: '%3A21%3A02Z&se=2025-12-20T18%3A21%3A00Z&sr=b&sp=r&sig=d0AMoAny8EVHasu4KARQeYy2KEx7XaS8Vhd39GdFBv8%3D'"}
解决办法
方法1:修改INI文件转义%
把INI文件中所有单独的%替换为%%,比如:
[pytest] fw_test_image_download_url = site.com?date=2024-12-19T16%%3A56Z
这样ansible.builtin.ini lookup读取后会自动解析回单个%。
方法2:用RawConfigParser直接读取(无需修改INI)
如果不能改动原INI文件,用Python的configparser.RawConfigParser来读取,它完全不处理插值逻辑:
- name: Retrieve FW Files tags: fw_ssh, retrieve_fw_vars ansible.builtin.set_fact: fw_tstg_url: "{{ lookup('ansible.builtin.pipe', 'python3 -c \"import configparser; import os; cfg = configparser.RawConfigParser(); cfg.read(os.path.expanduser(\'~/latestRelease.ini\')); print(cfg.get(\'pytest\', \'fw_test_image_download_url\'))\"') }}"
方法3:指定lookup的type为raw(Ansible 2.10+适用)
如果你的Ansible版本在2.10及以上,可以直接给ansible.builtin.ini lookup加上type='raw'参数,强制使用RawConfigParser:
- name: Retrieve FW Files tags: fw_ssh, retrieve_fw_vars ansible.builtin.set_fact: fw_tstg_url: "{{ lookup('ansible.builtin.ini', 'fw_test_image_download_url', section='pytest', file='~/latestRelease.ini', type='raw') }}"
内容的提问来源于stack exchange,提问作者Nemesis
相关产品推荐
相关产品推荐

