月次で定期実行しているGlue Jobを週次で実行するよう変更したかったため、Glue Jobのトリガーのスケジュールを変更するスクリプトを作成しました。
前提条件
- 1つのAWSアカウントの東京リージョン内に複数のGlue Jobがある。
- chap8-xxxという名前のGlue Jobが複数あり、トリガーによって毎月1日に実行している。
- chap8-xxxという名前のGlue Jobを「毎週月曜日10:00(UTC)」実行に変更したい。
やったこと
- トリガーの一覧を取得する。
- トリガーが紐づくGlue Job名を取得する
- Glue Job名がchap8から始まっていたら、スケジュールを書き換える。
スクリプト
import subprocess
import json
region = "ap-northeast-1"
profile = "default"
# AWS CLIを使用してトリガーリストを取得
result = subprocess.run(["aws", "glue", "get-triggers", "--region", region, "--profile", profile], stdout=subprocess.PIPE)
output = result.stdout.decode('utf-8')
# トリガーリストをパースして、Job名とトリガー情報を表示し、スケジュールを書き換える
json_output = json.loads(output)
for trigger in json_output["Triggers"]:
job_name = trigger["Actions"][0]["JobName"]
print("Job Name | Trigger Name: {}".format(job_name + " | " + trigger["Name"]))
print("Schedule: {}".format(trigger["Schedule"]))
if job_name.startswith('chap8'):
# cron書式で固定の値を指定する
new_schedule = "cron(0 10 ? * 2 *)" # 毎週月曜日10:00(UTC)実行
print("New Schedule: {}".format(new_schedule))
# スケジュールを書き換える
new_trigger = {
"Name": trigger["Name"],
"Actions": trigger["Actions"], # 元のトリガーのActionsをそのままコピー
"Schedule": new_schedule, # 書き換えたスケジュールを指定
"Description": trigger["Description"] # 元のトリガーのDescriptionをそのままコピー
}
args = [
"aws", "glue", "update-trigger", "--region", region, "--profile", profile,
"--name", trigger["Name"], "--trigger-update", json.dumps(new_trigger)
]
subprocess.run(args, stdout=subprocess.PIPE)