Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import boto3
- import time
- import subprocess #to change file permission
- from botocore.exceptions import ClientError
- student_id = "student-id-231231"
- try:
- ec2 = boto3.client('ec2')
- # response = ec2.create_key_pair(KeyName=student_id+"-key")
- # pemfile = open(student_id+"-key.pem", "w")
- # pemfile.write(response['KeyMaterial'])
- # pemfile.close()
- # subprocess.call(['chmod', '0400', student_id+"-key.pem"])
- ec2i = boto3.resource('ec2', region_name="ap-southeast-2")
- #create instance 1
- instance1 = ec2i.create_instances(
- ImageId='ami-d38a4ab1',
- MinCount=1,
- MaxCount=1,
- KeyName=student_id+"-key",
- InstanceType="t2.micro"
- )
- id1=instance1[0].id
- print id1
- #create instance 2
- instance2 = ec2i.create_instances(
- ImageId='ami-d38a4ab1',
- MinCount=1,
- MaxCount=1,
- KeyName=student_id+"-key",
- InstanceType="t2.micro"
- )
- id2=instance2[0].id
- print id2
- client = boto3.client('elbv2')
- #create load balancer
- response = client.create_load_balancer(
- Name='Load-balancer-123',
- Subnets=['subnet-00cee76c9e3367183','subnet-02d93083aec47cb01'],
- SecurityGroups=['sg-09769fcf4b6ded830'],
- Scheme='internet-facing',
- )
- loadarn = response['LoadBalancers'][0]['LoadBalancerArn']
- #create target group
- response = client.create_target_group(
- Name='my-target-group-5',
- Protocol='HTTP',
- Port=80,
- VpcId='vpc-050bd4e7c7677cc76',
- TargetType='instance'
- )
- arn = response['TargetGroups'][0]['TargetGroupArn']
- print arn
- time.sleep(18)#wait for instances to get initiated
- #register targets with target group
- response = client.register_targets(
- TargetGroupArn=arn,
- Targets=[
- {
- 'Id': id1,
- 'Port': 80
- },
- {
- 'Id': id2,
- 'Port': 80
- },
- ]
- )
- #create listener with given config
- response = client.create_listener(
- LoadBalancerArn=loadarn,
- Protocol='HTTP',
- Port=80,
- DefaultActions=[
- {
- 'Type': 'forward',
- 'TargetGroupArn': arn,
- },
- ]
- )
- print("Done")
- except ClientError as e:
- print(e)
Add Comment
Please, Sign In to add comment