如何在Ansible中检查文本存在及转换SSH根登录检查脚本为YAML
问题1:如何在Ansible的when条件中检查文本是否存在?
在Ansible中,可通过以下两种常用方法在when条件中检查文件内是否存在指定文本:
方法1:使用
command模块执行grep命令
通过grep查找目标文本,注册执行结果后,通过返回码(rc)判断是否找到文本:- name: 检查目标文本是否存在 command: grep -q "要查找的文本" /目标文件路径 register: text_check_result ignore_errors: true # 避免未找到文本时任务直接失败 changed_when: false # 标记该任务不会修改系统状态 - name: 文本存在时执行操作 debug: msg: "已找到目标文本" when: text_check_result.rc == 0 # grep找到文本时返回码为0 - name: 文本不存在时执行操作 debug: msg: "未找到目标文本" when: text_check_result.rc != 0方法2:使用
lineinfile模块(推荐,更符合Ansible风格)
利用lineinfile模块的检查模式(check_mode),注册结果后通过changed字段判断是否存在匹配行:- name: 检查目标文本行是否存在 lineinfile: path: /目标文件路径 regexp: '匹配目标文本的正则表达式' state: present check_mode: yes # 仅检查不实际修改文件 register: line_check_result - name: 文本行存在时执行操作 debug: msg: "已找到目标文本行" when: not line_check_result.changed # 检查模式下,行已存在则changed为false - name: 文本行不存在时执行操作 debug: msg: "未找到目标文本行" when: line_check_result.changed # 检查模式下,行不存在则changed为true
问题2:将Shell脚本转换为Ansible YAML格式并修正现有代码
原Shell脚本逻辑
原脚本的作用是:检查/etc/ssh/sshd_config中是否存在忽略大小写、前后允许空格的PermitRootLogin no配置行,存在则输出通过信息,否则输出失败信息。
转换后的Ansible YAML(两种实现方式)
方式1:模拟原Shell的grep逻辑
- name: 检查SSH root登录禁用状态 hosts: web tasks: - name: 查找PermitRootLogin no配置 command: grep -i "^\s*PermitRootLogin\s*no\s*" /etc/ssh/sshd_config register: root_login_check ignore_errors: true changed_when: false # 标记任务无状态变更 - name: 输出通过信息 debug: msg: "[ PASSED ] - Ensure SSH root login is disabled" when: root_login_check.rc == 0 - name: 输出失败信息 debug: msg: "[ FAILED ] - Ensure SSH root login is disabled" when: root_login_check.rc != 0
方式2:使用lineinfile模块(推荐)
- name: 检查SSH root登录禁用状态 hosts: web tasks: - name: 检查PermitRootLogin no配置行是否存在 lineinfile: path: /etc/ssh/sshd_config regexp: '^\s*PermitRootLogin\s*no\s*' state: present check_mode: yes register: root_login_check - name: 输出通过信息 debug: msg: "[ PASSED ] - Ensure SSH root login is disabled" when: not root_login_check.changed - name: 输出失败信息 debug: msg: "[ FAILED ] - Ensure SSH root login is disabled" when: root_login_check.changed
修正你编写的部分代码
你原代码的问题在于when条件写法错误(不能用$regexp),且逻辑需要调整。以下是修正后的版本,逻辑为:检查是否不存在PermitRootLogin yes行(即root登录已禁用):
- name: Check permitRootLogin hosts: web tasks: - name: 检查是否存在PermitRootLogin yes配置行 lineinfile: path: /etc/ssh/sshd_config state: absent regexp: '^\s*PermitRootLogin\s*yes\s*' check_mode: yes register: permit - name: 输出通过信息 debug: msg: "[ PASSED ] - Ensure SSH root login is disabled" when: not permit.changed # 无匹配行时changed为false,说明已禁用root登录 - name: 输出失败信息 debug: msg: "[ FAILED ] - Ensure SSH root login is disabled" when: permit.changed # 存在匹配行时changed为true,说明未禁用root登录
内容的提问来源于stack exchange,提问作者usertest5522
相关产品推荐
相关产品推荐

