【AWS CLI Samples】EC2

EC2

The execution of commands is primarily verified in AWS Cloud9.
If you would like to provide command examples, please submit them through the contact form.
You may also use this form to request corrections for the listed command examples.


Get the latest AMI ID for Amazon Linux 2.

aws ec2 describe-images \
--owners amazon \
--filters "Name=name,Values=amzn2-ami-hvm-2.0.*-x86_64-gp2" \
--query 'sort_by(Images, &CreationDate)[-1].ImageId' \
--output text

output

ami-0ce3d93513d1506e7

by anonymous

Get the latest AMI ID for Amazon Linux 2023.

aws ec2 describe-images \
--owners amazon \
--filters "Name=name,Values=al2023-ami-20*-kernel-6.1-x86_64" \
--query 'sort_by(Images, &CreationDate)[-1].ImageId' \
--output text

output

ami-0ab3794db9457b60a

by anonymous


Create a security group

aws ec2 create-security-group \
--group-name my-sg \
--description "My security group" \
--vpc-id vpc-1a2b3c4d

output

{
    "GroupId": "sg-903004f8"
}

by anonymous

[Security Group] Create a rule to allow HTTP from any source

aws ec2 authorize-security-group-ingress \
--group-id sg-903004f8 \
--protocol tcp \
--port 80 \
--cidr "0.0.0.0/0"

output

{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-abcdefghi01234561",
            "GroupId": "sg-903004f8",
            "GroupOwnerId": "6800000000003",
            "IsEgress": false,
            "IpProtocol": "tcp",
            "FromPort": 80,
            "ToPort": 80,
            "CidrIpv4": "0.0.0.0/0"
        }
    ]
}

by anonymous

[Security Group] Create an allow all rule from your public IP address

myip=$(curl -s https://checkip.amazonaws.com)
aws ec2 authorize-security-group-ingress \
--group-id sg-903004f8 \
--protocol -1 \
--cidr "$myip/32"

output

{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-abcdefghi01234562",
            "GroupId": "sg-903004f8",
            "GroupOwnerId": "6800000000003",
            "IsEgress": false,
            "IpProtocol": "-1",
            "FromPort": -1,
            "ToPort": -1,
            "CidrIpv4": "35.180.112.225/32"
        }
    ]
}

by anonymous

Launch an EC2 instance with the latest Amazon Linux 2023 AMI

ami=$(aws ec2 describe-images \
--owners amazon \
--filters "Name=name,Values=al2023-ami-20*-kernel-6.1-x86_64" \
--query 'sort_by(Images, &CreationDate)[-1].ImageId' \
--output text)
aws ec2 run-instances \
--image-id $ami \
--count 1 \
--instance-type t2.micro \
--key-name example_keypair \
--subnet-id subnet-0123456789abcde \
--security-group-ids sg-903004f8 sg-903004f9

output

