def run_commands_on_instance()

in ec2-spot-interruption-handler/spot-interruption-handler/index.py [0:0]


def run_commands_on_instance(instance_id, asg_name):
    # SSM RunCommand RunShellScript with commands configured in ParameterStore

    parameter_store_commands = ["{{ssm:" + os.environ['SSMParameterPrefix'] + asg_name + "}}"]
    
    # Reference commands directly from SSM Parameter Store, limit execution timeout to 2 minutes
    document_parameters= {
        'commands': parameter_store_commands,
        'executionTimeout': ["120"]
    }
    
    # Configure SSM RunCommand Logging to CloudWatchLogs
    cloudwatch_output_config = {
        'CloudWatchOutputEnabled' : bool(os.environ['EnableRunCommandOutputLogging']) 
    }

    # Send Command to the instance
    try:
        response = ssmclient.send_command(
            InstanceIds=[instance_id],
            DocumentName='AWS-RunShellScript',
            Parameters=document_parameters,
            CloudWatchOutputConfig=cloudwatch_output_config,
            TimeoutSeconds=30)
        logger.info("Running commands on instance {instanceid}. Command id: {id} ".format(
                instanceid=instance_id,id=response['Command']['CommandId']))
    except ssmclient.exceptions.InvalidInstanceId:
        logger.error ("SSM Agent is not running, or not registered to the endpoint or you don't have permissions to access the instance")
        raise e
    except ClientError as e:
        error_message = "Could not execute commands on instance {id}. ".format(id=instance_id)
        logger.error( error_message + e.response['Error']['Message'])
        raise e