I'm trying to automatically backup my EC2 instances through AWS Lambda.
I used these 2 scripts and they work just fine. https://gist.github.com/bkozora/724e01903a9ad481d21e https://gist.github.com/bkozora/d4f1cf0e5cf26acdd377
But I would like to add the functionality that the scripts only delete or backup the instances that have been launched today and have a Backup-Tag.
I think I could achieve this by additionally filtering the list of instances by Launch Time = (date of today) and then execute the function for the filtered list just before midnight.
Sadly I have no idea what the syntax would look like to achieve this since I'm completely new to this.
But just for further clarification the said part of the code should look something like this:
#....
var date = datetime.datetime.now();
Filters=[
{'Name': 'tag-key', 'Values': ['Backup']},
{'Name': 'instance.launch_time', 'Values': [date]}
]
#....
#(and then the code to make a backup of every instance in the filtered list.
Couldn't find anything on filtering lists by Launch Time so hopefully someone can help me out here.
For launch-time, you can give a wild card to match any time within a given date. If today is Dec 13th 2017, you can specify 2017-12-13*
import boto3
from datetime import date
date_filter = date.isoformat(date.today()) + '*'
ec2 = boto3.resource('ec2')
instances = ec2.instances.filter(Filters=[{'Name':'launch-time', 'Values':[date_filter]}])
for instance in instances:
print instance.instance_id
try this one:
import datetime
date_filter = (datetime.datetime.now() - datetime.timedelta(days=7)).strftime("%Y-%m-%d")
ec2_client.describe_instances(
Filters=[
{
'Name':'launch-time',
'Values':[date_filter+'*']
},
],
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With