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.

238 lines
9.1 KiB

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