├── .gitignore ├── README.md ├── __init__.py ├── api_gateway ├── create_api.py └── list_api_gateway.py ├── aws_lambda ├── create_function.py ├── lambda_function_url.py ├── list_lambda_arns.py ├── list_lambda_memory.py ├── list_lambdas.py └── trigger_lambda_asynchronously.py ├── cloud9 ├── create_environment.py └── list_environment_names.py ├── cloudformation └── get_stack_name.py ├── cloudfront └── list_distribution_id.py ├── cloudwatch ├── create_log_group.py ├── create_log_stream.py ├── list_log_groups.py └── put_log_events.py ├── codebuild ├── get_all_build_arns.py ├── get_build_arns.py ├── list_build_run_names.py └── list_project_names.py ├── codecommit └── create_repo.py ├── custom_scripts ├── __init__.py ├── deploy_lambda.py ├── publish_instance_ids.py └── test_queues.py ├── dynamodb ├── create_item.py ├── create_table.py ├── delete_table.py ├── list_tables.py └── scan_table.py ├── ebs └── list_volume_ids.py ├── ec2 ├── __init__.py ├── list_ami_ids.py ├── list_availability_zone.py ├── list_instance_ids.py ├── list_instance_names.py ├── list_instance_statuses.py ├── list_key_pair_names.py ├── list_security_group_ids.py ├── run_instance.py ├── run_ubuntu_instance.py ├── run_ubuntu_instance_call.py ├── stopping_instances.py └── terminate_instances.py ├── eventbridge └── list_rules.py ├── iam ├── attach_role_policy.py ├── create_policy.py ├── create_role.py ├── find_policy.py ├── list_policies.py └── list_role_names.py ├── polly └── generate_speech.py ├── rekognition └── detect_labels.py ├── s3 ├── create_bucket.py ├── delete_bucket.py ├── delete_non_empty_buckets.py ├── list_buckets.py ├── list_objects.py └── upload_object.py ├── sns ├── __init__.py ├── add_sns_subscription.py ├── create_sns_topic.py ├── list_sns_topics.py ├── print_sns_subscriptionarn.py ├── publish_sns_topic.py └── sns_pipeline.py ├── sqs ├── __init__.py ├── create_message.py ├── create_queue.py ├── delete_queue.py ├── get_messages.py ├── get_queue_url.py └── sqs_functions.py └── vpc ├── list_cidr_blocks.py ├── list_sg_ids.py ├── list_subnet_ids.py └── list_vpc_ids.py /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | *.pyc 3 | 4 | *.mp3 5 | *.jpg -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # boto3_python_scripts 2 | 3 | Repo for boto3 examples -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zaireali649/boto3_python_scripts/40dc703089d0a60d20026106de101a0d8cf48384/__init__.py -------------------------------------------------------------------------------- /api_gateway/create_api.py: -------------------------------------------------------------------------------- 1 | # import libraries 2 | 3 | import boto3 4 | 5 | #%% 6 | apigateway = boto3.client('apigatewayv2') 7 | 8 | response = apigateway.create_api( 9 | Name='silver-sept-2023-api', 10 | ProtocolType='HTTP', 11 | Target='arn:aws:lambda:us-east-1:458806987020:function:silver-sept-2023-lambda' 12 | ) 13 | 14 | print(response) -------------------------------------------------------------------------------- /api_gateway/list_api_gateway.py: -------------------------------------------------------------------------------- 1 | #%% 2 | 3 | # ============================================================================= 4 | # script for listing apis 5 | # ============================================================================= 6 | 7 | #%% 8 | # import libraries 9 | 10 | import boto3 11 | 12 | #%% 13 | # prep boto3 for Lambda 14 | 15 | client = boto3.client('apigateway') 16 | 17 | #%% 18 | # get apis 19 | 20 | response = client.get_rest_apis() 21 | 22 | #%% 23 | 24 | 25 | items = response['items'] 26 | 27 | for item in items: 28 | print(item['name']) -------------------------------------------------------------------------------- /aws_lambda/create_function.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | def create_function(client, roleARN, s3_bucket, s3_key, functionName='python_boto3_lambda', runtime='python3.8', handler='lambda_function.lambda_handler'): 4 | response = client.create_function( 5 | FunctionName=functionName, 6 | Runtime=runtime, 7 | Handler=handler, 8 | Role=roleARN, 9 | Code={ 10 | 'S3Bucket': s3_bucket, 11 | 'S3Key': s3_key, 12 | } 13 | ) 14 | 15 | return response 16 | 17 | 18 | 19 | if(__name__ == "__main__"): 20 | aws_lambda = boto3.client('lambda') 21 | 22 | response = create_function(aws_lambda, 'arn:aws:iam::458806987020:role/service-role/luit_red_jan_2023_lambda-role-fo8jlfny', 'zali-catch-all', 'lambda_function.zip') 23 | 24 | print(response) -------------------------------------------------------------------------------- /aws_lambda/lambda_function_url.py: -------------------------------------------------------------------------------- 1 | ######## Create a Sample Lambda Function URL and the necessary dependencies ######## 2 | 3 | import boto3 4 | 5 | #%% 6 | ### Create Hello Lambda .py ### 7 | 8 | lambda_code = ''' 9 | import json 10 | 11 | def lambda_handler(event, context): 12 | # TODO implement 13 | return { 14 | 'statusCode': 200, 15 | 'body': json.dumps('Hello from Lambda!') 16 | } 17 | ''' 18 | 19 | f = open("lambda_function.py", "w") 20 | f.write(lambda_code) 21 | f.close() 22 | 23 | #%% 24 | ### Create handler .zip ### 25 | 26 | from zipfile import ZipFile 27 | 28 | fZip = ZipFile('lambda-handler.zip', 'w') 29 | fZip.write('lambda_function.py') 30 | fZip.close() 31 | 32 | 33 | #%% 34 | ### Create Trust Policy for IAM Role 35 | 36 | import json 37 | 38 | trust_policy = json.dumps({ 39 | "Version": "2012-10-17", 40 | "Statement": [ 41 | { 42 | "Effect": "Allow", 43 | "Principal": { 44 | "Service": "lambda.amazonaws.com" 45 | }, 46 | "Action": "sts:AssumeRole" 47 | } 48 | ] 49 | }) 50 | 51 | 52 | #%% 53 | ### Create IAM Role 54 | 55 | client_iam = boto3.client('iam') 56 | 57 | response_create_role = client_iam.create_role( 58 | RoleName='lambda-role-boto3', 59 | AssumeRolePolicyDocument=trust_policy 60 | ) 61 | 62 | role_arn = response_create_role['Role']['Arn'] 63 | #%% 64 | ### Create Lambda Function 65 | 66 | client_lambda = boto3.client('lambda') 67 | 68 | f = open('lambda-handler.zip', 'rb') 69 | lambda_handler_zip = f.read() 70 | f.close() 71 | 72 | response_create_function = client_lambda.create_function( 73 | FunctionName='test_Lambda_Function_URLs_boto3', 74 | Runtime= 'python3.9', 75 | Role=role_arn, 76 | Code=dict(ZipFile=lambda_handler_zip), 77 | Handler='lambda_function.lambda_handler' 78 | ) 79 | 80 | #%% 81 | ### Add Public Access Permission 82 | 83 | client_lambda = boto3.client('lambda') 84 | 85 | response_add_permission = client_lambda.add_permission( 86 | FunctionName='test_Lambda_Function_URLs_boto3', 87 | StatementId='FunctionURLAllowPublicAccess', 88 | Action='lambda:InvokeFunctionUrl', 89 | Principal='*', 90 | FunctionUrlAuthType='NONE' 91 | ) 92 | 93 | #%% 94 | ### Create Lambda Function URL 95 | 96 | client_lambda = boto3.client('lambda') 97 | 98 | response_create_function_url_config = client_lambda.create_function_url_config( 99 | FunctionName='test_Lambda_Function_URLs_boto3', 100 | AuthType='NONE' 101 | ) 102 | 103 | function_URL = response_create_function_url_config['FunctionUrl'] 104 | print(function_URL) 105 | 106 | import requests 107 | response_requests = requests.get(function_URL) 108 | print(response_requests.text) 109 | 110 | -------------------------------------------------------------------------------- /aws_lambda/list_lambda_arns.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | aws_lambda = boto3.client('lambda') 4 | 5 | response = aws_lambda.list_functions() 6 | 7 | functions = response['Functions'] 8 | 9 | for function in functions: 10 | print(function['FunctionArn']) 11 | -------------------------------------------------------------------------------- /aws_lambda/list_lambda_memory.py: -------------------------------------------------------------------------------- 1 | # import the boto3 library 2 | import boto3 3 | 4 | # create an AWS Lambda client object 5 | aws_lambda = boto3.client('lambda') 6 | 7 | # make a request to the AWS Lambda API to list all available functions 8 | response = aws_lambda.list_functions() 9 | 10 | # extract the list of functions from the API response 11 | functions = response["Functions"] 12 | 13 | # iterate over the list of functions and print the function name and memory size 14 | for function in functions: 15 | print(function["FunctionName"], function["MemorySize"]) 16 | 17 | # The code imports the boto3 library, creates a client object for AWS Lambda, makes a request to the AWS Lambda API to list all available functions, 18 | # extracts the list of functions from the API response, iterates over the list of functions, and prints the name and memory size of each function. 19 | -------------------------------------------------------------------------------- /aws_lambda/list_lambdas.py: -------------------------------------------------------------------------------- 1 | #%% 2 | 3 | # ============================================================================= 4 | # script for listing lambdas 5 | # ============================================================================= 6 | 7 | #%% 8 | # import libraries 9 | 10 | import boto3 11 | 12 | #%% 13 | # prep boto3 for Lambda 14 | 15 | client = boto3.client('lambda') 16 | 17 | #%% 18 | # get lambda functions 19 | 20 | response = client.list_functions() 21 | 22 | #%% 23 | 24 | functions = response['Functions'] 25 | 26 | #%% 27 | 28 | for function in functions: 29 | print(function['FunctionName']) -------------------------------------------------------------------------------- /aws_lambda/trigger_lambda_asynchronously.py: -------------------------------------------------------------------------------- 1 | #%% 2 | 3 | # ============================================================================= 4 | # script for triggering a lambda asynchronously 5 | # ============================================================================= 6 | 7 | #%% 8 | # import libraries 9 | 10 | import boto3 11 | 12 | #%% 13 | # define parameters for run 14 | 15 | function_name = 'hello_world' 16 | 17 | #%% 18 | # prep boto3 for Lambda 19 | 20 | client = boto3.client("lambda") 21 | 22 | #%% 23 | # invoke function asynchronously 24 | 25 | response = client.invoke(FunctionName=function_name, 26 | InvocationType='Event' # asynchronous invoke 27 | ) 28 | -------------------------------------------------------------------------------- /cloud9/create_environment.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | import uuid # random string library 3 | 4 | cloud9 = boto3.client('cloud9') 5 | 6 | response = cloud9.create_environment_ec2( 7 | name=str(uuid.uuid4()), 8 | instanceType='t2.micro', 9 | imageId='amazonlinux-2-x86_64') 10 | 11 | print(response) -------------------------------------------------------------------------------- /cloud9/list_environment_names.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | # Create a boto3 client for AWS Systems Manager (SSM) service. 4 | ssm = boto3.client('ssm') 5 | 6 | # Get the AWS access key ID and secret access key from AWS Systems Manager Parameter Store. 7 | access_key_id_aws = ssm.get_parameter(Name='access_key_id_aws')['Parameter']['Value'] 8 | secret_access_key_aws = ssm.get_parameter(Name='secret_access_key_aws')['Parameter']['Value'] 9 | 10 | # Create a boto3 client for AWS Cloud9 service using the retrieved credentials. 11 | cloud9 = boto3.client('cloud9', 12 | aws_access_key_id=access_key_id_aws, 13 | aws_secret_access_key=secret_access_key_aws, 14 | ) 15 | 16 | # List Cloud9 environments. 17 | response = cloud9.list_environments() 18 | 19 | # Get the IDs of the Cloud9 environments. 20 | environmentIds = response["environmentIds"] 21 | 22 | # Describe the Cloud9 environments using the retrieved IDs. 23 | response = cloud9.describe_environments( 24 | environmentIds=environmentIds 25 | ) 26 | 27 | # Extract the environments from the response. 28 | environments = response["environments"] 29 | 30 | # Print the name of each Cloud9 environment. 31 | for environment in environments: 32 | print(environment["name"]) 33 | -------------------------------------------------------------------------------- /cloudformation/get_stack_name.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | cloudformation = boto3.client('cloudformation') 4 | 5 | response = cloudformation.describe_stacks() 6 | 7 | stacks = response['Stacks'] 8 | 9 | for stack in stacks: 10 | print(stack['StackName']) 11 | -------------------------------------------------------------------------------- /cloudfront/list_distribution_id.py: -------------------------------------------------------------------------------- 1 | import boto3 # Import the boto3 library to interact with AWS services 2 | 3 | # Create a CloudFront client using boto3 4 | cloudfront = boto3.client('cloudfront') 5 | 6 | # List all CloudFront distributions 7 | response = cloudfront.list_distributions() 8 | 9 | # Extract the DistributionList from the response 10 | distributionList = response["DistributionList"] 11 | 12 | # Get the list of distribution items 13 | items = distributionList["Items"] 14 | 15 | # Loop through each distribution item and print its Id 16 | for item in items: 17 | print(item["Id"]) 18 | -------------------------------------------------------------------------------- /cloudwatch/create_log_group.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | cloudwatch_logs = boto3.client('logs') 4 | 5 | try: 6 | response = cloudwatch_logs.create_log_group( 7 | logGroupName='lg_from_boto3' 8 | ) 9 | 10 | print(response) 11 | except cloudwatch_logs.exceptions.ResourceAlreadyExistsException as e: 12 | print(e) 13 | -------------------------------------------------------------------------------- /cloudwatch/create_log_stream.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | cloudwatch_logs = boto3.client('logs') 4 | 5 | try: 6 | response = cloudwatch_logs.create_log_stream( 7 | logGroupName='lg_from_boto3', 8 | logStreamName='ls_from_boto3' 9 | ) 10 | 11 | print(response) 12 | except cloudwatch_logs.exceptions.ResourceAlreadyExistsException as e: 13 | print(e) 14 | -------------------------------------------------------------------------------- /cloudwatch/list_log_groups.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | cloudwatch_logs = boto3.client('logs') 4 | 5 | logGroups = [] 6 | next_token = None 7 | 8 | # Use a while loop to handle pagination 9 | while True: 10 | if next_token: 11 | response = cloudwatch_logs.describe_log_groups(nextToken=next_token) 12 | else: 13 | response = cloudwatch_logs.describe_log_groups() 14 | 15 | logGroups.extend(response['logGroups']) 16 | 17 | # Check if there is a nextToken to continue pagination 18 | next_token = response.get('nextToken') 19 | if not next_token: 20 | break 21 | 22 | print(len(logGroups)) 23 | 24 | for logGroup in logGroups: 25 | print(logGroup['logGroupName']) 26 | -------------------------------------------------------------------------------- /cloudwatch/put_log_events.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | import time 3 | 4 | 5 | cloudwatch_logs = boto3.client('logs') 6 | 7 | try: 8 | response = cloudwatch_logs.put_log_events( 9 | logGroupName='lg_from_boto3', 10 | logStreamName='ls_from_boto3', 11 | logEvents=[ 12 | { 13 | 'timestamp': round(time.time() * 1000), 14 | 'message': 'Message from Boto3' 15 | }, 16 | ] 17 | ) 18 | 19 | print(response) 20 | except cloudwatch_logs.exceptions.ResourceAlreadyExistsException as e: 21 | print(e) 22 | -------------------------------------------------------------------------------- /codebuild/get_all_build_arns.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | codebuild = boto3.client('codebuild') 4 | 5 | response = codebuild.list_projects() 6 | 7 | projects = response["projects"] 8 | 9 | for project in projects: 10 | print(project) 11 | response = codebuild.list_builds_for_project( 12 | projectName=project 13 | ) 14 | 15 | names = response["ids"] 16 | 17 | for name in names: 18 | print(name) 19 | response = codebuild.batch_get_builds( 20 | ids=[ 21 | name, 22 | ] 23 | ) 24 | 25 | builds = response["builds"] 26 | 27 | for build in builds: 28 | print(build["id"], build["arn"]) -------------------------------------------------------------------------------- /codebuild/get_build_arns.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | codebuild = boto3.client('codebuild') 4 | 5 | response = codebuild.batch_get_builds( 6 | ids=[ 7 | 'black-may-2023:d5b4bb81-c554-470d-bd48-0fca6b8ae5b2', 8 | ] 9 | ) 10 | 11 | builds = response["builds"] 12 | 13 | for build in builds: 14 | print(build["id"], build["arn"]) -------------------------------------------------------------------------------- /codebuild/list_build_run_names.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | codebuild = boto3.client('codebuild') 4 | 5 | response = codebuild.list_builds_for_project( 6 | projectName='black-may-2023' 7 | ) 8 | 9 | names = response["ids"] 10 | 11 | for name in names: 12 | print(name) -------------------------------------------------------------------------------- /codebuild/list_project_names.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | codebuild = boto3.client('codebuild') 4 | 5 | response = codebuild.list_projects() 6 | 7 | projects = response["projects"] 8 | 9 | for project in projects: 10 | print(project) -------------------------------------------------------------------------------- /codecommit/create_repo.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | import uuid 3 | 4 | # Create a CodeCommit client 5 | codecommit = boto3.client('codecommit') 6 | 7 | # Create a new CodeCommit repository with the specified name 8 | response = codecommit.create_repository( 9 | repositoryName='zali-boto3-{}'.format(str(uuid.uuid4())) 10 | ) 11 | 12 | # Print the response from the repository creation 13 | print(response) 14 | -------------------------------------------------------------------------------- /custom_scripts/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zaireali649/boto3_python_scripts/40dc703089d0a60d20026106de101a0d8cf48384/custom_scripts/__init__.py -------------------------------------------------------------------------------- /custom_scripts/deploy_lambda.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import boto3 4 | import string 5 | import random 6 | 7 | sys.path.append('../') 8 | 9 | import aws_lambda.create_function as lcf 10 | 11 | aws_lambda_client = boto3.client('lambda') 12 | 13 | res = ''.join(random.choices(string.ascii_uppercase + 14 | string.digits, k=7)) 15 | 16 | functionName = 'python_boto3_lambda_' + res 17 | 18 | 19 | 20 | response = lcf.create_function(aws_lambda_client, 21 | 'arn:aws:iam::458806987020:role/service-role/luit_red_jan_2023_lambda-role-fo8jlfny', 22 | 'zali-catch-all', 23 | 'lambda_function.zip', 24 | functionName = functionName 25 | ) 26 | 27 | print(response) -------------------------------------------------------------------------------- /custom_scripts/publish_instance_ids.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import boto3 4 | 5 | sys.path.append('../') 6 | 7 | import ec2.list_instance_ids as lii 8 | import sns.publish_sns_topic as pst 9 | 10 | ec2 = boto3.client('ec2') 11 | instanceIds = lii.list_instance_ids(ec2) 12 | 13 | sns = boto3.client('sns') 14 | 15 | for instanceId in instanceIds: 16 | pst.sns_publish_topic(sns, 'arn:aws:sns:us-east-1:458806987020:Idontknow', instanceId) -------------------------------------------------------------------------------- /custom_scripts/test_queues.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import boto3 4 | import random 5 | 6 | sys.path.append('../') 7 | 8 | from sqs.sqs_functions import * 9 | 10 | sqs = boto3.client('sqs') 11 | 12 | QN = "gold-from-function-script" 13 | message = "Hey from custom SQS python functions! Random number: " + str(random.randint(0,300)).zfill(3) 14 | 15 | create_queue(sqs, QN) 16 | qurl = get_queue_url(sqs, QN) 17 | create_message(sqs, qurl, message) 18 | messages = get_messages(sqs, qurl) -------------------------------------------------------------------------------- /dynamodb/create_item.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | dynamodb = boto3.client('dynamodb') 4 | 5 | response = dynamodb.put_item( 6 | Item={ 7 | 'ID':{ 8 | 'S': '2ddf7888-2e48-11ed-a261-0242ac120002' , 9 | }, 10 | 'AlbumTitle': { 11 | 'S': 'Somewhat Famous', 12 | }, 13 | 'Artist': { 14 | 'S': 'No One You Know', 15 | }, 16 | 'Song': { 17 | 'S': 'Call Me Today', 18 | }, 19 | }, 20 | ReturnConsumedCapacity='TOTAL', 21 | TableName='Music', 22 | ) 23 | -------------------------------------------------------------------------------- /dynamodb/create_table.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | dynamodb = boto3.client('dynamodb') 4 | 5 | response = dynamodb.create_table( 6 | AttributeDefinitions=[ 7 | { 8 | 'AttributeName': 'ID', 9 | 'AttributeType': 'S', 10 | } 11 | ], 12 | KeySchema=[ 13 | { 14 | 'AttributeName': 'ID', 15 | 'KeyType': 'HASH', 16 | } 17 | ], 18 | ProvisionedThroughput={ 19 | 'ReadCapacityUnits': 1, 20 | 'WriteCapacityUnits': 1, 21 | }, 22 | TableName='Music', 23 | ) 24 | 25 | print(response) -------------------------------------------------------------------------------- /dynamodb/delete_table.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | dynamodb = boto3.client('dynamodb') 4 | 5 | response = dynamodb.delete_table(TableName='hells_kitchen') 6 | 7 | print(response) -------------------------------------------------------------------------------- /dynamodb/list_tables.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | dynamodb = boto3.client('dynamodb') 4 | 5 | response = dynamodb.list_tables() 6 | 7 | tableNames = response["TableNames"] 8 | 9 | for tableName in tableNames: 10 | print(tableName) 11 | -------------------------------------------------------------------------------- /dynamodb/scan_table.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | dynamodb = boto3.client('dynamodb') 4 | 5 | response = dynamodb.scan(TableName='movies') 6 | 7 | items = response["Items"] 8 | 9 | for item in items: 10 | print(item) 11 | for k, v in item.items(): 12 | print(k, list(v.values())[0]) -------------------------------------------------------------------------------- /ebs/list_volume_ids.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | ec2 = boto3.client('ec2') 4 | 5 | response = ec2.describe_volumes() 6 | 7 | volumes = response["Volumes"] 8 | 9 | for volume in volumes: 10 | print(volume["VolumeId"]) -------------------------------------------------------------------------------- /ec2/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zaireali649/boto3_python_scripts/40dc703089d0a60d20026106de101a0d8cf48384/ec2/__init__.py -------------------------------------------------------------------------------- /ec2/list_ami_ids.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | ec2 = boto3.client('ec2') 4 | 5 | response = ec2.describe_instances() 6 | 7 | reservations = response['Reservations'] 8 | 9 | for reservation in reservations: 10 | instances = reservation['Instances'] 11 | 12 | for instance in instances: 13 | print(instance['InstanceId'], instance['ImageId']) -------------------------------------------------------------------------------- /ec2/list_availability_zone.py: -------------------------------------------------------------------------------- 1 | import boto3 # Import the Boto3 library to interact with AWS services 2 | 3 | ec2 = boto3.client('ec2') # Create an EC2 client using Boto3 4 | 5 | response = ec2.describe_instances() # Call the describe_instances method to get information about EC2 instances 6 | 7 | reservations = response["Reservations"] # Extract the reservations from the response 8 | 9 | for reservation in reservations: # Iterate over each reservation 10 | instances = reservation["Instances"] # Extract the instances from the reservation 11 | for instance in instances: # Iterate over each instance in the reservation 12 | # Print the instance ID and the availability zone of the instance 13 | print(instance["InstanceId"], instance["Placement"]["AvailabilityZone"]) 14 | -------------------------------------------------------------------------------- /ec2/list_instance_ids.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | def list_instance_ids(ec2_client): 4 | response = ec2_client.describe_instances() 5 | 6 | reservations = response["Reservations"] 7 | 8 | instanceIds = [] 9 | 10 | for reservation in reservations: 11 | instances = reservation["Instances"] 12 | for instance in instances: 13 | instanceId = instance["InstanceId"] 14 | 15 | instanceIds.append(instanceId) 16 | 17 | return instanceIds 18 | 19 | if __name__ == "__main__": 20 | ec2 = boto3.client('ec2') 21 | instanceIds = list_instance_ids(ec2) 22 | print('\n'.join(instanceIds)) -------------------------------------------------------------------------------- /ec2/list_instance_names.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | def list_instance_names(ec2_client): 4 | response = ec2_client.describe_instances() 5 | 6 | reservations = response["Reservations"] 7 | 8 | instanceNames = [] 9 | 10 | for reservation in reservations: 11 | instances = reservation["Instances"] 12 | for instance in instances: 13 | if("Tags" in instance.keys()): 14 | tags = instance["Tags"] 15 | tags = { tag['Key']:tag['Value'] for tag in tags} 16 | if("Name" in tags.keys()): 17 | instanceNames.append(tags['Name']) 18 | else: 19 | instanceNames.append("Null: " + instance['InstanceId']) 20 | else: 21 | instanceNames.append("Null: " + instance['InstanceId']) 22 | 23 | return instanceNames 24 | 25 | if __name__ == "__main__": 26 | ec2 = boto3.client('ec2') 27 | instanceNames = list_instance_names(ec2) 28 | print('\n'.join(instanceNames)) -------------------------------------------------------------------------------- /ec2/list_instance_statuses.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | def list_instance_statuses(ec2_client): 4 | response = ec2_client.describe_instances() 5 | 6 | reservations = response["Reservations"] 7 | 8 | instanceStatuses = [] 9 | 10 | for reservation in reservations: 11 | instances = reservation["Instances"] 12 | for instance in instances: 13 | if("Tags" in instance.keys()): 14 | tags = instance["Tags"] 15 | tags = { tag['Key']:tag['Value'] for tag in tags} 16 | if("Name" in tags.keys()): 17 | instanceStatuses.append(tags['Name'] + ", State: " + instance["State"]["Name"]) 18 | else: 19 | instanceStatuses.append("Null: " + instance['InstanceId'] + ", State: " + instance["State"]["Name"]) 20 | else: 21 | instanceStatuses.append("Null: " + instance['InstanceId'] + ", State: " + instance["State"]["Name"]) 22 | 23 | return instanceStatuses 24 | 25 | if __name__ == "__main__": 26 | ec2 = boto3.client('ec2') 27 | instanceStatuses = list_instance_statuses(ec2) 28 | print('\n'.join(instanceStatuses)) -------------------------------------------------------------------------------- /ec2/list_key_pair_names.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | ec2 = boto3.client('ec2') 4 | 5 | response = ec2.describe_key_pairs() 6 | 7 | keypairs = response["KeyPairs"] 8 | 9 | for keypair in keypairs: 10 | print(keypair["KeyName"]) 11 | -------------------------------------------------------------------------------- /ec2/list_security_group_ids.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | ec2 = boto3.client('ec2') 4 | 5 | response = ec2.describe_security_groups() 6 | 7 | securityGroups = response["SecurityGroups"] 8 | 9 | for securityGroup in securityGroups: 10 | print(securityGroup["GroupId"]) -------------------------------------------------------------------------------- /ec2/run_instance.py: -------------------------------------------------------------------------------- 1 | #%% 2 | 3 | import boto3 4 | 5 | def create_apache_ec2(client): 6 | try: 7 | client.run_instances(MaxCount=1, 8 | MinCount=1, 9 | ImageId="ami-09e67e426f25ce0d7", 10 | InstanceType="t2.micro", 11 | KeyName="private-ec2", 12 | SecurityGroups=["launch-wizard-6"], 13 | UserData=boot_apache2_script) 14 | print("Started") 15 | except: 16 | print("Failed") 17 | 18 | 19 | #%% 20 | client = boto3.client('ec2') 21 | #%% 22 | 23 | boot_apache2_script='''#!/bin/bash 24 | apt update -y 25 | apt upgrade -y 26 | apt-get install -y apache2 27 | systemctl start apache2 28 | systemctl enable apache2''' 29 | 30 | 31 | #%% 32 | 33 | create_apache_ec2(client) -------------------------------------------------------------------------------- /ec2/run_ubuntu_instance.py: -------------------------------------------------------------------------------- 1 | 2 | import boto3 3 | 4 | def create_apache_ec2(client, MaxCount=1, MinCount=1, KeyName=None, SecurityGroups=["default"], UserData=None): 5 | region = client.meta.region_name 6 | 7 | amis = {"us-east-1":"ami-09e67e426f25ce0d7", "us-west-2":"ami-03d5c68bab01f3496"} 8 | 9 | try: 10 | ami = amis[region] 11 | except: 12 | print("Region not supported") 13 | return None 14 | 15 | if(UserData == None): 16 | UserData='''#!/bin/bash 17 | apt update -y 18 | apt-get install -y apache2 19 | systemctl start apache2 20 | systemctl enable apache2''' 21 | 22 | try: 23 | if(KeyName==None): 24 | client.run_instances(MaxCount=MaxCount, 25 | MinCount=MinCount, 26 | ImageId=ami, 27 | InstanceType="t2.micro", 28 | SecurityGroups=SecurityGroups, # name of the security group 29 | UserData=UserData) 30 | 31 | else: 32 | client.run_instances(MaxCount=MaxCount, 33 | MinCount=MinCount, 34 | ImageId=ami, 35 | InstanceType="t2.micro", 36 | KeyName=KeyName, 37 | SecurityGroups=SecurityGroups, # name of the security group 38 | UserData=UserData) 39 | print("Started") 40 | except Exception as e: 41 | print("Failed", e) 42 | 43 | if __name__ == "__main__": 44 | client = boto3.client('ec2') 45 | 46 | create_apache_ec2(client, KeyName="private-ec2", SecurityGroups=["launch-wizard-6"]) -------------------------------------------------------------------------------- /ec2/run_ubuntu_instance_call.py: -------------------------------------------------------------------------------- 1 | from run_ubuntu_instance import * 2 | 3 | client = boto3.client('ec2') 4 | 5 | create_apache_ec2(client, KeyName="private-ec2", SecurityGroups=["launch-wizard-6"]) -------------------------------------------------------------------------------- /ec2/stopping_instances.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | ec2 = boto3.client('ec2') 4 | 5 | dev_tag = { "Key":"Environment", "Value":"Dev"} 6 | 7 | response = ec2.describe_instances() 8 | 9 | reservations = response['Reservations'] 10 | 11 | for reservation in reservations: 12 | instances = reservation['Instances'] 13 | 14 | for instance in instances: 15 | if (dev_tag in instance['Tags'] and 'running' in instance['State']['Name']): 16 | print(instance['InstanceId']) 17 | ec2.stop_instances(InstanceIds=[instance['InstanceId']]) -------------------------------------------------------------------------------- /ec2/terminate_instances.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | ec2 = boto3.client('ec2') 4 | 5 | instanceIds = [''] 6 | 7 | response = ec2.terminate_instances(InstanceIds=instanceIds) 8 | 9 | print(response) -------------------------------------------------------------------------------- /eventbridge/list_rules.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | eventbridge = boto3.client("events") 4 | 5 | response = eventbridge.list_rules() 6 | 7 | rules = response["Rules"] 8 | 9 | for rule in rules: 10 | print(rule["Name"]) -------------------------------------------------------------------------------- /iam/attach_role_policy.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | iam = boto3.client('iam') 4 | 5 | 6 | 7 | 8 | response = iam.attach_role_policy( 9 | RoleName='lambda_role_from_py', PolicyArn='arn:aws:iam::458806987020:policy/lambda_sns_s3') 10 | 11 | print(response) -------------------------------------------------------------------------------- /iam/create_policy.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | iam = boto3.client('iam') 4 | 5 | 6 | role_policy = '''{ 7 | "Version": "2012-10-17", 8 | "Statement": [ 9 | { 10 | "Effect": "Allow", 11 | "Action": "logs:CreateLogGroup", 12 | "Resource": "arn:aws:logs:us-east-1:458806987020:*" 13 | }, 14 | { 15 | "Effect": "Allow", 16 | "Action": [ 17 | "logs:CreateLogStream", 18 | "logs:PutLogEvents" 19 | ], 20 | "Resource": [ 21 | "arn:aws:logs:us-east-1:458806987020:log-group:/aws/lambda/luit_red_jan_2023_lambda:*" 22 | ] 23 | }, 24 | { 25 | "Effect": "Allow", 26 | "Action": [ 27 | "s3:*", 28 | "s3-object-lambda:*" 29 | ], 30 | "Resource": "*" 31 | }, 32 | { 33 | "Action": [ 34 | "sns:*" 35 | ], 36 | "Effect": "Allow", 37 | "Resource": "*" 38 | } 39 | ] 40 | } 41 | ''' 42 | 43 | 44 | response = iam.create_policy( 45 | PolicyName='lambda_sns_s3', 46 | PolicyDocument=role_policy 47 | ) 48 | 49 | print(response) -------------------------------------------------------------------------------- /iam/create_role.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | iam = boto3.client('iam') 4 | 5 | trust_policy = '''{ 6 | "Version": "2012-10-17", 7 | "Statement": [ 8 | { 9 | "Effect": "Allow", 10 | "Principal": { 11 | "Service": "lambda.amazonaws.com" 12 | }, 13 | "Action": "sts:AssumeRole" 14 | } 15 | ] 16 | } 17 | ''' 18 | 19 | 20 | response = iam.create_role( 21 | RoleName='lambda_role_from_py', 22 | AssumeRolePolicyDocument=trust_policy 23 | ) 24 | 25 | print(response) -------------------------------------------------------------------------------- /iam/find_policy.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | iam = boto3.client('iam') 4 | 5 | policy_name = 'lambda_sns_s3' 6 | 7 | response = iam.list_policies() 8 | 9 | policies = response['Policies'] 10 | 11 | for policy in policies: 12 | if(policy_name in policy['PolicyName']): 13 | print(policy['PolicyName'], policy['Arn']) -------------------------------------------------------------------------------- /iam/list_policies.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | iam = boto3.client('iam') 4 | 5 | response = iam.list_policies() 6 | 7 | policies = response['Policies'] 8 | 9 | for policy in policies: 10 | print(policy['PolicyName'], policy['Arn']) -------------------------------------------------------------------------------- /iam/list_role_names.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | iam = boto3.client('iam') 4 | 5 | response = iam.list_roles() 6 | 7 | roles = response['Roles'] 8 | 9 | for role in roles: 10 | print(role['RoleName']) -------------------------------------------------------------------------------- /polly/generate_speech.py: -------------------------------------------------------------------------------- 1 | import boto3 # Import the AWS SDK for Python to interact with AWS services 2 | 3 | # Create a Polly client to interact with the Amazon Polly service 4 | polly = boto3.client('polly') 5 | 6 | # Request Polly to synthesize speech using the generative engine 7 | response = polly.synthesize_speech( 8 | Engine='generative', # Use the new generative engine for more natural speech 9 | OutputFormat='mp3', # Request the audio output in MP3 format 10 | Text='Hello from Boto3!',# The text that Polly will convert to speech 11 | VoiceId='Stephen' # Use the 'Stephen' voice for the synthesized speech 12 | ) 13 | 14 | # Extract the audio stream from the response 15 | audioStream = response['AudioStream'] 16 | 17 | # Save the audio stream to a file named 'example.mp3' 18 | with open("example.mp3", "wb") as f: 19 | f.write(audioStream.read()) # Read and write the binary MP3 content to file 20 | -------------------------------------------------------------------------------- /rekognition/detect_labels.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | from PIL import Image 3 | import io 4 | from typing import Optional 5 | 6 | def image_to_bytes(image_path: str, format: str = 'JPEG') -> Optional[bytes]: 7 | """ 8 | Convert an image file to a byte stream. 9 | 10 | Args: 11 | image_path (str): The file path to the image. 12 | format (str, optional): Format to encode the image (e.g., 'JPEG', 'PNG'). Defaults to 'JPEG'. 13 | 14 | Returns: 15 | Optional[bytes]: The image in byte format if successful, otherwise None. 16 | """ 17 | try: 18 | # Open the image using the Pillow library 19 | img = Image.open(image_path) 20 | 21 | # Create a BytesIO stream to hold the image data in memory 22 | img_bytes = io.BytesIO() 23 | 24 | # Save the image to the BytesIO stream in the specified format 25 | img.save(img_bytes, format=format) 26 | 27 | # Return the byte data from the BytesIO stream 28 | return img_bytes.getvalue() 29 | 30 | except FileNotFoundError: 31 | # Handle case where the image file does not exist 32 | print(f"Error: Image file not found at '{image_path}'") 33 | return None 34 | except Exception as e: 35 | # Handle any other unexpected errors 36 | print(f"An error occurred: {e}") 37 | return None 38 | 39 | # Define two image paths: one current directory, one nested 40 | image_path_cur: str = 'image.jpg' 41 | image_path_root: str = 'rekognition/image.jpg' 42 | 43 | # Attempt to convert the image to bytes from the current directory 44 | image_bytes: Optional[bytes] = image_to_bytes(image_path_cur) 45 | 46 | # Fallback to alternate path if the first conversion fails 47 | if not image_bytes: 48 | image_bytes = image_to_bytes(image_path_root) 49 | 50 | # If image was successfully converted to bytes 51 | if image_bytes: 52 | # Create a boto3 Rekognition client 53 | rekognition = boto3.client('rekognition') 54 | 55 | # Call Rekognition API to detect labels in the image 56 | response = rekognition.detect_labels( 57 | Image={'Bytes': image_bytes} 58 | ) 59 | 60 | # Output the label detection response 61 | print(response) 62 | 63 | else: 64 | # Inform the user of failure if neither image path worked 65 | print("Image conversion failed.") 66 | -------------------------------------------------------------------------------- /s3/create_bucket.py: -------------------------------------------------------------------------------- 1 | #%% 2 | 3 | # create a S3 Bucket 4 | 5 | import boto3 6 | import json 7 | 8 | client = boto3.client("s3") 9 | 10 | #%% 11 | 12 | response = client.create_bucket(Bucket="zali-bucket-test-boto3") 13 | 14 | print(json.dumps(response, indent=4)) 15 | -------------------------------------------------------------------------------- /s3/delete_bucket.py: -------------------------------------------------------------------------------- 1 | #%% 2 | 3 | # delete a S3 Bucket 4 | 5 | import boto3 6 | 7 | s3 = boto3.client('s3') 8 | 9 | #%% 10 | 11 | s3.delete_bucket(Bucket='zali-bucket-test-boto3') 12 | -------------------------------------------------------------------------------- /s3/delete_non_empty_buckets.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | def delete_bucket(bucket_name, s3_client, s3_resource): 4 | """Deletes all objects and versions in a bucket, then deletes the bucket itself.""" 5 | bucket = s3_resource.Bucket(bucket_name) 6 | 7 | # Delete all object versions (required for versioned buckets) 8 | try: 9 | bucket.object_versions.delete() 10 | print(f"Deleted all objects and versions in {bucket_name}") 11 | except Exception as e: 12 | print(f"Error deleting objects in {bucket_name}: {e}") 13 | 14 | # Delete the bucket itself 15 | try: 16 | s3_client.delete_bucket(Bucket=bucket_name) 17 | print(f"Deleted bucket: {bucket_name}") 18 | except Exception as e: 19 | print(f"Error deleting bucket {bucket_name}: {e}") 20 | 21 | def delete_matching_buckets(search_string, omit_buckets): 22 | s3_client = boto3.client("s3") 23 | s3_resource = boto3.resource("s3") 24 | response = s3_client.list_buckets() 25 | 26 | for bucket in response.get('Buckets', []): 27 | bucket_name = bucket['Name'] 28 | if bucket_name in omit_buckets: 29 | print(f"Found matching bucket but omitted: {bucket_name}") 30 | elif search_string in bucket_name: 31 | print(f"Found matching bucket: {bucket_name}") 32 | delete_bucket(bucket_name, s3_client, s3_resource) 33 | 34 | if __name__ == "__main__": 35 | search_term = "luit" 36 | omit_buckets = ["luit-automation"] 37 | delete_matching_buckets(search_term, omit_buckets) 38 | -------------------------------------------------------------------------------- /s3/list_buckets.py: -------------------------------------------------------------------------------- 1 | #%% 2 | 3 | # list S3 Buckets 4 | 5 | import boto3 6 | 7 | s3 = boto3.client('s3') 8 | 9 | #%% 10 | 11 | response = s3.list_buckets() 12 | 13 | #%% 14 | 15 | buckets = response["Buckets"] 16 | 17 | #%% 18 | 19 | for bucket in buckets: 20 | print(bucket["Name"]) -------------------------------------------------------------------------------- /s3/list_objects.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | s3 = boto3.client('s3') 4 | 5 | bucket_name="zali-catch-all" 6 | 7 | response = s3.list_objects( 8 | Bucket=bucket_name 9 | ) 10 | 11 | contents = response['Contents'] 12 | 13 | for content in contents: 14 | print(content['Key']) -------------------------------------------------------------------------------- /s3/upload_object.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | s3 = boto3.client('s3') 4 | 5 | filename = 'upload_object.py' 6 | bucket_name="zali-catch-all" 7 | 8 | with open(filename, 'rb') as data: 9 | s3.upload_fileobj(data, bucket_name, filename) 10 | print("Object Uploaded") -------------------------------------------------------------------------------- /sns/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zaireali649/boto3_python_scripts/40dc703089d0a60d20026106de101a0d8cf48384/sns/__init__.py -------------------------------------------------------------------------------- /sns/add_sns_subscription.py: -------------------------------------------------------------------------------- 1 | #%% 2 | 3 | import boto3 4 | 5 | def sns_subscribe_email(sns_client, TopicArn, email_address): 6 | sns_client.subscribe(TopicArn=TopicArn, Protocol='email', Endpoint=email_address) 7 | 8 | 9 | #%% 10 | 11 | if __name__ == "__main__": 12 | sns = boto3.client('sns') 13 | sns_subscribe_email(sns, 'arn:aws:sns:us-east-1:458806987020:Idontknow', 'zaire.ali@levelupintech.com') -------------------------------------------------------------------------------- /sns/create_sns_topic.py: -------------------------------------------------------------------------------- 1 | #%% 2 | 3 | import boto3 4 | 5 | def create_sns_topic(sns_client, Name): 6 | sns_client.create_topic(Name=Name) 7 | 8 | #%% 9 | 10 | if __name__ == "__main__": 11 | sns = boto3.client('sns') 12 | create_sns_topic(sns, 'Idontknow') -------------------------------------------------------------------------------- /sns/list_sns_topics.py: -------------------------------------------------------------------------------- 1 | #%% 2 | 3 | import boto3 4 | 5 | def list_sns_topics(sns_client): 6 | Topics = sns_client.list_topics()['Topics'] 7 | return [Topic['TopicArn'] for Topic in Topics] 8 | 9 | #%% 10 | 11 | if __name__ == "__main__": 12 | sns = boto3.client('sns') 13 | topics = list_sns_topics(sns) -------------------------------------------------------------------------------- /sns/print_sns_subscriptionarn.py: -------------------------------------------------------------------------------- 1 | import boto3 as AWS 2 | 3 | client = AWS.client('sns') 4 | 5 | response = client.list_subscriptions() 6 | 7 | #%% 8 | 9 | Subscriptions = response['Subscriptions'] 10 | 11 | print(len(Subscriptions)) 12 | 13 | for Subscription in Subscriptions: 14 | print(Subscription['SubscriptionArn']) 15 | 16 | -------------------------------------------------------------------------------- /sns/publish_sns_topic.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | def sns_publish_topic(sns_client, TopicArn, Message): 4 | sns_client.publish(TopicArn=TopicArn, Message=Message) 5 | print("Sent Message:", Message) 6 | 7 | #%% 8 | 9 | if __name__ == "__main__": 10 | sns = boto3.client('sns') 11 | sns_publish_topic(sns, 'arn:aws:sns:us-east-1:458806987020:Idontknow', 'JSONhariston did it!!!!') -------------------------------------------------------------------------------- /sns/sns_pipeline.py: -------------------------------------------------------------------------------- 1 | from create_sns_topic import create_sns_topic 2 | from list_sns_topics import list_sns_topics 3 | from add_sns_subscription import sns_subscribe_email 4 | from publish_sns_topic import sns_publish_topic 5 | 6 | import boto3 7 | 8 | if __name__ == "__main__": 9 | sns = boto3.client('sns') 10 | 11 | topic_name = 'from_pipeline' 12 | email = 'zaire.ali@levelupintech.com' 13 | message = 'Blue Cohort Did It!!!!!!' 14 | 15 | create_sns_topic(sns, topic_name) 16 | topicArns = list_sns_topics(sns) 17 | topicArn = [topicArn for topicArn in topicArns if topic_name in topicArn.split(":")[-1]][0] 18 | sns_subscribe_email(sns, topicArn, email) 19 | sns_publish_topic(sns, topicArn, message) -------------------------------------------------------------------------------- /sqs/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zaireali649/boto3_python_scripts/40dc703089d0a60d20026106de101a0d8cf48384/sqs/__init__.py -------------------------------------------------------------------------------- /sqs/create_message.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | sqs = boto3.client('sqs') 4 | 5 | response = sqs.send_message( 6 | QueueUrl='https://queue.amazonaws.com/458806987020/gold-queue', 7 | MessageBody='Message sent from Python <3' 8 | ) 9 | 10 | print("Message sent") -------------------------------------------------------------------------------- /sqs/create_queue.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | sqs = boto3.client('sqs') 4 | 5 | response = sqs.create_queue( 6 | QueueName='gold-queue' 7 | ) 8 | 9 | print('Queue created') -------------------------------------------------------------------------------- /sqs/delete_queue.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | sqs = boto3.client('sqs') 4 | 5 | response = sqs.delete_queue( 6 | QueueUrl='https://queue.amazonaws.com/458806987020/gold-queue' 7 | ) 8 | 9 | print("Queue Deleted") -------------------------------------------------------------------------------- /sqs/get_messages.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | sqs = boto3.client('sqs') 4 | 5 | response = sqs.receive_message( 6 | QueueUrl='https://queue.amazonaws.com/458806987020/gold-queue' 7 | ) 8 | 9 | messages = response['Messages'] 10 | 11 | for message in messages: 12 | data = message['Body'] 13 | print(data) -------------------------------------------------------------------------------- /sqs/get_queue_url.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | sqs = boto3.client('sqs') 4 | 5 | response = sqs.get_queue_url( 6 | QueueName='gold-queue' 7 | ) 8 | 9 | url = response['QueueUrl'] 10 | 11 | print(url) -------------------------------------------------------------------------------- /sqs/sqs_functions.py: -------------------------------------------------------------------------------- 1 | def create_queue(sqs, QueueName): 2 | response = sqs.create_queue( 3 | QueueName=QueueName 4 | ) 5 | 6 | print('Queue created') 7 | 8 | 9 | def get_queue_url(sqs, QueueName): 10 | response = sqs.get_queue_url( 11 | QueueName=QueueName 12 | ) 13 | 14 | url = response['QueueUrl'] 15 | 16 | print(url) 17 | return url 18 | 19 | def delete_queue(sqs, QueueUrl): 20 | response = sqs.delete_queue( 21 | QueueUrl=QueueUrl 22 | ) 23 | 24 | print("Queue Deleted") 25 | 26 | def create_message(sqs, QueueUrl, message): 27 | response = sqs.send_message( 28 | QueueUrl=QueueUrl, 29 | MessageBody=message 30 | ) 31 | 32 | print("Message sent") 33 | 34 | def get_messages(sqs, QueueUrl): 35 | response = sqs.receive_message( 36 | QueueUrl=QueueUrl 37 | ) 38 | 39 | messages = response['Messages'] 40 | 41 | out_messages = [] 42 | 43 | for message in messages: 44 | data = message['Body'] 45 | print(data) 46 | out_messages.append(data) 47 | 48 | return out_messages 49 | 50 | if __name__ == "__main__": 51 | import boto3 52 | import random 53 | 54 | sqs = boto3.client('sqs') 55 | 56 | QN = "gold-from-function-2" 57 | message = "Hey from custom SQS python functions! Random number: " + str(random.randint(0,300)).zfill(3) 58 | 59 | create_queue(sqs, QN) 60 | qurl = get_queue_url(sqs, QN) 61 | create_message(sqs, qurl, message) 62 | messages = get_messages(sqs, qurl) 63 | delete_queue(sqs, qurl) -------------------------------------------------------------------------------- /vpc/list_cidr_blocks.py: -------------------------------------------------------------------------------- 1 | # Import the 'boto3' library, which provides an interface to interact with Amazon Web Services (AWS) 2 | import boto3 3 | 4 | # Create an 'ec2' client using the 'boto3.client()' method, allowing interaction with AWS Elastic Compute Cloud (EC2) service 5 | vpc = boto3.client('ec2') 6 | 7 | # Use the 'describe_vpcs()' method of the 'vpc' client to retrieve information about Virtual Private Clouds (VPCs) 8 | response = vpc.describe_vpcs() 9 | 10 | # Extract the list of VPCs from the 'response' dictionary 11 | vpcs = response["Vpcs"] 12 | 13 | # Iterate through each VPC in the 'vpcs' list 14 | for vpc in vpcs: 15 | # Print the VPC ID and CIDR block (IP address range) associated with each VPC 16 | print(vpc["VpcId"], vpc["CidrBlock"]) 17 | -------------------------------------------------------------------------------- /vpc/list_sg_ids.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | vpc = boto3.client('ec2') 4 | 5 | response = vpc.describe_security_groups() 6 | 7 | securitygroups = response['SecurityGroups'] 8 | 9 | for securitygroup in securitygroups: 10 | print(securitygroup['GroupId']) -------------------------------------------------------------------------------- /vpc/list_subnet_ids.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | vpc = boto3.client('ec2') 4 | 5 | response = vpc.describe_subnets() 6 | 7 | subnets = response['Subnets'] 8 | 9 | for subnet in subnets: 10 | print(subnet['SubnetId']) -------------------------------------------------------------------------------- /vpc/list_vpc_ids.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | 3 | vpc_client = boto3.client('ec2') 4 | 5 | response = vpc_client.describe_vpcs() 6 | 7 | vpcs = response['Vpcs'] 8 | 9 | for vpc in vpcs: 10 | print(vpc['VpcId']) 11 | --------------------------------------------------------------------------------