{
    "Groups": [],
    "Instances": [
        {
            "AmiLaunchIndex": 0,
            "ImageId": "ami-0bb84b8ffd87024d8",
            "InstanceId": "i-5203422c",
            "InstanceType": "t2.micro",
            "KeyName": "example_keypair",
            "LaunchTime": "2013-07-19T02:42:39+00:00",
            "Monitoring": {
                "State": "disabled"
            },
            "Placement": {
                "AvailabilityZone": "us-east-1c",
                "GroupName": "",
                "Tenancy": "default"
            },
            "PrivateDnsName": "ip-10-0-1-114.ec2.internal",
            "PrivateIpAddress": "10.0.1.114",
            "ProductCodes": [],
            "PublicDnsName": "",
            "State": {
                "Code": 0,
                "Name": "pending"
            },
            "StateTransitionReason": "",
            "SubnetId": "subnet-0123456789abcde",
            "VpcId": "vpc-1a2b3c4d",
            "Architecture": "x86_64",
            "BlockDeviceMappings": [],
            "ClientToken": "a1234567-1111-2222-3333-a1b2c3d4e5f6",
            "EbsOptimized": false,
            "EnaSupport": true,
            "Hypervisor": "xen",
            "NetworkInterfaces": [
                {
                    "Attachment": {
                        "AttachTime": "2013-07-19T02:42:39+00:00",
                        "AttachmentId": "eni-attach-52193138",
                        "DeleteOnTermination": true,
                        "DeviceIndex": 0,
                        "Status": "attaching",
                        "NetworkCardIndex": 0
                    },
                    "Description": "",
                    "Groups": [
                        {
                            "GroupName": "default",
                            "GroupId": "sg-903004f9"
                        },
                        {
                            "GroupName": "my-sg",
                            "GroupId": "sg-903004f8"
                        }
                    ],
                    "Ipv6Addresses": [],
                    "MacAddress": "01:2e:3e:4e:5e:6e",
                    "NetworkInterfaceId": "eni-a7edb1c9",
                    "OwnerId": "6800000000003",
                    "PrivateDnsName": "ip-10-0-1-114.ec2.internal",
                    "PrivateIpAddress": "10.0.1.114",
                    "PrivateIpAddresses": [
                        {
                            "Primary": true,
                            "PrivateDnsName": "ip-10-0-1-114.ec2.internal",
                            "PrivateIpAddress": "10.0.1.114"
                        }
                    ],
                    "SourceDestCheck": true,
                    "Status": "in-use",
                    "SubnetId": "subnet-0123456789abcde",
                    "VpcId": "vpc-1a2b3c4d",
                    "InterfaceType": "interface"
                }
            ],
            "RootDeviceName": "/dev/xvda",
            "RootDeviceType": "ebs",
            "SecurityGroups": [
                {
                    "GroupName": "default",
                    "GroupId": "sg-903004f9"
                },
                {
                    "GroupName": "my-sg",
                    "GroupId": "sg-903004f8"
                }
            ],
            "SourceDestCheck": true,
            "StateReason": {
                "Code": "pending",
                "Message": "pending"
            },
            "VirtualizationType": "hvm",
            "CpuOptions": {
                "CoreCount": 1,
                "ThreadsPerCore": 1
            },
            "CapacityReservationSpecification": {
                "CapacityReservationPreference": "open"
            },
            "MetadataOptions": {
                "State": "pending",
                "HttpTokens": "required",
                "HttpPutResponseHopLimit": 2,
                "HttpEndpoint": "enabled",
                "HttpProtocolIpv6": "disabled",
                "InstanceMetadataTags": "disabled"
            },
            "EnclaveOptions": {
                "Enabled": false
            },
            "BootMode": "uefi-preferred",
            "PrivateDnsNameOptions": {
                "HostnameType": "ip-name",
                "EnableResourceNameDnsARecord": false,
                "EnableResourceNameDnsAAAARecord": false
            },
            "MaintenanceOptions": {
                "AutoRecovery": "default"
            },
            "CurrentInstanceBootMode": "legacy-bios"
        }
    ],
    "OwnerId": "6800000000003",
    "ReservationId": "r-5875ca20"
}

by anonymous

Delete an EC2 instance

aws ec2 terminate-instances \
--instance-ids i-5203422c

output

{
    "TerminatingInstances": [
        {
            "InstanceId": "i-5203422c",
            "CurrentState": {
                "Code": 32,
                "Name": "shutting-down"
            },
            "PreviousState": {
                "Code": 16,
                "Name": "running"
            }
        }
    ]
}

by anonymous

Delete a security group

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

output

None

by anonymous


See all EC2 instances

aws ec2 describe-instances \
--query 'Reservations[].Instances[].{InstanceId: InstanceId, PrivateIp: join(`, `, NetworkInterfaces[].PrivateIpAddress), Platform:Platform, State: State.Name, Name: Tags[?Key==`Name`].Value|[0]}' \
--output table

output

