LoginSignup
0
0

More than 5 years have passed since last update.

pythonプログラム実行後にEC2インスタンスを停止するためのAPI

Posted at

背景

GPUのあるEC2上でdeep-learningしたい、、、
でもGPUのインスタンスは高い、、、
学習完了後すぐにインスタンスを"停止"しないと無駄に課金されて高額請求がきそう、、、
でも学習スタートしたら、終わるまで放っておきたい、、、

AWS-CLIというのでEC2を起動させたり、停止したり、実行状態を監視したりできるらしい。

手順

1.AWS-CLIをインストール・AWSアカウント情報を紐づけ・セットアップ
以下の記事を参考にしました。
 参考記事:AWS CLIのインストールから初期設定のメモ"(https://qiita.com/n0bisuke/items/1ea245318283fa118f4a)

2.あとは↓のコードを実行するだけ。

stop_ec2.py
import subprocess

cmd_stop = ['aws', 'ec2', 'stop-instances', '--instance-ids', '<instance_id>'] 
try:
  res = subprocess.call(cmd_stop)
except:
  print("Error.")

参考記事:
・python上でunixコマンドを実行する(https://qiita.com/tdrk/items/9b23ad6a58ac4032bb3b)
・AWS CLIを使ってAmazon EC2を起動・停止するワンライナーまとめ(https://dev.classmethod.jp/cloud/aws/awscli-tips-ec2-start-stop/)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0