アプリケーション開発ポータルサイト
ServerNote.NET
Amazon.co.jpでPC関連商品タイムセール開催中!
カテゴリー【Amazon/AWSDebian
【Amazon/AWS】決まったスケジュールで自動的にインスタンスを起動・停止する
POSTED BY
2023-09-23

この記事のやりかたは2022/09現在できなくなっているようです。以下改定版をご参照ください。

【Amazon/AWS】決まったスケジュールで自動的にインスタンスを起動・停止する〔改訂版〕

開発用インスタンスは使うときだけ起動していれば良いので自動起動・停止は欠かせない。
AWSが推奨している方法はCloudFormation/スタックを使う方法。

当方環境Debian 10 Busterインスタンスで自動起動・停止を設定していきます。

Amazon CLI(awsコマンド)初期設定

各インスタンスには最初からAmazon CLI = awsコマンドが入っているが、これはそのままでは使えない。
マネージメントコンソールで作成したAPIアクセスキーIDとシークレットアクセスキーが必要になる。
上記APIキーは、新しいIAMユーザーの作成時の利用用途にAPIアクセスを許可し、「アクセスキーの作成」とすれば表示されるので、メモするかcsvダウンロードしておく。

初期化

一般ユーザーにて

aws --version

aws configure

AWS Access Key ID [None]: <アクセスキーID>
AWS Secret Access Key [None]: <シークレットアクセスキー>
Default region name [None]: ap-northeast-1
Default output format [None]: json

成功すると、$HOME/.aws/{config, credentials}ファイルが設定した値で作成される。

スタックを作成する

AWS/Documentation/AWS Solutions/Implementation Guide
https://docs.aws.amazon.com/solutions/latest/instance-scheduler/deployment.html#step1

のページから「Launch Solution」をクリックすると、必要事項が埋められたスタック新規作成画面が出る。
まず右上のリージョンがバージニア北部になっているのでアジアパシフィック (東京)ap-northeast-1を選びなおす

そのまま「次へ」とする。

「スタックの詳細を指定」で変更する項目は以下例

スタックの名前:AutoStartStop
Instance Scheduler tag name:Schedule
Region(s):ap-northeast-1
Default time zone:Asia/Tokyo
Frequency:5
Enable CloudWatch Logs:Yes
Started tags:state=started
Stopped tags:state=stopped

として「次へ」とする。

※当方環境ではRegion(s):ap-northeast-1と明示的に指定するのが重要で、これをしなかったら何故かインスタンスのawsコマンドからAPIでスタック表示がされなかった(Stack does not exist)が、Regionsを指定して作成し直したら表示されるようになった。

「スタックオプションの設定」は何も入力せず「次へ」とする。

レビュー AutoStartStop 最終確認画面

一番下までスクロールして「承認します」をチェックして「スタックの作成」する。

インスタンスのマシン内でスケジュールを設定する

次に対象となるインスタンスマシン内にログインし、CLIで設定する。

さきほどのスタックの情報を確認する

インスタンスからのaws-cliで確認できなければ操作はできない。

aws cloudformation list-stacks

    "StackSummaries": [
        {
            "StackId": "arn:aws:cloudformation:ap-northeast-1:428963168810:stack/AutoStartStop/AAAA-BBBB-CCCC-DDDD",
            "StackName": "AutoStartStop",
            "TemplateDescription": "(SO0030) - aws-instance-scheduler, version v1.3.3",
            "CreationTime": "2020-11-06T04:55:27.578Z",
            "StackStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackDriftStatus": "NOT_CHECKED"
            }
        }
    ]
}

CREATE_COMPLETEになっていることが確認できた。

setuptoolsのインストール

wget http://peak.telecommunity.com/dist/ez_setup.py

このまま実行してもurllib2.HTTPError: HTTP Error 403: SSL is requiredとエラーになるのでその箇所を手動で修正する。

vi ez_setup.py

変更前
DEFAULT_URL     = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3]

変更後
DEFAULT_URL     = "https://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3]

