ablog

不器用で落着きのない技術者のメモ

EMRクラスターを起動するシェルスクリプト

同じ名前のクラスターが存在したらスルーするEMRクラスター作成シェルスクリプト。ただし、同時実行すると複数クラスターが作成される。
厳密にやりたい場合は S3をトリガーとするLambdaの冪等性をDynamoDBで実現してみた | DevelopersIO のような方式にする必要がある。

  • create-emr.sh
#!/bin/bash
export LANG=en_US.UTF-8

is_cluster=`aws emr list-clusters|jq -r '.Clusters[]|select(.Name=="test-cluster" and .Status.State != "TERMINATED")'|wc -l`

if [ $is_cluster -gt 0 ] ; then
	echo "test-cluster is already exists"
else
	echo "create test-cluster"
	aws emr create-cluster \
	--name test-cluster \
	--ami-version 3.4.0 \
	--applications Name=Hive Name=Hue \
	--instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=c3.xlarge \
	InstanceGroupType=CORE,InstanceCount=2,InstanceType=c3.xlarge  \
	--use-default-roles
fi
% bash ./create_emr.sh
create test-cluster
{
    "ClusterId": "j-R9X68AQHT4VS"
}
  • 既に同名のクラスターが存在する場合は、作成しない
% bash create_emr.sh
test-cluster is already exists
  • 瞬間同時実行すると複数クラスターが作成される
% bash create_emr.sh & bash create_emr.sh & bash create_emr.sh
[1] 93606
[2] 93607
create test-cluster
create test-cluster
create test-cluster
{
    "ClusterId": "j-2HGB6SSEQBTCR"
}
{
    "ClusterId": "j-1IPYAEKJBIPCE"
}
[2]  + done       bash create_emr.sh
{
    "ClusterId": "j-2QL5MJM1BNC2U"
}
[1]  + done       bash create_emr.sh