Working with EC2 from the command line
Published: 2023-05-11 17:29:58

If you landed here by parachute and don't know how to configure LocalStack to simulate an AWS environment, follow this post: [Simulating AWS CLI with LocalStack](https://dev.to/israellopes/simulating-aws-cli-with-localstack-42kb)

<br />

What is EC2?

EC2 (Elastic Compute Cloud) is a cloud computing service from Amazon Web Services (AWS) that allows you to create and manage virtual machine instances in the cloud. EC2 instances provide scalable and flexible computing resources, allowing you to run applications and workloads in a virtualized environment.

Let's move forward now.

To upload our simulated aws environment, do:

``sudo docker run --rm -it -p 4566:4566 -p 4571:4571 localstack/localstack``

Let's create our first EC2 in CLI. To get started, follow the steps described in the line below:

To create EC2:``aws ec2 run-instances --image-id <ami-id> --instance-type <instance-type> --key-name <key-pair-name> --security-group-ids <security-group-id> --subnet-id <subnet-id> --count <number-of-instances>``

To run the EC2 create command, we need to provide details like IAM image type, number of instances, security group, access keys and other options.

--image-id: The ID of the Amazon Machine Image (AMI) image that will be used to create the EC2 instance. The AMI is the foundation for the instance and defines the operating system and other preinstalled software.

--instance-type: The type of EC2 instance you want to create. The instance type determines the compute resources, such as CPU, memory, and storage capacity, available to the instance.

  --key-name: The name of the key pair that you want to associate with the EC2 instance. This allows you to log into the instance using SSH (Secure Shell).

--security-group-ids: The security group ID that you want to associate the EC2 instance with. The security group defines the allowed traffic rules for the instance.

--subnet-id: The ID of the subnet (subnet) you want to launch the EC2 instance into. The subnet determines the network the instance will be placed on and can affect instance connectivity and availability.

--count: The number of EC2 instances you want to create. Specifies how many identical instances will be created.

We will then need to specify this information, let's follow below:

In order to choose our image for EC2, we can use the following command to list the images available on AWS: aws ec2 describe-images, note that it will return a very large json object with details of the image architecture.

Example of command output:
```
},
        {
            "Architecture": "x86_64",
            "CreationDate": "2023-05-11T09:57:08.000Z",
            "ImageId": "ami-fbc1c684",
            "ImageLocation": "None",
            "ImageType": "machine",
            "Public": true,
            "KernelId": "None",
            "OwnerId": "591542846629",
            "RamdiskId": "ari-1a2b3c4d",
            "State": "available",
            "BlockDeviceMappings": [
                {
                    "DeviceName": "/dev/xvda",
                    "Ebs": {
                        "DeleteOnTermination": false,
                        "SnapshotId": "snap-00e5f6c8",
                        "VolumeSize": 15,
                        "VolumeType": "standard"
                    }
                }
            ],
            "Description": "Amazon Linux AMI 2018.03.b x86_64 ECS HVM GP2",
            "Hypervisor": "xen",
            "ImageOwnerAlias": "amazon",
            "Name": "amzn-ami-2018.03.b-amazon-ecs-optimized",
            "RootDeviceName": "/dev/xvda",
            "RootDeviceType": "ebs",
            "Tags": [],
            "VirtualizationType": "hvm"
        },
```

Now we have to create a new security group, because it is he who will determine entry and exit rules. We must inform the name of the group we want to create and its description:

``aws ec2 create-security-group --group-name MyGroupTest --description "group description"``

Running the command returns something like this:

```
{
    "GroupId": "sg-0937433e1dbd16c91",
    "Tags": []
}
```
Keep the GroupId as it will be useful to create the EC2. If you already have a security-group already created, you can list them as follows: aws ec2 describe-security-groups. This will list all the groups you have.

We can also apply filters if you know the name of the group, in this case just use the name of the group we just created:

``aws ec2 describe-security-groups --filters "Name=group-name,Values=MyGroupTest"``

Let's move on.

Let's get the subnet-id, for that we can list them with the following:

``aws ec2 describe-subnets``

We can apply filters if we want too:

``aws ec2 describe-subnets --filters "Name=subnet-id,Values=<subnet-id>"``

I will use as an example the id "subnet-b8a4b5ff".

Let's get instance-type, just do the command to list:

``aws ec2 describe-instance-types``

In the return what interests us is the InstanceType field, it contains the name of the instance.

Finally, let's get the key-name, which is the name of the access key (key pair) that you will use to connect to the EC2 instance. This access key is a pair of public or private keys that are used to authenticate access to the EC2 instance.

If you already have one, we can list it as follows:

``aws ec2 describe-key-pairs``

In my case I don't have it yet, so I'll have to create one, follow the step:

``aws ec2 create-key-pair --key-name MyKeyPairTest --output text > MyKeyPairTest.pem``

This will create a new passkey called MyKeyPairTest and save the private key in the MyKeyPairTest.pem file, just be sure to save it in a safe place.

Now that we've collected all the necessary information, we can create EC2, mine looks like this:

```
aws ec2 run-instances \
  --image-id "ami-fbc1c684" \
  --instance-type "d3.2xlarge" \
  --key-name "MyKeyPairTest" \
  --security-group-ids "sg-0937433e1dbd16c91" \
  --subnet-id "subnet-b8a4b5ff" \
  --count 2
```

Now just run the command above to create our first EC2. Next step now and start our EC2 instance, just follow the example below:

``aws ec2 start-instances --instance-ids <instance-id>``

Standing as follows: ``aws ec2 start-instances --instance-ids "i-304d1f1933d722ab6"``

This is the successful return we want to have:

```
{
    "StartingInstances": [
        {
            "CurrentState": {
                "Code": 0,
                "Name": "pending"
            },
            "InstanceId": "i-304d1f1933d722ab6",
            "PreviousState": {
                "Code": 16,
                "Name": "running"
            }
        }
    ]
}
```

Here we finish our learning about EC2.

<br />

[![Texto alternativo da imagem](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ds4alkts3uxq0dsco0nv.png)](https://www.linkedin.com/in/israel-lopes-419a32189)