AWS Best Practices: How to Properly Inject Credentials & API Keys Using Boto3

Create secure applications by following nothing more than one of the four tenets of object-oriented programming.

Ali I. Metin
2 min readJun 21, 2021
Photo by FLY:D on Unsplash

A majorly overlooked aspect of productionizing an application is how to secure credentials or API keys. In production environments secrets such as these for connecting to AWS or any other services are handled through injection. This article uses Boto3 and a small pythonic application to showcase this best practice.

An example secrets file

This is the file to be consumed, it is a very simple yaml file mimicking a real-world case where you would get to inject these keys from an another application to your codebase, most common example of this is how Kubernetes distributes the secrets to pods. Even though the above .yaml file has credentials it can also have just as in the same form API Keys or any other data of this nature. In this guiding example we assume that this file has already been injected to the same directory as the below class:

A Pythonic Class for Connecting to AWS

This simple class employs best practices for encapsulation by using private instance variables and private methods. Python, unlike Java, does not provide us with keywords to define access levels but nevertheless with the usage of double underscores it will enforce encapsulation to a degree and will throw Attribute Not Found Errors when someone tries to access the private method or instance variables. The secret method is how you can allow the user of the class to call the private method of the same class by not breaking encapsulation. The .yaml file is parsed with secret consumer method by using pyyaml into a dictionary.

Another very interesting aspect of the code is that inside the class scope once the session is initialized it is associated with a private instance variable so you don’t have to initialize and connect to your account again and again for other related operations like putting some object to your bucket or listing the contents of your bucket. This simplifies the code and makes it avoids extra calls to your cloud vendor.

This line of thinking is very important to avoid any future headaches with your application so next time when you deploy your data-driven applications, secure you API keys and credentials in this way to block malicious intent.

--

--

Ali I. Metin

Data Engineer — MSc Computer Science Birkbeck, UoL — London, UK