Perhaps the number of places using AWS for Web services etc. is increasing. And, as is well known, you know that AWS also exposes console commands and APIs that can be controlled by libraries in various languages.
Recently, at the startup I work for, for example, when I launch a new instance, there is a procedure to put some instance in the security group, but I want to automate this! Because it's annoying and I forget! That's why I wrote the script in Python.
So, using the Python library Boto, it's easier to launch these instances and add them to security groups. So I would like to give you a brief overview of this Boto library.
Let's issue an Auth key for AWS. Ask them to issue a Key while following the help procedure below.
First of all, let's connect to AWS using Boto. In my case, I wrote as follows.
connection = boto.ec2.connect_to_region(
REGION,
aws_access_key_id=YOUR_ACCESS_KEY,
aws_secret_access_key=YOUR_SECRET_KEY)
One of the things I'm a little addicted to is how to specify the region
. When specifying region
, it is necessary to specify, for example, ʻap-northeast-1`.
Also, if you use connect_to_region
, the instance that will be the entrance to the connection will be issued. Future operations are basically done from here.
For example, let's get a list of currently existing security groups.
security = connection.get_all_security_groups(groupnames=['foo', 'bar'])
By doing this, you can get each security group. I haven't looked into it in detail, but if you just specify it with groupnames
, an instance will be issued to connect to each security group. For example, if you want to use the first group, it will look like the one below.
security[0].authorize(
ip_protocol="tcp",
from_ports=ps[1],
to_port=ps[1],
cidr_ip="YOUR.IP/32")
By the way, it's easy to forget that if you don't add / 32
etc. when you specify cidr_ip
, an error will be returned. Also, if the corresponding IP already exists in the security group, an error will be returned. Therefore, you need to try
as shown below.
try:
# do it
except EC2ResponseError, e:
if e.status == 400:
print("No Problem!!")
else:
raise e
By the way, if dry_run
succeeds, it seems that the status code of 412
is returned.
Automation has come to the fore as a recent keyword. Also, if you are a venture company, you may be using AWS in anticipation of sudden scale. However, it is troublesome to hit AWS one by one. But thankfully, AWS has a lot of APIs like this. Previously, I also set up an instance.
If you use such a library and make the usual procedure into one command, AWS business will be accelerated. Why don't you try one in your own language?
Recommended Posts