I started following AWS CDK (Cloud Development Kit) news and documentation for a while now. That's usually my lazy strategy when a new AWS product is launched, I finally decided that I wanted to start using it and create something that I'm familiar with and also find useful.
One of my favourites AWS products is EC2, for multiple reason:
- Compute is Universal, it have the potential to make many things with a server running Linux.
- EC2 Administration in AWS can be much more elastic, there are some additions from AWS System Manager that I enjoy using:
- No more SSH!, AWS SSM provides Session Manager instead that is Web Console, CLI and API friendly.
- Parameter Store is handy for keeping configuration values in a safe place outside the instance.
- User data for provisioning, because some bash script with a few commands always gets the job done.
- Elastic IPs (also knows as Public IP), probably the most simple way to connect your application to the internet!
- Amazon Linux 2, one less thing to worry about because AWS maintains a Redhat/Centos like distribution.
- All the goodies of EBS and snapshots.
- Spot Instances, because running your servers could be really affordable if your service is smart enough to handle interruptions.
So, I decided to deploy a single instance from Python code using CDK with all the AWS cool stuff to easy the management in around 60 lines of code.
This is a snippet of what you're going to find, instance creation:
instance = ec2.Instance(self, "Instance",
instance_type=ec2.InstanceType("t3.nano"),
machine_image=amzn_Linux,
vpc = vpc,
role = role
)
One common issue when using user data to install software is that eventually it hits a limit, CDK Assets allows me to invoke that script from a separate file and also handles the assets management in S3 for us.
asset = Asset(self, "Asset", path=os.path.join(dirname, "configure.sh"))
local_path = instance.user_data.add_s3_download_command(
bucket=asset.bucket,
bucket_key=asset.s3_object_key
)
instance.user_data.add_execute_file_command(
file_path=local_path
)
This is the full code example for getting that instance up and running:
I hope this gives you an idea of how powerful CDK in terms of describing infrastructure and the amount of time that saves if you where using the Python SDK or Cloudformation previously.
Top comments (0)