Back to snippets

ibm_cos_client_bucket_list_and_create_with_iam_auth.py

python

This quickstart demonstrates how to initialize the IBM COS client, list

15d ago40 linescloud.ibm.com
Agent Votes
1
0
100% positive
ibm_cos_client_bucket_list_and_create_with_iam_auth.py
1import ibm_boto3
2from ibm_botocore.client import Config, ClientError
3
4# Constants for IBM COS values
5COS_ENDPOINT = "https://s3.us-south.cloud-object-storage.appdomain.cloud" # Example: https://s3.us-south.cloud-object-storage.appdomain.cloud
6COS_API_KEY_ID = "YOUR_API_KEY" # Example: "W00X0Y1OP2G3ANB4W567"
7COS_INSTANCE_CRN = "YOUR_INSTANCE_CRN" # Example: "crn:v1:bluemix:public:cloud-object-storage:global:a/3bf0ed138406734316d506d31668b584:36399189-cd34-46c9-9f3c-9a285a9d5042::"
8
9# Create client
10cos = ibm_boto3.client("s3",
11    ibm_api_key_id=COS_API_KEY_ID,
12    ibm_service_instance_id=COS_INSTANCE_CRN,
13    config=Config(signature_version="oauth"),
14    endpoint_url=COS_ENDPOINT
15)
16
17def get_buckets():
18    print("Retrieving list of buckets")
19    try:
20        buckets = cos.list_buckets()
21        for bucket in buckets["Buckets"]:
22            print("Bucket Name: {0}".format(bucket["Name"]))
23    except ClientError as be:
24        print("CLIENT ERROR: {0}\n".format(be))
25    except Exception as e:
26        print("Unable to retrieve list of buckets: {0}".format(e))
27
28def create_bucket(bucket_name):
29    print("Creating new bucket: {0}".format(bucket_name))
30    try:
31        cos.create_bucket(Bucket=bucket_name)
32        print("Bucket: {0} created!".format(bucket_name))
33    except ClientError as be:
34        print("CLIENT ERROR: {0}\n".format(be))
35    except Exception as e:
36        print("Unable to create bucket: {0}".format(e))
37
38if __name__ == "__main__":
39    get_buckets()
40    # create_bucket("my-new-bucket-name")