himanshu208

Untitled

Sep 7th, 2018
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. import boto3
  2. import time
  3. import subprocess #to change file permission
  4. from botocore.exceptions import ClientError
  5. student_id = "student-id-231231"
  6.  
  7. try:
  8. ec2 = boto3.client('ec2')
  9. response = ec2.create_key_pair(KeyName=student_id+"-key")
  10. pemfile = open(student_id+"-key.pem", "w")
  11. pemfile.write(response['KeyMaterial'])
  12. pemfile.close()
  13. subprocess.call(['chmod', '0400', student_id+"-key.pem"])
  14.  
  15.  
  16. ec2i = boto3.resource('ec2', region_name="ap-southeast-2")
  17. #create instance 1
  18. instance1 = ec2i.create_instances(
  19. ImageId='ami-d38a4ab1',
  20. MinCount=1,
  21. MaxCount=1,
  22. KeyName=student_id+"-key",
  23. InstanceType="t2.micro"
  24. )
  25. id1=instance1[0].id
  26. print id1
  27. #create instance 2
  28. instance2 = ec2i.create_instances(
  29. ImageId='ami-d38a4ab1',
  30. MinCount=1,
  31. MaxCount=1,
  32. KeyName=student_id+"-key",
  33. InstanceType="t2.micro"
  34. )
  35. id2=instance2[0].id
  36. print id2
  37.  
  38.  
  39.  
  40. client = boto3.client('elbv2')
  41. #create load balancer
  42. #use your student id here
  43.  
  44. response = client.create_load_balancer(
  45. Name='Load-balancer-123',
  46. Subnets=['subnet-00cee76c9e3367183','subnet-02d93083aec47cb01'],
  47. SecurityGroups=['sg-09769fcf4b6ded830'],
  48. Scheme='internet-facing',
  49.  
  50. )
  51. loadarn = response['LoadBalancers'][0]['LoadBalancerArn']
  52. #create target group
  53. response = client.create_target_group(
  54. Name='my-target-group-5',
  55. Protocol='HTTP',
  56. Port=80,
  57. VpcId='vpc-050bd4e7c7677cc76',
  58. TargetType='instance'
  59. )
  60. arn = response['TargetGroups'][0]['TargetGroupArn']
  61. print arn# for the target group
  62. time.sleep(18)#wait for instances to get initiated
  63. #register targets with target group
  64. response = client.register_targets(
  65. TargetGroupArn=arn,
  66. Targets=[
  67. {
  68. 'Id': id1,
  69. 'Port': 80
  70. },
  71. {
  72. 'Id': id2,
  73. 'Port': 80
  74. },
  75. ]
  76. )
  77. #create listener with given config
  78. response = client.create_listener(
  79. LoadBalancerArn=loadarn,
  80. Protocol='HTTP',
  81. Port=80,
  82. DefaultActions=[
  83. {
  84. 'Type': 'forward',
  85. 'TargetGroupArn': arn,
  86.  
  87. },
  88. ]
  89. )
  90. print("Done")
  91. except ClientError as e:
  92. print(e)
Add Comment
Please, Sign In to add comment