Easily build network infrastructure and EC2 with AWS CDK Python

If you want to build AWS infrastructure and EC2 as a set quickly and easily, AWS CDK is a very useful tool. This time, I will show you how to use AWS CDK Python.

Premise

Work environment
AWS environment

--aws keypair: Created. Name it'testkey'.

Constitution

--VPC is cut at / 21. 10.0.0.0/21 --Subnet: 1 Public (/24), 1 Private (/24) --SecurityGroup: Open port 22 inbound to use SSH for EC2

procedure

Install CDK
# npm install -g aws-cdk
Create test project tescdk
# mkdir testcdk
# cd testcdk
# cdk init --language python
Applying project template app for python
Initializing a new git repository...
Executing Creating virtualenv...
# Welcome to your CDK Python project!
This is a blank project for Python development with CDK.
The `cdk.json` file tells the CDK Toolkit how to execute your app.
(abridgement)
## Useful commands
 * `cdk ls`          list all stacks in the app
 * `cdk synth`       emits the synthesized CloudFormation template
 * `cdk deploy`      deploy this stack to your default AWS account/region
 * `cdk diff`        compare deployed stack with current state
 * `cdk docs`        open CDK documentation
Enjoy!
Check directory and file structure
# tree
.
|-- .env
|-- README.md
|-- app.py
|-- cdk.json
|-- requirements.txt
|-- setup.py
|-- source.bat
`-- testcdk
    |-- __init__.py
    `-- testcdk_stack.py
Enable Python virtual environment

# source .env/bin/activate
(.env)

Add libraries required for EC2 creation in setup.py

setup.py


(abridgement)
install_requires=[
        "aws-cdk.core",
        "aws_cdk.aws_ec2",
],
(abridgement)
pip update and install required libraries

# pip install -e .
(abridgement)
Successfully installed attrs-19.3.0 aws-cdk.aws-cloudwatch-1.32.1 aws-cdk.aws-ec2-1.32.1 aws-cdk.aws-events-1.32.1 aws-cdk.aws-iam-1.32.1 aws-cdk.aws-kms-1.32.1 aws-cdk.aws-logs-1.32.1 aws-cdk.aws-s3-1.32.1 aws-cdk.aws-ssm-1.32.1 aws-cdk.core-1.32.1 aws-cdk.cx-api-1.32.1 aws-cdk.region-info-1.32.1 cattrs-1.0.0 constructs-2.0.1 jsii-1.1.0 publication-0.0.3 python-dateutil-2.8.1 six-1.14.0 testcdk typing-extensions-3.7.4.2
Specify the deployment destination region with app.py

app.py


#!/usr/bin/env python3

from aws_cdk import core

from testcdk.testcdk_stack import TestcdkStack


app = core.App()
TestcdkStack(app, "testcdk", env=core.Environment(region="ap-northeast-1"))

app.synth()
Edit the testcdk / testcdk_stack.py file

Write a stack to create a VPC, SecurityGroup, EC2.

testcdk_stack.py


from aws_cdk import (
        core,
        aws_ec2 <=Add this
)


class TestcdkStack(core.Stack):

    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # The code that defines your stack goes here
        #Write the code below this

        cidr = '10.0.0.0/21' #write cidr block

        vpc = aws_ec2.Vpc(
            self,
            id='test-vpc',
            cidr=cidr,
            nat_gateways=1,
            subnet_configuration=[
                aws_ec2.SubnetConfiguration(
                    cidr_mask=24,  #Define netmask for Public Subnet
                    name='public',
                    subnet_type=aws_ec2.SubnetType.PUBLIC,
                ),
                aws_ec2.SubnetConfiguration(
                    cidr_mask=24, #Define netmask for Private Subnet
                    name='private',
                    subnet_type=aws_ec2.SubnetType.PRIVATE,
                ),
            ],
        )

        security_group = aws_ec2.SecurityGroup(
            self,
            id='test-security-group',
            vpc=vpc,
            security_group_name='test-security-group'
        )

        security_group.add_ingress_rule(
            peer=aws_ec2.Peer.ipv4(cidr),
            connection=aws_ec2.Port.tcp(22), #Open Port 22 with Inbound
        )

        image_id = aws_ec2.AmazonLinuxImage(generation=aws_ec2.AmazonLinuxGeneration.AMAZON_LINUX_2).get_image(self).image_id #Specify EC2 image

        aws_ec2.CfnInstance(
            self,
            id='testec2',
            availability_zone="ap-northeast-1a", #Specify AZ
            image_id=image_id,
            instance_type="t3.micro", #Specify Instance Type
            key_name='testkey', #Specify Key Pair
            security_group_ids=[security_group.security_group_id],
            subnet_id=vpc.private_subnets[0].subnet_id, #Specify Private Subnet this time
            tags=[{
                "key": "Name",
                "value": "testec2" #Define the name to display in the web console
            }]
        )

