如何在Ansible的Git模块任务中配置changed_when检测本地修改
问题:Ansible Git任务中根据"Local modifications"标记任务变更
原任务配置
- name: Checkout in client folder ansible.builtin.git: repo: "{{ item.value.dev_repo | default('git@*****:***/****.git') }}" key_file: /tmp/oci_odoo.rsa accept_hostkey: true dest: "/opt/odoo/odoo_{{ item.key }}/addons" version: "{{ item.value.repo_branch | default('main') }}" force: false with_dict: "{{ clients }}" when: inventory_hostname in groups['main'] ignore_errors: true tags: tag1
问题场景
目标文件夹存在本地修改时,每次运行剧本都会触发错误,输出如下:
[11:06:42] ↳ module : Checkout in client folder | hostname | FAILED | 1.08s { - msg: One or more items failed - results: [ { - msg: Local modifications exist in the destination: /opt/odoo/odoo/addons (force=no). - changed: False - before: 1c9a771969222f8ebbab57bd1e173b821f684a04 - failed: True } - ansible_loop_var: item } ] - changed: False }
尝试的错误配置及报错
尝试添加register和changed_when来标记变更,但配置错误导致报错:
register: result changed_when: '"Local modifications" in result.results[msg]'
或:
register: result changed_when: '"Local modifications" in result.results.msg'
调试得到的result变量及错误:
{ - result: { - msg: One or more items failed - results: [ { - msg: Local modifications exist in the destination: /opt/odoo/odoo/addons (force=no). - changed: False - before: 1c9a771969222f8ebbab57bd1e173b821f684a04 - failed: True - changed_when_result: The conditional check '"Local modifications" in result.results[msg]' failed. The error was: error while evaluating conditional ("Local modifications" in result.results[msg]): 'dict object' has no attribute 'results' } - ansible_loop_var: item } ] - skipped: False - failed: True - changed: False } }
错误信息:The conditional check '"Local modifications" in result.results[msg]' failed. The error was: error while evaluating conditional ("Local modifications" in result.results[msg]): 'dict object' has no attribute 'results'
解决方案
正确的任务配置
- name: Checkout in client folder ansible.builtin.git: repo: "{{ item.value.dev_repo | default('git@*****:***/****.git') }}" key_file: /tmp/oci_odoo.rsa accept_hostkey: true dest: "/opt/odoo/odoo_{{ item.key }}/addons" version: "{{ item.value.repo_branch | default('main') }}" force: false with_dict: "{{ clients }}" when: inventory_hostname in groups['main'] ignore_errors: true register: git_result changed_when: > git_result.results | selectattr('msg', 'search', 'Local modifications') | list | length > 0 tags: tag1
配置说明
- 注册变量:将注册变量命名为
git_result,避免与单个循环项的结果混淆 - changed_when逻辑:
- 使用
selectattr过滤器遍历git_result.results列表,筛选出msg字段包含"Local modifications"的结果项 - 将筛选结果转为列表后判断长度,只要存在符合条件的项,就标记整个任务为
changed
- 使用
错误原因说明
- 原配置中直接访问
result.results[msg]或result.results.msg是语法错误:results是列表类型,不能直接通过.msg访问属性,必须遍历或筛选 - 循环任务中,
changed_when默认针对单个循环项的结果,而非整个任务的注册变量集合,导致原配置中找不到results属性
内容的提问来源于stack exchange,提问作者Louis Gromb
相关产品推荐
相关产品推荐