httpをhttpsに変更し、上記エラーが出ないようにして、以下実行

sudo -s

python ez_setup.py

Downloading https://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11-py2.7.egg
Processing setuptools-0.6c11-py2.7.egg
Copying setuptools-0.6c11-py2.7.egg to /usr/local/lib/python2.7/dist-packages
Adding setuptools 0.6c11 to easy-install.pth file
Installing easy_install script to /usr/local/bin
Installing easy_install-2.7 script to /usr/local/bin

Installed /usr/local/lib/python2.7/dist-packages/setuptools-0.6c11-py2.7.egg
Processing dependencies for setuptools==0.6c11
Finished processing dependencies for setuptools==0.6c11

python-boto3のインストール

sudo apt install python-boto3

zip/unzipのインストール

sudo apt install zip unzip

ようやくscheduler-cliのインストール

インストールに必要な材料が揃ったので本尊をインストール。

sudo -s

wget https://s3.amazonaws.com/solutions-reference/aws-instance-scheduler/latest/scheduler-cli.zip
unzip scheduler-cli.zip

python setup.py install
running install
Checking .pth file support in /usr/local/lib/python2.7/dist-packages/
/usr/bin/python -E -c pass
TEST PASSED: /usr/local/lib/python2.7/dist-packages/ appears to support .pth files
running bdist_egg
running egg_info
writing requirements to scheduler_cli.egg-info/requires.txt
writing scheduler_cli.egg-info/PKG-INFO
writing top-level names to scheduler_cli.egg-info/top_level.txt
writing dependency_links to scheduler_cli.egg-info/dependency_links.txt
writing entry points to scheduler_cli.egg-info/entry_points.txt
reading manifest file 'scheduler_cli.egg-info/SOURCES.txt'
writing manifest file 'scheduler_cli.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-x86_64/egg
running install_lib
running build_py
creating build/bdist.linux-x86_64/egg
creating build/bdist.linux-x86_64/egg/scheduler_cli
copying build/lib.linux-x86_64-2.7/scheduler_cli/scheduler_cli.py -> build/bdist.linux-x86_64/egg/scheduler_cli
copying build/lib.linux-x86_64-2.7/scheduler_cli/__main__.py -> build/bdist.linux-x86_64/egg/scheduler_cli
copying build/lib.linux-x86_64-2.7/scheduler_cli/__init__.py -> build/bdist.linux-x86_64/egg/scheduler_cli
byte-compiling build/bdist.linux-x86_64/egg/scheduler_cli/scheduler_cli.py to scheduler_cli.pyc
byte-compiling build/bdist.linux-x86_64/egg/scheduler_cli/__main__.py to __main__.pyc
byte-compiling build/bdist.linux-x86_64/egg/scheduler_cli/__init__.py to __init__.pyc
creating build/bdist.linux-x86_64/egg/EGG-INFO
copying scheduler_cli.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO
copying scheduler_cli.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying scheduler_cli.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying scheduler_cli.egg-info/entry_points.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying scheduler_cli.egg-info/requires.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying scheduler_cli.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
zip_safe flag not set; analyzing archive contents...
creating 'dist/scheduler_cli-v1.2.0-py2.7.egg' and adding 'build/bdist.linux-x86_64/egg' to it
removing 'build/bdist.linux-x86_64/egg' (and everything under it)
Processing scheduler_cli-v1.2.0-py2.7.egg
Removing /usr/local/lib/python2.7/dist-packages/scheduler_cli-v1.2.0-py2.7.egg
Copying scheduler_cli-v1.2.0-py2.7.egg to /usr/local/lib/python2.7/dist-packages
scheduler-cli v1.2.0 is already the active version in easy-install.pth
Installing scheduler-cli script to /usr/local/bin

Installed /usr/local/lib/python2.7/dist-packages/scheduler_cli-v1.2.0-py2.7.egg
Processing dependencies for scheduler-cli==v1.2.0
Searching for boto3==1.9.86
Best match: boto3 1.9.86
Adding boto3 1.9.86 to easy-install.pth file

