Skip to content

Instantly share code, notes, and snippets.

@cumet04
Created January 29, 2020 03:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cumet04/342f44291b716e990e66f7d4e3c69f52 to your computer and use it in GitHub Desktop.
Save cumet04/342f44291b716e990e66f7d4e3c69f52 to your computer and use it in GitHub Desktop.
import boto3
ec2 = boto3.client("ec2")
ssm = boto3.client("ssm")
# refs https://qiita.com/cumet04/items/5888e037105e6ea5f6bc
def lambda_handler(event, context):
try:
targets = target_instances("cron", "true")
if len(targets) == 0:
print("No Targets")
execute(targets, ["false"])
except Exception as e:
raise e
def target_instances(tagname, tagvalue):
resp = ec2.describe_instances(Filters=[{"Name": f"tag:{tagname}", "Values": [tagvalue]}])
instances = []
for resv in resp["Reservations"]:
for i in resv["Instances"]:
instances.append(i)
return [instances[0]] # 先頭の1件を選ぶ
def execute(targets, commands):
notify_sns_arn = "SOME_NOTIFY_SNS_TOPIC_ARN"
service_role_arn = "NOTIFY_ROLE_FOR_SSM"
ids = [i["InstanceId"] for i in targets]
ssm.send_command(
InstanceIds=ids,
DocumentName="AWS-RunShellScript",
Parameters={"commands": commands, "executionTimeout": ["3600"]},
ServiceRoleArn=service_role_arn,
NotificationConfig={
"NotificationArn": notify_sns_arn,
"NotificationEvents": ["TimedOut", "Cancelled", "Failed"],
"NotificationType": "Command",
},
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment