AWS study notes (1)--CLI basics

1. Installing the AWS CLI
Install the AWS CLI Using pip on linux
1) Install python
---Check to see if Python is already installed---
$ python --version


---Install python---
$ sudo yum install python


2) Install pip
---check pip---
$ pip -V


---install pip---
$ curl -O https://bootstrap.pypa.io/get-pip.py
$ sudo python get-pip.py

 

If an old version of pip has been installed, it will not be updated by executing the above command again. How to update, please execute the following command:

pip install --upgrade pip


3) Install AWS CLI
$ sudo pip install awscli


4) Test AWS CLI
$ aws help
Enter q to exit


2. Configuring the AWS CLI
$ aws configure
AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Default region name [None]: cn-north-1
Default output format [None]: json

 

The AWS CLI will prompt you for four pieces of information.
These information will be saved in ~/.aws/credentials, ~/.aws/config files respectively. The next time you run this command, just press Enter for the items that do not need to be changed.


To get your access key ID and secret access key
1) Open the IAM console.
2) In the navigation pane, choose Users.
3) Choose your IAM user name (not the check box).
4) Choose the Security Credentials tab and then choose Create Access Key.
5) To see your access key, choose Show User Security Credentials. Your credentials will look something like this:
    Access Key ID: AKIAIOSFODNN7EXAMPLE
    Secret Access Key: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
6) Choose Download Credentials, and store the keys in a secure location


Be sure to save it, it's only one chance. If it is not saved, it can only be deleted and rebuilt, and multiple keys can be created.


Named Profiles
The AWS CLI supports named profiles stored in the config and credentials files. You can configure additional profiles by using aws configure with the --profile option or by adding entries to the config and credentials files.

 

Command Line Options

--profile – name of a profile to use, or "default" to use the default profile.
--region – AWS region to call.
--output – output format. 支持json(默认),text,table
--endpoint-url – The endpoint to make the call against. The endpoint can be the address of a proxy or an endpoint URL for the in-use AWS region. 一般情况下不需指定,CLI基于使用的region决定。

 

Example: describe instances

$ aws ec2 describe-instances --output table --region cn-north-1
displays all instances under the cn-north-1 region in table form

 

Note: The machine time must be synchronized with the server, otherwise the following error will be reported: AWS was not able to validate the provided access credentials


Time synchronization method:
$ sudo yum install ntp
$ sudo service ntpd start


3. Using the AWS CLI
1) 查看帮助
$ aws help
$ aws ec2 help
$ aws ec2 describe-instances help


2) Filter & Query
--filter option to set filter conditions:
$ aws ec2 describe-instances --output table --region cn-north-1 --filter Name=availability-zone,Values=cn-north-1b

Use quotation marks if Values ​​contains spaces, and see the help for the parameters supported by filter Name.


The syntax for combining multiple conditions is as follows:
$ aws ec2 describe-instances --filters Name=instance-type,Values=m1.small,m1.medium Name=availability-zone,Values=us-west-2c

 

Load parameters from file:

$ aws ec2 describe-instances --filters file://filter.json

 

[
  {
    "Name": "instance-type",
    "Values": ["t2.micro", "m1.medium"]
  },
  {
    "Name": "availability-zone",
    "Values": ["us-west-2c"]
  }
]

 

Find by custom tag:

aws ec2 describe-instances --filter Name=tag:Name,Values=prod-asd-app1-1a

 

The --query option customizes the content and style of the output

Show the first volume in the Volumeslist

$ aws ec2 describe-volumes --query 'Volumes[0]'
{
    "AvailabilityZone": "us-west-2a",
    "Attachments": [
        {
            "AttachTime": "2013-09-17T00:55:03.000Z",
            "InstanceId": "i-a071c394",
            "VolumeId": "vol-e11a5288",
            "State": "attached",
            "DeleteOnTermination": true,
            "Device": "/dev/sda1"
        }
    ],
    "VolumeType": "standard",
    "VolumeId": "vol-e11a5288",
    "State": "in-use",
    "SnapshotId": "snap-f23ec1c8",
    "CreateTime": "2013-09-17T00:55:03.000Z",
    "Size": 30
}

 

Iterates through the entire list and filters out three elements: VolumeId, AvailabilityZoneandSize,并指定别名:

$ aws ec2 describe-volumes --query 'Volumes[*].{ID:VolumeId,AZ:AvailabilityZone,Size:Size}'
[
    {
        "AZ": "us-west-2a",
        "ID": "vol-e11a5288",
        "Size": 30
    },
    {
        "AZ": "us-west-2a",
        "ID": "vol-2e410a47",
        "Size": 8
    }
]

 

Use the key1.key2[0].key3 syntax to filter elements deeply nested in the structure:

