Search code examples
amazon-web-servicesamazon-ec2aws-cloudformationaws-security-group

AWS - SSH into EC2 created via Cloudformation


I am new to AWS and I wanted to ask this. Is there a way to SSH into an EC2 instance created via Cloudformation?

I just wanted to ask since key pairs are generated upon manual creation of EC2 instances in the AWS console right? What if the EC2 was created from Cloudformation?


Solution

  • When you create an ec2 instance, then you can use an existing KeyPair to login into the other hosts. You just need to provide the existing KeyPair whenever you create any instance. Make sure KeyPair file has been downloaded after creating it.

    In case of cloudformation, just mention the same keyPair in Template.

    Below is the sample cloudformation yaml having KeyPair mentioned :

    ---
    Resources:
      MyInstance:
        Type: AWS::EC2::Instance
        Properties:
          AvailabilityZone: us-east-1a
          ImageId: ami-0b898040803850657
          InstanceType: t2.micro
          KeyName : EssentialKeyPair
    

    You need to make sure it is present in the EC2 Dashboard as well

    enter image description here

    Once stack creates your EC2 instance, just log in to the host using below command :

    ssh -i EssentialKeyPair.pem ec2-user@<Public-IP>
    

    You can verify whether your instance is using the same keyPair that you have provided in the Template through EC2 Dashboard :

    enter image description here