随着云的越来越火,aws也变得越来越火,ops从底层的网线,磁盘脱离出来,再也不用跑到机房插网线了,亚马逊提供了很多的服务,让我们能更方便的管理我们的主机,你可以在web页面看到aws远超强大!但是我们今天要说一下另外一种方式
作为一个命令党,让我们打开页面是很难得,我们总是希望,通过一个命令就可以看到所有的instance, 然后如果想重启一个服务器的话,通过命令行来实现,而不是打开浏览器,登录,查找,右键,重启,刷新,aws早就为我们提供了相应的api接口
看一个例子,云主机的启动与停止
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import sys import boto3 from botocore.exceptions import ClientError instance_id = sys.argv[2] action = sys.argv[1].upper() ec2 = boto3.client('ec2') if action == 'ON': # Do a dryrun first to verify permissions try: ec2.start_instances(InstanceIds=[instance_id], DryRun=True) except ClientError as e: if 'DryRunOperation' not in str(e): raise # Dry run succeeded, run start_instances without dryrun try: response = ec2.start_instances(InstanceIds=[instance_id], DryRun=False) print(response) except ClientError as e: print(e) else: # Do a dryrun first to verify permissions try: ec2.stop_instances(InstanceIds=[instance_id], DryRun=True) except ClientError as e: if 'DryRunOperation' not in str(e): raise # Dry run succeeded, call stop_instances witout dryrun try: response = ec2.stop_instances(InstanceIds=[instance_id], DryRun=False) print(response) except ClientError as e: print(e) |
在我们运行这个脚本之前,我们需要和aws建立认证
1 2 3 4 |
$cat ~/.aws/credentials [default] aws_access_key_id = YOUR_ACCESS_KEY aws_secret_access_key = YOUR_SECRET_KEY |
上边的这些认证key可以在web页面的IAM模块找到
1 2 3 |
$cat ~/.aws/config [default] region=us-east-1 |
除了这些,我们还要先安装boto
1 |
pip install boto3 |
更多信息参考:https://boto3.readthedocs.io/en/latest/guide/quickstart.html
Latest posts by Zhiming Zhang (see all)
- aws eks node 自动化扩展工具 Karpenter - 8月 10, 2022
- ReplicationController and ReplicaSet in Kubernetes - 12月 20, 2021
- public key fingerprint - 5月 27, 2021