Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Cloud Storage Bucket creation

I want to create a google bucket if it doesn't exist. Otherwise, I want to reuse the bucket name. How to do it? Its equivalent of the unix command

mkdir -p dir_name

I used the command but my shell script crashes when I run this next time.

gsutil mb -l ASIA gs://my_bucket_name_blah_blah

like image 926
nizam.sp Avatar asked Oct 31 '15 13:10

nizam.sp


2 Answers

After six years ....

I found this GitLab script can use as reference to solve this problem

The key part is

if ! gsutil ls -p ${GCP_PROJECT_ID} gs://${BUCKET} &> /dev/null; \
    then \
        echo creating gs://${BUCKET} ... ; \
        gsutil mb -p ${GCP_PROJECT_ID} -c regional -l ${GCP_REGION} gs://${BUCKET}; \
        sleep 10; \
    fi

That's a block of Makefile, but it's almost same as a shell script

like image 45
BoHuang Avatar answered Oct 09 '22 15:10

BoHuang


You could check for the existence of the bucket first. I think something like this would work:

gsutil ls -b gs://my_bucket_name_blah_blah || gsutil mb -l ASIA gs://my_bucket_name_blah_blah

Since the first command will return a 0 error code if the bucket already exists, the second command will only be executed if the bucket does not exist.

Note however that the first command will also return a non-zero exit code in the case of errors (transient error or permission denied). So you might need a more robust way of creating buckets.

like image 122
jterrace Avatar answered Oct 09 '22 14:10

jterrace