B2 CLI - CORS rules in the command line

This article contains a couple of tips to help utilize the b2 cli to help implement CORS rules.

 

When using the b2 cli, the arguments to set the CORS rules are accessed through the b2 command line:

b2 update-bucket [--bucketInfo <json>] [--corsRules <json>] [--lifecycleRules <json>] <bucketName> [allPublic | allPrivate]

The easiest way I have found to add the rules is with a json file that contains the rule set.

For this case I will add a test block of json that can be copied to a file and saved locally.

[
  {
    "corsRuleName": "downloadFromAnyOrigin",
    "allowedOrigins": [
      "https"
    ],
    "allowedHeaders": [
      "range"
    ],
    "allowedOperations": [
      "b2_download_file_by_id",
      "b2_download_file_by_name"
    ],
    "exposeHeaders": [
      "x-bz-content-sha1"
    ],
    "maxAgeSeconds": 3600
  }
]

Once you have your validated json file with your rule set you can add them to your bucket.

In the following example, it will be assumed that the json file will be named rules.json and in the current working directory.

To do this you will need to run the command as follows:

b2 update-bucket --corsRules "$(<./rules.json)" bucketName allPublic

This example can be used, once you have a validated json file of rules, but it will make the specified bucket public.

The output below is what displays when the command works correctly:

{
"accountId": "d9xxxf5427b",
"bucketId": "dxxxxx2dec998xxxxx02071b",
"bucketInfo": {},
"bucketName": "TestBucket",
"bucketType": "allPublic",
"corsRules": [
{
"allowedHeaders": [
"range"
],
"allowedOperations": [
"b2_download_file_by_id",
"b2_download_file_by_name"
],
"allowedOrigins": [
"https"
],
"corsRuleName": "downloadFromAnyOrigin",
"exposeHeaders": [
"x-bz-content-sha1"
],
"maxAgeSeconds": 3600
}
],
"lifecycleRules": [],
"revision": 4
}

The failures that may occur are usually based around the json file not being valid so be sure to use a validation tool like jq, on the json file if you encounter issues.

Using CORS through the command line without a file

To use the CORS rules through the command line without a file you will need to be sure to escape all of the double quote around the key pairs.

 

b2 update-bucket --corsRules "[{\"corsRuleName\":\"downloadFromAnyOrigin\", \"allowedOrigins\": [\"https\"], \"allowedHeaders\": [\"range\"], \"allowedOperations\": [\"b2_download_file_by_id\", \"b2_download_file_by_name\"], \"exposeHeaders\": [\"x-bz-content-sha1\"], \"maxAgeSeconds\": 3600}]" bucketName allPublic

The command below will apply the same values and the method of calling the json through a file.

Be sure that you use double-quotes (") to surround the json key pairs, this set of double-quotes is not escaped.  These are the first and last double quotes in the code block above.

 

Have more questions? Submit a request

0 Comments

Article is closed for comments.
Powered by Zendesk