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

Ansible中‘when not in group_names’条件未生效问题求助

问题分析与解决方案

问题根源

你的when条件语法存在多余的括号,导致Jinja2解析时出现歧义,原本应该为false的条件被错误评估,使得堡垒机上本应跳过的任务被执行。

从debug输出可以确认group_names确实包含bastion,但原条件("'bastion' not in group_names")中的外层括号是冗余的,干扰了表达式的正确解析,导致条件被判定为true,任务执行。

修复方案

修改最后一个任务的when条件,去掉多余的括号,或者调整为更清晰的逻辑写法:

写法1:去掉冗余括号

when: "'bastion' not in group_names"

写法2:逻辑更清晰的反向判断

when: not ('bastion' in group_names)

写法3:直接检查主机是否在bastion组(更直观)

when: inventory_hostname not in groups['bastion']

修改后的完整任务代码:

- name: Add lines to project sudoers.d file
  tags: create_project_accounts, add_sudoers
  become: true
  ansible.builtin.lineinfile:
    path: "/etc/sudoers.d/{{ project_sudoersd_file }}"
    state: present
    create: yes
    mode: '644'
    owner: root
    group: root
    line: "{{ item }}"
    validate: 'visudo -cf %s'
  when: not ('bastion' in group_names)
  loop:
    - '%devgroup1 ALL=(ALL) ALL'
    - 'itsectool ALL=(ALL) ALL'
    - 'citool ALL=(ALL) ALL'

验证效果

修改后重新在堡垒机上执行playbook,最后一个任务会显示skipped,不会创建/etc/sudoers.d/project_sudoers文件,符合预期要求。

内容的提问来源于stack exchange,提问作者chief_finanigans

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 21:35:14