8000 ec2 boto3 · techiescamp/python-for-devops@30881a2 · GitHub
[go: up one dir, main page]

Skip to content

Commit 30881a2

Browse files
committed
ec2 boto3
1 parent 5eea9e0 commit 30881a2

File tree

3 files changed

+184
-1
lines changed

3 files changed

+184
-1
lines changed

boto3/create-instance.py

Lines changed: 136 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,139 @@
11
#! /bin/python3
22

3-
import boto3
3+
import boto3, os
4+
from botocore.exceptions import ClientError
5+
6+
vpc_id = "vpc-0d42bf2f27be967ff"
7+
subnet_id = "subnet-00b5ede5e160caa59"
8+
ami_id = "ami-0ddf424f81ddb0720"
9+
instance_type = "t2.small"
10+
app_name = "flask"
11+
12+
create_key = True
13+
key_name = "dev-key"
14+
key_location = "/Users/bibinwilson/.ssh/devops-class/"
15+
16+
ec2 = boto3.client('ec2')
17+
18+
def createSecurityGroup():
19+
global security_group_id
20+
try:
21+
response = ec2.create_security_group(GroupName=app_name + "-sg",
22+
Description=app_name + "Security Group",
23+
VpcId=vpc_id,
24+
TagSpecifications=[
25+
{
26+
'ResourceType': 'security-group',
27+
'Tags': [
28+
{
29+
'Key': 'Name',
30+
'Value': app_name + "-sg"
31+
}
32+
]
33+
},
34+
],
35+
)
36+
security_group_id = response['GroupId']
37+
print('Security Group Created %s in vpc %s.' % (security_group_id, vpc_id))
38+
39+
data = ec2.authorize_security_group_ingress(
40+
GroupId=security_group_id,
41+
IpPermissions=[
42+
{
43+
'IpProtocol': 'tcp',
44+
'FromPort': 80,
45+
'ToPort': 80,
46+
'IpRanges': [
47+
{
48+
'CidrIp': '0.0.0.0/0'
49+
}
50+
]
51+
},
52+
{
53+
'IpProtocol': 'tcp',
54+
'FromPort': 22,
55+
'ToPort': 22,
56+
'IpRanges': [
57+
{
58+
'CidrIp': '0.0.0.0/0'
59+
}
60+
]
61+
}
62+
])
63+
print('Ingress Successfully Set %s' % data)
64+
except ClientError as e:
65+
print(e)
66+
67+
def createKeyPair():
68+
69+
try:
70+
key_pair = ec2.create_key_pair(KeyName=key_name)
71+
72+
ssh_private_key = key_pair["KeyMaterial"]
73+
74+
with os.fdopen(os.open(key_location + "app-key.pem", os.O_WRONLY | os.O_CREAT, 0o400), "w+") as handle:
75+
handle.write(ssh_private_key)
76+
except ClientError as e:
77+
print(e)
78+
79+
def createInstance():
80+
blockDeviceMappings = [
81+
{
82+
'DeviceName': "/dev/sda1",
83+
'Ebs': {
84+
'DeleteOnTermination': True,
85+
'VolumeSize': 20,
86+
'VolumeType': 'gp2'
87+
}
88+
},
89+
]
90+
91+
instances = ec2.run_instances(
92+
ImageId= ami_id,
93+
MinCount=1,
94+
MaxCount=1,
95+
InstanceType=instance_type,
96+
SubnetId=subnet_id,
97+
KeyName=key_name,
98+
SecurityGroupIds=[security_group_id],
99+
BlockDeviceMappings=blockDeviceMappings,
100+
TagSpecifications=[
101+
{
102+
'ResourceType': 'instance',
103+
'Tags': [
104+
{
105+
'Key': 'Name',
106+
'Value': app_name + "-server"
107+
}
108+
]
109+
},
110+
{
111+
'ResourceType': 'volume',
112+
'Tags': [
113+
{
114+
'Key': 'Name',
115+
'Value': app_name + "-root-disk"
116+
}
117+
]
118+
}
119+
]
120+
)
121+
122+
print(instances["Instances"][0]["InstanceId"])
123+
124+
125+
if __name__ == "__main__":
126+
127+
createSecurityGroup()
128+
129+
if create_key == True:
130+
createKeyPair();
131+
132+
createInstance()
133+
134+
135+
# References
136+
# [1] https://codeflex.co/boto3-create-ec2-with-tags/
137+
# [2] https://www.learnaws.org/2020/12/16/aws-ec2-boto3-ultimate-guide/
138+
# [3] https://arjunmohnot.medium.com/aws-ec2-management-with-python-and-boto-3-59d849f1f58f
4139

database/postgresql.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import psycopg2
2+
3+
try:
4+
connection = psycopg2.connect(database="dvdrental",
5+
host="192.168.5.5",
6+
user="postgres",
7+
password="myPassword",
8+
port="5432")
9+
cursor = connection.cursor()
10+
sql_query = "select * from actor"
11+
12+
cursor.execute(sql_query)
13+
print("Selecting rows from mobile table using cursor.fetchall")
14+
actor_records = cursor.fetchall()
15+
16+
print("Print each row and it's columns values")
17+
for row in actor_records:
18+
print("Id = ", row[0], )
19+
print("Model = ", row[1])
20+
print("Price = ", row[2], "\n")
21+
22+
except (Exception, psycopg2.Error) as error:
23+
print("Error while fetching data from PostgreSQL", error)
24+
25+
finally:
26+
if connection:
27+
cursor.close()
28+
connection.close()
29+
print("PostgreSQL connection is closed")

generic/exception-handling.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import os
2+
import sys
3+
4+
directory = "demodir_"
5+
symbols = "~!@#$%^*()_-+={}[]:>;',</?*-+"
6+
def createDir(dir):
7+
try:
8+
if any(char in symbols for char in directory):
9+
raise ValueError("The directory name contains special characters. Please use only alphabets")
10+
os.mkdir(dir)
11+
except ValueError as ve:
12+
print(ve)
13+
except OSError:
14+
print("Folder already Exist. Plese delte it or try with a differnt name")
15+
createDir(directory)
16+
17+
finally:
18+
with open("directory.log", "a") as myfile:
19+
myfile.write("directory creation attempted at %s" % str(datetime.datetime.now()))

0 commit comments

Comments
 (0)
0