$ aws ec2 describe-volumes --query 'Volumes[*].{ID:VolumeId,InstanceId:Attachments[0].InstanceId,AZ:AvailabilityZone,Size:Size}'
[
    {
        "InstanceId": "i-a071c394",
        "AZ": "us-west-2a",
        "ID": "vol-e11a5288",
        "Size": 30
    },
    {
        "InstanceId": "i-4b41a37c",
        "AZ": "us-west-2a",
        "ID": "vol-2e410a47",
        "Size": 8
    }
]

 

If no alias is specified, it will be output in order:

$ aws ec2 describe-volumes --query 'Volumes[*].[VolumeId, Attachments[0].InstanceId, AvailabilityZone, Size]'
[
    [
        "vol-e11a5288",
        "i-a071c394",
        "us-west-2a",
        30
    ],
    [
        "vol-2e410a47",
        "i-4b41a37c",
        "us-west-2a",
        8
    ]
]

 

Filter results by the value of a specific field:

$ aws ec2 describe-volumes --query 'Volumes[?AvailabilityZone==`us-west-2a`]'

 

Query all running EC2 Instances

aws ec2 describe-instances --query 'Reservations[*].Instances[*].{State:State.Name,Ip:PrivateIpAddress,InstanceId:InstanceId,Name:Tags[0].Value}' --filter Name=instance-state-name,Values=running


3) Generate CLI Skeleton and CLI Input JSON Parameters
Most AWS CLI commands support --generate-cli-skeletonand --cli-input-jsonparameters, which can be used to store parameters in JSON and read parameters from files.

When passing in large chunks of data, it may be simpler to save the JSON as a file and reference it from the command line. JSON data in files is easier to read, edit, and share with others.


generate-cli-skeleton

$ aws ec2 run-instances --generate-cli-skeleton

{
    "DryRun": true,
    "ImageId": "",
    "MinCount": 0,
    "MaxCount": 0,
    "KeyName": "",
    "SecurityGroups": [
        ""
    ],
    "SecurityGroupIds": [
        ""
    ],
    "UserData": "",
    "InstanceType": "",
    "Placement": {
        "AvailabilityZone": "",
        "GroupName": "",
        "Tenancy": "",
        "HostId": "",
        "Affinity": ""
    },
    "KernelId": "",
    "RamdiskId": "",
    "BlockDeviceMappings": [
        {
            "VirtualName": "",
            "DeviceName": "",
            "Ebs": {
                "SnapshotId": "",
                "VolumeSize": 0,
                "DeleteOnTermination": true,
                "VolumeType": "",
                "Iops": 0,
                "Encrypted": true
            },
            "NoDevice": ""
        }
    ],
    "Monitoring": {
        "Enabled": true
    },
    "SubnetId": "",
    "DisableApiTermination": true,
    "InstanceInitiatedShutdownBehavior": "",
    "PrivateIpAddress": "",
    "ClientToken": "",
    "AdditionalInfo": "",
    "NetworkInterfaces": [
        {
            "NetworkInterfaceId": "",
            "DeviceIndex": 0,
            "SubnetId": "",
            "Description": "",
            "PrivateIpAddress": "",
            "Groups": [
                ""
            ],
            "DeleteOnTermination": true,
            "PrivateIpAddresses": [
                {
                    "PrivateIpAddress": "",
                    "Primary": true
                }
            ],
            "SecondaryPrivateIpAddressCount": 0,
            "AssociatePublicIpAddress": true
        }
    ],
    "IamInstanceProfile": {
        "Arn": "",
        "Name": ""
    },
    "EbsOptimized": true
}


Save skeleton to file
$ aws ec2 run-instances --generate-cli-skeleton > ec2runinst.json


Remove unnecessary parameters and set appropriate parameter values ​​when using.

{
    "DryRun": true,
    "ImageId": "ami-dfc39aef",
    "KeyName": "mykey",
    "SecurityGroupIds": [
        "sg-aa737dcf"
    ],
    "InstanceType": "t2.micro",
    "SubnetId": "subnet-ab9035dc"
}

 Set the DryRunparameter to true to use EC2's dry run feature, which can be used to test configurations without creating resources.

cli-input-json

$ aws ec2 run-instances --cli-input-json file://ec2runinst.json
A client error (DryRunOperation) occurred when calling the RunInstances operation: Request would have succeeded, but DryRun flag is set.

A dry run error indicates that the JSON is well-formed and the parameter values ​​are valid.

Set the DryRun parameter to false and run run-instancesthe command to start the instance.

 

Amazon Web Services

AWS China

AWS Documentation

AWS CLI Documentation

AWS CLI User Guide

AWS CLI Command Reference

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327033420&siteId=291194637
Recommended