Skip to content

Instantly share code, notes, and snippets.

@ssheff
Forked from deepak7093/Enable_LB_Access_Logs.py
Created September 16, 2021 01:46
Show Gist options
  • Save ssheff/021161c6f35d434c9314a81642292da8 to your computer and use it in GitHub Desktop.
Save ssheff/021161c6f35d434c9314a81642292da8 to your computer and use it in GitHub Desktop.
Python script to enable AWS load balancer access logs
import boto3
"""
## Pre-requsites: Need to add tag on loadbalancer as `Environment:Production`.
Name: Enable AccessLogs for production load-balancers
Author: Deepak Dalvi
Version: 1.0.0
"""
AWS_ACCESS_KEY = ''
AWS_SECRET_KEY = ''
DEFAULT_REGION = 'ap-southeast-1'
S3BucketName = ''
# Fetch all loadbalancer details
def get_elb_name():
elb_names = []
tags = []
prod_lb = []
elb = boto3.client('elb', aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_SECRET_KEY, region_name=DEFAULT_REGION)
res = elb.describe_load_balancers()
# print(res)
for item in res['LoadBalancerDescriptions']:
elb_names.append(item['LoadBalancerName'])
# print("elb_name:", elb_names)
# Describe tags API has limit of 20 lb at a time, so addting below logic
for item in range(0, len(elb_names)):
temp_elb = []
tags_res = []
temp_elb.append(elb_names[item])
tags_res = elb.describe_tags(LoadBalancerNames=temp_elb)
for tag in tags_res['TagDescriptions'][0]['Tags']:
try:
if tag['Key'].lower() == "environment" and tag['Value'].lower() == "production" :
prod_lb.append(tags_res['TagDescriptions'][0]['LoadBalancerName'])
except KeyError:
print("error")
continue
# print(prod_lb)
# Fetch and update attribute of LB
for lb in prod_lb:
att = elb.describe_load_balancer_attributes(LoadBalancerName=lb)
print(att['LoadBalancerAttributes']['AccessLog']['Enabled'])
if att['LoadBalancerAttributes']['AccessLog']['Enabled'] == False:
print("AcessLogs Not enabled, Need Action")
elb.modify_load_balancer_attributes(LoadBalancerName=lb,LoadBalancerAttributes={'AccessLog': {'Enabled': True,'S3BucketName': S3BucketName,'EmitInterval': 60,'S3BucketPrefix': lb+"-logs"}})
print("Successfully enabled access logs for %s at location %s" %(lb,S3BucketName))
else:
print("AccessLogs alrady enabled for %s" %(lb))
def get_alb_name():
alb_names = []
alb = boto3.client('elbv2', aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_SECRET_KEY, region_name=DEFAULT_REGION)
res = alb.describe_load_balancers()
for item in res['LoadBalancers']:
alb_names.append(item['LoadBalancerArn'])
prod_alb = []
for item in range(0, len(alb_names)):
temp_alb = []
tags_res = []
temp_alb.append(alb_names[item])
tags_res = alb.describe_tags(ResourceArns=temp_alb)
# print(tags_res)
for tag in tags_res['TagDescriptions'][0]['Tags']:
try:
if tag['Key'].lower() == "environment" and tag['Value'].lower() == "production":
prod_alb.append(
tags_res['TagDescriptions'][0]['ResourceArn'])
except KeyError:
print("error")
continue
# print(prod_alb)
for lb in prod_alb:
att = alb.describe_load_balancer_attributes(LoadBalancerArn=lb)
# Get ALB name from ARN
alb_name = lb.split(':')[-1:][0].split('/')[2]
for item in att['Attributes']:
# print(item['Key'])
if item['Key'] == 'access_logs.s3.enabled' and item['Value'] == 'false':
print("AcessLogs Not enabled, Need Action")
#alb.modify_load_balancer_attributes(LoadBalancerName=lb,LoadBalancerAttributes={'AccessLog': {'Enabled': True,'S3BucketName': S3BucketName,'EmitInterval': 60,'S3BucketPrefix': lb+"-logs"}})
alb.modify_load_balancer_attributes(
Attributes=[
{'Key': 'deletion_protection.enabled','Value': 'true'},
{'Key': 'access_logs.s3.enabled', 'Value': 'true'},
{'Key': 'access_logs.s3.bucket', 'Value': S3BucketName},
{'Key': 'access_logs.s3.prefix', 'Value': alb_name}
],
LoadBalancerArn=lb,
)
print("Successfully enabled access logs for %s at location %s" %(alb_name,S3BucketName))
else:
if item['Key'] == 'access_logs.s3.enabled' and item['Value'] == 'true':
print("AccessLogs alrady enabled for %s" %(alb_name))
def main():
get_elb_name()
get_alb_name()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment