In the previous post I described some of the design considerations for this script and what modules I use. In this post, we will look at using YAML to collect data and use it in Python in the form of a dictionary. Why YAML? YAML is commonly used as a readable way of storing configuration data and there are modules for Python to read that data.

The YAML file is a very basic one containing these mappings:

outside_interface: outside
aws_service: s3
aws_region: eu-north-1

The three dashes indicate the start of the file and the three dots indicate the end of the file. We have configured what service we are interested in (S3) and in what region (eu-north-1). The outside interface in our Cisco ASA is named outside.

The natural fit to work with mappings in Python is a dictionary. We need to get the data from the file named aws_prefix.yml into a dictionary. To do that, we will use the following code:

def get_yaml_data() -> dict:
    """Gets the interface name, ASA IP address AWS service, and region 
    from the YAML file and returns a dictionary"""
        with open("aws_prefix.yml") as yaml_file:
            yaml_dict = yaml.load(yaml_file, Loader=yaml.FullLoader)
            return yaml_dict
    except IOError as e:

Before we run the code, let’s go through line by line what the code does:

Line 1 defines the function used to get the data. We are using type hints to indicate that the function will return a dictionary.

Line 2-3 is what is known as a docstring. It simply describes what the function does.

Line 4 is the start of a try/except block. We try to open the file named aws_prefix.yml with a file handler of yaml_file. We can then refer to the file as yaml_file.

Line 5 is where we use the yaml.load command to load our yaml_file using the yaml.FullLoader and store the results into yaml_dict.

Line 6 simply returns the dictionary.

Line 7 is for error handling. If the file is not found or can’t be read, an error message is printed and the script exits.

We then run the code to get the YAML data. I will be using iPython for this:

In [3]: yaml_dict = get_yaml_data()

In [4]: yaml_dict
{'outside_interface': 'outside',
 'aws_service': 's3',
 'aws_region': 'eu-north-1',
 'asa_ip': ''}

In [5]: type(yaml_dict)
Out[5]: dict

As you can see, our YAML data is now readily available in a dict. We can then access the service and region in the following manner:

In [6]: yaml_dict["aws_service"]
Out[6]: 's3'

In [7]: yaml_dict["aws_region"]
Out[7]: 'eu-north-1'

That’s all for this time! See you in the next post!

Python Script Pulling AWS IP Prefixes – Part 2
Tagged on:     

One thought on “Python Script Pulling AWS IP Prefixes – Part 2

Leave a Reply

Your email address will not be published. Required fields are marked *