通过阿里云命令行工具 aliyuncli 购买服务器

开始想通过 aliyuncli 的 golang 源码进行编译安装(注:python 版的 aliyuncli 已不再维护),但没成功,详见 通过 golang 源码编译阿里云命令行工具 aliyuncli 出错 

后来改为直接下载编译好的 aliyuncli

wget -qO- http://aliyun-cli.oss-cn-hangzhou.aliyuncs.com/aliyun-cli-linux-3.0.0-amd64.tgz | tar xvz -C /usr/local/bin

使用前通过 aliyun configure 命令配置 access key

# aliyun configure
Configuring profile '' in '' authenticate mode...
Access Key Id []: xxx
Access Key Secret []: yyy
Default Region Id []: cn-hangzhou
Default Output Format [json]: json (Only support json))
Default Language [zh|en] en: 
Saving profile[] ...Done.

启用自动补全

echo 'complete -C /usr/local/bin/aliyun aliyun' >> .bash_profile

然后使用下面的命令购买按量付费的服务器

aliyun ecs CreateInstance \
  --RegionId cn-hangzhou(地域) \
  --ZoneId cn-hangzhou-b(可用区) \
  --InstanceChargeType PostPaid(按量付费) \
  --IoOptimized optimized(IO优化) \
  --InstanceType ecs.n4.xlarge(实例规格) \
  --ImageId m-xxx(镜像ID) \
  --VSwitchId vsw-xxx(VPC交换机ID) \
  --InternetChargeType PayByTraffic(公网按使用流量计费) \
  --InternetMaxBandwidthOut 1(公网最大带宽) \
  --SecurityGroupId sg-xxx(安全组ID) \
  --HostName webserver-temp(主机名) \
  --InstanceName webserver-temp(实例名称) 

执行上面的命令可以完成购买,但目前存在的问题:

1)虽然指定了 InternetChargeType 与 InternetMaxBandwidthOut ,但创建的服务器没有分配公网 IP

2)服务器创建后处于停止状态,不能自动启动

3)缺少知道释放时间的参数

。。。

后来知道了:

1)分配公网IP需要执行 aliyun ecs AllocatePublicIpAddress 命令

2)启动服务器需要执行 aliyun ecs StartInstance 命令

3)设置自动释放时间需要执行 aliyun ecs ModifyInstanceAutoReleaseTime 命令

改进后的 shell 脚本如下

Result=`aliyun ecs CreateInstance \
  --RegionId cn-hangzhou(地域) \
  --ZoneId cn-hangzhou-b(可用区) \
  --InstanceChargeType PostPaid(按量付费) \
  --IoOptimized optimized(IO优化) \
  --InstanceType ecs.n4.xlarge(实例规格) \
  --ImageId m-xxx(镜像ID) \
  --VSwitchId vsw-xxx(VPC交换机ID) \
  --InternetChargeType PayByTraffic(公网按使用流量计费) \
  --InternetMaxBandwidthOut 1(公网最大带宽) \
  --SecurityGroupId sg-xxx(安全组ID) \
  --HostName webserver-temp(主机名) \
  --InstanceName webserver-temp(实例名称)`
InstanceId=`echo "$Result" | grep -Po "(i-[^\"]+)"`
sleep 30s
aliyun ecs AllocatePublicIpAddress --InstanceId $InstanceId
aliyun ecs StartInstance --InstanceId $InstanceId
aliyun ecs ModifyInstanceAutoReleaseTime --InstanceId $InstanceId --AutoReleaseTime $1

实测有效。

posted @ 2018-04-22 17:55  dudu  阅读(1020)  评论(1编辑  收藏  举报