2013/03/30

使用 Command Line Tool 建立 AWS EC2 Instance

AWS 以已經有提供 web 界面可以操作了,為何還要使用 command line 呢?答案是為了自動化的過程。Auto scaling 就是一個很好的例子。


Install AWS Command Line Interface

It run in Python environment, and installed by pip.
$ pip install awscli


Setup credential and region

Method 1
$ vim ~/.aws.conf
aws_access_key_id=AKIAIJQ7YGMRQTBIH7HJ
aws_secret_access_key=ngbsB02udwOmDztTesTJuuZ8ZdkA2ZRq0VHvunX
region=us-east-1
$ export AWS_CONFIG_FILE=~/.aws.conf

Method 2
$ export AWS_ACCESS_KEY_ID=AKIAIJQ7YGMRQTBIH7HJ
$ export AWS_SECRET_ACCESS_KEY=ngbsB02udwOmDztTesTJuuZ8ZdkA2ZRq0VHvunX
$ export AWS_DEFAULT_REGION=us-east-1

若沒有設定好,則會出現下面的 error
Unable to locate credentials
You must specify a region or set the AWS_DEFAULT_REGION environment variable.


Create Instance

$ aws ec2 run-instances --image-id ami-002bf169 --min-count 1 --max-count 1 \
--instance-type m1.small --placement '{"availability_zone":"us-east-1a"}'
{
    "OwnerId": "132130202433",
    "ReservationId": "r-ec8f2587",
    "requestId": "05125c46-dfbd-4ef4-89a8-0efe6f59ba87",
    "Groups": [
        {
            "GroupName": "default",
            "GroupId": "sg-2337df4f"
        }
    ],
    "Instances": [
        {
            "Monitoring": {
                "State": "disabled"
            },
            "PublicDnsName": "",
            "KernelId": "aki-825ea7eb",
            "State": {
                "Code": 0,
                "Name": "pending"
            },
            "EbsOptimized": false,
            "LaunchTime": "2013-03-30T02:58:42.000Z",
            "ProductCodes": [],
            "StateTransitionReason": "",
            "InstanceId": "i-ff16069f",
            "ImageId": "ami-002bf169",
            "PrivateDnsName": "",
            "SecurityGroups": [
                {
                    "GroupName": "default",
                    "GroupId": "sg-2437df4f"
                }
            ],
            "ClientToken": "",
            "InstanceType": "m1.small",
            "NetworkInterfaces": [],
            "Placement": {
                "Tenancy": "default",
                "GroupName": "",
                "AvailabilityZone": "us-east-1a"
            },
            "Hypervisor": "xen",
            "BlockDeviceMappings": [],
            "Architecture": "x86_64",
            "StateReason": {
                "Message": "pending",
                "Code": "pending"
            },
            "VirtualizationType": "paravirtual",
            "RootDeviceType": "instance-store",
            "AmiLaunchIndex": 0
        }
    ]
}

image-id 就是 AMI 的 id,它可以是 My AMI 也可以是 Community AMI


列出目前所有的 instance
$ aws ec2 describe-instances


關於 ec2 的操作,更詳細的可以看
$ aws ec2 help
$ aws ec2 run-instances help


Reference


沒有留言:

張貼留言