Jananath Banuka
Jananath Banuka

Reputation: 633

How to check only specific s3 bucket exists using boto3

I am trying to list a specific bucket in my aws account. But I have used list_buckets() method which returns all the buckets. Purpose is to check if this bucket exists or not

I could have used head_bucket() method, but it doesn't return anything in return (according to boto3 documentation)

I am using mistral workflows to get this bucket (still calling boto3 methtods) not python

But somehow, is there a boto3 method to check if the s3 bucket exists or not?

I need to get the return and compare it accordingly to check if the bucket exists. So if that condition satisfies, it only triggers the next task in mistral stackstorm workflow.

In case you need I will put the workflow as well.

check_if_exists:
        action: aws_boto3.boto3action
        input:
          action_name: "list_buckets"
          region: <% $.bucket_region %>
          service: "s3"
        publish:
          return_code: <% task(check_if_exists).result.result.Buckets.select($.Name) %>
        on-success:
           - task_one
        on-error:
          - fail

Upvotes: 0

Views: 4052

Answers (2)

Arif Hossain
Arif Hossain

Reputation: 606

You should be able to use head_bucket() method. This will return 200 OK if the bucket exists and you have necessary permissions to access it. If the bucket does not exist or if you do not have permission, you will get 403 or 404.

Boto3 Documentation: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.head_bucket

Upvotes: 1

John Rotenstein
John Rotenstein

Reputation: 269340

You could use one of the get_bucket_*() operations, such as get_bucket_location().

However, this will only function correctly if you have permission to run this operation on the bucket and if the bucket belongs to the same account as your IAM credentials.

Upvotes: 0

Related Questions