Check the stack for Cloudformation output by cdk synth

# cdk synth
Resources:
  testvpc8985080E:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/21
      EnableDnsHostnames: true
      EnableDnsSupport: true
      InstanceTenancy: default
(abridgement)

You can also save the stack to yaml with cdk synth.


cdk synth > cdk.yaml
Check the list of deployable stacks
# cdk ls
testcdk
Deploy by specifying the created stack testcdk
# cdk deploy testcdk
testcdk: deploying...
testcdk creating CloudFormation changeset

Cloudformation will run in the specified AWS account region, and VPC and Subnet, Security Group, and EC2 will be created.

reference

Getting Started With the AWS CDK

Recommended Posts

Easily build network infrastructure and EC2 with AWS CDK Python
AWS CDK with Python
Neural network with OpenCV 3 and Python 3
[AWS] Build an ECR with AWS CDK
Easily download mp3 / mp4 with python and youtube-dl!
Touch AWS with Serverless Framework and Python
Build python environment with pyenv on EC2 (ubuntu)
[AWS] Let's build an ECS Cluster with CDK
Getting started with AWS IoT easily in Python
Build PyPy and Python execution environment with Docker
Template network config generation with Python and Jinja2
Easily beep with python
Easily build HPC on AWS with genuine AWS Cfn Cluster
Dynamic HTML pages made with AWS Lambda and Python
# 2 Build a Python environment on AWS EC2 instance (ubuntu18.04)
Create Amazon Linux with AWS EC2 and log in
Execute python3 system with PHP exec () on AWS EC2
Build a python virtual environment with virtualenv and virtualenvwrapper
Make ordinary tweets fleet-like with AWS Lambda and Python
Programming with Python and Tkinter
Try hitting the Twitter API quickly and easily with Python
Encryption and decryption with Python
Python and hardware-Using RS232C with Python-
Easily write JSON and Python dataclass conversions with quicktype and dacite
Build python3 environment with ubuntu 16.04
Build python environment with direnv
Easily build CNN with Keras
python with pyenv and venv
Let's build git-cat with Python
Network programming with Python Scapy
This and that for using Step Functions with CDK + Python
Site monitoring and alert notification with AWS Lambda + Python + Slack
Works with Python and R
Build a 64-bit Python 2.7 environment with TDM-GCC and MinGW-w64 on Windows 7
Build a Python environment on your Mac with Anaconda and PyCharm
Build a detonation velocity website with Cloud Run and Python (Flask)
# 3 Build a Python (Django) environment on AWS EC2 instance (ubuntu18.04) part2
Make a scraping app with Python + Django + AWS and change jobs
Install pip in Serverless Framework and AWS Lambda with Python environment
I tried to easily detect facial landmarks with python and dlib
[python3] Implement debug log output function easily with logging and Click
How to build Python and Jupyter execution environment with VS Code
Communicate with FX-5204PS with Python and PyUSB
Robot running with Arduino and python
Install Python 2.7.9 and Python 3.4.x with pip.
AM modulation and demodulation with python
[Python] font family and font with matplotlib
Scraping with Node, Ruby and Python
Build python virtual environment with virtualenv
ruby environment construction with aws EC2
Scraping with Python, Selenium and Chromedriver
Easily implement subcommands with python click
Text extraction with AWS Textract (Python3.6)
Easily handle lists with python + sqlite3
Build Mysql + Python environment with docker
For me: Infrastructure and network notes
JSON encoding and decoding with python
Hadoop introduction and MapReduce with Python
[GUI with Python] PyQt5-Drag and drop-
Build mlpy with python3.3 (64bit) (windows 64bit)
Reading and writing NetCDF with Python