编辑现有的yaml文件,但保留原始注释

2024-10-02 22:37:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个Python脚本,将IPtables配置转换为YAML文件中的防火墙multi。我最初使用的是pyyaml,但是后来发现这删除了我需要保留的所有注释,我发现拉梅尔亚姆勒可以用来保留评论,但是,我正在努力让这个工作。在

import sys
import io
import string
from collections import defaultdict
import ruamel.yaml 


#loading the yaml file 

try:
      config = ruamel.yaml.round_trip_load(open('test.yaml'))
except ruamel.yaml.YAMLError as exc:
      print(exc)

print (config)

# Output class
#this = defaultdict(list)
this = {}
rule_number = 200
iptables_key_name = "ha247::firewall_addrule::firewall_multi"


# Do stuff here
for key, value in config.items():
 # Maipulate iptables rules only
   if key == 'iptables::rules':

# Set dic withim iptables_key_name
     this[iptables_key_name] = {}
     for rule, rule_value in value.items():

# prefix rule with ID
         new_rule =("%s %s" % (rule_number,rule))
         rule_number = rule_number + 1



# Set dic within [iptables_key_name][rule]
         this[iptables_key_name][new_rule] = {}
# Ensure we have action
         this[iptables_key_name][new_rule]['action'] = 'accept'
         for b_key, b_value in rule_value.items():
# Change target to action as rule identifier
             b_key = b_key.replace('target','action')
# Save each rule and ensure we are lowrcase
             this[iptables_key_name][new_rule][b_key] = str(b_value).lower()

  elif key == 'ha247::security::enable': 
      this['ha247::security_firewall::enable'] = value

  elif key == 'iptables::safe_ssh':
      this['ha247::security_firewall::safe_ssh'] = value

  else:
# Print to yaml
     this[key] = value


# Write YAML file
  with io.open('result.yaml', 'w', encoding='utf8') as outfile:
       ruamel.yaml.round_trip_dump(this, outfile, default_flow_style=False, allow_unicode=True)

输入文件(测试.yaml)在

^{pr2}$

的输出结果.yaml在

ha247::firewall_addrule::firewall_multi:
  200 ACCEPT_HTTP:
    action: accept
    port: '80'
  201 HTTPS:
    action: accept
    port: '443'

ha247::security_firewall::enable: true
ha247::security_firewall::safe_ssh: false
simple_nginx::ssl_ciphers:     
simple_nginx::vhosts:
 <domain>:
    backend: php-fpm
    document_root: /var/www/
    force_www: true
    server_alias: www.
    server_name: .com
    ssl_enabled: true
    ssl_managed_enabled: true
    ssl_managed_name: www.
    template: php-magento-template

这就是问题所在,您可以看到它更改了所有格式并删除了我们需要保留的注释,另一个问题是它删除了顶部的三个连字符,这将导致configuration manager无法读取文件。在


Tags: keynameimportyamlnumberiptablesnewvalue
1条回答
网友
1楼 · 发布于 2024-10-02 22:37:59

由于映射的缩进位置是1、2、3和4个位置,因此无法精确地获得所需的内容。如前所述,ruamel.yaml只有一个设置应用于所有映射(默认为2)。在

目前文档的开始(和结束)标记没有在输入上进行分析,所以您将不得不做一些最小的额外工作。在

然而,最大的问题是你对使用往返装载机和倾卸机意味着什么的误解。它的意思是将一个YAML文档加载到Python数据结构中,更改该数据结构,然后写出相同的数据结构。您可以临时创建一个新的数据结构(this),从YAML加载的数据结构(config)中分配一些值,然后写出新的数据结构(this)。从您对print()的调用中,您可以看到您正在加载一个CommentedMap作为根数据结构,而您的普通Python dict当然不知道您可能已经加载并附加到config的任何注释。在

因此,首先看看使用一个最小的程序,它可以加载和转储输入文件,而不必(显式地)更改任何内容。我将使用新的API,并建议您也这样做,尽管您可能也可以用旧API完成这项工作。在新API中,allow_unicode是默认的True。在

