himanshu208

Untitled

Sep 6th, 2018
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 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. response = client.create_load_balancer(
  43. Name='Load-balancer-123',
  44. Subnets=['subnet-00cee76c9e3367183','subnet-02d93083aec47cb01'],
  45. SecurityGroups=['sg-09769fcf4b6ded830'],
  46. Scheme='internet-facing',
  47.  
  48. )
  49. loadarn = response['LoadBalancers'][0]['LoadBalancerArn']
  50. #create target group
  51. response = client.create_target_group(
  52. Name='my-target-group-5',
  53. Protocol='HTTP',
  54. Port=80,
  55. VpcId='vpc-050bd4e7c7677cc76',
  56. TargetType='instance'
  57. )
  58. arn = response['TargetGroups'][0]['TargetGroupArn']
  59. print arn
  60. time.sleep(18)#wait for instances to get initiated
  61. #register targets with target group
  62. response = client.register_targets(
  63. TargetGroupArn=arn,
  64. Targets=[
  65. {
  66. 'Id': id1,
  67. 'Port': 80
  68. },
  69. {
  70. 'Id': id2,
  71. 'Port': 80
  72. },
  73. ]
  74. )
  75. #create listener with given config
  76. response = client.create_listener(
  77. LoadBalancerArn=loadarn,
  78. Protocol='HTTP',
  79. Port=80,
  80. DefaultActions=[
  81. {
  82. 'Type': 'forward',
  83. 'TargetGroupArn': arn,
  84.  
  85. },
  86. ]
  87. )
  88. print("Done")
  89. except ClientError as e:
  90. print(e)
Add Comment
Please, Sign In to add comment