Create an Amazon EC2 instance with Session Manager access using Terraform

Sometimes, connecting an EC2 instance after provisioning is necessary to verify whether the user-data script ran successfully, review if something is passing/failing, etc. As of August 2023, there are four ways of connecting to an Amazon EC2 instance running on Linux from the AWS console  -EC2 Instance Connect, Session Manager, SSH client, and EC2 serial console. Connecting to an Amazon EC2 instance using Session Manager is easiest and most secure.

Using Terraform, an IaC engineer can manage access to an Amazon EC2 instance by attaching an IAM role to the EC2 instance. Previously, I wrote a note explaining the steps in detail. You can read that at  -attach-iam-role-to-aws-ec2-instance-using-terraform. I will be borrowing heavily from that on this note.

Amazon has a managed policy that enables access to an EC2 instance from the AWS console. It is the arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore managed policy. Now that we have identified the managed permission policy, there are only four easy concepts to apply.

(a) create a aws_iam_role Terraform resource with an assume_role_policy for the ec2.amazonaws.com principal,
81-image-2
(b) Attach the AmazonSSMManagedInstanceCore managed policy to the role,
81-image-3
(c) create the aws_iam_instance_profile role from the aws_iam_role,
81-image-4
and finally, (d) attach the iam_instance_profile to the EC2 instance.
81-image-5
If you want the Terraform code sample, look at my GitHub repository: ec2-userdata-terraform.
Please note that the branch name is  add-iam-role-for-session-manager. The GitHub repository includes the necessary code to provision additional resources like the VPC, subnet, route table, internet gateway, etc. Using the code in the GitHub repository, you can create an EC2 instance and connect to that using the session manager from the AWS Console. While reviewing the code, please review the security group rule. The security group attached to the Amazon EC2 instance does not have an ingress rule. The session manager bypasses the ingress security group rule. However, it requires the egress rule to communicate with the SSM endpoint.
81-image-6
After running the Terraform code, you will see that an Amazon EC2 instance has been created in your AWS console. Select the instance and click on the Connect button. You will be presented with the below options, in case of Linux.
81-image-1
Select “Session Manager” and click on Connect. You will then have CLI access to the instance.
There are specific AMIs that support session manager access. These AMIs are mentioned in this user guide: AWS Systems Manager. If interested, try to provision the resources using the Terraform code from the GitHub repository. Please let me know if you have any questions or suggestions.

3 thoughts on “Create an Amazon EC2 instance with Session Manager access using Terraform

Leave a comment