Created
November 13, 2024 22:34
-
-
Save charlesrc019/0548e3b2888b861c3abf52c1bcbab0f8 to your computer and use it in GitHub Desktop.
web_manage_aws_services_easy.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import boto3 | |
def lambda_handler(event, context): | |
msg = None | |
try: | |
data = json.loads(event['body'].lower()) | |
# Manage EC2 instances. | |
if data['service'] == 'ec2': | |
client = boto3.client('ec2') | |
# Get instance list from names. | |
if ('items' not in data) or (len(data['items']) < 1): | |
raise Exception('No items specified!') | |
response = client.describe_instances( | |
Filters=[{'Name': 'tag:Name', 'Values': data['items']}] | |
) | |
instances = [ | |
instance['InstanceId'] | |
for reservation in response['Reservations'] | |
for instance in reservation['Instances'] | |
] | |
if not instances: | |
raise Exception('No instances found matching specified names!') | |
# Execute actions. | |
if data['action'] == 'start': | |
client.start_instances(InstanceIds=instances) | |
msg = f'Successfully started instances.' | |
elif data['action'] == 'stop': | |
client.stop_instances(InstanceIds=instances) | |
msg = f'Successfully stopped instances.' | |
elif data['action'] == 'reboot': | |
client.reboot_instances(InstanceIds=instances) | |
msg = f'Successfully rebooted instances.' | |
else: | |
raise Exception(f'Specified action "{data["action"]}" unknown!') | |
# Manage Route53. | |
elif data['service'] == 'route53': | |
if data['action'] != 'upsert': | |
raise Exception(f'Specified action "{data["action"]}" unknown!') | |
# Extract parameters. | |
if ('items' not in data) or (len(data['items']) != 1): | |
raise Exception('Invalid items specified!') | |
tmp1 = data['items'][0].split('>') | |
if len(tmp1) != 2: | |
raise Exception('Invalid action item specified!') | |
tmp2 = tmp1[0].split('.') | |
if len(tmp2) != 3: | |
raise Exception('Invalid domain specified!') | |
subdomain = tmp2[0] | |
domain = '.'.join(tmp2[1:]) | |
tmp2 = tmp1[1].split('.') | |
if len(tmp2) != 4: | |
raise Exception('Invalid IP specified!') | |
ip = tmp1[1] | |
client = boto3.client('route53') | |
# Get hosted zone ID from name. | |
response = client.list_hosted_zones_by_name(DNSName=domain) | |
zone_id = None | |
hosted_zones = response['HostedZones'] | |
for zone in hosted_zones: | |
if zone['Name'] == domain + ".": | |
zone_id = zone['Id'].split('/')[-1] | |
if zone_id is None: | |
raise Exception('No hosted zone found matching specified name!') | |
# Create DNS change. | |
change_batch = { | |
'Comment': 'upsert via lambda', | |
'Changes': [ | |
{ | |
'Action': 'UPSERT', | |
'ResourceRecordSet': { | |
'Name': subdomain + '.' + domain + '.', | |
'Type': 'A', | |
'TTL': 60, | |
'ResourceRecords': [{'Value': ip}] | |
} | |
} | |
] | |
} | |
response = client.change_resource_record_sets( | |
HostedZoneId=zone_id, | |
ChangeBatch=change_batch | |
) | |
msg = "Successfully updated DNS." | |
# Manage CloudFront. | |
elif data['service'] == 'cloudfront': | |
if data['action'] != 'refresh': | |
raise Exception(f'Specified action "{data["action"]}" unknown!') | |
client = boto3.client('cloudfront') | |
# Get the distribution ID by description. | |
if ('items' not in data) or (len(data['items']) != 1): | |
raise Exception('Invalid items specified!') | |
distributions = client.list_distributions() | |
distribution_id = None | |
if 'DistributionList' in distributions and distributions['DistributionList']['Quantity'] > 0: | |
for distribution in distributions['DistributionList']['Items']: | |
if distribution.get('Comment') == data['items'][0]: | |
distribution_id = distribution['Id'] | |
break | |
if distribution_id is None: | |
raise Exception('No distribution found matching specified name!') | |
# Create the invalidation | |
response = client.create_invalidation( | |
DistributionId=distribution_id, | |
InvalidationBatch={ | |
'Paths': { | |
'Quantity': 1, | |
'Items': ['/*'] # Invalidating all files | |
}, | |
'CallerReference': str(hash('/*')) | |
} | |
) | |
msg = "Successfully refreshed distribution." | |
else: | |
raise Exception(f'Specified service "{data["service"]}" unknown!') | |
# Send success message. | |
if msg is not None: | |
return { | |
'statusCode': 200, | |
'body': msg | |
} | |
else: | |
raise Exception('Unknown error!') | |
# Send error message. | |
except Exception as e: | |
return { | |
'statusCode': 400, | |
'body': str(e) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment