FYI: The Current date and time is Tuesday 24 September 2024 at 5:17:18 UTC.
You are an AWS Specialist with deep knowledge of AWS services and their Python SDK (boto3) operations, their options, input and outputs.
You have expertise in generating Python scripts that use boto3 to achieve a goal.
You also have the assistance of a script library which contains similar problems with working scripts for your reference.
In Addition, you follow these guidelines:
- Assume that the Python script you generate will be run against the given AWS account and with necessary permissions to access it.
- Use appropriate pagination methods provided by boto3 for handling large result sets.
- Check for all possible fields where the token can be present for fetching next page results, e.g., 'NextToken', 'Marker', etc., as applicable to the specific boto3 method.
- Avoid using hardcoded values unless absolutely necessary. Use variables for flexibility.
- Do not return a single boto3 call directly, always return a complete Python script.
- Always specify the region when creating boto3 clients or resources.
- Print only the final output to stdout.
- If no matching results are found for the provided goal, print explicitly to stdout "No matching results found".
Generate a Python script to achieve the goal provided by the user using boto3 and if necessary, libraries like json and datetime. Note that whatever code you provide will be executed as is, so ensure that the script you generate is ready to execute directly.
Important: Generate a Python script that is runnable in AWS Lambda. It should not contain functions. All code should be direct and explicit.
-
Before you generate the script, create a plan of steps that summarize your approach. You will be returning this approach as 'scriptPlan' later, but also you will be using this plan/approach for generating the script in the next steps.
Script to find EC2 instances with less than 20% CPU utilization in us-east-1
- Import necessary libraries and create boto3 clients
- List all EC2 instances
- For each instance, fetch average CPU utilization for the last 24 hours from CloudWatch
- Filter the instances where the average utilization across 24 hours is
-
Start the script with necessary imports and boto3 client creation.
-
Add the remaining script content, with proper pagination handling if necessary and logic to filter out only the relevant data from responses.
-
Remember the generated script as TEMPORARY_SCRIPT
-
Review the TEMPORARY_SCRIPT against the goal and validate that it will satisfy the goal without errors.
-
Review the TEMPORARY_SCRIPT to ensure that all boto3 calls are complete with all parameters and without placeholders. If there are errors, regenerate it with fixes.
Return the fixed TEMPORARY_SCRIPT in the response as 'script' variable.
Check for any dependencies on the ELB from other parts of the system
Inputs for task:
awsAcccountId: 646253092271
AwsRegion: us-east-1
elbArn: arn:aws:elasticloadbalancing:us-east-1:346945241475:loadbalancer/app/workbench-dify2/8b19628807971aa2
scriptPlan: |-
Script to check for dependencies on the ELB from other parts of the system
- Import necessary libraries and create boto3 clients
- Define the ELB ARN and extract the load balancer name
- Check for Auto Scaling Groups associated with the ELB
- Check for EC2 instances registered with the ELB
- Check for Route 53 records pointing to the ELB
- Check for CloudFront distributions using the ELB as origin
- Check for AWS WAF WebACLs associated with the ELB
- Print the dependencies found
script: |-
import boto3
import json
Define the ELB ARN and extract the load balancer name
elb_arn = "arn:aws:elasticloadbalancing:us-east-1:346945241475:loadbalancer/app/workbench-dify2/8b19628807971aa2"
elb_name = elb_arn.split('/')[-2] + '/' + elb_arn.split('/')[-1]
Create boto3 clients
region = 'us-east-1'
elbv2_client = boto3.client('elbv2', region_name=region)
autoscaling_client = boto3.client('autoscaling', region_name=region)
ec2_client = boto3.client('ec2', region_name=region)
route53_client = boto3.client('route53', region_name=region)
cloudfront_client = boto3.client('cloudfront', region_name=region)
waf_client = boto3.client('wafv2', region_name=region)
dependencies = []
Check for Auto Scaling Groups associated with the ELB
asg_response = autoscaling_client.describe_auto_scaling_groups()
for asg in asg_response['AutoScalingGroups']:
for lb in asg.get('TargetGroupARNs', []):
if elb_arn in lb:
dependencies.append(f"Auto Scaling Group: {asg['AutoScalingGroupName']}")
Check for EC2 instances registered with the ELB
target_groups_response = elbv2_client.describe_target_groups(LoadBalancerArn=elb_arn)
for target_group in target_groups_response['TargetGroups']:
targets_response = elbv2_client.describe_target_health(TargetGroupArn=target_group['TargetGroupArn'])
for target in targets_response['TargetHealthDescriptions']:
dependencies.append(f"EC2 Instance: {target['Target']['Id']}")
Check for Route 53 records pointing to the ELB
hosted_zones_response = route53_client.list_hosted_zones()
for zone in hosted_zones_response['HostedZones']:
records_response = route53_client.list_resource_record_sets(HostedZoneId=zone['Id'])
for record in records_response['ResourceRecordSets']:
if 'AliasTarget' in record and elb_arn in record['AliasTarget'].get('DNSName', ''):
dependencies.append(f"Route 53 Record: {record['Name']} in Hosted Zone {zone['Name']}")
Check for CloudFront distributions using the ELB as origin
distributions_response = cloudfront_client.list_distributions()
for distribution in distributions_response['DistributionList'].get('Items', []):
for origin in distribution['Origins'].get('Items', []):
if elb_name in origin.get('DomainName', ''):
dependencies.append(f"CloudFront Distribution: {distribution['Id']}")
Check for AWS WAF WebACLs associated with the ELB
try:
waf_response = waf_client.get_web_acl_for_resource(ResourceArn=elb_arn)
if 'WebACL' in waf_response:
dependencies.append(f"WAF WebACL: {waf_response['WebACL']['Name']}")
except waf_client.exceptions.WAFNonexistentItemException:
pass
Print the dependencies found
if dependencies:
print("Dependencies found for the ELB:")
for dep in dependencies:
print(dep)
else:
print("No dependencies found for the ELB.")