How do i create an aws ec2 instance using the cli?



  • Note: Making the assumption you have setup your access credentials using "aws configure" first.

    We use the aws ec2 run-instances command to create EC2 instances, it requires some input values, An AMI ID, the type of instance, a security group, and a ssh key-pair.

    Get the AMI ID

    Use aws describe-images to find the ami id, sorted by date order.

    $ aws ec2 describe-images --filters "Name=description,Values=Amazon Linux AMI * x86_64 HVM GP2"  --query 'Images[*].[CreationDate, Description, ImageId]' --output text | sort -k 1 | tail
    2016-10-29T00:50:47.000Z	Amazon Linux AMI 2016.09.0.20161028 x86_64 HVM GP2	ami-5ec1673e
    2016-12-20T23:24:47.000Z	Amazon Linux AMI 2016.09.1.20161221 x86_64 HVM GP2	ami-1e299d7e
    2017-01-20T23:39:56.000Z	Amazon Linux AMI 2016.09.1.20170119 x86_64 HVM GP2	ami-f173cc91
    2017-03-20T09:29:58.000Z	Amazon Linux AMI 2017.03.rc-0.20170320 x86_64 HVM GP2	ami-463ab226
    2017-03-28T01:56:52.000Z	Amazon Linux AMI 2017.03.rc-1.20170327 x86_64 HVM GP2	ami-b275e0d2
    2017-04-02T05:52:50.000Z	Amazon Linux AMI 2017.03.0.20170401 x86_64 HVM GP2	ami-8ca83fec
    2017-04-17T08:14:47.000Z	Amazon Linux AMI 2017.03.0.20170417 x86_64 HVM GP2	ami-4836a428
    2017-05-12T00:47:38.000Z	Amazon Linux AMI 2017.03.0.20170417 x86_64 HVM GP2	ami-2cd2b74c
    2017-06-17T21:56:55.000Z	Amazon Linux AMI 2017.03.1.20170617 x86_64 HVM GP2	ami-a07379d9
    2017-06-23T23:30:48.000Z	Amazon Linux AMI 2017.03.1.20170623 x86_64 HVM GP2	ami-6df1e514
    

    Get the instance type.
    Take a look at the instance type and choose one. https://aws.amazon.com/ec2/instance-types/

    Create the security group.
    In order to create a security group you need to place it within a particular VPC. Determine which VPC you want your security group using this command:

    $ aws ec2 describe-vpcs
    

    then

    $ aws ec2 create-security-group --group-name TestInstance --description "Test Instance" --vpc-id <your VPC>
    

    Enable ssh access into the instance. Restrict the CIDR ip to your own IP, using common cidr notation: eg: 0.0.0.0/0

    $ aws ec2 authorize-security-group-ingress --group-name TestInstace --protocol tcp --port 22 --cidr <your ip>
    

    Verify the security group details.

    $ aws ec2 describe-security-groups --group-names TestInstance --output text
    

    Create you ssh key-pair.

    $ aws ec2 create-key-pair --key-name TestInstance
    

    Copy everything from BEGIN line to END line and echo it out to a file.

    $ echo "BEGIN.......END" > ~/.ssh/testinstance.pem
    $ chmod 600 ~/.ssh/testinstance.pem
    

    Finally create your instance.

    $ aws ec2 run-instances --instance-type t2.medium --key-name TestInstance --security-group-ids sg-12edt0d --image-id ami-b4q7rst2
    

Log in to reply
 

© Lightnetics 2024