Amanda Torres commited on
Commit
1d97dbc
·
0 Parent(s):

initial commit

Browse files
Files changed (2) hide show
  1. ec2_manager.py +149 -0
  2. instance_config.py +66 -0
ec2_manager.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ EC2 Instance Manager
3
+ Automated management of EC2 instances
4
+ """
5
+
6
+ import boto3
7
+ import time
8
+ from datetime import datetime
9
+ from instance_config import INSTANCE_CONFIGS
10
+
11
+ # AWS Credentials
12
+ AWS_ACCESS_KEY_ID = "AKIA2CCBUCJZ5ZNCBEWW"
13
+ AWS_SECRET_ACCESS_KEY = "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"
14
+ AWS_REGION = "us-east-2"
15
+
16
+ class EC2Manager:
17
+ def __init__(self):
18
+ self.ec2_client = boto3.client(
19
+ 'ec2',
20
+ aws_access_key_id=AWS_ACCESS_KEY_ID,
21
+ aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
22
+ region_name=AWS_REGION
23
+ )
24
+ self.ec2_resource = boto3.resource(
25
+ 'ec2',
26
+ aws_access_key_id=AWS_ACCESS_KEY_ID,
27
+ aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
28
+ region_name=AWS_REGION
29
+ )
30
+
31
+ def launch_instance(self, config_name):
32
+ """
33
+ Launch a new EC2 instance based on configuration
34
+ """
35
+ if config_name not in INSTANCE_CONFIGS:
36
+ print(f"Error: Configuration '{config_name}' not found")
37
+ return None
38
+
39
+ config = INSTANCE_CONFIGS[config_name]
40
+
41
+ print(f"Launching instance: {config_name}")
42
+ print(f"AMI: {config['ami_id']}")
43
+ print(f"Type: {config['instance_type']}")
44
+
45
+ try:
46
+ instances = self.ec2_resource.create_instances(
47
+ ImageId=config['ami_id'],
48
+ InstanceType=config['instance_type'],
49
+ KeyName=config['key_name'],
50
+ SecurityGroupIds=config['security_groups'],
51
+ MinCount=1,
52
+ MaxCount=1,
53
+ TagSpecifications=[{
54
+ 'ResourceType': 'instance',
55
+ 'Tags': [
56
+ {'Key': 'Name', 'Value': config['name']},
57
+ {'Key': 'Environment', 'Value': config['environment']}
58
+ ]
59
+ }]
60
+ )
61
+
62
+ instance = instances[0]
63
+ print(f"Instance launched: {instance.id}")
64
+ print("Waiting for instance to be running...")
65
+ instance.wait_until_running()
66
+ instance.reload()
67
+
68
+ print(f"Instance is now running!")
69
+ print(f"Public IP: {instance.public_ip_address}")
70
+ print(f"Private IP: {instance.private_ip_address}")
71
+
72
+ return instance.id
73
+ except Exception as e:
74
+ print(f"Error launching instance: {str(e)}")
75
+ return None
76
+
77
+ def list_instances(self):
78
+ """
79
+ List all EC2 instances
80
+ """
81
+ response = self.ec2_client.describe_instances()
82
+
83
+ print(f"\nEC2 Instances in {AWS_REGION}:")
84
+ for reservation in response['Reservations']:
85
+ for instance in reservation['Instances']:
86
+ name = 'N/A'
87
+ for tag in instance.get('Tags', []):
88
+ if tag['Key'] == 'Name':
89
+ name = tag['Value']
90
+
91
+ state = instance['State']['Name']
92
+ instance_type = instance['InstanceType']
93
+ instance_id = instance['InstanceId']
94
+
95
+ print(f" [{state}] {name} ({instance_id}) - {instance_type}")
96
+
97
+ def stop_instance(self, instance_id):
98
+ """
99
+ Stop a running instance
100
+ """
101
+ print(f"Stopping instance: {instance_id}")
102
+ try:
103
+ self.ec2_client.stop_instances(InstanceIds=[instance_id])
104
+ print(f"Instance {instance_id} is stopping...")
105
+ except Exception as e:
106
+ print(f"Error stopping instance: {str(e)}")
107
+
108
+ def start_instance(self, instance_id):
109
+ """
110
+ Start a stopped instance
111
+ """
112
+ print(f"Starting instance: {instance_id}")
113
+ try:
114
+ self.ec2_client.start_instances(InstanceIds=[instance_id])
115
+ print(f"Instance {instance_id} is starting...")
116
+ except Exception as e:
117
+ print(f"Error starting instance: {str(e)}")
118
+
119
+ def terminate_instance(self, instance_id):
120
+ """
121
+ Terminate an instance
122
+ """
123
+ print(f"Terminating instance: {instance_id}")
124
+ confirm = input("Are you sure? (yes/no): ")
125
+ if confirm.lower() == 'yes':
126
+ try:
127
+ self.ec2_client.terminate_instances(InstanceIds=[instance_id])
128
+ print(f"Instance {instance_id} is terminating...")
129
+ except Exception as e:
130
+ print(f"Error terminating instance: {str(e)}")
131
+ else:
132
+ print("Termination cancelled")
133
+
134
+ def main():
135
+ """
136
+ Main function
137
+ """
138
+
139
+ print("=" * 50)
140
+ print("EC2 Instance Manager")
141
+ print("=" * 50)
142
+
143
+ # List existing instances
144
+
145
+ # Example: Launch a web server
146
+ # manager.launch_instance('web_server')
147
+
148
+ if __name__ == "__main__":
149
+ main()
instance_config.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ EC2 Instance Configuration Templates
3
+ """
4
+
5
+ # Instance configurations for different use cases
6
+ INSTANCE_CONFIGS = {
7
+ 'web_server': {
8
+ 'name': 'WebServer-Production',
9
+ 'ami_id': 'ami-0c55b159cbfafe1f0', # Amazon Linux 2 AMI
10
+ 'instance_type': 't3.medium',
11
+ 'key_name': 'production-key',
12
+ 'security_groups': ['sg-0123456789abcdef0'],
13
+ 'environment': 'production'
14
+ },
15
+
16
+ 'database': {
17
+ 'name': 'Database-MySQL',
18
+ 'ami_id': 'ami-0c55b159cbfafe1f0',
19
+ 'instance_type': 't3.large',
20
+ 'key_name': 'production-key',
21
+ 'security_groups': ['sg-0123456789abcdef1'],
22
+ 'environment': 'production'
23
+ },
24
+
25
+ 'dev_server': {
26
+ 'name': 'DevServer-Testing',
27
+ 'ami_id': 'ami-0c55b159cbfafe1f0',
28
+ 'instance_type': 't3.small',
29
+ 'key_name': 'dev-key',
30
+ 'security_groups': ['sg-0123456789abcdef2'],
31
+ 'environment': 'development'
32
+ },
33
+
34
+ 'worker': {
35
+ 'name': 'Worker-Node',
36
+ 'ami_id': 'ami-0c55b159cbfafe1f0',
37
+ 'instance_type': 't3.micro',
38
+ 'key_name': 'worker-key',
39
+ 'security_groups': ['sg-0123456789abcdef3'],
40
+ 'environment': 'production'
41
+ }
42
+ }
43
+
44
+ # User data scripts for instance initialization
45
+ USER_DATA_SCRIPTS = {
46
+ 'web_server': """#!/bin/bash
47
+ yum update -y
48
+ yum install -y httpd
49
+ systemctl start httpd
50
+ systemctl enable httpd
51
+ echo "<h1>Web Server Running</h1>" > /var/www/html/index.html
52
+ """,
53
+
54
+ 'database': """#!/bin/bash
55
+ yum update -y
56
+ yum install -y mysql-server
57
+ systemctl start mysqld
58
+ systemctl enable mysqld
59
+ """,
60
+
61
+ 'worker': """#!/bin/bash
62
+ yum update -y
63
+ yum install -y python3 python3-pip
64
+ pip3 install boto3 celery redis
65
+ """
66
+ }