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
相关产品推荐
相关产品推荐

