Simplified Guide to Logging into EC2 Instances Using Systems Manager - Session Manager
Introduction
AWS Systems Manager - Session Manager provides a secure and efficient way to manage EC2 instances without requiring SSH keys, bastion hosts, or open ports. This guide will walk you through setting up and using Session Manager, ensuring your AWS environment remains secure and cost-effective.
For more detailed information, visit the official documentation.
Why Use Session Manager
- No SSH keys: Eliminates the need to manage and secure SSH keys.
- No bastion hosts: Removes the requirement for intermediary servers to access EC2 instances.
- No inbound rules on port 22: Improves security by avoiding open ports in your security group.
Setting Up AWS Resources
To use Session Manager, you need an IAM role with the AmazonSSMManagedInstanceCore policy attached to your EC2 instance (line 30). Below is an example CloudFormation template for setting this up:
AWSTemplateFormatVersion: 2010-09-09
Resources:
EC2:
Type: AWS::EC2::Instance
Properties:
IamInstanceProfile: !Ref InstanceProfile
ImageId: ami-0f310fced6141e627
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:
- 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 stack using the following command:
aws cloudformation deploy --template-file template.yaml --stack-name ec2-session-manager --capabilities CAPABILITY_NAMED_IAM
Additional Configuration for Private Subnets
If your EC2 instances are in private subnets, set up the following VPC endpoints:
com.amazonaws.region.ssm
com.amazonaws.region.ec2messages
com.amazonaws.region.ssmmessages
Refer to the VPC endpoints documentation for more details.
Logging Into EC2 Instances
To start a session with your instance, replace i-xxxxxxxxxxxxxxxxx
with your instance ID and run the following command:
aws ssm start-session --target i-xxxxxxxxxxxxxxxxx
The output will indicate a successful login:
Starting session with SessionId: your-session-id
sh-4.2$
Cleaning Up Resources
To delete the provisioned resources, run the following command:
aws cloudformation delete-stack --stack-name ec2-session-manager
Conclusion
AWS Systems Manager - Session Manager simplifies EC2 instance management by removing the need for traditional SSH keys and bastion hosts. Its secure and cost-effective design makes it an excellent choice for modern AWS architectures.
Happy Coding! 🚀