aws-chmurki/main.py
2023-01-26 19:40:53 +01:00

129 lines
3.3 KiB
Python

from aws_cli import aws_access_key_id, aws_secret_access_key, aws_session_token, DEFAULT_VPC
from user_data import user_data
import boto3, time
PREFIX = 'peachy'
if __name__ == '__main__':
ec2 = boto3.resource(
'ec2',
region_name='us-east-1',
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key,
aws_session_token=aws_session_token,
)
#TODO key pair
key_pair = ec2.create_key_pair(
KeyName=PREFIX + '_key',
KeyType='ed25519',
KeyFormat='pem',
)
#TODO security group
security_group = ec2.create_security_group(
Description=PREFIX + '_group',
GroupName=PREFIX + '_group',
VpcId=DEFAULT_VPC,
)
inbound_rules = security_group.authorize_ingress(
GroupId=security_group.group_id,
CidrIp='0.0.0.0/0',
IpProtocol='tcp',
FromPort=80,
ToPort=80,
)
#TODO instancja EC2
instance1, instance2 = ec2.create_instances(
ImageId='ami-0b5eea76982371e91',
MinCount=2,
MaxCount=2,
InstanceType='t2.micro',
KeyName=key_pair.name,
UserData=user_data,
SecurityGroups=[security_group.group_name],
)
while True:
time.sleep(1)
instance1 = ec2.Instance(instance1.id)
instance2 = ec2.Instance(instance2.id)
if instance1.state['Code'] == 16 and instance2.state['Code'] == 16:
break
#TODO target group
elbv2 = boto3.client(
'elbv2',
region_name='us-east-1',
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key,
aws_session_token=aws_session_token,
)
target_group = elbv2.create_target_group(
Name=PREFIX + '-TargetGroup',
Protocol='TCP',
Port=80,
VpcId=DEFAULT_VPC,
TargetType='instance',
IpAddressType='ipv4',
)
registered_targets = elbv2.register_targets(
TargetGroupArn=target_group['TargetGroups'][0]['TargetGroupArn'],
Targets=[
{
'Id': instance1.id,
'Port': 80,
},
{
'Id': instance2.id,
'Port': 80,
},
]
)
#TODO elastic IP
ec2_client = boto3.client(
'ec2',
region_name='us-east-1',
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key,
aws_session_token=aws_session_token,
)
allocation = ec2_client.allocate_address(
Domain='vpc'
)
#TODO load balancer
load_balancer = elbv2.create_load_balancer(
Name=PREFIX + '-LoadBalancer',
SubnetMappings=[
{
'SubnetId': instance1.subnet_id,
'AllocationId': allocation['AllocationId'],
},
],
Scheme='internet-facing',
Type='network',
IpAddressType='ipv4',
)
listener = elbv2.create_listener(
LoadBalancerArn=load_balancer['LoadBalancers'][0]['LoadBalancerArn'],
Protocol='TCP',
Port=80,
DefaultActions=[
{
'Type': 'forward',
'TargetGroupArn': target_group['TargetGroups'][0]['TargetGroupArn'],
},
],
)
print(f'{allocation["PublicIp"]}:80')