You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

237 lines
9.0 KiB

  1. import boto3
  2. from botocore.exceptions import ClientError
  3. ################################################################################################
  4. #
  5. # Configuration Parameters
  6. #
  7. ################################################################################################
  8. # !!!!!!!! You cannot use RDS in AWS Ecucate Account !!!!!!!!
  9. # place your credentials in ~/.aws/credentials, as mentioned in AWS Educate Classroom,
  10. # Account Details, AWC CLI -> Show (Copy and paste the following into ~/.aws/credentials)
  11. # changed to use us-east, to be able to use AWS Educate Classroom
  12. region = 'us-east-1'
  13. availabilityZone = 'us-east-1a'
  14. # region = 'eu-central-1'
  15. # availabilityZone = 'eu-central-1b'
  16. # AMI ID of Amazon Linux 2 image 64-bit x86 in us-east-1 (can be retrieved, e.g., at
  17. # https://console.aws.amazon.com/ec2/v2/home?region=us-east-1#LaunchInstanceWizard:)
  18. imageId = 'ami-0d5eff06f840b45e9'
  19. # for eu-central-1, AMI ID of Amazon Linux 2 would be:
  20. # imageId = 'ami-0cc293023f983ed53'
  21. # potentially change instanceType to t2.micro for "free tier" if using a regular account
  22. # for production, t3.nano seams better
  23. instanceType = 't2.nano'
  24. keyName = 'srieger-pub'
  25. ################################################################################################
  26. #
  27. # boto3 clients and resources (dependencies)
  28. #
  29. ################################################################################################
  30. client = boto3.setup_default_session(region_name=region)
  31. ec2Client = boto3.client("ec2")
  32. ec2Resource = boto3.resource('ec2')
  33. rdsClient = boto3.client("rds")
  34. # if you only have one VPC, vpc_id can be retrieved using:
  35. response = ec2Client.describe_vpcs()
  36. vpc_id = response.get('Vpcs', [{}])[0].get('VpcId', '')
  37. # if you have more than one VPC, vpc_id should be specified, and code
  38. # top retrieve VPC id below needs to be commented out
  39. # vpc_id = 'vpc-eedd4187'
  40. subnet_id = ec2Client.describe_subnets(
  41. Filters=[
  42. {
  43. 'Name': 'availability-zone', 'Values': [availabilityZone]
  44. }
  45. ])['Subnets'][0]['SubnetId']
  46. ################################################################################################
  47. #
  48. # boto3 code to deploy the application
  49. #
  50. ################################################################################################
  51. print("Deleting old instance...")
  52. print("------------------------------------")
  53. response = ec2Client.describe_instances(Filters=[{'Name': 'tag-key', 'Values': ['tug-of-war-rds']}])
  54. print(response)
  55. reservations = response['Reservations']
  56. for reservation in reservations:
  57. for instance in reservation['Instances']:
  58. if instance['State']['Name'] == "running" or instance['State']['Name'] == "pending":
  59. response = ec2Client.terminate_instances(InstanceIds=[instance['InstanceId']])
  60. print(response)
  61. instanceToTerminate = ec2Resource.Instance(instance['InstanceId'])
  62. instanceToTerminate.wait_until_terminated()
  63. print("Deleting old DB instance...")
  64. print("------------------------------------")
  65. try:
  66. response = rdsClient.delete_db_instance(
  67. DBInstanceIdentifier='tug-of-war-rds-db1',
  68. SkipFinalSnapshot=True,
  69. DeleteAutomatedBackups=True
  70. )
  71. except ClientError as e:
  72. print(e)
  73. waiter = rdsClient.get_waiter('db_instance_deleted')
  74. waiter.wait(DBInstanceIdentifier='tug-of-war-rds-db1')
  75. #time.sleep(5)
  76. print("Delete old security group...")
  77. print("------------------------------------")
  78. try:
  79. response = ec2Client.delete_security_group(GroupName='tug-of-war-rds')
  80. except ClientError as e:
  81. print(e)
  82. print("Create security group...")
  83. print("------------------------------------")
  84. try:
  85. response = ec2Client.create_security_group(GroupName='tug-of-war-rds',
  86. Description='tug-of-war-rds',
  87. VpcId=vpc_id)
  88. security_group_id = response['GroupId']
  89. print('Security Group Created %s in vpc %s.' % (security_group_id, vpc_id))
  90. data = ec2Client.authorize_security_group_ingress(
  91. GroupId=security_group_id,
  92. IpPermissions=[
  93. {'IpProtocol': 'tcp',
  94. 'FromPort': 3306,
  95. 'ToPort': 3306,
  96. 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
  97. {'IpProtocol': 'tcp',
  98. 'FromPort': 22,
  99. 'ToPort': 22,
  100. 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
  101. {'IpProtocol': 'tcp',
  102. 'FromPort': 80,
  103. 'ToPort': 80,
  104. 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
  105. {'IpProtocol': 'tcp',
  106. 'FromPort': 443,
  107. 'ToPort': 443,
  108. 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}
  109. ])
  110. print('Ingress Successfully Set %s' % data)
  111. except ClientError as e:
  112. print(e)
  113. print("Running new DB instance...")
  114. print("------------------------------------")
  115. response = rdsClient.create_db_instance(DBInstanceIdentifier="tug-of-war-rds-db1",
  116. AllocatedStorage=20,
  117. DBName='cloud_tug_of_war',
  118. # Engine='mariadb',
  119. Engine='mysql',
  120. # General purpose SSD
  121. StorageType='gp2',
  122. #StorageEncrypted=True,
  123. AutoMinorVersionUpgrade=True,
  124. # Set this to true later?
  125. MultiAZ=False,
  126. MasterUsername='cloud_tug_of_war',
  127. MasterUserPassword='cloudpass',
  128. VpcSecurityGroupIds=[security_group_id],
  129. #DBInstanceClass='db.m3.2xlarge',
  130. DBInstanceClass='db.t3.micro',
  131. Tags=[
  132. {'Key': 'Name', 'Value': 'tug-of-war-rds-db1'},
  133. {'Key': 'tug-of-war-rds', 'Value': 'db'}
  134. ],
  135. )
  136. waiter = rdsClient.get_waiter('db_instance_available')
  137. waiter.wait(DBInstanceIdentifier='tug-of-war-rds-db1')
  138. response = ec2Client.describe_security_groups(Filters=[{'Name': 'group-name', 'Values': ['tug-of-war-rds']}])
  139. security_group_id = response.get('SecurityGroups', [{}])[0].get('GroupId', '')
  140. response = rdsClient.describe_db_instances(DBInstanceIdentifier='tug-of-war-rds-db1')
  141. print(response)
  142. dbEndpointAddress = response['DBInstances'][0]['Endpoint']['Address']
  143. dbEndpointPort = response['DBInstances'][0]['Endpoint']['Port']
  144. print(str(dbEndpointAddress) + ":" + str(dbEndpointPort))
  145. userDataWebServer = ('#!/bin/bash\n'
  146. '# extra repo for RedHat rpms\n'
  147. 'yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm\n'
  148. '# essential tools\n'
  149. 'yum install -y joe htop git\n'
  150. '# httpd and mysql client\n'
  151. 'yum install -y httpd mariadb\n'
  152. '# fix php5.x PDO prob PDO::__construct(): Server sent charset (255) unknown to the client.\n'
  153. '# by using Amazons Linux 2 PHP extras\n'
  154. 'amazon-linux-extras install -y php7.4\n'
  155. '\n'
  156. 'service httpd start\n'
  157. '\n'
  158. # 'wget http://mmnet.informatik.hs-fulda.de/cloudcomp/tug-of-war-in-the-clouds.tar.gz\n'
  159. # 'cp tug-of-war-in-the-clouds.tar.gz /var/www/html/\n'
  160. # 'tar zxvf tug-of-war-in-the-clouds.tar.gz\n'
  161. 'cd /var/www/html\n'
  162. 'wget https://gogs.informatik.hs-fulda.de/srieger/cloud-computing-msc-ai-examples/raw/master/example-projects/tug-of-war-in-the-clouds/web-content/index.php\n'
  163. 'wget https://gogs.informatik.hs-fulda.de/srieger/cloud-computing-msc-ai-examples/raw/master/example-projects/tug-of-war-in-the-clouds/web-content/cloud.php\n'
  164. 'wget https://gogs.informatik.hs-fulda.de/srieger/cloud-computing-msc-ai-examples/raw/master/example-projects/tug-of-war-in-the-clouds/web-content/config.php\n'
  165. '\n'
  166. '# change hostname of db connection\n'
  167. 'sed -i s/localhost/' + dbEndpointAddress + '/g /var/www/html/config.php\n'
  168. '\n'
  169. '# create default table\n'
  170. 'echo "create table clouds ( cloud_id INT AUTO_INCREMENT, name VARCHAR(255) NOT NULL, value INT, max_value INT, PRIMARY KEY (cloud_id))" | mysql -h ' + dbEndpointAddress + ' -u cloud_tug_of_war -pcloudpass cloud_tug_of_war\n'
  171. )
  172. for i in range(1, 2):
  173. print("Running new Web Server instance...")
  174. print("------------------------------------")
  175. response = ec2Client.run_instances(
  176. ImageId=imageId,
  177. InstanceType=instanceType,
  178. Placement={'AvailabilityZone': availabilityZone, },
  179. KeyName=keyName,
  180. MinCount=1,
  181. MaxCount=1,
  182. UserData=userDataWebServer,
  183. SecurityGroupIds=[
  184. security_group_id,
  185. ],
  186. TagSpecifications=[
  187. {
  188. 'ResourceType': 'instance',
  189. 'Tags': [
  190. {'Key': 'Name', 'Value': 'tug-of-war-rds-webserver' + str(i)},
  191. {'Key': 'tug-of-war-rds', 'Value': 'webserver'}
  192. ],
  193. }
  194. ],
  195. )
  196. instanceIdWeb = response['Instances'][0]['InstanceId']
  197. instance = ec2Resource.Instance(instanceIdWeb)
  198. instance.wait_until_running()
  199. instance.load()
  200. print("tug-of-war-in-the-clouds can be accessed at: " + instance.public_ip_address)