Using /usr/lib/python2.7/dist-packages
Searching for jmespath==0.9.4
Best match: jmespath 0.9.4
Adding jmespath 0.9.4 to easy-install.pth file

Using /usr/lib/python2.7/dist-packages
Searching for requests==2.21.0
Best match: requests 2.21.0
Adding requests 2.21.0 to easy-install.pth file

Using /usr/lib/python2.7/dist-packages
Searching for argparse==1.2.1
Best match: argparse 1.2.1
Adding argparse 1.2.1 to easy-install.pth file

Using /usr/lib/python2.7
Finished processing dependencies for scheduler-cli==v1.2.0

月曜日~金曜日 10:00~20:00の間で稼働するスケジュールを組む

当方環境では上記の期間のみ当インスタンスを動かしたいので設定した。

材料はrootでシステムにインストールされたので、コマンド実行は一般ユーザー=aws congigureしたユーザ=で行う。

scheduler-cli create-period --stack AutoStartStop --region ap-northeast-1 --name period1 --begintime 10:00 --endtime 20:00 --weekdays mon-fri
{
   "Period": {
      "Weekdays": [
         "mon-fri"
      ],
      "Endtime": "20:00",
      "Type": "period",
      "Begintime": "10:00",
      "Name": "period1"
   }
}
scheduler-cli create-schedule --stack AutoStartStop --name auto-start-stop --periods period1 --description "auto start/stop" --timezone Asia/Tokyo --region ap-northeast-1
{
   "Schedule": {
      "RetainRunning": false,
      "Enforced": false,
      "Hibernate": false,
      "Description": "auto start/stop",
      "UseMetrics": false,
      "StopNewInstances": true,
      "Periods": [
         "period1"
      ],
      "UseMaintenanceWindow": false,
      "Timezone": "Asia/Tokyo",
      "Type": "schedule",
      "Name": "auto-start-stop"
   }
}

Unable to locate credentialsと言われた場合、awsコマンド初期設定に問題がある。aws configreで初期設定を行う。

An error occurred (ValidationError) when calling the DescribeStackResource operation: Stack 'XXXXXXX' does not existと言われた場合、最初のGUIで行ったスタックが正しく作成されていない。aws cloudformation list-stacksで確認する。

インスタンスにタグ付けする

GUIマネージメントコンソールに戻って、当該インスタンスを開き、「タグ」タブ→「タグの管理」を開く。

新規タグを作成

キー(Key):Schedule
値(Value):auto-start-stop

とする。キーは最初スタック作成時のInstance Scheduler tag name、値はscheduler-cli create-scheduleで--name指定したものをセット。

これで当該インスタンスは、月曜日~金曜日の10:00~20:00のみ「実行中」となり、その他の時間帯は「停止」することになる。

スケジュールの取り消し(削除)

やめる場合、まず当該インスタンスのマネージメントコンソール「タグ」タブ→「タグの管理」を開き、
設定したキー/Schedule・値/auto-start-stopのタグを削除する。

次に当該インスタンスを起動し、スケジュールを削除すればOK。
ピリオドは残しておいても問題ないが、削除するならdelete-periodとする。

scheduler-cli delete-schedule --stack AutoStartStop --name auto-start-stop
{
   "Schedule": "auto-start-stop"
}
scheduler-cli delete-period --stack AutoStartStop --name period1
{
   "Period": "period1"
}
※本記事は当サイト管理人の個人的な備忘録です。本記事の参照又は付随ソースコード利用後にいかなる損害が発生しても当サイト及び管理人は一切責任を負いません。
※本記事内容の無断転載を禁じます。
【WEBMASTER/管理人】
自営業プログラマーです。お仕事ください!
ご連絡は以下アドレスまでお願いします★

☆ServerNote.NETショッピング↓
ShoppingNote / Amazon.co.jp
☆お仲間ブログ↓
一人社長の不動産業務日誌
【キーワード検索】