import sys
from ruamel.yaml import YAML

yaml = YAML()
yaml.explicit_start = True
yaml.indent(mapping=3)
yaml.preserve_quotes = True  # not necessary for your current input

with open('test.yaml') as fp:
    data = yaml.load(fp)
yaml.dump(data, sys.stdout)

它给出了:

^{pr2}$

这与您的输入test.yaml的不同之处在于缩进一致(即diff -b没有区别)。在


您的代码实际上不起作用(因为缩进而导致语法错误),如果确实如此,则不清楚

ha247::security_firewall::enable: true
ha247::security_firewall::safe_ssh: false
simple_nginx::ssl_ciphers:   

在输出中,也不知道<doamin><domain>中是如何改变的(你在做一些可疑的事情,否则<domain>的值中的键不会神奇地被排序。在

假设为输入test.yaml

 -

# Enable default set of security rules


# Configure firewall
iptables::rules:
 ACCEPT_HTTP:
    port: '80'
 HTTPS:
    port: '443'

ha247::security::enable: true         # EOL Comment
iptables::safe_ssh: false
simple_nginx::ssl_ciphers:
# Configure the website
simple_nginx::vhosts:
    <doamin>:
     backend: php-fpm
     template: php-magento-template
     server_name:
     server_alias: www.
     document_root: /var/www/
     ssl_enabled: true
     ssl_managed_enabled: true
     ssl_managed_name: www.
     force_www: true

以及以下程序:

import sys
from ruamel.yaml import YAML

yaml = YAML()
yaml.explicit_start = True
yaml.indent(mapping=3)
yaml.preserve_quotes = True  # not necessary for your current input

with open('test.yaml') as fp:
    data = yaml.load(fp)


key_map = {
    'iptables::rules': ['ha247::firewall_addrule::firewall_multi', None, 200],
    'ha247::security::enable': ['ha247::security_firewall::enable', None],
    'iptables::safe_ssh': ['ha247::security_firewall::safe_ssh', None],
}

for idx, key in enumerate(data):
    if key in key_map:
        key_map[key][1] = idx

rule_number = 200

for key in key_map:
    km_val = key_map[key]
    if km_val[1] is None:  # this is the index in data, if found
        continue
    # pop the value and reinsert it in the right place with the new name
    value = data.pop(key)
    data.insert(km_val[1], km_val[0], value)
    # and move the key related comments
    data.ca._items[km_val[0]] = data.ca._items.pop(key, None)
    if key == 'iptables::rules':
        data[km_val[0]] = xd = {}  # normal dict nor comments preserved
        for rule, rule_value in value.items():
            new_rule = "{} {}".format(rule_number, rule)
            rule_number += 1
            xd[new_rule] = nr = {}
            nr['action'] = 'accept'
            for b_key, b_value in rule_value.items():
                b_key = b_key.replace('target', 'action')
                nr[b_key] = b_value.lower() if isinstance(b_value, str) else b_value


yaml.dump(data, sys.stdout)

你会得到:

 -

# Enable default set of security rules


# Configure firewall
ha247::firewall_addrule::firewall_multi:
   200 ACCEPT_HTTP:
      action: accept
      port: '80'
   201 HTTPS:
      action: accept
      port: '443'

ha247::security_firewall::enable: true # EOL Comment
ha247::security_firewall::safe_ssh: false
simple_nginx::ssl_ciphers:
# Configure the website
simple_nginx::vhosts:
   <doamin>:
      backend: php-fpm
      template: php-magento-template
      server_name:
      server_alias: www.
      document_root: /var/www/
      ssl_enabled: true
      ssl_managed_enabled: true
      ssl_managed_name: www.
      force_www: true

这应该是一个良好的基础开始。在

请注意,我使用了.format(),而不是老式的%格式。我也只使用小写b_value如果它是一个字符串,那么你的代码会把一个整数转换成一个字符串,这将导致你的输出中没有引号开头。在

相关问题 更多 >