|
| 1 | +#!/usr/bin/env python |
| 2 | +"""Provide a Command Line Interface to manage MySimpleStack stack. |
| 3 | +
|
| 4 | +The stack consists of a VPC with private and public subnets in eu-west-1a AZ |
| 5 | +and a NAT Gateway to route traffic from the private subnet to the Internet. |
| 6 | +It also deploys an instance in the private subnet with its IAM profile, and |
| 7 | +a security group. |
| 8 | +
|
| 9 | +As it relies on CFNProjectMain it requires a deployment and a |
| 10 | +CloudFormation roles named respectively cfn-user/CFNAllowDeployOfMySimpleStack |
| 11 | +and cfn-service/CFNServiceRoleForMySimpleStack. |
| 12 | +
|
| 13 | +The 'CFNAllow' role must be assumable by the user deploying the stack. |
| 14 | +The 'CFNServiceRole' must trust the CloudFormation service. |
| 15 | +
|
| 16 | +For more details on how to manage the stack run: |
| 17 | +./deploy_simple_stack.py --help |
| 18 | +""" |
| 19 | +from __future__ import annotations |
| 20 | +from functools import cached_property |
| 21 | +import sys |
| 22 | +from typing import TYPE_CHECKING |
| 23 | + |
| 24 | +from e3.aws.troposphere import CFNProjectMain, Construct, name_to_id, Stack |
| 25 | +from e3.aws.troposphere.ec2 import VPCv2 |
| 26 | +from e3.aws.troposphere.iam.role import Role |
| 27 | +from e3.aws.troposphere.iam.policy_statement import Trust |
| 28 | +from troposphere import ec2, iam, Ref, GetAtt, Tags |
| 29 | + |
| 30 | +if TYPE_CHECKING: |
| 31 | + from troposphhere import AWSObject |
| 32 | + |
| 33 | +STACK_NAME = "MySimpleStack" |
| 34 | +ACCOUNT_ID = "012345678910" |
| 35 | +REGION = "eu-west-1" |
| 36 | +AZ = "eu-west-1a" |
| 37 | +IAM_PATH = "/my-simple-stack/" |
| 38 | +INSTANCE_AMI = "ami-1234" |
| 39 | + |
| 40 | +# S3 Bucket where templates are pushed for deployment |
| 41 | +# The "CFNAllowDeployOf" role must be allowed to push files to: |
| 42 | +# my-cfn-bucket/my-simple-stack/* |
| 43 | +# The "CFNServiceRole" must be allowed to read files from: |
| 44 | +# my-cfn-bucket/my-simple-stack/* |
| 45 | +CFN_BUCKET = "my-cfn-bucket" |
| 46 | + |
| 47 | + |
| 48 | +class SimpleInstance(Construct): |
| 49 | + """Provide a construct deploying a simple instance.""" |
| 50 | + |
| 51 | + def __init__(self, name: str, vpc: VPCv2, ami: str, instance_type: str) -> None: |
| 52 | + """Initialize a SimpleInstance instance. |
| 53 | +
|
| 54 | + :param name: name of the instance |
| 55 | + :param vpc: a vpc to host the instance |
| 56 | + :param ami: AMI for the instance |
| 57 | + :param instance_type: the EC2 instance type |
| 58 | + """ |
| 59 | + self.name = name |
| 60 | + self.vpc = vpc |
| 61 | + self.ami = ami |
| 62 | + self.instance_type = instance_type |
| 63 | + |
| 64 | + @cached_property |
| 65 | + def role(self) -> Role: |
| 66 | + """Return a role for the simple instance.""" |
| 67 | + return Role( |
| 68 | + name=f"{self.name}InstanceRole", |
| 69 | + description="Simple instance instance role", |
| 70 | + path=IAM_PATH, |
| 71 | + trust=Trust(services=["ec2"]), |
| 72 | + managed_policy_arns=[ |
| 73 | + # Access to CloudWatch and SSM |
| 74 | + "arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy", |
| 75 | + "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore", |
| 76 | + "arn:aws:iam::aws:policy/AmazonSSMPatchAssociation", |
| 77 | + ], |
| 78 | + ) |
| 79 | + |
| 80 | + @cached_property |
| 81 | + def profile(self) -> iam.InstanceProfile: |
| 82 | + """Return an instance profile for the simple instance.""" |
| 83 | + profile_name = f"{self.name}InstanceProfile" |
| 84 | + return iam.InstanceProfile( |
| 85 | + title=name_to_id(profile_name), |
| 86 | + InstanceProfileName=profile_name, |
| 87 | + Path=IAM_PATH, |
| 88 | + Roles=[self.role.name], |
| 89 | + DependsOn=self.role.name, |
| 90 | + ) |
| 91 | + |
| 92 | + @cached_property |
| 93 | + def security_group(self) -> ec2.SecurityGroup: |
| 94 | + """Return instance security group. |
| 95 | +
|
| 96 | + Allow no inbound and all outbound. |
| 97 | + """ |
| 98 | + group_name = f"{self.name}SG" |
| 99 | + return ec2.SecurityGroup( |
| 100 | + name_to_id(group_name), |
| 101 | + GroupDescription=f"Security group for {self.name} instance", |
| 102 | + GroupName=group_name, |
| 103 | + SecurityGroupEgress=[ |
| 104 | + ec2.SecurityGroupRule(CidrIp="0.0.0.0/0", IpProtocol="-1"), |
| 105 | + ec2.SecurityGroupRule(CidrIpv6="::/0", IpProtocol="-1"), |
| 106 | + ], |
| 107 | + SecurityGroupIngress=[], |
| 108 | + VpcId=Ref(self.vpc.vpc), |
| 109 | + ) |
| 110 | + |
| 111 | + @cached_property |
| 112 | + def instance(self) -> ec2.Instance: |
| 113 | + """Return a simple instance.""" |
| 114 | + return ec2.Instance( |
| 115 | + title=name_to_id(self.name), |
| 116 | + ImageId=self.ami, |
| 117 | + IamInstanceProfile=Ref(self.profile), |
| 118 | + InstanceType=self.instance_type, |
| 119 | + SubnetId=Ref(self.vpc.private_subnets[AZ]), |
| 120 | + # Use default security group that comes with the VPC |
| 121 | + SecurityGroupIds=[GetAtt(self.security_group, "GroupId")], |
| 122 | + PropagateTagsToVolumeOnCreation=True, |
| 123 | + BlockDeviceMappings=[ |
| 124 | + ec2.BlockDeviceMapping( |
| 125 | + Ebs=ec2.EBSBlockDevice(VolumeType="gp3", VolumeSize="20"), |
| 126 | + DeviceName="/dev/sda1", |
| 127 | + ) |
| 128 | + ], |
| 129 | + Tags=Tags({"Name": self.name}), |
| 130 | + ) |
| 131 | + |
| 132 | + def resources(self, stack: Stack) -> list[AWSObject | Construct]: |
| 133 | + """Return resources for this construct.""" |
| 134 | + return [ |
| 135 | + self.role, |
| 136 | + self.profile, |
| 137 | + self.security_group, |
| 138 | + self.instance, |
| 139 | + ] |
| 140 | + |
| 141 | + |
| 142 | +class MySimpleStackMain(CFNProjectMain): |
| 143 | + """Provide CLI to manage MySimpleStack stack.""" |
| 144 | + |
| 145 | + def create_stack(self) -> list[Stack]: |
| 146 | + """Create MySimpleStack stack.""" |
| 147 | + vpc = VPCv2( |
| 148 | + name_prefix=self.stack.name, |
| 149 | + cidr_block="10.50.0.0/16", |
| 150 | + availability_zones=[AZ], |
| 151 | + ) |
| 152 | + self.add(vpc) |
| 153 | + self.add( |
| 154 | + SimpleInstance( |
| 155 | + name="MySimpleInstance", |
| 156 | + vpc=vpc, |
| 157 | + ami="MYAMi-1234", |
| 158 | + instance_type="t4g.small", |
| 159 | + ) |
| 160 | + ) |
| 161 | + return self.stack |
| 162 | + |
| 163 | + |
| 164 | +def main(args: list[str] | None = None) -> None: |
| 165 | + """Entry point. |
| 166 | +
|
| 167 | + :param args: the list of positional parameters. If None then |
| 168 | + ``sys.argv[1:]`` is used |
| 169 | + """ |
| 170 | + project = MySimpleStackMain( |
| 171 | + name=STACK_NAME, |
| 172 | + account_id=ACCOUNT_ID, |
| 173 | + stack_description="Stack deploying an instance", |
| 174 | + s3_bucket=f"cfn-gitlab-adacore-{REGION}", |
| 175 | + regions=[REGION], |
| 176 | + ) |
| 177 | + sys.exit(project.execute(args)) |
| 178 | + |
| 179 | + |
| 180 | +if __name__ == "__main__": |
| 181 | + main() |
0 commit comments