Ceci est l'article du 13ème jour de Advent Calender sur le serveur de code 2019.
Dans la continuité de la dernière fois, je voudrais lancer EC2 Instance.
table des matières Environnement local 1er jour Environnement en ligne, jour 1 Améliorer l'environnement de travail
Environnement en ligne, jour 2 Créer un réseau virtuel
Environnement en ligne 3ème jour Lancement d'une instance EC2 avec Boto3
Environnement en ligne, jour 4 Essayez d'exécuter Code-Server dans le cloud
Environnement en ligne 5ème jour Lancer le serveur de code sur Docker
Environnement en ligne, jour 6 automatisons
Environnement en ligne 7ème jour Deploy compose sur git sur EC2
... En ligne .. Construit avec le fichier Coompose
Version en ligne .. Essayez K8S
...
Remodelage démoniaque
https://aws.amazon.com/ec2/
EC2 est un serveur virtuel fourni par AWS. Un serveur chargé en quelques secondes. Vous pouvez utiliser Linux librement.
Construisons un réseau avant de lancer EC2 Instance. Vous pouvez utiliser celui par défaut, mais essayez-le.
https://aws.amazon.com/vpc/
Tout d'abord, créez un réseau virtuel. ..
import boto3
from boto3_type_annotations import ec2
instance_name= "advent-code-server"
ec2client:ec2.Client = boto3.client("ec2")
res = ec2client.create_vpc(CidrBlock='10.1.0.0/16')
print("{}".format(res))
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.create_vpc
Avec juste cela, vous pouvez le créer. CidrBlock signifie l'adresse IP à allouer. Dans ce cas Les adresses IP de 10.1.0.0 à 10.1.255.255 sont disponibles.
Frappons TAG pour une gestion facile
import boto3
from boto3_type_annotations import ec2
from typing import Dict, List
instance_name= "advent-code-server"
def attach_tag(id:str):
res = ec2client.create_tags(Resources=[id], Tags=[{"Key": "Name", "Value": instance_name}])
print("{}".format(res))
def create_vpc():
print(">>> CREATE VPC")
res = ec2client.create_vpc(CidrBlock='10.1.0.0/16')
print("{}".format(res))
vpc_id = res['Vpc']['VpcId']
attach_tag(vpc_id)
return vpc_id
Oui c'est fait. Vous pouvez créer un réseau virtuel en appelant create_vpc ()
.
Vous devez pouvoir supprimer ce que vous avez créé à tout moment. Écrivons un script à supprimer
def rm_vpc():
print(">>> Delete vpcs")
res = ec2client.describe_vpcs(Filters=[{"Name":"tag:Name","Values":[instance_name]}])
print("{}".format(res))
for vpc in res["Vpcs"]:
res = ec2client.delete_vpc(VpcId=vpc['VpcId'])
print("{}".format(res))
Puisque la balise est jointe, elle est facile à supprimer. Recherchez le VPC associé au tag et supprimez le VPC trouvé.
import boto3
from boto3_type_annotations import ec2
from botocore.exceptions import ClientError
from typing import Dict, List
instance_name= "advent-code-server"
ec2client:ec2.Client = boto3.client("ec2")
def attach_tag(id:str):
res = ec2client.create_tags(Resources=[id], Tags=[{"Key": "Name", "Value": instance_name}])
print("{}".format(res))
def create_vpc():
print(">>> CREATE VPC")
res = ec2client.create_vpc(CidrBlock='10.1.0.0/16')
print("{}".format(res))
vpc_id = res['Vpc']['VpcId']
attach_tag(vpc_id)
return vpc_id
def delete_vpc():
print(">>> Delete vpcs")
res = ec2client.describe_vpcs(Filters=[{"Name":"tag:Name","Values":[instance_name]}])
print("{}".format(res))
for vpc in res["Vpcs"]:
res = ec2client.delete_vpc(VpcId=vpc['VpcId'])
print("{}".format(res))
if __name__ == "__main__":
create_vpc()
rm_vpc()
Vous avez maintenant le code pour créer et supprimer!
∧_∧
/ \ (・ ∀ ・) / ヽ
(● et Tsu ●)..Pause..
\/⊂, non \ non
Shi '
https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html
Le VPC ne pourra pas se connecter à Internet à ce stade. Configurons une passerelle pour se connecter.
def create_gateway(vpc_id:str):
print(">>> CREATE GATEWAY")
res = ec2client.create_internet_gateway()
print("{}".format(res))
gateway_id = res['InternetGateway']['InternetGatewayId']
attach_tag(gateway_id)
print(">>> ATTACH GATEWAY")
res = ec2client.attach_internet_gateway(InternetGatewayId=gateway_id,VpcId=vpc_id)
print("{}".format(res))
J'ai créé une passerelle et l'ai associée à un VPC.
Maintenant, écrivons le code à supprimer.
def delete_gateway():
print(">> Detach Gateway")
res = ec2client.describe_vpcs(Filters=[{"Name":"tag:Name","Values":[instance_name]}])
print("{}".format(res))
for vpc in res["Vpcs"]:
res = ec2client.describe_internet_gateways(Filters=[{"Name":"tag:Name","Values":[instance_name]}])
print("{}".format(res))
for gateway in res['InternetGateways']:
res = ec2client.detach_internet_gateway(InternetGatewayId=gateway['InternetGatewayId'],VpcId=vpc['VpcId'])
print("{}".format(res))
print(">> Delete Gateway")
res = ec2client.describe_internet_gateways(Filters=[{"Name":"tag:Name","Values":[instance_name]}])
print("{}".format(res))
for gateway in res['InternetGateways']:
res = ec2client.delete_internet_gateway(InternetGatewayId=gateway['InternetGatewayId'])
print("{}".format(res))
Pour le supprimer, vous devez dissocier le VPC. Ensuite, de la même manière, recherchez les données associées à la balise et supprimez-les.
import boto3
from boto3_type_annotations import ec2
from botocore.exceptions import ClientError
from typing import Dict, List
instance_name= "advent-code-server"
ec2client:ec2.Client = boto3.client("ec2")
def attach_tag(id:str):
res = ec2client.create_tags(Resources=[id], Tags=[{"Key": "Name", "Value": instance_name}])
print("{}".format(res))
def create_vpc():
print(">>> CREATE VPC")
res = ec2client.create_vpc(CidrBlock='10.1.0.0/16')
print("{}".format(res))
vpc_id = res['Vpc']['VpcId']
attach_tag(vpc_id)
return vpc_id
def delete_vpc():
print(">>> Delete vpcs")
res = ec2client.describe_vpcs(Filters=[{"Name":"tag:Name","Values":[instance_name]}])
print("{}".format(res))
for vpc in res["Vpcs"]:
res = ec2client.delete_vpc(VpcId=vpc['VpcId'])
print("{}".format(res))
def create_gateway(vpc_id:str):
print(">>> CREATE GATEWAY")
res = ec2client.create_internet_gateway()
print("{}".format(res))
gateway_id = res['InternetGateway']['InternetGatewayId']
attach_tag(gateway_id)
print(">>> ATTACH GATEWAY")
res = ec2client.attach_internet_gateway(InternetGatewayId=gateway_id,VpcId=vpc_id)
print("{}".format(res))
def delete_gateway():
print(">> Detach Gateway")
res = ec2client.describe_vpcs(Filters=[{"Name":"tag:Name","Values":[instance_name]}])
print("{}".format(res))
for vpc in res["Vpcs"]:
res = ec2client.describe_internet_gateways(Filters=[{"Name":"tag:Name","Values":[instance_name]}])
print("{}".format(res))
for gateway in res['InternetGateways']:
res = ec2client.detach_internet_gateway(InternetGatewayId=gateway['InternetGatewayId'],VpcId=vpc['VpcId'])
print("{}".format(res))
print(">> Delete Gateway")
res = ec2client.describe_internet_gateways(Filters=[{"Name":"tag:Name","Values":[instance_name]}])
print("{}".format(res))
for gateway in res['InternetGateways']:
res = ec2client.delete_internet_gateway(InternetGatewayId=gateway['InternetGatewayId'])
print("{}".format(res))
if __name__ == "__main__":
vpc_id:str = create_vpc()
gateway_id:str = create_gateway(vpc_id)
delete_gateway()
delete_vpc()
Vous avez maintenant le code pour créer et supprimer!
∧_∧
/ \ (・ ∀ ・) / ヽ
(● et Tsu ●)..Pause..
\/⊂, non \ non
Shi '
https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html
Définissons le sous-réseau. Le sous-réseau est le réseau défini par VPC, Il peut être divisé, regroupé et géré.
Créer
def create_subnet(vpc_id:str):
print(">>> CREATE SUBNET")
res = ec2client.create_subnet(CidrBlock='10.1.0.0/24',VpcId=vpc_id)
print("{}".format(res))
subnet_id = res['Subnet']['SubnetId']
attach_tag(subnet_id)
return subnet_id
Effacer
def delete_subnet():
print(">> Delete subnet")
res = ec2client.describe_subnets(Filters=[{"Name":"tag:Name","Values":[instance_name]}])
print("{}".format(res))
for subnet in res["Subnets"]:
res = ec2client.delete_subnet(SubnetId=subnet['SubnetId'])
print("{}".format(res))
CidrBlock signifie l'adresse IP à allouer. Dans ce cas Les adresses IP de 10.1.0.0 à 10.1.0.255 sont disponibles.
Définissons la sécurité comme le port à libérer et le port à fermer.
Créer
def create_security_group():
print(">>> CREATE SECURITY GROUP")
res = ec2client.create_security_group(Description="AdventCodeServer",GroupName=instance_name)
print("{}".format(res))
group_id = res['GroupId']
attach_tag(group_id)
return group_id
Effacer
def delete_security_group():
res = ec2client.describe_security_groups(Filters=[{"Name":"tag:Name","Values":[instance_name]}])
print("{}".format(res))
for sg in res['SecurityGroups']:
res = ec2client.delete_security_group(GroupId=sg["GroupId"])
print("{}".format(res))
Paramètres de port ajoutés
def create_security_group_ingress():
print(">>>> CREATE SECURITY GROUP INGRESS")
res = ec2client.authorize_security_group_ingress(
GroupName=instance_name, IpPermissions=[
{
'IpProtocol': 'tcp',
'FromPort': 8443,
'ToPort': 8443,
'IpRanges':[
{'CidrIp': '0.0.0.0/0', 'Description' : '8443'}
]
},
{
'IpProtocol': 'tcp',
'FromPort': 8080,
'ToPort': 8080,
'IpRanges':[
{'CidrIp': '0.0.0.0/0', 'Description' : '8080'}
]
},
{
'IpProtocol': 'tcp',
'FromPort': 22,
'ToPort': 22,
'IpRanges':[
{'CidrIp': '0.0.0.0/0', 'Description' : '8080'}
]
},
])
print("{}".format(res))
import boto3
from boto3_type_annotations import ec2
from botocore.exceptions import ClientError
from typing import Dict, List
instance_name= "advent-code-server"
ec2client:ec2.Client = boto3.client("ec2")
def attach_tag(id:str):
res = ec2client.create_tags(Resources=[id], Tags=[{"Key": "Name", "Value": instance_name}])
print("{}".format(res))
def create_vpc():
print(">>> CREATE VPC")
res = ec2client.create_vpc(CidrBlock='10.1.0.0/16')
print("{}".format(res))
vpc_id = res['Vpc']['VpcId']
attach_tag(vpc_id)
return vpc_id
def delete_vpc():
print(">>> Delete vpcs")
res = ec2client.describe_vpcs(Filters=[{"Name":"tag:Name","Values":[instance_name]}])
print("{}".format(res))
for vpc in res["Vpcs"]:
res = ec2client.delete_vpc(VpcId=vpc['VpcId'])
print("{}".format(res))
def create_gateway(vpc_id:str):
print(">>> CREATE GATEWAY")
res = ec2client.create_internet_gateway()
print("{}".format(res))
gateway_id = res['InternetGateway']['InternetGatewayId']
attach_tag(gateway_id)
print(">>> ATTACH GATEWAY")
res = ec2client.attach_internet_gateway(InternetGatewayId=gateway_id,VpcId=vpc_id)
print("{}".format(res))
def delete_gateway():
print(">> Detach Gateway")
res = ec2client.describe_vpcs(Filters=[{"Name":"tag:Name","Values":[instance_name]}])
print("{}".format(res))
for vpc in res["Vpcs"]:
res = ec2client.describe_internet_gateways(Filters=[{"Name":"tag:Name","Values":[instance_name]}])
print("{}".format(res))
for gateway in res['InternetGateways']:
res = ec2client.detach_internet_gateway(InternetGatewayId=gateway['InternetGatewayId'],VpcId=vpc['VpcId'])
print("{}".format(res))
print(">> Delete Gateway")
res = ec2client.describe_internet_gateways(Filters=[{"Name":"tag:Name","Values":[instance_name]}])
print("{}".format(res))
for gateway in res['InternetGateways']:
res = ec2client.delete_internet_gateway(InternetGatewayId=gateway['InternetGatewayId'])
print("{}".format(res))
def create_subnet(vpc_id:str):
print(">>> CREATE SUBNET")
res = ec2client.create_subnet(CidrBlock='10.1.0.0/24',VpcId=vpc_id)
print("{}".format(res))
subnet_id = res['Subnet']['SubnetId']
attach_tag(subnet_id)
return subnet_id
def delete_subnet():
print(">> Delete subnet")
res = ec2client.describe_subnets(Filters=[{"Name":"tag:Name","Values":[instance_name]}])
print("{}".format(res))
for subnet in res["Subnets"]:
res = ec2client.delete_subnet(SubnetId=subnet['SubnetId'])
print("{}".format(res))
def create_security_group():
print(">>> CREATE SECURITY GROUP")
res = ec2client.create_security_group(Description="AdventCodeServer",GroupName=instance_name)
print("{}".format(res))
group_id = res['GroupId']
attach_tag(group_id)
return group_id
def delete_security_group():
res = ec2client.describe_security_groups(Filters=[{"Name":"tag:Name","Values":[instance_name]}])
print("{}".format(res))
for sg in res['SecurityGroups']:
res = ec2client.delete_security_group(GroupId=sg["GroupId"])
print("{}".format(res))
def create_security_group_ingress():
print(">>>> CREATE SECURITY GROUP INGRESS")
res = ec2client.authorize_security_group_ingress(
GroupName=instance_name, IpPermissions=[
{
'IpProtocol': 'tcp',
'FromPort': 8443,
'ToPort': 8443,
'IpRanges':[
{'CidrIp': '0.0.0.0/0', 'Description' : '8443'}
]
},
{
'IpProtocol': 'tcp',
'FromPort': 8080,
'ToPort': 8080,
'IpRanges':[
{'CidrIp': '0.0.0.0/0', 'Description' : '8080'}
]
},
{
'IpProtocol': 'tcp',
'FromPort': 22,
'ToPort': 22,
'IpRanges':[
{'CidrIp': '0.0.0.0/0', 'Description' : '8080'}
]
},
])
print("{}".format(res))
if __name__ == "__main__":
vpc_id:str = create_vpc()
gateway_id:str = create_gateway(vpc_id)
subnet_id = create_subnet(vpc_id)
group_id = create_security_group()
create_security_group_ingress()
#create_instance()
#delete_instance()
delete_security_group()
delete_subnet()
delete_gateway()
delete_vpc()
Vous avez maintenant le code pour créer et supprimer! Ceci termine les paramètres réseau.
Commençons par un serveur virtuel dans le réseau virtuel créé !!
https://github.com/kyorohiro/advent-2019-code-server/tree/master/remote_cs01
Recommended Posts