

# Using Amazon EC2 in the AWS CLI
<a name="cli-services-ec2"></a>


| An introduction to Amazon Elastic Compute Cloud | 
| --- | 
|  [![AWS Videos](http://img.youtube.com/vi/https://www.youtube.com/embed/TsRBftzZsQo/0.jpg)](http://www.youtube.com/watch?v=https://www.youtube.com/embed/TsRBftzZsQo)  | 

Amazon Elastic Compute Cloud (Amazon EC2) provides highly scalable and flexible virtual computing environments. Amazon EC2 allows you to provision and manage virtual servers, known as Amazon EC2 instances, to meet a wide range of computing needs.

Amazon EC2 instances are virtual machines that can be customized with various configurations of CPU, memory, storage, and networking capabilities. You can choose from a diverse selection of instance types, ranging from lightweight, cost-effective options to powerful, high-performance instances, depending on your application requirements. This flexibility enables you to match your computing needs to optimize performance and cost-efficiency. 

Additionally, Amazon EC2 offers a suite of features that empowers you to manage your compute resources effectively. These include the ability to quickly launch new instances, create custom machine images (AMIs) for rapid deployment, and scaling computing capacity up or down as needed. 

You can access the features of Amazon EC2 using the AWS Command Line Interface (AWS CLI). To list the AWS CLI commands for Amazon EC2, use the following command.

```
aws ec2 help
```

Before you run any commands, set your default credentials. For more information, see [Configuring settings for the AWS CLI](cli-chap-configure.md).

This topic shows short-form examples of AWS CLI commands that perform common tasks for Amazon EC2.

For long-form examples of AWS CLI commands, see [AWS CLI code examples repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli) on *GitHub*.

**Topics**
+ [

# Creating, displaying, and deleting Amazon EC2 key pairs in the AWS CLI
](cli-services-ec2-keypairs.md)
+ [

# Creating, configuring, and deleting Amazon EC2 security groups in the AWS CLI
](cli-services-ec2-sg.md)
+ [

# Launching, listing, and deleting Amazon EC2 instances in the AWS CLI
](cli-services-ec2-instances.md)
+ [

# Change an Amazon EC2 instance type with a bash script in the AWS CLI
](cli-services-ec2-instance-type-script.md)

# Creating, displaying, and deleting Amazon EC2 key pairs in the AWS CLI
<a name="cli-services-ec2-keypairs"></a>

You can use the AWS Command Line Interface (AWS CLI) to create, display, and delete your key pairs for Amazon Elastic Compute Cloud (Amazon EC2). You use key pairs to connect to an Amazon EC2 instance. You can provide the key pair to Amazon EC2 when you create the instance, and then use that key pair to authenticate when you connect to the instance.

**Note**  
For additional command examples, see the [AWS CLI reference guide](https://docs.aws.amazon.com/cli/latest/reference/index.html).

**Topics**
+ [

## Prerequisites
](#cli-services-ec2-keypairs-prereqs)
+ [

## Create a key pair
](#creating-a-key-pair)
+ [

## Display your key pair
](#displaying-a-key-pair)
+ [

## Delete your key pair
](#deleting-a-key-pair)
+ [

## References
](#cli-services-ec2-keypairs-references)

## Prerequisites
<a name="cli-services-ec2-keypairs-prereqs"></a>

To run the `ec2` commands, you need to:
+ Install and configure the AWS CLI. For more information, see [Installing or updating to the latest version of the AWS CLI](getting-started-install.md) and [Authentication and access credentials for the AWS CLI](cli-chap-authentication.md).
+ Set your IAM permissions to allow for Amazon EC2 access. For more information about IAM permissions for Amazon EC2, see [IAM policies for Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-policies-for-amazon-ec2.html) in the *Amazon EC2 User Guide*.

## Create a key pair
<a name="creating-a-key-pair"></a>

To create a key pair, use the `[aws ec2 create-key-pair](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-key-pair.html)` command with the `--query` option, and the `--output text` option to pipe your private key directly into a file.

```
$ aws ec2 create-key-pair --key-name MyKeyPair --query 'KeyMaterial' --output text > MyKeyPair.pem
```

For PowerShell, the `> file` redirection defaults to UTF-8 encoding, which cannot be used with some SSH clients. So, you must convert the output by piping it to the `out-file` command and explicitly set the encoding to `ascii`.

```
PS C:\>aws ec2 create-key-pair --key-name MyKeyPair --query 'KeyMaterial' --output text | out-file -encoding ascii -filepath MyKeyPair.pem
```

The resulting `MyKeyPair.pem` file looks similar to the following.

```
-----BEGIN RSA PRIVATE KEY-----
EXAMPLEKEYKCAQEAy7WZhaDsrA1W3mRlQtvhwyORRX8gnxgDAfRt/gx42kWXsT4rXE/b5CpSgie/
vBoU7jLxx92pNHoFnByP+Dc21eyyz6CvjTmWA0JwfWiW5/akH7iO5dSrvC7dQkW2duV5QuUdE0QW
Z/aNxMniGQE6XAgfwlnXVBwrerrQo+ZWQeqiUwwMkuEbLeJFLhMCvYURpUMSC1oehm449ilx9X1F
G50TCFeOzfl8dqqCP6GzbPaIjiU19xX/azOR9V+tpUOzEL+wmXnZt3/nHPQ5xvD2OJH67km6SuPW
oPzev/D8V+x4+bHthfSjR9Y7DvQFjfBVwHXigBdtZcU2/wei8D/HYwIDAQABAoIBAGZ1kaEvnrqu
/uler7vgIn5m7lN5LKw4hJLAIW6tUT/fzvtcHK0SkbQCQXuriHmQ2MQyJX/0kn2NfjLV/ufGxbL1
mb5qwMGUnEpJaZD6QSSs3kICLwWUYUiGfc0uiSbmJoap/GTLU0W5Mfcv36PaBUNy5p53V6G7hXb2
bahyWyJNfjLe4M86yd2YK3V2CmK+X/BOsShnJ36+hjrXPPWmV3N9zEmCdJjA+K15DYmhm/tJWSD9
81oGk9TopEp7CkIfatEATyyZiVqoRq6k64iuM9JkA3OzdXzMQexXVJ1TLZVEH0E7bhlY9d8O1ozR
oQs/FiZNAx2iijCWyv0lpjE73+kCgYEA9mZtyhkHkFDpwrSM1APaL8oNAbbjwEy7Z5Mqfql+lIp1
YkriL0DbLXlvRAH+yHPRit2hHOjtUNZh4Axv+cpg09qbUI3+43eEy24B7G/Uh+GTfbjsXsOxQx/x
p9otyVwc7hsQ5TA5PZb+mvkJ5OBEKzet9XcKwONBYELGhnEPe7cCgYEA06Vgov6YHleHui9kHuws
ayav0elc5zkxjF9nfHFJRry21R1trw2Vdpn+9g481URrpzWVOEihvm+xTtmaZlSp//lkq75XDwnU
WA8gkn6O3QE3fq2yN98BURsAKdJfJ5RL1HvGQvTe10HLYYXpJnEkHv+Unl2ajLivWUt5pbBrKbUC
gYBjbO+OZk0sCcpZ29sbzjYjpIddErySIyRX5gV2uNQwAjLdp9PfN295yQ+BxMBXiIycWVQiw0bH
oMo7yykABY7Ozd5wQewBQ4AdSlWSX4nGDtsiFxWiI5sKuAAeOCbTosy1s8w8fxoJ5Tz1sdoxNeGs
Arq6Wv/G16zQuAE9zK9vvwKBgF+09VI/1wJBirsDGz9whVWfFPrTkJNvJZzYt69qezxlsjgFKshy
WBhd4xHZtmCqpBPlAymEjr/TOlbxyARmXMnIOWIAnNXMGB4KGSyl1mzSVAoQ+fqR+cJ3d0dyPl1j
jjb0Ed/NY8frlNDxAVHE8BSkdsx2f6ELEyBKJSRr9snRAoGAMrTwYneXzvTskF/S5Fyu0iOegLDa
NWUH38v/nDCgEpIXD5Hn3qAEcju1IjmbwlvtW+nY2jVhv7UGd8MjwUTNGItdb6nsYqM2asrnF3qS
VRkAKKKYeGjkpUfVTrW0YFjXkfcrR/V+QFL5OndHAKJXjW7a4ejJLncTzmZSpYzwApc=
-----END RSA PRIVATE KEY-----
```

Your private key isn't stored in AWS and can be retrieved ***only*** when it's created. You can't recover it later. Instead, if you lose the private key, you must create a new key pair.

If you're connecting to your instance from a Linux computer, we recommend that you use the following command to set the permissions of your private key file so that only you can read it.

```
$ chmod 400 MyKeyPair.pem
```

## Display your key pair
<a name="displaying-a-key-pair"></a>

A "fingerprint" is generated from your key pair, and you can use it to verify that the private key that you have on your local machine matches the public key that's stored in AWS. 

The fingerprint is an SHA1 hash taken from a DER-encoded copy of the private key. This value is captured when the key pair is created, and is stored in AWS with the public key. You can view the fingerprint in the Amazon EC2 console or by running the AWS CLI command `[aws ec2 describe-key-pairs](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-key-pairs.html)`. 

The following example displays the fingerprint for `MyKeyPair`.

```
$ aws ec2 describe-key-pairs --key-name MyKeyPair
{
    "KeyPairs": [
        {
            "KeyName": "MyKeyPair",
            "KeyFingerprint": "1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f"
        }
    ]
}
```

For more information about keys and fingerprints, see [Amazon EC2 Key Pairs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) in the *Amazon EC2 User Guide*.

## Delete your key pair
<a name="deleting-a-key-pair"></a>

To delete a key pair, run the `[aws ec2 delete-key-pair](https://docs.aws.amazon.com/cli/latest/reference/ec2/delete-key-pair.html)` command, substituting *`MyKeyPair`* with the name of the pair to delete.

```
$ aws ec2 delete-key-pair --key-name MyKeyPair
```

## References
<a name="cli-services-ec2-keypairs-references"></a>

**AWS CLI reference:**
+ `[aws ec2](https://docs.aws.amazon.com/cli/latest/reference/ec2/index.html)`
+ `[aws ec2 create-key-pair](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-key-pair.html)`
+ `[aws ec2 delete-key-pair](https://docs.aws.amazon.com/cli/latest/reference/ec2/delete-key-pair.html)`
+ `[aws ec2 describe-key-pairs](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-key-pairs.html)`

**Other reference:**
+ [Amazon Elastic Compute Cloud Documentation](https://docs.aws.amazon.com/ec2/)
+ To view and contribute to AWS SDK and AWS CLI code examples, see the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/) on *GitHub*.

# Creating, configuring, and deleting Amazon EC2 security groups in the AWS CLI
<a name="cli-services-ec2-sg"></a>

You can create a security group for your Amazon Elastic Compute Cloud (Amazon EC2) instances that essentially operates as a firewall, with rules that determine what network traffic can enter and leave. 

Use the AWS Command Line Interface (AWS CLI) to create a security group, add rules to existing security groups, and delete security groups. 

**Note**  
For additional command examples, see the [AWS CLI reference guide](https://docs.aws.amazon.com/cli/latest/reference/index.html).

**Topics**
+ [

## Prerequisites
](#cli-services-ec2-sg-prereqs)
+ [

## Create a security group
](#creating-a-security-group)
+ [

## Add rules to your security group
](#configuring-a-security-group)
+ [

## Delete your security group
](#deleting-a-security-group)
+ [

## References
](#cli-services-ec2-sg-references)

## Prerequisites
<a name="cli-services-ec2-sg-prereqs"></a>

To run the `ec2` commands, you need to:
+ Install and configure the AWS CLI. For more information, see [Installing or updating to the latest version of the AWS CLI](getting-started-install.md) and [Authentication and access credentials for the AWS CLI](cli-chap-authentication.md).
+ Set your IAM permissions to allow for Amazon EC2 access. For more information about IAM permissions for Amazon EC2, see [IAM policies for Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-policies-for-amazon-ec2.html) in the *Amazon EC2 User Guide*.

## Create a security group
<a name="creating-a-security-group"></a>

You can create security groups associated with virtual private clouds (VPCs) .

The following `[aws ec2 create-security-group](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-security-group.html)` example shows how to create a security group for a specified VPC.

```
$ aws ec2 create-security-group --group-name my-sg --description "My security group" --vpc-id vpc-1a2b3c4d
{
    "GroupId": "sg-903004f8"
}
```

To view the initial information for a security group, run the `[aws ec2 describe-security-groups](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-security-groups.html)` command. You can reference an EC2-VPC security group only by its `vpc-id`, not its name.

```
$ aws ec2 describe-security-groups --group-ids sg-903004f8
{
    "SecurityGroups": [
        {
            "IpPermissionsEgress": [
                {
                    "IpProtocol": "-1",
                    "IpRanges": [
                        {
                            "CidrIp": "0.0.0.0/0"
                        }
                    ],
                    "UserIdGroupPairs": []
                }
            ],
            "Description": "My security group"
            "IpPermissions": [],
            "GroupName": "my-sg",
            "VpcId": "vpc-1a2b3c4d",
            "OwnerId": "123456789012",
            "GroupId": "sg-903004f8"
        }
    ]
}
```

## Add rules to your security group
<a name="configuring-a-security-group"></a>

When you run an Amazon EC2 instance, you must enable rules in the security group to allow incoming network traffic for your means of connecting to the image. 

For example, if you're launching a Windows instance, you typically add a rule to allow inbound traffic on TCP port 3389 to support Remote Desktop Protocol (RDP). If you're launching a Linux instance, you typically add a rule to allow inbound traffic on TCP port 22 to support SSH connections. 

Use the `[aws ec2 authorize-security-group-ingress](https://docs.aws.amazon.com/cli/latest/reference/ec2/authorize-security-group-ingress.html)` command to add a rule to your security group. A required parameter of this command is the public IP address of your computer, or the network (in the form of an address range) that your computer is attached to, in [CIDR](https://wikipedia.org/wiki/Classless_Inter-Domain_Routing) notation.

**Note**  
We provide the following service, [https://checkip.global.api.aws/](https://checkip.global.api.aws/), to enable you to determine your public IP address. To find other services that can help you identify your IP address, use your browser to search for "*what is my IP address*". If you connect through an ISP or from behind your firewall using a dynamic IP address (through a NAT gateway from a private network), your address can change periodically. In that case, you must find out the range of IP addresses used by client computers.

The following example shows how to add a rule for RDP (TCP port 3389) to an EC2-VPC security group with the ID `sg-903004f8` using your IP address.

To start, find your IP address.

```
$ curl https://checkip.amazonaws.com
x.x.x.x
```

You can then add the IP address to your security group by running the `[aws ec2 authorize-security-group-ingress](https://docs.aws.amazon.com/cli/latest/reference/ec2/authorize-security-group-ingress.html)` command.

```
$ aws ec2 authorize-security-group-ingress --group-id sg-903004f8 --protocol tcp --port 3389 --cidr x.x.x.x/x
```

The following command adds another rule to enable SSH to instances in the same security group.

```
$ aws ec2 authorize-security-group-ingress --group-id sg-903004f8 --protocol tcp --port 22 --cidr x.x.x.x/x
```

To view the changes to the security group, run the `[aws ec2 describe-security-groups](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-security-groups.html)` command.

```
$ aws ec2 describe-security-groups --group-ids sg-903004f8
{
    "SecurityGroups": [
        {
            "IpPermissionsEgress": [
                {
                    "IpProtocol": "-1",
                    "IpRanges": [
                        {
                            "CidrIp": "0.0.0.0/0"
                        }
                    ],
                    "UserIdGroupPairs": []
                }
            ],
            "Description": "My security group"
            "IpPermissions": [
                {
                    "ToPort": 22,
                    "IpProtocol": "tcp",
                    "IpRanges": [
                        {
                            "CidrIp": "x.x.x.x/x"
                        }
                    ]
                    "UserIdGroupPairs": [],
                    "FromPort": 22
                }
            ],
            "GroupName": "my-sg",
            "OwnerId": "123456789012",
            "GroupId": "sg-903004f8"
        }
    ]
}
```

## Delete your security group
<a name="deleting-a-security-group"></a>

To delete a security group, run the `[aws ec2 delete-security-group](https://docs.aws.amazon.com/cli/latest/reference/ec2/delete-security-group.html)` command. 

**Note**  
You can't delete a security group if it's currently attached to an environment.

The following command example deletes an EC2-VPC security group.

```
$ aws ec2 delete-security-group --group-id sg-903004f8
```

## References
<a name="cli-services-ec2-sg-references"></a>

**AWS CLI reference:**
+ `[aws ec2](https://docs.aws.amazon.com/cli/latest/reference/ec2/index.html)`
+ `[aws ec2 authorize-security-group-ingress](https://docs.aws.amazon.com/cli/latest/reference/ec2/authorize-security-group-ingress.html)`
+ `[aws ec2 create-security-group](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-security-group.html)`
+ `[aws ec2 delete-security-group](https://docs.aws.amazon.com/cli/latest/reference/ec2/delete-security-group.html)`
+ `[aws ec2 describe-security-groups](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-security-groups.html)`

**Other reference:**
+ [Amazon Elastic Compute Cloud Documentation](https://docs.aws.amazon.com/ec2/)
+ To view and contribute to AWS SDK and AWS CLI code examples, see the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/) on *GitHub*.

# Launching, listing, and deleting Amazon EC2 instances in the AWS CLI
<a name="cli-services-ec2-instances"></a>

You can use the AWS Command Line Interface (AWS CLI) to launch, list, and delete Amazon Elastic Compute Cloud (Amazon EC2) instances. If you launch an instance that isn't within the AWS Free Tier, you are billed after you launch the instance and charged for the time that the instance is running, even if it remains idle.

**Note**  
For additional command examples, see the [AWS CLI reference guide](https://docs.aws.amazon.com/cli/latest/reference/index.html).

**Topics**
+ [

## Prerequisites
](#cli-services-ec2-instances-prereqs)
+ [

## Launch your instance
](#launching-instances)
+ [

## Add a block device to your instance
](#block-device-mapping)
+ [

## Add a tag to your instance
](#tagging-instances)
+ [

## Connect to your instance
](#connecting-to-instances)
+ [

## List your instances
](#listing-instances)
+ [

## Delete your instance
](#terminating-instances)
+ [

## References
](#cli-services-ec2-instances-references)

## Prerequisites
<a name="cli-services-ec2-instances-prereqs"></a>

To run the `ec2` commands in this topic, you need to:
+ Install and configure the AWS CLI. For more information, see [Installing or updating to the latest version of the AWS CLI](getting-started-install.md) and [Authentication and access credentials for the AWS CLI](cli-chap-authentication.md).
+ Set your IAM permissions to allow for Amazon EC2 access. For more information about IAM permissions for Amazon EC2, see [IAM policies for Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-policies-for-amazon-ec2.html) in the *Amazon EC2 User Guide*.
+ Create a [key pair](cli-services-ec2-keypairs.md) and a [security group](cli-services-ec2-sg.md).
+ Select an Amazon Machine Image (AMI) and note the AMI ID. For more information, see [Finding a Suitable AMI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html) in the *Amazon EC2 User Guide*.

## Launch your instance
<a name="launching-instances"></a>

To launch an Amazon EC2 instance using the AMI you selected, use the `[aws ec2 run-instances](https://docs.aws.amazon.com/cli/latest/reference/ec2/run-instances.html)` command. You can launch the instance into a virtual private cloud (VPC).

Initially, your instance appears in the `pending` state, but changes to the `running` state after a few minutes.

The following example shows how to launch a `t2.micro` instance in the specified subnet of a VPC. Replace the *italicized* parameter values with your own.

```
$ aws ec2 run-instances --image-id ami-xxxxxxxx --count 1 --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-903004f8 --subnet-id subnet-6e7f829e
{
    "OwnerId": "123456789012",
    "ReservationId": "r-5875ca20",
    "Groups": [
        {
            "GroupName": "my-sg",
            "GroupId": "sg-903004f8"
        }
    ],
    "Instances": [
        {
            "Monitoring": {
                "State": "disabled"
            },
            "PublicDnsName": null,
            "Platform": "windows",
            "State": {
                "Code": 0,
                "Name": "pending"
            },
            "EbsOptimized": false,
            "LaunchTime": "2013-07-19T02:42:39.000Z",
            "PrivateIpAddress": "10.0.1.114",
            "ProductCodes": [],
            "VpcId": "vpc-1a2b3c4d",
            "InstanceId": "i-5203422c",
            "ImageId": "ami-173d747e",
            "PrivateDnsName": "ip-10-0-1-114.ec2.internal",
            "KeyName": "MyKeyPair",
            "SecurityGroups": [
                {
                    "GroupName": "my-sg",
                    "GroupId": "sg-903004f8"
                }
            ],
            "ClientToken": null,
            "SubnetId": "subnet-6e7f829e",
            "InstanceType": "t2.micro",
            "NetworkInterfaces": [
                {
                    "Status": "in-use",
                    "SourceDestCheck": true,
                    "VpcId": "vpc-1a2b3c4d",
                    "Description": "Primary network interface",
                    "NetworkInterfaceId": "eni-a7edb1c9",
                    "PrivateIpAddresses": [
                        {
                            "PrivateDnsName": "ip-10-0-1-114.ec2.internal",
                            "Primary": true,
                            "PrivateIpAddress": "10.0.1.114"
                        }
                    ],
                    "PrivateDnsName": "ip-10-0-1-114.ec2.internal",
                    "Attachment": {
                        "Status": "attached",
                        "DeviceIndex": 0,
                        "DeleteOnTermination": true,
                        "AttachmentId": "eni-attach-52193138",
                        "AttachTime": "2013-07-19T02:42:39.000Z"
                    },
                    "Groups": [
                        {
                            "GroupName": "my-sg",
                            "GroupId": "sg-903004f8"
                        }
                    ],
                    "SubnetId": "subnet-6e7f829e",
                    "OwnerId": "123456789012",
                    "PrivateIpAddress": "10.0.1.114"
                }              
            ],
            "SourceDestCheck": true,
            "Placement": {
                "Tenancy": "default",
                "GroupName": null,
                "AvailabilityZone": "us-west-2b"
            },
            "Hypervisor": "xen",
            "BlockDeviceMappings": [
                {
                    "DeviceName": "/dev/sda1",
                    "Ebs": {
                        "Status": "attached",
                        "DeleteOnTermination": true,
                        "VolumeId": "vol-877166c8",
                        "AttachTime": "2013-07-19T02:42:39.000Z"
                    }
                }              
            ],
            "Architecture": "x86_64",
            "StateReason": {
                "Message": "pending",
                "Code": "pending"
            },
            "RootDeviceName": "/dev/sda1",
            "VirtualizationType": "hvm",
            "RootDeviceType": "ebs",
            "Tags": [
                {
                    "Value": "MyInstance",
                    "Key": "Name"
                }
            ],
            "AmiLaunchIndex": 0
        }
    ]
}
```

## Add a block device to your instance
<a name="block-device-mapping"></a>

Each instance that you launch has an associated root device volume. You can use block device mapping to specify additional Amazon Elastic Block Store (Amazon EBS) volumes or instance store volumes to attach to an instance when it's launched.

To add a block device to your instance, specify the `--block-device-mappings` option when you use `run-instances`.

The following example parameter provisions a standard Amazon EBS volume that is 20 GB in size, and maps it to your instance using the identifier `/dev/sdf`.

```
--block-device-mappings "[{\"DeviceName\":\"/dev/sdf\",\"Ebs\":{\"VolumeSize\":20,\"DeleteOnTermination\":false}}]"
```

The following example adds an Amazon EBS volume, mapped to `/dev/sdf`, based on an existing snapshot. A snapshot represents an image that is loaded onto the volume for you. When you specify a snapshot, you don't have to specify a volume size; it will be large enough to hold your image. However, if you do specify a size, it must be greater than or equal to the size of the snapshot.

```
--block-device-mappings "[{\"DeviceName\":\"/dev/sdf\",\"Ebs\":{\"SnapshotId\":\"snap-a1b2c3d4\"}}]"
```

The following example adds two volumes to your instance. The number of volumes available to your instance depends on its instance type.

```
--block-device-mappings "[{\"DeviceName\":\"/dev/sdf\",\"VirtualName\":\"ephemeral0\"},{\"DeviceName\":\"/dev/sdg\",\"VirtualName\":\"ephemeral1\"}]"
```

The following example creates the mapping (`/dev/sdj`), but doesn't provision a volume for the instance.

```
--block-device-mappings "[{\"DeviceName\":\"/dev/sdj\",\"NoDevice\":\"\"}]"
```

For more information, see [Block Device Mapping](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html) in the *Amazon EC2 User Guide*.

## Add a tag to your instance
<a name="tagging-instances"></a>

A tag is a label that you assign to an AWS resource. It enables you to add metadata to your resources that you can use for a variety of purposes. For more information, see [Tagging Your Resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) in the *Amazon EC2 User Guide*.

The following example shows how to add a tag with the key name "`Name`" and the value "`MyInstance`" to the specified instance, by using the `[aws ec2 create-tags](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-tags.html)` command.

```
$ aws ec2 create-tags --resources i-5203422c --tags Key=Name,Value=MyInstance
```

## Connect to your instance
<a name="connecting-to-instances"></a>

When your instance is running, you can connect to it and use it just as you'd use a computer sitting in front of you. For more information, see [Connect to Your Amazon EC2 Instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-to-linux-instance.html) in the *Amazon EC2 User Guide*.

## List your instances
<a name="listing-instances"></a>

You can use the AWS CLI to list your instances and view information about them. You can list all your instances, or filter the results based on the instances that you're interested in.

The following examples show how to use the `[aws ec2 describe-instances](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html)` command.

The following command lists all your instances.

```
$ aws ec2 describe-instances
```

The following command filters the list to only your `t2.micro` instances and outputs only the `InstanceId` values for each match.

```
$ aws ec2 describe-instances --filters "Name=instance-type,Values=t2.micro" --query "Reservations[].Instances[].InstanceId"
[
    "i-05e998023d9c69f9a"
]
```

The following command lists any of your instances that have the tag `Name=MyInstance`.

```
$ aws ec2 describe-instances --filters "Name=tag:Name,Values=MyInstance"
```

The following command lists your instances that were launched using any of the following AMIs: `ami-x0123456`, `ami-y0123456`, and `ami-z0123456`.

```
$ aws ec2 describe-instances --filters "Name=image-id,Values=ami-x0123456,ami-y0123456,ami-z0123456"
```

## Delete your instance
<a name="terminating-instances"></a>

You can use the AWS CLI to terminate (delete) an Amazon EC2 instance when you no longer need it.

**Important**  
**Terminating an instance is permanent and irreversible.**  
After you terminate an instance, you can no longer connect to it, and it can't be recovered. All attached Amazon EBS volumes that are configured to be deleted on termination are also permanently deleted and can't be recovered. All data stored on instance store volumes is permanently lost. For more information, see [ How instance termination works](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/how-ec2-instance-termination-works.html).  
Before you terminate an instance, ensure that you have backed up all data that you need to retain after the termination to persistent storage.

As soon as the state of the instance changes to `shutting-down` or `terminated`, you stop incurring charges for that instance. If you want to reconnect to an instance later, use [stop-instances](https://docs.aws.amazon.com/cli/v1/reference/ec2/stop-instances.html) instead of `terminate-instances`. For more information, see [Terminate Your Instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html) in the *Amazon EC2 User Guide*.

The following example shows how to delete an instance using the `[aws ec2 terminate-instances](https://docs.aws.amazon.com/cli/latest/reference/ec2/terminate-instances.html)` command.

```
$ aws ec2 terminate-instances --instance-ids i-5203422c
{
    "TerminatingInstances": [
        {
            "InstanceId": "i-5203422c",
            "CurrentState": {
                "Code": 32,
                "Name": "shutting-down"
            },
            "PreviousState": {
                "Code": 16,
                "Name": "running"
            }
        }
    ]
}
```

## References
<a name="cli-services-ec2-instances-references"></a>

**AWS CLI reference:**
+ `[aws ec2](https://docs.aws.amazon.com/cli/latest/reference/ec2/index.html)`
+ `[aws ec2 create-tags](https://docs.aws.amazon.com/cli/latest/reference/ec2/create-tags.html)`
+ `[aws ec2 describe-instances](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html)`
+ `[aws ec2 run-instances](https://docs.aws.amazon.com/cli/latest/reference/ec2/run-instances.html)`
+ `[aws ec2 terminate-instances](https://docs.aws.amazon.com/cli/latest/reference/ec2/terminate-instances.html)`

**Other reference:**
+ [Amazon Elastic Compute Cloud Documentation](https://docs.aws.amazon.com/ec2/)
+ To view and contribute to AWS SDK and AWS CLI code examples, see the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/) on *GitHub*.

# Change an Amazon EC2 instance type with a bash script in the AWS CLI
<a name="cli-services-ec2-instance-type-script"></a>

This bash scripting example for Amazon EC2 changes the instance type for an Amazon EC2 instance using the AWS Command Line Interface (AWS CLI). It stops the instance if it's running, changes the instance type, and then, if requested, restarts the instance. Shell scripts are programs designed to run in a command line interface.

**Note**  
For additional command examples, see the [AWS CLI reference guide](https://docs.aws.amazon.com/cli/latest/reference/index.html).

**Topics**
+ [

## Before you start
](#cli-services-ec2-instance-type-script-prereqs)
+ [

## About this example
](#cli-services-ec2-instance-type-script-about)
+ [

## Parameters
](#cli-services-ec2-instance-type-script-params)
+ [

## Files
](#cli-services-ec2-instance-type-script-files.title)
+ [

## References
](#cli-services-ec2-instance-type-script-references)

## Before you start
<a name="cli-services-ec2-instance-type-script-prereqs"></a>

Before you can run any of the below examples, the following things need to be completed.
+ Install and configure the AWS CLI. For more information, see [Installing or updating to the latest version of the AWS CLI](getting-started-install.md) and [Authentication and access credentials for the AWS CLI](cli-chap-authentication.md).
+ The profile that you use must have permissions that allow the AWS operations performed by the examples.
+ A running Amazon EC2 instance in the account for which you have permission to stop and modify. If you run the test script, it launches an instance for you, tests changing the type, and then terminates the instance.
+ As an AWS best practice, grant this code least privilege, or only the permissions required to perform a task. For more information, see [Grant Least Privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege) in the *AWS Identity and Access Management (IAM) User Guide*.
+ This code has not been tested in all AWS Regions. Some AWS services are available only in specific Regions. For more information, see [ Service Endpoints and Quotas](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html) in the *AWS General Reference Guide*. 
+ Running this code can result in charges to your AWS account. It is your responsibility to ensure that any resources created by this script are removed when you are done with them. 

## About this example
<a name="cli-services-ec2-instance-type-script-about"></a>

This example is written as a function in the shell script file `change_ec2_instance_type.sh` that you can `source` from another script or from the command line. Each script file contains comments describing each of the functions. Once the function is in memory, you can invoke it from the command line. For example, the following commands change the type of the specified instance to `t2.nano`:

```
$ source ./change_ec2_instance_type.sh
$ ./change_ec2_instance_type -i *instance-id* -t new-type
```

For the full example and downloadable script files, see [Change Amazon EC2 Instance Type](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2/change-ec2-instance-type) in the *AWS Code Examples Repository* on *GitHub*.

## Parameters
<a name="cli-services-ec2-instance-type-script-params"></a>

**-i** - *(string)* Specifies the instance ID to modify.

**-t** - *(string)* Specifies the Amazon EC2 instance type to switch to.

**-r** - *(switch)* By default, this is unset. If `-r` is set, restarts the instance after the type switch.

**-f** - *(switch)* By default, the script prompts the user to confirm shutting down the instance before making the switch. If `-f` is set, the function doesn't prompt the user before shutting down the instance to make the type switch

**-v** - *(switch)* By default, the script operates silently and displays output only in the event of an error. If `-v` is set, the function displays status throughout its operation.

## Files
<a name="cli-services-ec2-instance-type-script-files.title"></a>

**`change_ec2_instance_type.sh`**  
The main script file contains the `change_ec2_instance_type()` function that performs the following tasks:  
+ Verifies that the specified Amazon EC2 instance exists.
+ Unless `-f` is selected, warns the user before stopping the instance.
+ Changes the instance type
+ If you set `-r`, restarts the instance and confirms that the instance is running
View the code for `[change\$1ec2\$1instance\$1type.sh](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/aws-cli/bash-linux/ec2/change-ec2-instance-type/change_ec2_instance_type.sh)` on *GitHub*.

**`test_change_ec2_instance_type.sh`**  
The file `test_change_ec2_instance_type.sh` script tests the various code paths for the `change_ec2_instance_type` function. If all steps in the test script work correctly, the test script removes all resources that it created.  
You can run the test script with the following parameters:  
+ **-v** - *(switch)* The each test shows a pass/failure status as they run. By default, the tests runs silently and the output includes only the final overall pass/failure status.
+ **-i** - *(switch)* The script pauses after each test to enable you to browse the intermediate results of each step. Enables you to examine the current status of the instance using the Amazon EC2 console. The script proceeds to the next step after you press *ENTER* at the prompt.
View the code for `[test\$1change\$1ec2\$1instance\$1type.sh](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/aws-cli/bash-linux/ec2/change-ec2-instance-type/test_change_ec2_instance_type.sh)` on *GitHub*.

**`awsdocs_general.sh`**  
The script file `awsdocs_general.sh` holds general purpose functions used across advanced examples for the AWS CLI.  
View the code for `[awsdocs\$1general.sh](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/aws-cli/bash-linux/ec2/change-ec2-instance-type/awsdocs_general.sh)` on *GitHub*.

## References
<a name="cli-services-ec2-instance-type-script-references"></a>

**AWS CLI reference:**
+ `[aws ec2](https://docs.aws.amazon.com/cli/v1/reference/ec2/index.html)`
+ `[aws ec2 describe-instances](https://docs.aws.amazon.com/cli/v1/reference/ec2/describe-instances.html)`
+ `[aws ec2 modify-instance-attribute](https://docs.aws.amazon.com/cli/v1/reference/ec2/modify-instance-attribute.html)`
+ `[aws ec2 start-instances](https://docs.aws.amazon.com/cli/v1/reference/ec2/start-instances.html)`
+ `[aws ec2 stop-instances](https://docs.aws.amazon.com/cli/v1/reference/ec2/stop-instances.html)`
+ `[aws ec2 wait instance-running](https://docs.aws.amazon.com/cli/v1/reference/ec2/wait/instance-running.html)`
+ `[aws ec2 wait instance-stopped](https://docs.aws.amazon.com/cli/v1/reference/ec2/wait/instance-stopped.html)`

**Other reference:**
+ [Amazon Elastic Compute Cloud Documentation](https://docs.aws.amazon.com/ec2/)
+ To view and contribute to AWS SDK and AWS CLI code examples, see the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/) on *GitHub*.