How to use terminate_instances method in localstack

Best Python code snippet using localstack_python

TerminateEC2-lambda.py

Source:TerminateEC2-lambda.py Github

copy

Full Screen

1import boto32import datetime3#####4# First function will try to filter for EC2 instances that contain a tag named 'TerminationDate' which is set to '{Today's Date}'5# If that condition is met, function will compare current date (YYYY-MM-DD) to the value of the 'TerminationDate' tag.6# Value of the 'TerminationDate' tag must be in the following format 'YYYY-MM-DD' - Example : '2021-04-29' 7# 8# In order to trigger this function make sure to setup a CloudWatch event which will be executed every day. 9# The following Lambda Function needs a role with permission to terminate EC2 instances and write to CloudWatch logs.10# 11# Example EC2 Instance tags: 12# 13# TerminationDate: 2021-04-2914#####15#define boto3 connection16ec2 = boto3.resource('ec2')17def lambda_handler(event, context):18 19 # Get current time in format YYYY-MM-DD20 current_date = datetime.date.today().isoformat()21 22 # Find all the instances that are tagged with TerminationDate: {Today's Date}23 filters = [24 {25 'Name': 'tag:TerminationDate',26 'Values': [current_date]27 }28 ]29 # Search all the instances which contains scheduled filter 30 instances = ec2.instances.filter(Filters=filters)31 terminate_instances = [] 32 # Locate all instances that are tagged to terminate.33 for instance in instances:34 for tag in instance.tags:35 if tag['Key'] == 'TerminationDate':36 if tag['Value'] == current_date:37 terminate_instances.append(instance.id)38 print(f"Searching for instances with a TerminationDate tag value of: {current_date}.")39 40 # Terminate all instances with TerminateDate values of todays's date. 41 if len(terminate_instances) > 0:42 # perform the termination43 terminate = ec2.instances.filter(InstanceIds=terminate_instances).terminate()44 terminate 45 print(f"The following instances were found and have been terminated: {terminate_instances}.")46 else:...

Full Screen

Full Screen

terminate_instances.py

Source:terminate_instances.py Github

copy

Full Screen

1import logging2import boto33from botocore.exceptions import ClientError4def terminate_instances(instance_ids):5 """Terminate one or more Amazon EC2 instances6 :param instance_ids: List of string IDs of EC2 instances to terminate7 :return: List of state information for each instance specified in instance_ids.8 If error, return None.9 """10 # Terminate each instance in the argument list11 ec2 = boto3.client('ec2')12 try:13 states = ec2.terminate_instances(InstanceIds=instance_ids)14 except ClientError as e:15 logging.error(e)16 return None17 return states['TerminatingInstances']18def main():19 """Exercise terminate_instances()"""20 # Assign these values before running the program21 ec2_instance_ids = ['EC2_INSTANCE_ID']22 # Set up logging23 logging.basicConfig(level=logging.DEBUG,24 format='%(levelname)s: %(asctime)s: %(message)s')25 # Terminate the EC2 instance(s)26 states = terminate_instances(ec2_instance_ids)27 if states is not None:28 logging.debug('Terminating the following EC2 instances')29 for state in states:30 logging.debug(f'ID: {state["InstanceId"]}')31 logging.debug(f' Current state: Code {state["CurrentState"]["Code"]}, '32 f'{state["CurrentState"]["Name"]}')33 logging.debug(f' Previous state: Code {state["PreviousState"]["Code"]}, '34 f'{state["PreviousState"]["Name"]}')35if __name__ == '__main__':...

Full Screen

Full Screen

ec2_terminate.py

Source:ec2_terminate.py Github

copy

Full Screen

1import logging2import boto33from botocore.exceptions import ClientError4def terminate_instances(instance_ids):5 """Terminate one or more Amazon EC2 instances6 :param instance_ids: List of string IDs of EC2 instances to terminate7 :return: List of state information for each instance specified in instance_ids.8 If error, return None.9 """10 # Terminate each instance in the argument list11 ec2 = boto3.client('ec2')12 try:13 states = ec2.terminate_instances(InstanceIds=instance_ids)14 except ClientError as e:15 logging.error(e)16 return None17 return states['TerminatingInstances']18def main():19 """Exercise terminate_instances()"""20 # Assign these values before running the program21 ec2_instance_ids = ['EC2_INSTANCE_ID']22 # Set up logging23 logging.basicConfig(level=logging.DEBUG,24 format='%(levelname)s: %(asctime)s: %(message)s')25 # Terminate the EC2 instance(s)26 states = terminate_instances(ec2_instance_ids)27 if states is not None:28 logging.debug('Terminating the following EC2 instances')29 for state in states:30 logging.debug(f'ID: {state["InstanceId"]}')31 logging.debug(f' Current state: Code {state["CurrentState"]["Code"]}, '32 f'{state["CurrentState"]["Name"]}')33 logging.debug(f' Previous state: Code {state["PreviousState"]["Code"]}, '34 f'{state["PreviousState"]["Name"]}')35if __name__ == '__main__':...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful