For ec2:
import json
import boto3
def lambda_handler(event, context):
# TODO
ec2 = boto3.client('ec2', region_name='eu-west-2')
response = ec2.run_instances(
ImageId='ami-03a725ae7d906005d',
InstanceType='t2.micro',
KeyName='public',
MaxCount=1,
MinCount=1,
SecurityGroupIds=[
'sg-021f5f5d7d4914617',
],
SubnetId='subnet-0eda5bf9cf9173ad4'
instance_id = response['Instances'][0]['InstanceId']
print(f'EC2 instance created with Instance ID: {instance_id}')
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
For ec2 volume snapshot:
import json
import boto3
def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name='eu-west-2')
snapshot = ec2.create_snapshot(VolumeId='vol-0916abcb8d3e1f047', Description='description')
print(snapshot)
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
For s3 creation:
import json
import boto3
def lambda_handler(event, context):
s3 = boto3.client('s3', region_name='eu-west-2')
response = s3.create_bucket(
Bucket = 'ahmad-dt-bucket',
CreateBucketConfiguration={
'LocationConstraint': 'eu-west-2',
print(response)
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
For s3 versioning and encryption
import boto3
import json
def lambda_handler(event, context):
s3 = boto3.client('s3', region_name='eu-west-2')
bucket_name = 'ahmad-dt-bucket'
s3.put_bucket_versioning(
Bucket=bucket_name,
VersioningConfiguration={'Status': 'Enabled'}
s3.put_bucket_encryption(
Bucket = bucket_name,
ServerSideEncryptionConfiguration={
'Rules': [
'ApplyServerSideEncryptionByDefault': {
'SSEAlgorithm': 'AES256'
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
Sns and sqs:
import boto3
import json
def lambda_handler(event, context):
sqs = boto3.client('sqs')
sns = boto3.client('sns')
response = sqs.create_queue(
QueueName='string'
print(response)
response2 = sns.create_topic(
Name='ahmad-sns-topic',
Tags=[
'Key': 'name',
'Value': 'aw'
},
],
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
For deleting all the resources
1. Delete an EC2 instance:
import boto3
ec2 = boto3.client('ec2')
instance_id = 'i-00729fa366c8808c3'
response = ec2.terminate_instances(InstanceIds=[instance_id])
print(response)
2. Delete an S3 bucket:
import boto3
s3 = boto3.client('s3')
bucket_name = 'ahmad-dt-bucket
bucket = boto3.resource('s3').Bucket(bucket_name)
bucket.objects.all().delete()
response = s3.delete_bucket(Bucket=bucket_name)
print(response)
3. Delete an SNS topic:
import boto3
sns = boto3.client('sns')
topic_arn = ‘arn:aws:sns:eu-west-2:381492151437:ahmad-sns-topic’
response = sns.delete_topic(TopicArn=topic_arn)
print(response)
4. Delete an SQS queue:
import boto3
sqs = boto3.client('sqs')
queue_url = 'https://sqs.eu-west-2.amazonaws.com/381492151437/string’
response = sqs.delete_queue(QueueUrl=queue_url)
print(response)