Session ManagerプラグインをインストールしてローカルWindows PCからEC2へSession Managerで接続してみた

2023.02.09

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

今回はブログのタイトル通りローカルWindows PCからEC2へSession Managerで接続してみました。
普段私はローカルPCからSession ManagerでEC2へ接続することは無く、以下の公式ドキュメントの手順でマネジメントコンソールから接続しています。
セッションを開始する (Amazon EC2 コンソール)

環境確認

今回はWindows 10 Pro 64 ビットのものを使用しています。
1. [Windows]+[I]キーでWindowsの設定を開く
2. [システム]→[詳細情報]→[デバイスの仕様]→[システムの種類]を確認する
以下の画像のように表示されていれば64bit版のWindowsになります。

また、AWS CLIとAdministratorAccessの権限が付いたIAMユーザーのアクセスキー、シークレットアクセスキーを設定済みです。
AWS CLIのインストールとアクセスキーなどの設定は以下のブログをご確認ください。

接続準備

Session Managerプラグインのインストール

AWS CLIを使用してSession Managerを使用するにはSession Managerプラグインというものが必要になります。
Session Managerプラグインが無い状態でEC2に接続しようとすると以下のエラーが出てきます。

SessionManagerPlugin is not found. Please refer to SessionManager Documentation here: http://docs.aws.amazon.com/console/systems-manager/session-manager-plugin-not-found


以下の公式ドキュメントの通りにインストールしていきます。
Windows に Session Manager プラグインをインストールする
PowerShellを起動して以下のコマンドを実行してください。
以下のコマンドを実行するとSession Managerプラグインのインストーラーがダウンロードされます。

curl https://s3.amazonaws.com/session-manager-downloads/plugin/latest/windows/SessionManagerPluginSetup.exe -o SessionManagerPluginSetup.exe

ダウンロードされたらインストーラーを実行します。

./SessionManagerPluginSetup.exe

実行すると以下のインストールウィザードが開くので「I agree to license terms and conditions」のチェックボックスにチェックを入れて「Install」をクリックします。

インストールが完了すると以下の画像の通り「Installation Successfully Completed」と表示されるので「Close」で閉じます。

Closeで閉じたらPowerShellで以下のコマンドを実行します。

session-manager-plugin

以下のメッセージが表示されればインストールは完了です。

The Session Manager plugin was installed successfully. Use the AWS CLI to start a session.

接続先EC2の作成

ここでの作業は接続先のEC2をCloudFormationで作成していきます。
以下のCloudFormationで作成を行います。

CloudFormationテンプレート (ここをクリックしてください)
AWSTemplateFormatVersion: "2010-09-09"

Description: Session Test Stack

Metadata:
# ------------------------------------------------------------#
# Metadata
# ------------------------------------------------------------# 
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label: 
          default: Parameters for VPC
        Parameters:
          - VPCCIDR
      - Label: 
          default: Parameters for Subnet
        Parameters:
          - PublicSubnet01CIDR
      - Label: 
          default: Parameters for EC2
        Parameters:
          - EC2VolumeSize
          - EC2VolumeIOPS
          - EC2AMI
          - EC2InstanceType

Parameters:
# ------------------------------------------------------------#
# Parameters
# ------------------------------------------------------------# 
  VPCCIDR:
    Default: 172.30.0.0/16
    Type: String

  PublicSubnet01CIDR:
    Default: 172.30.0.0/24
    Type: String

  EC2VolumeSize:
    Default: 30
    Type: Number

  EC2VolumeIOPS:
    Default: 3000
    Type: Number

  EC2AMI:
    Default: ami-06ee4e2261a4dc5c3
    Type: AWS::EC2::Image::Id

  EC2InstanceType:
    Default: t3.micro
    Type: String

Resources:
# ------------------------------------------------------------#
# VPC
# ------------------------------------------------------------# 
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: !Ref VPCCIDR
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags: 
        - Key: Name
          Value: test-vpc

# ------------------------------------------------------------#
# InternetGateway
# ------------------------------------------------------------# 
  InternetGateway:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags: 
        - Key: Name
          Value: test-igw

  InternetGatewayAttachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      InternetGatewayId: !Ref InternetGateway
      VpcId: !Ref VPC

# ------------------------------------------------------------#
# Subnet
# ------------------------------------------------------------# 
  PublicSubnet01:
    Type: AWS::EC2::Subnet
    Properties:
      AvailabilityZone: ap-northeast-1c
      CidrBlock: !Ref PublicSubnet01CIDR
      MapPublicIpOnLaunch: true
      Tags: 
        - Key: Name
          Value: test-pub-01
      VpcId: !Ref VPC

# ------------------------------------------------------------#
# RouteTable
# ------------------------------------------------------------# 
  PublicRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Name
          Value: test-pub-rtb

  PublicRouteTableRoute1:
    Type: AWS::EC2::Route
    Properties:
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref InternetGateway
      RouteTableId: !Ref PublicRouteTable

  PublicRtAssociation1:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref PublicRouteTable
      SubnetId: !Ref PublicSubnet01

# ------------------------------------------------------------#
# Security Group
# ------------------------------------------------------------# 
  EC2SG:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: for ec2
      GroupName: test-sg-ec2
      SecurityGroupEgress: 
        - CidrIp: 0.0.0.0/0
          FromPort: -1
          IpProtocol: -1
          ToPort: -1
      Tags: 
        - Key: Name
          Value: test-sg-ec2
      VpcId: !Ref VPC

# ------------------------------------------------------------#
# IAM
# ------------------------------------------------------------# 
  EC2IAMRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument: 
        Version: "2012-10-17"
        Statement: 
          - Effect: Allow
            Principal: 
              Service: 
                - ec2.amazonaws.com
            Action: 
              - 'sts:AssumeRole'
      ManagedPolicyArns: 
        - arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
      RoleName: test-iam-role-ec2
      Tags:
        - Key: Name
          Value: test-iam-role-ec2

  EC2IAMInstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      InstanceProfileName: test-iam-instanceprofile-ec2
      Roles: 
        - !Ref EC2IAMRole

# ------------------------------------------------------------#
# KeyPair
# ------------------------------------------------------------# 
  KeyPair:
    Type: AWS::EC2::KeyPair
    Properties: 
      KeyName: test-ec2-key
      KeyType: rsa
      Tags: 
        - Key: Name
          Value: test-ec2-key

# ------------------------------------------------------------#
# EC2
# ------------------------------------------------------------# 
  EC2:
    Type: AWS::EC2::Instance
    Properties:
      BlockDeviceMappings: 
        - DeviceName: /dev/xvda
          Ebs:
            DeleteOnTermination: true
            Encrypted: true
            Iops: !Ref EC2VolumeIOPS
            VolumeSize: !Ref EC2VolumeSize
            VolumeType: gp3
      DisableApiTermination: false
      EbsOptimized: true
      IamInstanceProfile: !Ref EC2IAMInstanceProfile
      ImageId: !Ref EC2AMI
      InstanceType: !Ref EC2InstanceType
      KeyName: !Ref KeyPair
      NetworkInterfaces: 
        - AssociatePublicIpAddress: true
          DeleteOnTermination: true
          DeviceIndex: 0
          GroupSet: 
            - !Ref EC2SG
          SubnetId: !Ref PublicSubnet01
      Tags:
        - Key: Name
          Value: test-ec2

以下の画像はCloudFormationで作成されるリソースの構成図です。

VPCとパブリックサブネットが作成されその中にEC2が一台起動するようになっています。

デプロイは以下のコマンドを実行します。
VPCのCIDRなどを変更したい場合はコマンドのオプションで「--parameters」を入れてください。

aws cloudformation create-stack --stack-name CloudFormationスタック名 --template-body file://CloudFormationテンプレートファイル名 --capabilities CAPABILITY_NAMED_IAM

接続確認

上記の手順でSession ManagerプラグインのインストールとEC2の起動まで行えたら以下のコマンドを実行してEC2へ接続確認します。

aws ssm start-session --target EC2のID

コマンドを実行してログインシェルが表示されていれば成功です。
念のため以下のコマンドでOSの情報を確認してみます。

cat /etc/os-release

実行すると以下の内容が表示されます。

NAME="Amazon Linux"
VERSION="2"
ID="amzn"
ID_LIKE="centos rhel fedora"
VERSION_ID="2"
PRETTY_NAME="Amazon Linux 2"
ANSI_COLOR="0;33"
CPE_NAME="cpe:2.3:o:amazon:amazon_linux:2"
HOME_URL="https://amazonlinux.com/"

さいごに

Session Managerでポートフォワーディングを行いEC2を踏み台にRDSへ接続することも可能なのでSession Managerを是非ご活用ください。
AWS Systems Manager Session Managerでポートフォワーディングを使用してリモートホストに接続する