In previous tutorial we installed, configured & tested Python Boto. We learned how to create and run python script from the interpreter. There is a better way to organize your code into modules and packages. Additionally, we will also look at Python classes. First, let's setup a simple structure for our DevOps project.
Up until now we ran our scripts and some arbitrary code using Python interpreter. But what happens when the Python interpreter is closed? All statements & variables defined during the interpreter session are gone...Poof! Naaaaah! Not exactly what you want, right? Well then, meet Python Module.
Python module allows us to define and hold our functions in a file. It is a mechanism to organize related functions / code in one place. As a benefit: We will end up with a well managed code which is easier to read and understand. There is more to a "well managed code", but you get the gist. Additionally, to use the module all we have to do is import the module. That's it.
All sounds great. Now what if we have modules, sub modules and nested sub modules. We need some kind of packaging, right? And therefore to your surprise next we will look at a Python Packaging system.
Python has a very simple packaging system. It is solely based on directory structure and the "init.py" file. So what is "init.py"? Any directory with this file is marked or read as a Python Package. In our case to make the DevOps python package, all we have to do is create a directory called DevOps and add an "init.py" file to it. Simple, right? So, let's create this package now.
At the terminal, create a new folder called "DevOps".
Riteshs-MacBook-Pro-2:~ rpatel$ mkdir DevOps
Next add "init.py" file to the DevOps folder.
#change directory to DevOps and add __init__.py file
Riteshs-MacBook-Pro-2:~ rpatel$ cd DevOps
Riteshs-MacBook-Pro-2:DevOps rpatel$ touch __init__.py
Next, we want to group all aws related code in one place and therefore we will create a sub directory called aws and put another "init.py" file under this directory. If it is a sub-package within the main package, then we will add it's own "init.py" file to the subdirectory. This will mark all subdirectories as sub-packages. With me? So, let's create our sub-package now.
Make a new folder called aws under DevOps and add another "init.py" file to the aws subfolder.
#create a sub folder aws
Riteshs-MacBook-Pro-2:DevOps rpatel$ mkdir aws
Riteshs-MacBook-Pro-2:DevOps rpatel$ cd aws
#create an __init__.py file for the sub folder
Riteshs-MacBook-Pro-2:aws rpatel$ touch __init__.py
And so we have initialized the DevOps project and it should look like below. A bare-bone project.
With the skeleton project in place we are set to go. In the next tutorial I will show how to print detailed information on EC2 instances using Boto EC2. But wait...just listing instances is not enough, right? Well, I will also show you how to start | stop & terminate instance(s).
Project files are located @ github. Fork and enjoy!
See you then.