AI Dashboard is available on the Web, Apple, Google, and Microsoft, PRO version
AWS Lambda to auto start stop Ec2 instance on schedule using python and boto3
Use this lambda function to auto start stop all Ec2 instances based on schedule from tags.
#Auto Shutodown - Start EC2 instances based on tags
import boto3
import os
import json
import croniter
import datetime
# Enter the region your instances are in. Include only the region without specifying Availability Zone; e.g., 'us-east-1'
region = 'us-west-2'
EC2_STATUS_CODE_RUNNING = 16
EC2_STATUS_CODE_STOPPED = 80
Get 20% off Google Google Workspace (Google Meet) Standard Plan with the following codes: 96DRHDRA9J7GTN6
Get 20% off Google Workspace (Google Meet) Business Plan (AMERICAS): M9HNXHX3WC9H7YE (Email us for more codes)
def lambda_handler(event, context):
ec2 = boto3.client(‘ec2’, region_name=region)
#auto_start_stop_tag = ‘tc:uptime_schedule_gmt’
auto_start_tag = ‘tc:start_time_schedule_gmt_24h_format’
auto_shutdown_tag = ‘tc:shutdown_time_schedule_gmt_24h_format’
instances_to_shutdown = []
instances_to_start = []
# Query ec2 machines for auto_start_stop_tag,
#instances_with_schedules = get_instance_schedules(auto_start_stop_tag)
instances_with_start_schedules = get_instance_schedules(auto_start_tag)
instances_with_shutdown_schedules = get_instance_schedules(auto_shutdown_tag)
print(“instances_with_start_schedules: %s” % instances_with_start_schedules)
print(“instances_with_shutdown_schedules: %s” % instances_with_shutdown_schedules)
for instance_id, values in instances_with_start_schedules.items():
now = datetime.datetime.now()
print(“now: %s” % now)
iterator = croniter.croniter(values[‘Schedule’], now)
next_run_time = iterator.get_next(datetime.datetime)
print(“next_run_time: %s” % next_run_time)
duration_until_next_run_time = next_run_time – now
print(“duration_until_next_start_time: %s” % duration_until_next_run_time)
duration_of_one_hour = datetime.timedelta(hours=1)
if duration_until_next_run_time <= duration_of_one_hour and values[‘State’][‘Code’] == EC2_STATUS_CODE_STOPPED: print(“true”) print(“instance_to_stop.append(%s)” % instance_id) instances_to_start.append(instance_id) for instance_id, values in instances_with_shutdown_schedules.items(): now = datetime.datetime.now() print(“now: %s” % now) iterator = croniter.croniter(values[‘Schedule’], now) next_run_time = iterator.get_next(datetime.datetime) print(“next_run_time: %s” % next_run_time) duration_until_next_run_time = next_run_time – now print(“duration_until_next_shutdown_time: %s” % duration_until_next_run_time) duration_of_one_hour = datetime.timedelta(hours=1) if duration_until_next_run_time <= duration_of_one_hour and values[‘State’][‘Code’] == EC2_STATUS_CODE_RUNNING: print(“instance_to_shutdown.append(%s)” % instance_id) instances_to_shutdown.append(instance_id) if len(instances_to_shutdown) > 0:
ec2.stop_instances(InstanceIds=instances_to_shutdown)
print(‘stopped your instances: ‘ + str(instances_to_shutdown))
send_shutdown_notification(instances_to_shutdown, “STOPPED”)
if len(instances_to_start) > 0:
ec2.start_instances(InstanceIds=instances_to_start)
print(‘started your instances: ‘ + str(instances_to_start))
send_start_notification(instances_to_start, “STARTED”)
def send_shutdown_notification(instances, event):
instances_json_object = {“instances”:instances, “event”:event}
instances_json_string = json.dumps(instances_json_object)
instances_json_bytes = instances_json_string.encode(‘utf-8’)
lambda_arn = os.environ[‘LAMBDA_NOTIFICATION_SHUTDOWN_ARN’]
lambda_client = boto3.client(“lambda”)
lambda_client.invoke(
FunctionName=lambda_arn,
InvocationType=’Event’,
LogType=’None’,
Payload=instances_json_bytes
)
def send_start_notification(instances, event):
instances_json_object = {“instances”:instances, “event”:event}
instances_json_string = json.dumps(instances_json_object)
instances_json_bytes = instances_json_string.encode(‘utf-8’)
lambda_arn = os.environ[‘LAMBDA_NOTIFICATION_START_ARN’]
lambda_client = boto3.client(“lambda”)
lambda_client.invoke(
FunctionName=lambda_arn,
InvocationType=’Event’,
LogType=’None’,
Payload=instances_json_bytes
)
def get_instance_schedules(tag_name):
# When passed a tag key, tag value this will return a list of InstanceIds that were found.
ec2client = boto3.client(‘ec2’)
response = ec2client.describe_instances(
Filters=[
{
‘Name’: ‘tag-key’,
‘Values’: [tag_name]
}
]
)
instancelist = {}
for reservation in (response[“Reservations”]):
for instance in reservation[“Instances”]:
tag_value = ”
for tag in instance[‘Tags’]:
if tag[‘Key’] == tag_name:
tag_value = tag[‘Value’]
break
instancelist[instance[“InstanceId”]] = {‘Schedule’:tag_value,’State’:instance[‘State’]}
return instancelist
Active Hydrating Toner, Anti-Aging Replenishing Advanced Face Moisturizer, with Vitamins A, C, E & Natural Botanicals to Promote Skin Balance & Collagen Production, 6.7 Fl Oz
Age Defying 0.3% Retinol Serum, Anti-Aging Dark Spot Remover for Face, Fine Lines & Wrinkle Pore Minimizer, with Vitamin E & Natural Botanicals
Firming Moisturizer, Advanced Hydrating Facial Replenishing Cream, with Hyaluronic Acid, Resveratrol & Natural Botanicals to Restore Skin's Strength, Radiance, and Resilience, 1.75 Oz
Skin Stem Cell Serum
Smartphone 101 - Pick a smartphone for me - android or iOS - Apple iPhone or Samsung Galaxy or Huawei or Xaomi or Google Pixel
Can AI Really Predict Lottery Results? We Asked an Expert.
Djamgatech
Read Photos and PDFs Aloud for me iOS
Read Photos and PDFs Aloud for me android
Read Photos and PDFs Aloud For me Windows 10/11
Read Photos and PDFs Aloud For Amazon
Get 20% off Google Workspace (Google Meet) Business Plan (AMERICAS): M9HNXHX3WC9H7YE (Email us for more)
Get 20% off Google Google Workspace (Google Meet) Standard Plan with the following codes: 96DRHDRA9J7GTN6(Email us for more)
FREE 10000+ Quiz Trivia and and Brain Teasers for All Topics including Cloud Computing, General Knowledge, History, Television, Music, Art, Science, Movies, Films, US History, Soccer Football, World Cup, Data Science, Machine Learning, Geography, etc....
List of Freely available programming books - What is the single most influential book every Programmers should read
- Bjarne Stroustrup - The C++ Programming Language
- Brian W. Kernighan, Rob Pike - The Practice of Programming
- Donald Knuth - The Art of Computer Programming
- Ellen Ullman - Close to the Machine
- Ellis Horowitz - Fundamentals of Computer Algorithms
- Eric Raymond - The Art of Unix Programming
- Gerald M. Weinberg - The Psychology of Computer Programming
- James Gosling - The Java Programming Language
- Joel Spolsky - The Best Software Writing I
- Keith Curtis - After the Software Wars
- Richard M. Stallman - Free Software, Free Society
- Richard P. Gabriel - Patterns of Software
- Richard P. Gabriel - Innovation Happens Elsewhere
- Code Complete (2nd edition) by Steve McConnell
- The Pragmatic Programmer
- Structure and Interpretation of Computer Programs
- The C Programming Language by Kernighan and Ritchie
- Introduction to Algorithms by Cormen, Leiserson, Rivest & Stein
- Design Patterns by the Gang of Four
- Refactoring: Improving the Design of Existing Code
- The Mythical Man Month
- The Art of Computer Programming by Donald Knuth
- Compilers: Principles, Techniques and Tools by Alfred V. Aho, Ravi Sethi and Jeffrey D. Ullman
- Gödel, Escher, Bach by Douglas Hofstadter
- Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin
- Effective C++
- More Effective C++
- CODE by Charles Petzold
- Programming Pearls by Jon Bentley
- Working Effectively with Legacy Code by Michael C. Feathers
- Peopleware by Demarco and Lister
- Coders at Work by Peter Seibel
- Surely You're Joking, Mr. Feynman!
- Effective Java 2nd edition
- Patterns of Enterprise Application Architecture by Martin Fowler
- The Little Schemer
- The Seasoned Schemer
- Why's (Poignant) Guide to Ruby
- The Inmates Are Running The Asylum: Why High Tech Products Drive Us Crazy and How to Restore the Sanity
- The Art of Unix Programming
- Test-Driven Development: By Example by Kent Beck
- Practices of an Agile Developer
- Don't Make Me Think
- Agile Software Development, Principles, Patterns, and Practices by Robert C. Martin
- Domain Driven Designs by Eric Evans
- The Design of Everyday Things by Donald Norman
- Modern C++ Design by Andrei Alexandrescu
- Best Software Writing I by Joel Spolsky
- The Practice of Programming by Kernighan and Pike
- Pragmatic Thinking and Learning: Refactor Your Wetware by Andy Hunt
- Software Estimation: Demystifying the Black Art by Steve McConnel
- The Passionate Programmer (My Job Went To India) by Chad Fowler
- Hackers: Heroes of the Computer Revolution
- Algorithms + Data Structures = Programs
- Writing Solid Code
- JavaScript - The Good Parts
- Getting Real by 37 Signals
- Foundations of Programming by Karl Seguin
- Computer Graphics: Principles and Practice in C (2nd Edition)
- Thinking in Java by Bruce Eckel
- The Elements of Computing Systems
- Refactoring to Patterns by Joshua Kerievsky
- Modern Operating Systems by Andrew S. Tanenbaum
- The Annotated Turing
- Things That Make Us Smart by Donald Norman
- The Timeless Way of Building by Christopher Alexander
- The Deadline: A Novel About Project Management by Tom DeMarco
- The C++ Programming Language (3rd edition) by Stroustrup
- Patterns of Enterprise Application Architecture
- Computer Systems - A Programmer's Perspective
- Agile Principles, Patterns, and Practices in C# by Robert C. Martin
- Growing Object-Oriented Software, Guided by Tests
- Framework Design Guidelines by Brad Abrams
- Object Thinking by Dr. David West
- Advanced Programming in the UNIX Environment by W. Richard Stevens
- Hackers and Painters: Big Ideas from the Computer Age
- The Soul of a New Machine by Tracy Kidder
- CLR via C# by Jeffrey Richter
- The Timeless Way of Building by Christopher Alexander
- Design Patterns in C# by Steve Metsker
- Alice in Wonderland by Lewis Carol
- Zen and the Art of Motorcycle Maintenance by Robert M. Pirsig
- About Face - The Essentials of Interaction Design
- Here Comes Everybody: The Power of Organizing Without Organizations by Clay Shirky
- The Tao of Programming
- Computational Beauty of Nature
- Writing Solid Code by Steve Maguire
- Philip and Alex's Guide to Web Publishing
- Object-Oriented Analysis and Design with Applications by Grady Booch
- Effective Java by Joshua Bloch
- Computability by N. J. Cutland
- Masterminds of Programming
- The Tao Te Ching
- The Productive Programmer
- The Art of Deception by Kevin Mitnick
- The Career Programmer: Guerilla Tactics for an Imperfect World by Christopher Duncan
- Paradigms of Artificial Intelligence Programming: Case studies in Common Lisp
- Masters of Doom
- Pragmatic Unit Testing in C# with NUnit by Andy Hunt and Dave Thomas with Matt Hargett
- How To Solve It by George Polya
- The Alchemist by Paulo Coelho
- Smalltalk-80: The Language and its Implementation
- Writing Secure Code (2nd Edition) by Michael Howard
- Introduction to Functional Programming by Philip Wadler and Richard Bird
- No Bugs! by David Thielen
- Rework by Jason Freid and DHH
- JUnit in Action
#BlackOwned #BlackEntrepreneurs #BlackBuniness #AWSCertified #AWSCloudPractitioner #AWSCertification #AWSCLFC02 #CloudComputing #AWSStudyGuide #AWSTraining #AWSCareer #AWSExamPrep #AWSCommunity #AWSEducation #AWSBasics #AWSCertified #AWSMachineLearning #AWSCertification #AWSSpecialty #MachineLearning #AWSStudyGuide #CloudComputing #DataScience #AWSCertified #AWSSolutionsArchitect #AWSArchitectAssociate #AWSCertification #AWSStudyGuide #CloudComputing #AWSArchitecture #AWSTraining #AWSCareer #AWSExamPrep #AWSCommunity #AWSEducation #AzureFundamentals #AZ900 #MicrosoftAzure #ITCertification #CertificationPrep #StudyMaterials #TechLearning #MicrosoftCertified #AzureCertification #TechBooks
Top 1000 Canada Quiz and trivia: CANADA CITIZENSHIP TEST- HISTORY - GEOGRAPHY - GOVERNMENT- CULTURE - PEOPLE - LANGUAGES - TRAVEL - WILDLIFE - HOCKEY - TOURISM - SCENERIES - ARTS - DATA VISUALIZATION
Top 1000 Africa Quiz and trivia: HISTORY - GEOGRAPHY - WILDLIFE - CULTURE - PEOPLE - LANGUAGES - TRAVEL - TOURISM - SCENERIES - ARTS - DATA VISUALIZATION
Exploring the Pros and Cons of Visiting All Provinces and Territories in Canada.
Exploring the Advantages and Disadvantages of Visiting All 50 States in the USA
Health Health, a science-based community to discuss health news and the coronavirus (COVID-19) pandemic
- Test-at-home kit for cancer patients approved for useby /u/Sariel007 on May 11, 2024 at 1:22 pm
submitted by /u/Sariel007 [link] [comments]
- The World Must Work Together to Tackle the Growing Avian Influenza Crisis | Blog | Nature | PBSby /u/Bean_Tiger on May 11, 2024 at 10:49 am
submitted by /u/Bean_Tiger [link] [comments]
- Roughly 1 in 8 US adults have taken GLP-1 drugs like Wegovy, poll showsby /u/ThinkerSis on May 11, 2024 at 4:33 am
submitted by /u/ThinkerSis [link] [comments]
- Cancer mortality has declined in many countriesby /u/eortizospina on May 11, 2024 at 3:40 am
submitted by /u/eortizospina [link] [comments]
- California city declares a health emergency amid tuberculosis outbreakby /u/thinkB4WeSpeak on May 11, 2024 at 1:25 am
submitted by /u/thinkB4WeSpeak [link] [comments]
Today I Learned (TIL) You learn something new every day; what did you learn today? Submit interesting and specific facts about something that you just found out here.
- TIL of drummer Cozy Powell's fatal car crash. He was traveling 104mph in the rain while drunk and talking on his phone with a woman who was cheating on her husband with him. He also had no seatbelt on, a leaking tire, and was still recovering from a recent motorcycle accident.by /u/YRwerunning on May 11, 2024 at 2:47 pm
submitted by /u/YRwerunning [link] [comments]
- TIL Nuclear Submarines can stay underwater for 30 years of operation. The only resource that limits the time underwater is the food supply for the crew and maintenance of the vessel.by /u/whstlngisnvrenf on May 11, 2024 at 2:44 pm
submitted by /u/whstlngisnvrenf [link] [comments]
- TIL when Henry Ford's River Rouge factory became fully operational in 1928, it consumed as much water per day as the cities of Detroit, Cincinnati, and New Orleans combined.by /u/TheProcrastafarian on May 11, 2024 at 1:50 pm
submitted by /u/TheProcrastafarian [link] [comments]
- TIL that the white specks in a Thomas English Muffin are farina.by /u/vmwnzella59 on May 11, 2024 at 1:36 pm
submitted by /u/vmwnzella59 [link] [comments]
- TIL Wolverine almost a cameo in Spider-Man 1, Hugh Jackman travelled to New York to film a scene but the idea was scrapped when the production team realized they had lost Wolverine's suitby /u/rocklou on May 11, 2024 at 12:53 pm
submitted by /u/rocklou [link] [comments]
Reddit Science This community is a place to share and discuss new scientific research. Read about the latest advances in astronomy, biology, medicine, physics, social science, and more. Find and submit new publications and popular science coverage of current research.
- AI systems are already skilled at deceiving and manipulating humans. Research found by systematically cheating the safety tests imposed on it by human developers and regulators, a deceptive AI can lead us humans into a false sense of securityby /u/Wagamaga on May 11, 2024 at 4:02 pm
submitted by /u/Wagamaga [link] [comments]
- Scientists unlock key to breeding ‘carbon gobbling’ plants with a major appetite | This could help engineer climate-resilient crops capable of sucking carbon dioxide from the atmosphere more efficiently, helping to produce more food in the process.by /u/chrisdh79 on May 11, 2024 at 3:44 pm
submitted by /u/chrisdh79 [link] [comments]
- Group-based psilocybin therapy shows promise in enhancing psychological flexibility | The findings suggest that changes in psychological flexibility may play a crucial role in the therapeutic benefits of psilocybin experiences.by /u/chrisdh79 on May 11, 2024 at 2:05 pm
submitted by /u/chrisdh79 [link] [comments]
- Researchers have devised a technique to convert chicken fat into carbon-based electrodes for supercapacitors, which store energy and power LEDs | Thiourea-treated carbon nanoparticles from chicken fat (h-CNOs) in the negative electrode of a supercapacitor exhibit exceptional performance.by /u/chrisdh79 on May 11, 2024 at 12:52 pm
submitted by /u/chrisdh79 [link] [comments]
- Study involving overweight or obese older adults found that consuming 60 grams of a mixture of walnuts, pistachios, cashews, and hazelnuts daily for 16 weeks improved insulin sensitivity in the brain.by /u/mvea on May 11, 2024 at 12:25 pm
submitted by /u/mvea [link] [comments]
Reddit Sports Sports News and Highlights from the NFL, NBA, NHL, MLB, MLS, and leagues around the world.
- Jerry Rice on son Brenden's draft slide: Prove teams wrongby /u/PrincessBananas85 on May 11, 2024 at 2:49 pm
submitted by /u/PrincessBananas85 [link] [comments]
- Sean Burroughs, former MLB player, Little League World Series and Olympic champion, dies at 43by /u/Oldtimer_2 on May 11, 2024 at 1:07 pm
submitted by /u/Oldtimer_2 [link] [comments]
- US-owned Belgian soccer team blocked by protesting fans from going to gameby /u/Oldtimer_2 on May 11, 2024 at 1:03 pm
submitted by /u/Oldtimer_2 [link] [comments]
- Maryland women roll in NCAA lacrosse opener behind backup goalieby /u/davster39 on May 11, 2024 at 5:45 am
submitted by /u/davster39 [link] [comments]
- Pacers defend home court, gain 1st win over Knicksby /u/Oldtimer_2 on May 11, 2024 at 2:31 am
submitted by /u/Oldtimer_2 [link] [comments]