sciencefair2023/cdk/sfec2/sci_stack.py

72 lines
2.8 KiB
Python

import os
import aws_cdk as cdk
import aws_cdk.aws_ec2 as ec2
import aws_cdk.aws_iam as iam
from constructs import Construct
from aws_cdk.aws_s3_assets import Asset
class SciInstancesStack(cdk.Stack):
def __init__(self, vpcStack: Construct, construct_id:
str, env: cdk.Environment, **kwargs) -> None:
super().__init__(vpcStack, construct_id, env=env, **kwargs)
role = iam.Role(self, "InstanceSSM", assumed_by=iam.ServicePrincipal("ec2.amazonaws.com"))
role.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name("AmazonSSMManagedInstanceCore"))
imageId = ec2.MachineImage.lookup(name='debian-11-amd64-20221219-1234')
ec2instance = ec2.Instance(self, "ec2",
vpc=vpcStack.vpc,
instance_type=ec2.InstanceType("t2.nano"),
machine_image=imageId,
security_group = vpcStack.SciSG,
role=role,
key_name='id-paco-2022'
)
# Script in S3 as Asset
asset = Asset(self, "userdata", path=os.path.join("..", "init.sh"))
local_path = ec2instance.user_data.add_s3_download_command(
bucket=asset.bucket,
bucket_key=asset.s3_object_key
)
# Userdata executes script from S3
ec2instance.user_data.add_execute_file_command(
file_path=local_path
)
asset.grant_read(ec2instance.role)
cdk.CfnOutput(self, "instance", value=ec2instance.instance_public_ip)
class VpcBasisStack(cdk.Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
self.vpc = ec2.Vpc(self, 'out-vpc',
ip_addresses=ec2.IpAddresses.cidr('172.19.19.0/24'),
max_azs = 1,
subnet_configuration=[
ec2.SubnetConfiguration(
name = 'pub',
subnet_type = ec2.SubnetType.PUBLIC,
cidr_mask = 26
)
],
nat_gateways = 0
)
# Create standard Security Group for all EC2 instances
self.SciSG = ec2.SecurityGroup(self, 'Sci-sg', vpc=self.vpc,
allow_all_outbound=True, security_group_name='Sci-sg' )
self.SciSG.add_ingress_rule(peer=ec2.Peer.ipv4('173.79.190.162/32'),
connection=ec2.Port.tcp(22), description="ssh in from home")
self.SciSG.add_ingress_rule(peer=ec2.Peer.ipv4('70.164.19.200/29'),
connection=ec2.Port.tcp(22), description="ssh in from nova")
self.SciSG.add_ingress_rule(peer=ec2.Peer.any_ipv6(),
connection=ec2.Port.tcp(80), description="HTTP open to the world, ipv6")
self.SciSG.add_ingress_rule(peer=ec2.Peer.any_ipv4(),
connection=ec2.Port.tcp(80), description="HTTP open to the world, ipv4")
app = cdk.App()