Skip to content

Instantly share code, notes, and snippets.

@mda590
Last active April 1, 2019 10:04
Show Gist options
  • Save mda590/fd86db68b85a9c6a830193f8534623cd to your computer and use it in GitHub Desktop.
Save mda590/fd86db68b85a9c6a830193f8534623cd to your computer and use it in GitHub Desktop.

This shows a config file which can be parsed with Python's configparser. Rules.py will read this config file and construct a JSON object with IP addresses dynamically.

rules.conf

[domain1-rule]
Name = domain1-rule
RuleType = Forward
DomainName = domain1
Ips = 10.10.10.10, 10.10.10.11, 10.10.10.12
Port = 53

[domain2-rule]
Name = domain2-rule
RuleType = Forward
DomainName = domain2
Ips = 10.10.10.10, 10.10.10.11
Port = 53

[domain3-rile]
Name = domain3-rule
RuleType = Forward
DomainName = domain3
Ips = 10.10.10.13, 10.10.10.14, 10.10.10.15
Port = 8500

Rules.py

import boto3
import configparser

def test_function(config):
    print(config)

rules_config = configparser.ConfigParser()
rules_config.read('rules.conf')

domains = rules_config.sections()

for domain in domains:
    name = rules_config.get(domain, 'Name')
    rule_type = rules_config.get(domain, 'RuleType')
    rule_domain = rules_config.get(domain, 'DomainName')
    ips = rules_config.get(domain, 'Ips')
    port = rules_config.get(domain, 'Port')

    print("Adding rule: {} - {} - {}".format(name, rule_type, rule_domain))

    test_function(
        config={
            'TargetIps': [{'Ip': ip, 'Port': port} for ip in ips.split(", ")]
        }
    )

Output

Below is what you should get when you run the above Python script:

Adding rule: domain1-rule - Forward - domain1
{'TargetIps': [{'Ip': '10.10.10.10', 'Port': '53'}, {'Ip': '10.10.10.11', 'Port': '53'}, {'Ip': '10.10.10.12', 'Port': '53'}]}
Adding rule: domain2-rule - Forward - domain2
{'TargetIps': [{'Ip': '10.10.10.10', 'Port': '53'}, {'Ip': '10.10.10.11', 'Port': '53'}]}
Adding rule: domain3-rule - Forward - domain3
{'TargetIps': [{'Ip': '10.10.10.13', 'Port': '8500'}, {'Ip': '10.10.10.14', 'Port': '8500'}, {'Ip': '10.10.10.15', 'Port': '8500'}]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment