Login to EC2 Instance through Systems Manager - Session Manager

Login to EC2 Instance through Systems Manager - Session Manager

Takahiro Iwasa
(岩佐 孝浩)
Takahiro Iwasa (岩佐 孝浩)
2 min read
EC2 Session Manager Systems Manager

AWS users can log in to EC2 instances using Systems Manager - Session Manager. It can help you secure AWS accounts with no additional costs. For example, you can accomplish the following:

  • No SSH keys
  • No bastion hosts
  • No security group inbound rules with 22 port opened

For detailed information, please refer to the official documentation.

Creating AWS Resources

An IAM role attached to an EC2 instance needs AmazonSSMManagedInstanceCore the managed policy. (line 31)

AWSTemplateFormatVersion: 2010-09-09
Resources:
  EC2:
    Type: AWS::EC2::Instance
    Properties:
      IamInstanceProfile: !Ref InstanceProfile
      ImageId: ami-0f310fced6141e627 # Amazon Linux 2 AMI (HVM), SSD Volume Type
      InstanceType: t3.small
      SecurityGroups:
        - !Ref SecurityGroup

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

  IamRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service: ec2.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        # Necessary for Session Manager
        - arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
      RoleName: ec2-role

  SecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Example
      GroupName: ec2-security-group
      SecurityGroupIngress:
        - CidrIp: 0.0.0.0/0
          FromPort: 443
          IpProtocol: tcp
          ToPort: 443

Deploy the CloudFormation stack with the following command.

aws cloudformation deploy --template-file template.yaml --stack-name ec2-session-manager --capabilities CAPABILITY_NAMED_IAM

If you intend to connect to EC2 instances in private subnets, you need the following VPC endpoints. For more information, please refer to an official documentation.

  • com.amazonaws.region.ssm
  • com.amazonaws.region.ec2messages
  • com.amazonaws.region.ssmmessages

Logging In to EC2 Instance

Replace i-xxxxxxxxxxxxxxxxx with your actual instance ID, and run the following command. It should succeed to log in.

$ aws ssm start-session --target i-xxxxxxxxxxxxxxxxx

Starting session with SessionId: iwasa.takahiro-xxxxxxxxxxxxxxxxx
sh-4.2$

Cleaning Up

Clean up the provisioned AWS resources with the following command.

aws cloudformation delete-stack --stack-name ec2-session-manager
Takahiro Iwasa
(岩佐 孝浩)

Takahiro Iwasa (岩佐 孝浩)

Software Developer at iret, Inc.
Architecting and developing cloud native applications mainly with AWS. Japan AWS Top Engineers 2020-2023