import boto3 import base64 from dotenv import load_dotenv import os load_dotenv() PREFIX = "464979" REGION = "us-east-1" AMI_ID = "ami-0b5eea76982371e91" REPO_URL = "https://git.wmi.amu.edu.pl/s464979/chmury-aws.git" INSTANCE_TYPE = "t2.micro" aws_access_key_id = os.getenv("AWS_ACCESS_KEY_ID") aws_secret_access_key = os.getenv("AWS_SECRET_ACCESS_KEY") aws_session_token = os.getenv("AWS_SESSION_TOKEN") user_data_script = f"""#!/bin/bash sudo yum update -y sudo yum install -y git cd /home/ec2-user git clone {REPO_URL} cd chmury-aws chmod +x webservice ./webservice """ ec2_client = boto3.client( 'ec2', region_name=REGION, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, aws_session_token=aws_session_token, ) elbv2 = boto3.client( 'elbv2', region_name=REGION, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, aws_session_token=aws_session_token, ) autoscaling = boto3.client( 'autoscaling', region_name=REGION, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, aws_session_token=aws_session_token, ) cloudwatch = boto3.client( 'cloudwatch', region_name=REGION, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, aws_session_token=aws_session_token, ) vpc_cidr = '10.0.0.0/16' vpc_response = ec2_client.create_vpc(CidrBlock=vpc_cidr) vpc_id = vpc_response['Vpc']['VpcId'] ec2_client.modify_vpc_attribute(VpcId=vpc_id, EnableDnsSupport={'Value': True}) ec2_client.modify_vpc_attribute(VpcId=vpc_id, EnableDnsHostnames={'Value': True}) ec2_client.create_tags(Resources=[vpc_id], Tags=[{'Key': 'Name', 'Value': PREFIX + '-vpc'}]) ig_response = ec2_client.create_internet_gateway() ig_id = ig_response['InternetGateway']['InternetGatewayId'] ec2_client.attach_internet_gateway(InternetGatewayId=ig_id, VpcId=vpc_id) subnet_cidr = '10.0.1.0/24' subnet_response = ec2_client.create_subnet(CidrBlock=subnet_cidr, VpcId=vpc_id) subnet_id = subnet_response['Subnet']['SubnetId'] ec2_client.modify_subnet_attribute(SubnetId=subnet_id, MapPublicIpOnLaunch={'Value': True}) ec2_client.create_tags(Resources=[subnet_id], Tags=[{'Key': 'Name', 'Value': PREFIX + '-subnet'}]) rt_response = ec2_client.create_route_table(VpcId=vpc_id) rt_id = rt_response['RouteTable']['RouteTableId'] ec2_client.create_route(RouteTableId=rt_id, DestinationCidrBlock='0.0.0.0/0', GatewayId=ig_id) ec2_client.associate_route_table(RouteTableId=rt_id, SubnetId=subnet_id) key_pair = ec2_client.create_key_pair(KeyName=PREFIX + '-key', KeyType='ed25519') sg_response = ec2_client.create_security_group( Description=PREFIX + '-sg', GroupName=PREFIX + '-sg', VpcId=vpc_id ) sg_id = sg_response['GroupId'] ec2_client.authorize_security_group_ingress( GroupId=sg_id, IpPermissions=[{ 'IpProtocol': 'tcp', 'FromPort': 8080, 'ToPort': 8080, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}] }] ) tg_response = elbv2.create_target_group( Name=PREFIX + '-TargetGroup', Protocol='TCP', Port=8080, VpcId=vpc_id, TargetType='instance', IpAddressType='ipv4', ) tg_arn = tg_response['TargetGroups'][0]['TargetGroupArn'] alloc_response = ec2_client.allocate_address(Domain='vpc') allocation_id = alloc_response['AllocationId'] nlb_response = elbv2.create_load_balancer( Name=PREFIX + '-LoadBalancer', SubnetMappings=[{'SubnetId': subnet_id, 'AllocationId': allocation_id}], Scheme='internet-facing', Type='network', IpAddressType='ipv4', ) lb_arn = nlb_response['LoadBalancers'][0]['LoadBalancerArn'] lb_dns = nlb_response['LoadBalancers'][0]['DNSName'] elbv2.create_listener( LoadBalancerArn=lb_arn, Protocol='TCP', Port=8080, DefaultActions=[{ 'Type': 'forward', 'TargetGroupArn': tg_arn, }], ) lt_response = ec2_client.create_launch_template( LaunchTemplateName=PREFIX + '-LT', LaunchTemplateData={ 'ImageId': AMI_ID, 'InstanceType': INSTANCE_TYPE, 'KeyName': PREFIX + '-key', 'SecurityGroupIds': [sg_id], 'UserData': base64.b64encode(user_data_script.encode('utf-8')).decode('utf-8'), } ) asg_name = PREFIX + '-ASG' autoscaling.create_auto_scaling_group( AutoScalingGroupName=asg_name, LaunchTemplate={ 'LaunchTemplateId': lt_response['LaunchTemplate']['LaunchTemplateId'], 'Version': '$Latest' }, MinSize=2, MaxSize=5, DesiredCapacity=2, VPCZoneIdentifier=subnet_id, TargetGroupARNs=[tg_arn], HealthCheckType='EC2', HealthCheckGracePeriod=90, Tags=[ { 'Key': 'Name', 'Value': PREFIX + '-instance', 'PropagateAtLaunch': True } ] ) scale_out_response = autoscaling.put_scaling_policy( AutoScalingGroupName=asg_name, PolicyName= PREFIX + '-ScaleOutPolicy', PolicyType='SimpleScaling', AdjustmentType='ChangeInCapacity', ScalingAdjustment=1, Cooldown=180 ) scale_out_policy_arn = scale_out_response['PolicyARN'] cloudwatch.put_metric_alarm( AlarmName= PREFIX + '-HighCPU-Alarm', ComparisonOperator='GreaterThanThreshold', EvaluationPeriods=2, MetricName='CPUUtilization', Namespace='AWS/EC2', Period=60, Statistic='Average', Threshold=30.0, # Zmienić jeśli potrzeba późniejszego skalowania ActionsEnabled=True, AlarmActions=[scale_out_policy_arn], Dimensions=[ { 'Name': 'AutoScalingGroupName', 'Value': asg_name }, ], Unit='Percent' ) print(f"Load Balancer DNS: {lb_dns}")