首页 > 解决方案 > Ansible - 使用正则表达式检查文件中是否存在字符串

问题描述

我需要验证PermitRootLogin参数是否等于“否”,例如:

PermitRootLogin no

但有时这些词之间有不止一个空格。出于这个原因,我使用正则表达式,但显然我做错了。这是似乎很糟糕的行:

when: check_config.stdout.find('PermitRootLogin\s+no') != -1

知道如何解决这个问题吗?

- hosts: redhat
  tasks:

  - name: check file
    shell: cat /etc/ssh/sshd_config
    register: check_config

  - name: compare string 
    when: check_config.stdout.find('PermitRootLogin\s+no') != -1
    debug: msg="this server is ok"

标签: regexansible

解决方案


问:我需要验证 PermitRootLogin 参数是否等于“no”

A:使用查找选择来确定服务器是否正常。例如

- debug:
    msg: 'this server is ok'
  when: lookup('file', '/etc/ssh/sshd_config').splitlines()|
        select('match', '^PermitRootLogin\s+no$' )|list

如果要在配置中放置/替换该行,请使用lineinfile。例如

- lineinfile:
    path: /etc/ssh/sshd_config
    regexp: '^PermitRootLogin(.*)$'
    line: 'PermitRootLogin no'

(未测试)


笔记

  • 查找插件在 Ansible 控制机器上进行评估,而不是在目标/远程。使用delegate_to检查远程主机。

推荐阅读