You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible中如何在filter内拼接变量与字符串实现过滤?

解决Ansible中动态变量在rejectattr过滤器中的引用问题

你遇到的问题核心是:item.key ~ '_git_records'拼接出来的是变量名的字符串(比如int_domain_git_records),而非该字符串对应的变量值。rejectattr过滤器会把这个字符串当成判断条件,而非实际的记录列表,导致过滤失效。

以下两种方案可以解决这个问题:

方案一:使用vars lookup插件直接引用动态变量

通过lookup('vars', '变量名字符串')可以直接将字符串形式的变量名转换为对应的变量值。修改后的任务代码如下:

- name: Find difference between remote hosts and Git file
  ansible.builtin.set_fact:
    "{{ item.key }}_inconsistent_hostnames": "{{ remote_records | selectattr('domain', '==', item.value) | rejectattr('hostname', 'in', lookup('vars', item.key ~ '_git_records')) }}"
  loop: "{{ domains | dict2items }}"

方案二:将动态变量统一存入字典(推荐)

把所有Git记录整理到一个字典中,避免零散的动态变量名,引用起来更直观:

第一步:修改生成Git记录的任务

- name: Generates list of hostnames for every domain present in var domain
  ansible.builtin.set_fact:
    git_records: "{{ git_records | default({}) | combine({ item.key: list_of_A_records }) }}"
  loop: "{{ domains | dict2items }}"

这里list_of_A_records替换为你实际生成A记录列表的代码。

第二步:在对比任务中引用字典值

- name: Find difference between remote hosts and Git file
  ansible.builtin.set_fact:
    "{{ item.key }}_inconsistent_hostnames": "{{ remote_records | selectattr('domain', '==', item.value) | rejectattr('hostname', 'in', git_records[item.key]) }}"
  loop: "{{ domains | dict2items }}"

验证变量是否正确获取

可以添加debug任务确认变量值是否符合预期:

# 针对方案一的debug
- name: Debug dynamic git records
  ansible.builtin.debug:
    var: lookup('vars', item.key ~ '_git_records')
  loop: "{{ domains | dict2items }}"

# 针对方案二的debug
- name: Debug git records dictionary
  ansible.builtin.debug:
    var: git_records[item.key]
  loop: "{{ domains | dict2items }}"

内容的提问来源于stack exchange,提问作者trust in ratio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 22:13:14