Lambda Pricing
- no of requests
- excution duration
- memory allocations (GB-seconds)
- aditional cost – vpc logs, applicatin logs storage
- provisined concurrency build or triggers.
create lambda and ec2 instance tag enviroment dev
- sample code based ec2 tags
- stop
- start
- permissions: (role)
- lambada execute
- ec2 instance action
sample code for stop and start ec2 instance
import boto3
def lambda_handler(event, context):
ec2 = boto3.client('ec2')
tag_key = event.get('tag_key', 'schedule')
tag_value = event.get('tag_value', 'schedule')
action = event.get('action')
response = ec2.describe_instances(
Filters=[
{
'Name': f'tag:{tag_key}',
'Values': [tag_value]
}
]
)
results = []
for reservation in response['Reservations']:
for instance in reservation['Instances']:
instance_id = instance['InstanceId']
state = instance['State']['Name']
if action == 'start' and state == 'stopped':
ec2.start_instances(InstanceIds=[instance_id])
results.append(f"Started {instance_id}")
elif action == 'stop' and state == 'running':
ec2.stop_instances(InstanceIds=[instance_id])
results.append(f"Stopped {instance_id}")
else:
results.append(f"Instance {instance_id} is in state {state}")
return {
"results": results
}
example event
{
"action": "stop",
"tag_key": "Environment",
"tag_value": "dev"
}
Task:
- create lambda and deploy above sample code
- try deploy code aws cli