diff --git a/changelogs/fragments/357-s3_bucket-use-head.yml b/changelogs/fragments/357-s3_bucket-use-head.yml new file mode 100644 index 00000000000..78cb20e7bf8 --- /dev/null +++ b/changelogs/fragments/357-s3_bucket-use-head.yml @@ -0,0 +1,2 @@ +minor_changes: +- s3_bucket - updated to use HeadBucket instead of ListBucket when testing for bucket existence (https://github.com/ansible-collections/amazon.aws/pull/357). diff --git a/plugins/modules/s3_bucket.py b/plugins/modules/s3_bucket.py index 591551ac5fc..302e856246f 100644 --- a/plugins/modules/s3_bucket.py +++ b/plugins/modules/s3_bucket.py @@ -509,10 +509,12 @@ def create_or_update_bucket(s3_client, module, location): def bucket_exists(s3_client, bucket_name): - # head_bucket appeared to be really inconsistent, so we use list_buckets instead, - # and loop over all the buckets, even if we know it's less performant :( - all_buckets = s3_client.list_buckets(Bucket=bucket_name)['Buckets'] - return any(bucket['Name'] == bucket_name for bucket in all_buckets) + try: + s3_client.head_bucket(Bucket=bucket_name) + bucket_exists = True + except is_boto3_error_code('404'): + bucket_exists = False + return bucket_exists @AWSRetry.exponential_backoff(max_delay=120)