-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_ec2_instance_provisioning.py
More file actions
134 lines (120 loc) · 5.05 KB
/
Copy path02_ec2_instance_provisioning.py
File metadata and controls
134 lines (120 loc) · 5.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# Personal License Agreement
# Copyright Notice
#
# © 2026 Voltaire Bazurto Blacio. All rights reserved.
# License Terms
#
# Ownership: All code contained in this portfolio is the sole property of Voltaire Bazurto Blacio and is hereby copyrighted by me.
#
# Permitted Use: Others are welcome to view and study the code for personal, educational, or non-commercial purposes. You may share insights or information about the code, but you cannot use it for any commercial products, either as-is or in a derivative form.
#
# Restrictions: The code may not be used, reproduced, or distributed for commercial purposes under any circumstances without my explicit written permission.
#
# Rights Reserved: I reserve the right to use the code, or any future versions thereof, for my own purposes in any way I choose, including but not limited to the development of future commercial derivative works under my name or personal brand.
#
# Disclaimer: The code is provided "as is" without warranty of any kind, either express or implied. I am not responsible for any damages resulting from the use of this code.
#
# By accessing this portfolio, you agree to abide by these terms.
import boto3
import base64
import sys
if len(sys.argv) > 2:
EC2_SUBNET_ID = sys.argv[1]
EC2_SECURITY_GROUP_ID = sys.argv[2]
else:
print(f'A subnet ID and a security group ID are required to be used for the EC2 instance.\nUsage: script.py <subnet-id> <security-group-id>\n')
exit(1)
EC2_INSTANCE_ID = 'hr-recruit-app-demo-aws'
AWS_REGION = 'us-east-1'
AMI_ID = 'ami-0f3caa1cf4417e51b'
EC2_INSTANCE_TYPE = 't3.micro'
DEFAULT_SECURITY_GROUP_ID = '' #Use your security group id here
if EC2_SECURITY_GROUP_ID:
DEFAULT_SECURITY_GROUP_ID = EC2_SECURITY_GROUP_ID
def create_hr_recruit_app_instance(ec2_client):
user_script = """#!/bin/bash
# Update packages and install Docker
dnf update -y
# Install Docker and other tools
dnf install -y docker
dnf install -y htop
dnf install -y wget
# Start Docker
systemctl start docker
systemctl enable docker
# Add ec2-user to docker group so you don't need sudo (optional)
usermod -a -G docker ec2-user
# Create docker env file
touch /home/ec2-user/config.env
echo "JDBC_DATABASE_URL=jdbc:postgresql://<docker-host-ip-gateway>:<db-port>/hr_recruit_app\n
DATABASE_USER=<db-user>\n
DATABASE_PASSWORD=<db-pwd>\n
DATABASE_SCHEMA=vbazurtob_portfolio\n
" >> /home/ec2-user/config.env
# Pull and run your Java application
docker run -d -p 80:8080 --env-file /home/ec2-user/config.env vbazurtob/hrrecruitapp:latest
"""
# Encode user data
user_data_encoded = base64.b64encode(user_script.encode('utf-8')).decode('utf-8')
# I add an Ipv6 address to instance automatically
ec2_client.modify_subnet_attribute(
SubnetId=EC2_SUBNET_ID,
AssignIpv6AddressOnCreation={ 'Value': True }
)
result = ec2_client.run_instances(
ImageId=AMI_ID,
InstanceType=EC2_INSTANCE_TYPE,
BlockDeviceMappings=[
{
'DeviceName': '/dev/xvda',
'Ebs': {
'VolumeSize': 8,
'VolumeType': 'gp3',
'DeleteOnTermination': True,
'Encrypted': False,
}
}
],
MinCount=1,
MaxCount=1,
UserData=user_data_encoded,
SubnetId=EC2_SUBNET_ID,
TagSpecifications=[
{
'ResourceType': 'instance',
'Tags': [{'Key': 'Name', 'Value': EC2_INSTANCE_ID}],
}
],
SecurityGroupIds=[
DEFAULT_SECURITY_GROUP_ID
],
)
print(f"Launching Instance: {result['Instances'][0]['InstanceId']}\n")
return result
def check_if_running(instance_name):
# Filter for instances with the specific Name tag and that are NOT terminated
instances = ec2.instances.filter(
Filters=[
{'Name': 'tag:Name', 'Values': [instance_name]},
{'Name': 'instance-state-name', 'Values': ['running', 'pending']}
]
)
for instance in instances:
print(f"Instance {instance.id} is already {instance.state['Name']}.")
return instance.id
print("No running instance found with that name.")
return None
if __name__ == "__main__":
ec2 = boto3.client('ec2', region_name=AWS_REGION)
result_launch = create_hr_recruit_app_instance(ec2)
created_instance_id = result_launch['Instances'][0]['InstanceId']
print(f"Waiting for {created_instance_id} to reach 'running' state...\n")
waiter = ec2.get_waiter('instance_running')
waiter.wait(InstanceIds=[created_instance_id])
print(f"Instance is now running!\n")
# Get instance details
instance_details = ec2.describe_instances(InstanceIds=[created_instance_id])
public_ip = instance_details['Reservations'][0]['Instances'][0].get('PublicIpAddress')
private_ip = instance_details['Reservations'][0]['Instances'][0]['PrivateIpAddress']
print(f"Public IP: {public_ip}\n")
print(f"Private IP: {private_ip}\n")