python boto issue with displaying latest snapshot for each instance - python

I am trying to print Instance name, volume id , instance ID, instance private IP, snapshot start time snapshot ID in one tabular form.
Code :-
#!/usr/bin/python
import os
import boto.ec2
import time
import datetime
conn = boto.ec2.connect_to_region("eu-west-1")
reservations = conn.get_all_instances()
tags = conn.get_all_tags()
snapshots = conn.get_all_snapshots(owner="self")
instances = [i for r in reservations for i in r.instances]
import datetime
today = datetime.datetime.today()
one_day = datetime.timedelta(days=1)
yesterday = today - one_day
from datetime import datetime
for inst in instances:
for snap in snapshots:
start_time = datetime.strptime (snap.start_time.split('.')[0],'%Y-%m-%dT%H:%M:%S')
if start_time > yesterday and 'Name' in inst.tags:
print "%s (%s) (%s) (%s) [%s] " % (inst.tags['Name'], start_time, snap.volume_id
It's looping through all instances again & again. E.g-> I have 17 instances then it loops through all instances 17*17 times and displays the result.
Any suggestions..

It looks like your snapshots don't come from your instances so you could use something like this
for inst, snap in zip(instances, snapshots):
do stuff
That way it will loop through both at the same time and not all of your snapshots per instance

Related

Get local date time and time in Django

How can I get the local date and time in Django?
I tried this solution. But it works only for the date now.
from django.utils import timezone
now = timezone.localtime(timezone.now()) #OK
date = timezone.localtime(timezone.date()) #Error
time = timezone.localtime(timezone.time()) #Error
Preferably in the same format as for datetime
now = datetime.datetime.now() #'2020-04-28 17:57:34.120383'
date = datetime.datetime.now().date() #'2020-04-28
time = datetime.datetime.now().time() #18:12:08.987472
Extract the date and time from the local instant object.
from django.utils import timezone
now = timezone.localtime(timezone.now())
date = now.date()
time = now.time()

insert conditional for hours

Good evening, could you help me in how I can put a condition so that a message comes out saying that you can not take an hour because it is already busy ?, I currently have this:
class reserva (models.Model):
_name='gimnasio.reserva'
tipo_reserva=fields.Selection([('clase','Clase'),('evaluacion','Evaluacion')])
fecha_reserva=fields.Date()
start_time=fields.Float()
end_time=fields.Float()
def fecha(self):
if self.star_time==self.star_time:
raise validationError('the hour is busy')
I have another question for you. you know how to configure Datetime only for hour and minutes because I only need hour and minutes but not the date.
To configure Datetime only for hour and minutes.
time = fields.Datetime("time")
custom_time = fields.Char('my_custome_time')
#api.onchange('time')
def _get_time(self):
if self.time:
for rec in self:
# datetime value is a string like 'YYYY-mm-dd HH:MM:SS'
# so just extract string from position 11 to 16
_time = self.time[11:16]
self.custom_time = _time
rec.custom_time = self.custom_time
I think you can use strptime method from datetime module.
from datetime import datetime as dt
start_time = fields.Float()
end_time = fields.Float()
#api.onchange('start_time','end_time')
def _check(self):
records = self.env["gimnasio.reserva"].search([("day", '=', the day you want to check eg. "2019-06-13")])
for rec in records:
ref_start = dt.strptime(str(rec.start_time), "%H:%M")
curr_start = dt.strptime(str(self.start_time), "%H:%M")
if ref_start == curr_start:
raise validationError('the hour is busy')
I didn't debug yet, you can try it.
how to eliminate the default date that you added ("2019-06-13") and that any date should not have the same busy schedule?
In this case you don't need datetime module just
#api.constrains("start_time")
def _check(self):
# search db for any record have same start time.
records = self.env["gimnasio.reserva"].search([('start_time ','=', self.start_time)])
if len(records) > 0:
raise validationError('the hour is busy')

Get AWS EC2 specific tag/value combo + instance id

I'm new to Python and programing. I need to create a Lambda function using Python 3.7 that will look for a specific tag/value combo and return the tag value along with the instance id . I can get both with my current code but I'm having a hard time figuring out how to combine these. boto3.resource gives me the tag value and boto3.client gives me the instance id.
I have EC2 instances (1000's) where we need to monitor the tag value for the tag 'expenddate' and compare the value (mm/dd/yy) to the current date (mm/dd/yy) and alert when 'expenddate' value is less than the current date.
import boto3
import collections
import datetime
import time
import sys
from datetime import date as dt
def lambda_handler(event, context):
today = datetime.date.today()
mdy = today_string = today.strftime('%m/%d/%y')
ec2 = boto3.resource('ec2')
for instance in ec2.instances.all():
if instance.tags is None:
continue
for tag in instance.tags:
if tag['Key'] == 'expenddate':
if (tag['Value']) <= mdy:
print ("Tag has expired!!!!!!!!!!!")
else:
print ("goodby")
client = boto3.client('ec2')
resp = client.describe_instances(Filters=[{
'Name': 'tag:expenddate',
'Values': ['*']
}])
for reservation in resp['Reservations']:
for instance in reservation['Instances']:
print("InstanceId is {} ".format(instance['InstanceId']))
I want to end up with a combined instance id and tag value or two variables that I can combine later.
change
print ("Tag has expired!!!!!!!!!!!")
to
# initialise array
expiredInstances=[]
.
.
.
.
.
print ("%s has expired" % instance.id)
expiredInstances.append({'instanceId':instance.id,'tag-value':tag['Value']})
That will give you an array of instanceId's with tag values

list RDS snapshot created today using Boto 3

I am doing a Python Lambda function to describe list of RDS snapshots created today. The challenge is how to convert the datetime.datetime.today() into a format which RDS client understands?
UPDATE: I have implemented some changes suggested, I have added a string variable to convert the date expression into format which Boto3 RDS understands.
'SnapshotCreateTime': datetime(2015, 1, 1),
today = (datetime.today()).date()
rds_client = boto3.client('rds')
snapshots = rds_client.describe_db_snapshots(SnapshotType='automated')
harini = "datetime("+ today.strftime('%Y,%m,%d') + ")"
print harini
print snapshots
for i in snapshots['DBSnapshots']:
if i['SnapshotCreateTime'].date() == harini:
print(i['DBSnapshotIdentifier'])
print (today)
it is still unable to retrieve list of automated snapshots created today
SnapshotCreateTime is a datetime.datetime object. So, you can just do i['SnapshotCreateTime'].date() to get the date.
import boto3
from datetime import datetime, timezone
today = (datetime.today()).date()
rds_client = boto3.client('rds')
snapshots = rds_client.describe_db_snapshots()
for i in snapshots['DBSnapshots']:
if i['SnapshotCreateTime'].date() == today:
print(i['DBSnapshotIdentifier'])
print (today)

Determine if an entity is created 'today'

I am creating an app which, on any given day, only one entity can be created per day. Here is the model:
class MyModel(ndb.Model):
created = ndb.DateTimeProperty(auto_now_add=True)
Since only one entity is allowed to be created per day, we will need to compare the MyModel.created property to today's date:
import datetime
class CreateEntity(webapp2.RequestHandler):
def get(self):
today = datetime.datetime.today()
my_model = MyModel.query(MyModel.created == today).get()
if my_model:
# print("Today's entity already exists")
else:
# create today's new entity
The problem is that I cannot compare the two dates like this. How can I check if an entity was already created 'today'?
I ended up changing the property from DateTimeProperty to DateProperty. Now I am able to do this:
today_date = datetime.datetime.today().date()
today_entity = MyModel.query(MyModel.created == today_date).get()
You are comparing a DateTime object with a Date object.
Instead of
my_model = MyModel.query(MyModel.created == today).get()
use
my_model = MyModel.query(MyModel.created.date() == today).get()
Seems like the only one solution is to use a "range" query, here's a relevant answer https://stackoverflow.com/a/14963648/762270
You can't query by created property using == since you don't actually know the exact creation datetime (which is what you'll find in created due to the auto_now_add=True option)
But you could query for the most recently created entity and check if its creation datetime is today. Something along these lines:
class CreateEntity(webapp2.RequestHandler):
def get(self):
now = datetime.datetime.utcnow()
# get most recently created one:
entity_list = MyModel.query().order(-MyModel.created).fetch(limit=1)
entity = entity_list[0] if entity_list else None
if entity and entity.created.year == now.year and \
entity.created.month == now.month and \
entity.created.day == now.day:
# print("Today's entity already exists")
else:
# create today's new entity
Or you could compute a datetime for today's 0:00:00 am and query for created bigger than that.
Or you could drop the auto_now_add=True option and explicitly set created to a specific time of the day (say midnight exactly) and then you can query for the datetime matching that time of day today.
Using a range query for a single specific known value you want to lookup is overkill and expensive, I would use one of these 2 solutions:
1 - Extra Property
Sacrifice a little space with an extra property, though since it's one per day, it shouldn't be a big deal.
from datetime import datetime
class MyModel(ndb.Model):
def _pre_put_hook(self):
self.date = datetime.today().strftime("%Y%m%d")
created = ndb.DateTimeProperty(auto_now_add=True)
date = ndb.StringProperty()
class CreateEntity(webapp2.RequestHandler):
def get(self):
today = datetime.today().strftime("%Y%m%d")
my_model = MyModel.query(MyModel.date == today).get()
if my_model:
logging.info("Today's entity already exists")
else:
# MyModel.date gets set automaticaly by _pre_put_hook
my_model = MyModel()
my_model.put()
logging.info("create today's new entity")
2 - Use [today] as Entity ID (preferred)
I would rather use today as the ID for my Entity, that's the fastest/cheaper/optimal way to retrieve your entity later. It could also be a combination with something else, i.e. ID=<userid+today>, in case that entity is per user, or maybe just add userid as a parent (ancestor). So it would be something like this:
from datetime import datetime
class MyModel(ndb.Model):
created = ndb.DateTimeProperty(auto_now_add=True)
class CreateEntity(webapp2.RequestHandler):
def get(self):
today = datetime.today().strftime("%Y%m%d")
my_model = MyModel.get_by_id(today)
if my_model:
logging.info("Today's entity already exists")
else:
my_model = MyModel(id=today)
my_model.put()
logging.info("create today's new entity")

Categories