Ansible-lint 自定义规则与正则表达式匹配

问题描述 投票:0回答:1

我想使用 Ansible-lint 检查我的 yaml 文件中的子网格式是否正确。

:10.10.10.0/32

错误:10.10.10.0 /32

我创建了一个自定义规则:

     from ansiblelint import AnsibleLintRule
     import re

     class CheckCustomPattern(AnsibleLintRule):
         id = 'CUSTOM005'
         shortdesc = 'Check if pattern "\\s\/[1-3][0-9]" is found'
         description = 'This rule checks if the pattern "\\s\/[1-3][0-9]" is found in any file.'
         severity = 'HIGH'
         tags = ['files']

         def match(self, file, text):
             with open(file['path'], 'r') as file_content:
                 content = file_content.read()
                 if re.search(r'\s\/[1-3][0-9]', content):
                     return True
             return False

我已经针对测试人员检查了正则表达式,它是正确的。

当我运行它时,tt 匹配所有 IP 地址,甚至是正确的 IP 地址。它甚至可以匹配非 IP 地址,例如 [ TCP UDP ICMP ] 等随机字符串。我已经在测试器中检查了正则表达式语法,它是正确的。

不确定我错过了什么。

python ansible yaml ansible-lint
1个回答
0
投票

这是预期的:您正在加载整个文件并检查整个文件。您应该改为迭代行列表。我已经有好几年没有编写过简单的 Python 代码了,但下面是它以一种过于简单的方式看起来的样子:

# playbook.yaml
---
- hosts: localhost
  connection: local
  gather_facts: false
  tasks:
    - debug:
        msg: '10.10.10.0/32'

    - debug:
        msg: '10.10.10.0 /32'

    - debug:
        msg: '10.10.10.0  /32'

    - debug:
        msg: '[ TCP UDP ICMP ]'
# match.py
import re

with open('playbook.yaml', 'r') as file_content:
    content = file_content.read()
    incorrect_subnet_spacing_regex = r'\s\/[1-3][0-9]'
    for index, line in enumerate(content.split('\n')):
        match = re.search(incorrect_subnet_spacing_regex, line)
        if match:
            print(f'Incorrect subnet at line {index}, position {match.start()}: {line}')

对于示例文件,上面的代码将产生以下结果:

Alexanders-Mini:78189854 alexander$ python3 match.py 
Incorrect subnet at line 9, position 24:         msg: '10.10.10.0 /32'
Incorrect subnet at line 12, position 25:         msg: '10.10.10.0  /32'

我会调整正则表达式,因为例如,斜杠后面可能会添加一个空格。

© www.soinside.com 2019 - 2024. All rights reserved.