--------------------------------------------------------------------------
|                    DescribeInstances                           |
+----------------------+-------+-----------+-----------------+-----------+
|     InstanceId       | Name  | Platform  |    PrivateIp    |   State   |
+----------------------+-------+-----------+-----------------+-----------+
|  i-1234567890abcdef1 |  no1  |  None     |  172.31.100.101 |  running  |
|  i-1234567890abcdef2 |  no2  |  None     |  172.31.100.102 |  stopped  |
|  i-1234567890abcdef3 |  no3  |  None     |  172.31.100.103 |  stopped  |
|  i-1234567890abcdef4 |  no4  |  windows  |  172.31.100.104 |  stopped  |
+----------------------+-------+-----------+-----------------+-----------+

by anonymous

See all Windows EC2 instances

aws ec2 describe-instances \
--query 'Reservations[].Instances[?Platform==`windows`][].{InstanceId: InstanceId, PrivateIp: join(`, `, NetworkInterfaces[].PrivateIpAddress), Platform:Platform, State: State.Name, Name: Tags[?Key==`Name`].Value|[0]}' \
--output table

output

--------------------------------------------------------------------------
|                    DescribeInstances                           |
+----------------------+-------+-----------+-----------------+-----------+
|     InstanceId       | Name  | Platform  |    PrivateIp    |   State   |
+----------------------+-------+-----------+-----------------+-----------+
|  i-1234567890abcdef4 |  no4  |  windows  |  172.31.100.104 |  stopped  |
+----------------------+-------+-----------+-----------------+-----------+

by anonymous

See all Linux EC2 instances

aws ec2 describe-instances \
--query 'Reservations[].Instances[?Platform!=`windows`][].{InstanceId: InstanceId, PrivateIp: join(`, `, NetworkInterfaces[].PrivateIpAddress), Platform:Platform, State: State.Name, Name: Tags[?Key==`Name`].Value|[0]}' \
--output table

output

--------------------------------------------------------------------------
|                    DescribeInstances                           |
+----------------------+-------+-----------+-----------------+-----------+
|     InstanceId       | Name  | Platform  |    PrivateIp    |   State   |
+----------------------+-------+-----------+-----------------+-----------+
|  i-1234567890abcdef1 |  no1  |  None     |  172.31.100.101 |  running  |
|  i-1234567890abcdef2 |  no2  |  None     |  172.31.100.102 |  stopped  |
|  i-1234567890abcdef3 |  no3  |  None     |  172.31.100.103 |  stopped  |
+----------------------+-------+-----------+-----------------+-----------+

by anonymous


Allocation of Elastic IP addresses determined to be in Japan (JP) by RIR (100 attempts)

now=$(aws ec2 describe-addresses | grep '"PublicIp"' | wc -l)
quota=$(aws service-quotas list-service-quotas --service-code ec2 --query 'Quotas[?QuotaName==`EC2-VPC Elastic IPs`].Value' --output text | awk -F . '{print $1}')
vacant=$((quota - now))
k=0
array=()

for i in {1..100}; do
ip=$(aws ec2 allocate-address --query 'PublicIp' --output text)
dns=$(echo $ip | awk -F . '{print $4"."$3"."$2"."$1}')".cc.wariate.jp"
code=$(dig +short txt $dns)
echo $code $ip
let k++
array+=($ip)

if [ $code = "JP" ]; then
j=1
for v in "${array[@]}"; do
eip=$(aws ec2 describe-addresses --filters "Name=public-ip,Values=$v" --query Addresses[].AllocationId[] --output text)
if [ $j -ne $vacant ]; then
aws ec2 release-address --allocation-id $eip
fi
let j++
done
break
fi

if [ $k -eq $vacant ]; then
for v in "${array[@]}"; do
eip=$(aws ec2 describe-addresses --filters "Name=public-ip,Values=$v" --query Addresses[].AllocationId[] --output text)
aws ec2 release-address --allocation-id $eip
done
k=0
array=()
fi

sleep 2; done

output

"US" 54.168.131.200
"US" 54.168.131.201
"US" 54.168.131.202
"US" 54.168.131.203
"US" 54.168.131.204
"US" 54.168.131.205
"US" 54.168.131.206
...

by anonymous

タイトルとURLをコピーしました