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.

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