Lambda demo functions for Server Stop/Start/Status

This commit is contained in:
Torsten 2024-04-07 08:29:43 +02:00
parent 3436132866
commit 8f62d9bf83
5 changed files with 106 additions and 1 deletions

View file

@ -6,5 +6,6 @@
"landscape": false,
"margin": "0",
"downscalePercent": 100
}
},
"readableLineLength": false
}

View file

@ -0,0 +1,15 @@
```python
#StopServer
import boto3
region = 'eu-central-1'
#instances = ['i-0de7cce6fcdf8c0e6']
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
ec2.stop_instances(InstanceIds=["i-0de7cce6fcdf8c0e6"])
return {
'message' : 'stopped'
}
```
`

View file

@ -0,0 +1,13 @@
```python
#StartServer
import boto3
region = 'eu-central-1'
#instances = ['i-0de7cce6fcdf8c0e6']
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
ec2.start_instances(InstanceIds=["i-0de7cce6fcdf8c0e6"])
return {
'message' : 'server started'
}
```

View file

@ -0,0 +1,45 @@
```python
import boto3
import time
import datetime
#ec2 = boto3.resource('ec2')
ec2 = boto3.client('ec2')
awa_server_instance_id = "i-0de7cce6fcdf8c0e6"
def lambda_handler(event, context):
#return "1.2.3.4"
#filters = [
# {
# 'Name': 'instance-state-name',
# 'Values': ['running']
# }
#]
#
#instances = ec2.instances.filter(Filters=filters)
#
#for instance in instances:
# print(instance)
response = ec2.describe_instances()
for reservation in response['Reservations']:
for instance in reservation['Instances']:
instance_id = instance.get('InstanceId', 'NONE')
ip = instance.get('PublicIpAddress', 'DOWN')
if instance_id == awa_server_instance_id:
#return {
# 'statusCode': 200,
# 'ip': ip
#}
return ip+'\n'
#return {
# 'statusCode': 200,
# 'ip': "DOWN"
#}
return "DOWN\n"
```

View file

@ -0,0 +1,31 @@
```python
#Get Uptime
import boto3
import time
import datetime
region = 'eu-central-1'
instances = ['i-0de7cce6fcdf8c0e6']
ec2 = boto3.resource('ec2')
print("Executing script")
def lambda_handler(event, context):
for instance in ec2.instances.all():
if instance.id =="i-0de7cce6fcdf8c0e6":
state = instance.state["Name"]
if state != "running":
return {
'state' : state,
'uptime': '-'
}
else:
launch_time = (instance.launch_time).strftime("%Y-%m-%d %H:%M:%S")
launch_time = datetime.datetime.strptime(launch_time, "%Y-%m-%d %H:%M:%S")
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
current_time = datetime.datetime.strptime(current_time, "%Y-%m-%d %H:%M:%S")
uptime = (current_time - launch_time)
threshold = datetime.timedelta(minutes = 2)
return {
'state' : state,
'uptime': str(uptime)
}
```