I am trying to create a Python script that will convert our IPtables config to firewall multi within a YAML file. I originally was using pyyaml, however, later found that this removes all comments which I will need to keep, I found that ruamel.yaml can be used to keep comments, however, I am struggling to get this to work.
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)
The input file (test.yaml)
---
# Enable default set of security rules
# Configure firewall
iptables::rules:
ACCEPT_HTTP:
port: '80'
HTTPS:
port: '443'
# 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
The output of result.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
This is where the problem lies, as you can see it has changed all the formatting and deleted comments which we need to keep, another issue is it has removed the three hyphens at the top which will for configuration manager unable to read the file.