LoginSignup
0
0

More than 1 year has passed since last update.

Session Managerで接続するための踏み台EC2を立てるCloudformation

Last updated at Posted at 2022-04-23

やること

今回はPublic Subnetの中に置いたEC2にSessionManagerで接続できるCloudformationを作成します。(下図左)
今回と同様のやりかたで、NATに紐付けたPrivate Subnetの中に置いたEC2にも接続できます。(下図中)

スクリーンショット 2022-04-24 9.03.18.png

ただし、NATに紐づかないPrivate Subnetの中のEC2に対しては、VPCエンドポイントの作成が必要です。(上図右)
この場合の対応は下記参照ください。

実装

ec2.yml
AWSTemplateFormatVersion: 2010-09-09
Parameters:
  EnvironmentName:
    Type: String
    Default: sample
  KeyName:
    Type: AWS::EC2::KeyPair::KeyName
    Default: sample-key-pair
    ConstraintDescription: must be the name of an existing EC2 KeyPair.
  InstanceType:
    Type: String
    Default: t2.micro
  LatestAmiId:
    Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
    Default: '/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2'
  VpcId:
    Type: String
  PublicSubnetId:
    Type: String

Resources:
  SessionManagerRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub ${EnvironmentName}-SessionManagerRole
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action: sts:AssumeRole
            Principal:
              Service: ec2.amazonaws.com
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
      Tags:
        - Key: Name
          Value: !Sub ${EnvironmentName} SessionManagerRole

  SSMInstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Path: /
      Roles:
        - !Ref SessionManagerRole

  InstanceSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Default setting
      VpcId: !Ref VpcId
      Tags:
        - Key: Name
          Value: !Sub ${EnvironmentName}-EC2-sg

  EC2Instance:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: !Ref InstanceType
      KeyName: !Ref KeyName
      ImageId: !Ref LatestAmiId
      IamInstanceProfile: !Ref SSMInstanceProfile
      NetworkInterfaces:
        - AssociatePublicIpAddress: true
          DeviceIndex: 0
          GroupSet:
            - !Ref InstanceSecurityGroup
          SubnetId: !Ref PublicSubnetId
      UserData: !Base64 |
        #!/bin/bash
        sudo yum update
        sudo yum install -y https://s3.ap-northeast-1.amazonaws.com/amazon-ssm-ap-northeast-1/latest/linux_amd64/amazon-ssm-agent.rpm
        systemctl enable amazon-ssm-agent
        systemctl start amazon-ssm-agent
      Tags:
        - Key: Name
          Value: !Sub ${EnvironmentName} EC2 to connect via session manager

参考

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