regex - 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"
解决方案
问:我需要验证 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检查远程主机。
推荐阅读
- sql - 大表列的数据分析(SQL Server)
- javascript - 运行“git push heroku master”时出现错误
- layout - 避免在 Draggabilly 中拖动元素
- android - 如何在editText框的右下角显示editText字符限制?下面的例子
- r - 求解代数方程
- php - file_put_contents 将不同的时间戳保存到服务器
- bash - 为什么变量不适用于条件
- python - 如何将时间戳列中的值转换为数字
- c# - 如何设置变量等于嵌套类的 JsonProperty 属性...C#
- python-3.x - 导入不在 python 中运行