(scope constructs.Construct, id string, props *Ec2InstanceStackProps)
| 17 | } |
| 18 | |
| 19 | func NewEc2InstanceStack(scope constructs.Construct, id string, props *Ec2InstanceStackProps) awscdk.Stack { |
| 20 | var sprops awscdk.StackProps |
| 21 | if props != nil { |
| 22 | sprops = props.StackProps |
| 23 | } |
| 24 | sourceDir, err := os.Getwd() |
| 25 | if err != nil { |
| 26 | fmt.Println("Error getting source path: ", err) |
| 27 | return nil |
| 28 | } |
| 29 | |
| 30 | // Construct the abs path of asset script |
| 31 | scriptPath := filepath.Join(sourceDir, "configure.sh") |
| 32 | |
| 33 | stack := awscdk.NewStack(scope, &id, &sprops) |
| 34 | |
| 35 | // Define VPC |
| 36 | vpc := ec2.NewVpc(stack, jsii.String("VPC"), &ec2.VpcProps{ |
| 37 | NatGateways: jsii.Number(0), |
| 38 | SubnetConfiguration: &[]*ec2.SubnetConfiguration{ |
| 39 | { |
| 40 | CidrMask: jsii.Number(24), |
| 41 | Name: jsii.String("asterisk"), |
| 42 | SubnetType: ec2.SubnetType_PUBLIC, |
| 43 | }, |
| 44 | }, |
| 45 | }) |
| 46 | |
| 47 | // Define AMI |
| 48 | ami := ec2.NewAmazonLinuxImage(&ec2.AmazonLinuxImageProps{ |
| 49 | Generation: ec2.AmazonLinuxGeneration_AMAZON_LINUX_2, |
| 50 | Edition: ec2.AmazonLinuxEdition_STANDARD, |
| 51 | Virtualization: ec2.AmazonLinuxVirt_HVM, |
| 52 | Storage: ec2.AmazonLinuxStorage_GENERAL_PURPOSE, |
| 53 | }) |
| 54 | |
| 55 | // Instance Role and SSM managed policy |
| 56 | role := iam.NewRole(stack, jsii.String("InstanceSSM"), &iam.RoleProps{ |
| 57 | AssumedBy: iam.NewServicePrincipal(jsii.String("ec2.amazonaws.com"), nil), |
| 58 | }) |
| 59 | |
| 60 | role.AddManagedPolicy(iam.ManagedPolicy_FromAwsManagedPolicyName(jsii.String("AmazonSSMManagedInstanceCore"))) |
| 61 | |
| 62 | // Define Instance |
| 63 | instance := ec2.NewInstance(stack, jsii.String("Instance"), &ec2.InstanceProps{ |
| 64 | InstanceType: ec2.NewInstanceType(jsii.String("t3.nano")), |
| 65 | MachineImage: ami, |
| 66 | Vpc: vpc, |
| 67 | Role: role, |
| 68 | }) |
| 69 | |
| 70 | // Script in S3 as asset |
| 71 | asset := assets.NewAsset(stack, jsii.String("Asset"), &assets.AssetProps{ |
| 72 | Path: jsii.String(scriptPath), |
| 73 | }) |
| 74 | localAsset := instance.UserData().AddS3DownloadCommand(&ec2.S3DownloadOptions{ |
| 75 | Bucket: asset.Bucket(), |
| 76 | BucketKey: asset.S3ObjectKey(), |
no outgoing calls