AWS学习笔记(一)--CLI基础知识

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

如果已安装过老版本的pip,再次执行以上命令是不会更新的,那如何更新呢,请执行以下命令:

pip install --upgrade pip


3) Install AWS CLI
$ sudo pip install awscli


4) Test AWS CLI
$ aws help
输入q退出


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.
这些信息将分别保存在~/.aws/credentials,~/.aws/config文件内。下次再运行此命令,不需改动的项直接按回车即可。


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


注意一定要保存下来,仅有这一次机会。如未保存只能删除重建,可以创建多个密钥。


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决定。

示例:describe instances

$ aws ec2 describe-instances --output table --region cn-north-1
以表格的形式显示cn-north-1 region下的所有instance

注意: 机器时间一定要与服务器同步,否则会报以下错误:AWS was not able to validate the provided access credentials


时间同步方法:
$ 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 选项设置过滤条件:
$ aws ec2 describe-instances --output table --region cn-north-1 --filter Name=availability-zone,Values=cn-north-1b

如果Values包含空格要使用引号,filter Name支持的参数请查看帮助。


多种条件组合语法如下:
$ aws ec2 describe-instances --filters Name=instance-type,Values=m1.small,m1.medium Name=availability-zone,Values=us-west-2c

从文件加载参数:

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

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

根据自定义的tag查找:

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

--query 选项自定义输出的内容和样式

显示 Volumes 列表中的第一个卷

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

循环访问整个列表,并筛选出三个元素:VolumeIdAvailabilityZoneSize,并指定别名:

$ 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
    }
]

使用key1.key2[0].key3 语法来筛选深度嵌套在结构中的元素:

$ 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
    }
]

如未指定别名,将按顺序输出:

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

按特定字段的值筛选结果:

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

查询所有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
大多数 AWS CLI 命令支持 --generate-cli-skeleton--cli-input-json 参数,可使用这些参数在 JSON 中存储参数并从文件中读取参数。

当传入大块数据时,将 JSON 保存为一个文件并从命令行引用它可能更为简单。文件中的 JSON 数据更容易读取、编辑和与他人共享。


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
}


将skeleton保存到文件
$ aws ec2 run-instances --generate-cli-skeleton > ec2runinst.json


使用时删除不必要的参数并设置合适的参数值。

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

 将 DryRun 参数设置为 true 可使用 EC2 的空运行功能,可利用此功能在不创建资源的情况下测试配置。

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.

空运行错误表明,JSON 格式正确且参数值有效。

将 DryRun 参数设置为 false,再次运行 run-instances 命令可启动实例。

Amazon Web Services

AWS中国

AWS文档

AWS CLI 文档

AWS CLI 用户指南

AWS CLI Command Reference

猜你喜欢

转载自billben.iteye.com/blog/2327883