0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AWS CDKでセッションマネージャーを利用してEC2へ接続が可能になるコードのメモ

Last updated at Posted at 2023-05-14

はじめに

AWS CDKでプライベートサブネットを一つ区切り、EC2を配置し、
AWS System managerのSession ManagerからEC2へ接続するだけのAWS CDKのコードです。
typescriptで記載しています。
構築時のベースにお使いください。

import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as cdk from "aws-cdk-lib"            //Tag付け用
import * as ec2 from "aws-cdk-lib/aws-ec2";   //VPC,Subnet,SG,EC2用
import * as iam from "aws-cdk-lib/aws-iam";   //SSM用ポリシーアタッチ用

export class TakoyakiEc2Stack extends Stack {      //CdkEc2Stackは現在のプロジェクト名称、スタック名称に併せて編集
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    ////////////////////////////////////////////////
    //VPC Subnet定義
    ////////////////////////////////////////////////
    const Takoyakivpc = new ec2.Vpc(this,"VPC",{
      vpcName: "C-vpc", //VPC Name  
      cidr: "192.168.0.0/24", //VPC cidr
      maxAzs: 1, //AZ
      
      subnetConfiguration :[
        {
          cidrMask: 24,
          name:"C01-subnet-private-EC2",
          subnetType: ec2.SubnetType.PRIVATE_ISOLATED,
        },
        ]
      
    })
    ////////////////////////////////////////////////
    //SG定義
    ////////////////////////////////////////////////
    //エンドポイント用途SG//
    const securityGroupForSSM = new ec2.SecurityGroup(this, "SgForSSM",{
      vpc: Takoyakivpc, //VPC指定
      securityGroupName: "c01-sg-ssm",
      allowAllOutbound: true,
      description: "ForSSM",
    });
    securityGroupForSSM.addIngressRule(##参考文献
      ec2.Peer.ipv4("192.168.0.0/24"),
      ec2.Port.tcp(443),
      "From SSM"
    );

    //エンドポイント用途EC2//
    const securityGroupForEC2 = new ec2.SecurityGroup(this, "SgForBstn",{
      vpc: Takoyakivpc, //VPC指定
      securityGroupName: "c01-sg-Bstn",
      allowAllOutbound: false,
      description: "ForBstn",
    });
    securityGroupForEC2.addEgressRule(
      ec2.Peer.ipv4("192.168.0.0/24"),
      ec2.Port.tcp(443),
      "ForBstn"#
    );

    ////////////////////////////////////////////////
    //VPCエンドポイント   Session Manager の使用
    ////////////////////////////////////////////////
    //SSM用途
    const VPCEndpointSSM = new ec2.InterfaceVpcEndpoint(this, "endpointForSSM",
    {
      vpc: Takoyakivpc,
      service: ec
#はじめに2.InterfaceVpcEndpointAwsService.SSM,
      privateDnsEnabled: true,
      securityGroups: [securityGroupForSSM],
      subnets: Takoyakivpc.selectSubnets({
        subnetGroupName :"C01-subnet-private-EC2"
      })
    });
    //SSM用(msg)
    const VPCEndpointSSMmsg = new ec2.InterfaceVpcEndpoint(this, "endpointForSSMmsg",
    {
      vpc: Takoyakivpc,
      service: ec2.InterfaceVpcEndpointAwsService.SSM_MESSAGES,
      privateDnsEnabled: true,
      securityGroups: [securityGroupForSSM],
      subnets: Takoyakivpc.selectSubnets({
        subnetGroupName :"C01-subnet-private-EC2"
      })
    });
    //EC2
    const VPCEndpointEC2 = new ec2.InterfaceVpcEndpoint(this, "endpointForEC2msg",
    {
      vpc: Takoyakivpc,
      service: ec2.InterfaceVpcEndpointAwsService.EC2_MESSAGES,
      privateDnsEnabled: true,
      securityGroups: [securityGroupForSSM],
      subnets: Takoyakivpc.selectSubnets({
        subnetGroupName :"C01-subnet-private-EC2"
      })
    });

    ////////////////////////////////////////////////
    //IAM      Session Manager の使用
    ////////////////////////////////////////////////
    //SSM用
    const iamRoleForSSM =new iam.Role(this,"iamRoleforSSM", {
        roleName: "c01-role-ec2-ssm",
        assumedBy: new iam.ServicePrincipal("ec2.amazonaws.com"),
        managedPolicies: [
            {
                managedPolicyArn:"arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore",
            },
        ],
    });
    
  ////////////////////////////////////////////////
  //EC2
  ////////////////////////////////////////////////
  const ec2Instance = new ec2.Instance(this, 'EC2Instance', {
    vpc: Takoyakivpc,
    vpcSubnets: Takoyakivpc.selectSubnets({
        subnetGroupName :"C01-subnet-private-EC2"
      }),
    role: iamRoleForSSM,
    securityGroup: securityGroupForEC2,
    instanceType: ec2.InstanceType.of(ec2.InstanceClass.T2, ec2.InstanceSize.MICRO),
    machineImage: ec2.MachineImage.latestAmazonLinux({generation: ec2.AmazonLinuxGeneration.AMAZON_LINUX_2})
  }
  );
  cdk.Tags.of(ec2Instance).add("Name", "C01-private-EC2");
  }
}

参考文献

セッションマネージャーを使って鍵ストレスの無いEC2アクセス!
https://dev.classmethod.jp/articles/ec2-access-with-session-manager/

5分で理解するAWS CDK
https://qiita.com/Brutus/items/6c8d9bfaab7af53d154a

AWS CDK - コマンド
https://qiita.com/leomaro7/items/1c06b2875490a2f866e2

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?