【问题标题】:Unable to parse yaml file in python无法在 python 中解析 yaml 文件
【发布时间】:2021-01-28 09:19:05
【问题描述】:

我正在尝试解析下面的 yaml 文件,尝试使用不同的 yaml 解析器,但我无法解析 yaml 文件。有没有办法使用任何其他 python 库来解析这个 yaml 文件。

policies:
  - name: test
    resource: ec2
    mode:
      type: periodic
      schedule: rate(1 day)
      role: arn:aws:iam::{account_id}:role/role_name
      tags:
        Name: ${tag_name}
        Project: ${tag_project}
    filters:
      - and:
        - type: value
          key: testname
          value: "${aws_account_id}"
        - type: value
          whitelist: %{ for acct_id in split (",", resource_list) }
            - "${acct_id}" %{ endfor }

python 脚本:

import glob
from pathlib import Path
import ruamel.yaml

def print_table(filepath):
 file_name = Path(filepath)
 yaml = ruamel.yaml.YAML()
 data = yaml.load(file_name)
 name = data['name']
 print(name)

if __name__ == "__main__":
    print_table('test.yaml')
    

错误:

ruamel.yaml.scanner.ScannerError: while scanning for the next token
found character '%' that cannot start any token
  in "test.yaml", line 17, column 26

【问题讨论】:

  • “无法解析”是什么意思?如果您遇到错误,请编辑您的问题以包含回溯的整个文本。
  • 您的 yaml 文件似乎无效。是否有任何其他语言可以使用此文件?
  • 看起来你的 yaml 是从模板生成的,%{ endfor } 的错误最终出现在你的 yaml 中 - 它不应该。
  • 我认为这是一个完全没有运行过的yaml文件的模板。
  • 这是一项托管政策,但出于安全问题,我已更改了值。

标签: python python-3.x yaml


【解决方案1】:

只需使用${{each in }}

policies:
  - name: test
    resource: ec2
    mode:
      type: periodic
      schedule: rate(1 day)
      role: arn:aws:iam::{account_id}:role/role_name
      tags:
        Name: ${tag_name}
        Project: ${tag_project}
    filters:
      - and:
        - type: value
          key: testname
          value: "${aws_account_id}"
        - type: value
          whitelist:
              ${{each acct_id in split (",", resource_list)}} - ${{acct_id}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-23
    • 2018-02-16
    • 2010-12-18
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    相关资源
    最近更新 更多