【AWS CLI 샘플 모음】EC2

EC2

명령어 실행 가능 여부는 주로 AWS Cloud9에서 확인하고 있습니다.
명령어 예시를 제공해 주실 분은 문의 양식을 통해 보내 주세요.
기재된 명령어 예시의 수정 요청도 이곳에서 연락해 주세요.


Amazon Linux 2의 최신 AMI ID를 가져옵니다.

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

출력

ami-0ce3d93513d1506e7

by anonymous

Amazon Linux 2023의 최신 AMI ID를 가져옵니다.

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

출력

ami-0ab3794db9457b60a

by anonymous


보안 그룹 만들기

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

출력

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

by anonymous

[보안 그룹] 모든 소스에서 HTTP 권한 부여 규칙 만들기

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

출력

{
    "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

[보안 그룹] 자신의 공용 IP 주소에서 모든 권한 부여 규칙 만들기

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

출력

{
    "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

최신 Amazon Linux 2023 AMI에서 EC2 인스턴스 시작

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

출력

{
    "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

EC2 인스턴스 삭제

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

출력

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

by anonymous

보안 그룹 삭제

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

출력

None

by anonymous


모든 EC2 인스턴스 참조

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

출력

--------------------------------------------------------------------------
|                    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

모든 Windows EC2 인스턴스 찾아보기

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

출력

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

by anonymous

모든 Linux EC2 인스턴스 찾아보기

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

출력

--------------------------------------------------------------------------
|                    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


RIR에서 일본(JP)으로 판정되는 Elastic IP 주소 할당(100회 시도)

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

출력

"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をコピーしました