IBM Cloud Docs
Node.js の使用

Node.js の使用

IBM Cloud® Object Storage SDK for Node.js は、IBM Cloud Object Storage を活用するための最新の機能を提供します。

SDK のインストール

Node.js は、 Web アプリケーション を作成し、エンド・ユーザー用に Object Storage のインスタンスをカスタマイズするための優れた方法です。 Object Storage SDK for Node.js をインストールする推奨される方法は、 Node.js用の npm パッケージ・マネージャーを使用することです。 コマンド行に以下のコマンドを入力します。

npm install ibm-cos-sdk

SDK を直接ダウンロードするために、ソース・コードは GitHubでホストされます。

個々のメソッドやクラスの詳細については、 SDKのAPIドキュメントをご覧ください。

はじめに

最小要件

SDK を実行するには、Node 4.x+ が必要です。

クライアントの作成と資格情報の入手

COS に接続するために、資格情報 (API キー、サービス・インスタンス ID、および IBM 認証エンドポイント) を指定することによりクライアントが作成および構成されます。 これらの値は、資格情報ファイルまたは環境変数から自動的に入手することもできます。

サービス資格情報を生成した後は、結果の JSON 文書を ~/.bluemix/cos_credentials に保存できます。 クライアントの作成時に他の資格情報が明示的に設定されない限り、SDK は、このファイルから資格情報を自動的に入手します。 cos_credentials ファイルに HMAC 鍵が含まれている場合、クライアントは署名を使用して認証を受けます。そうでない場合、クライアントは、提供される API キーを使用してベアラー・トークンで認証を受けます。

default セクション・ヘッディングには、デフォルト・プロファイルおよび資格情報に関連した値を指定します。 同じ共有構成ファイル内に追加のプロファイルを作成して、それぞれのプロファイルに独自の資格情報を設定できます。 以下は、デフォルト・プロファイルが設定された構成ファイルの例です。

[default]
ibm_api_key_id = <DEFAULT_IBM_API_KEY>
ibm_service_instance_id = <DEFAULT_IBM_SERVICE_INSTANCE_ID>
ibm_auth_endpoint = <DEFAULT_IBM_AUTH_ENDPOINT>

AWS S3 からマイグレーションする場合は、~/.aws/credentials から資格情報データを以下の形式で入手することもできます。

aws_access_key_id = <DEFAULT_ACCESS_KEY_ID>
aws_secret_access_key = <DEFAULT_SECRET_ACCESS_KEY>

~/.bluemix/cos_credentials~/.aws/credentials の両方が存在する場合は、cos_credentials が優先されます。

コード例

コードでは、図に示すように、不等号括弧またはその他の余分の文字を削除する必要があります。

Node.jsの概要-いったんインストールされると、通常は Nodejs.orgからのこの例のように、構成と呼び出しが必要になります。 類似のモデルに従います

構成の初期化

const IBM = require('ibm-cos-sdk');

var config = {
    endpoint: '<endpoint>',
    apiKeyId: '<api-key>',
    serviceInstanceId: '<resource-instance-id>',
    signatureVersion: 'iam',
};

var cos = new IBM.S3(config);

キー値

バケットの作成

LocationConstraint の有効なプロビジョニング・コードのリストについては、ストレージ・クラスのガイドを参照してください。

function createBucket(bucketName) {
    console.log(`Creating new bucket: ${bucketName}`);
    return cos.createBucket({
        Bucket: bucketName,
        CreateBucketConfiguration: {
          LocationConstraint: 'us-standard'
        },
    }).promise()
    .then((() => {
        console.log(`Bucket: ${bucketName} created!`);
    }))
    .catch((e) => {
        console.error(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK リファレンス

テキスト・オブジェクトの作成

function createTextFile(bucketName, itemName, fileText) {
    console.log(`Creating new item: ${itemName}`);
    return cos.putObject({
        Bucket: bucketName,
        Key: itemName,
        Body: fileText
    }).promise()
    .then(() => {
        console.log(`Item: ${itemName} created!`);
    })
    .catch((e) => {
        console.error(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK リファレンス

バケットのリスト

function getBuckets() {
    console.log('Retrieving list of buckets');
    return cos.listBuckets()
    .promise()
    .then((data) => {
        if (data.Buckets != null) {
            for (var i = 0; i < data.Buckets.length; i++) {
                console.log(`Bucket Name: ${data.Buckets[i].Name}`);
            }
        }
    })
    .catch((e) => {
        console.error(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK リファレンス

バケット内の項目のリスト

function getBucketContents(bucketName) {
    console.log(`Retrieving bucket contents from: ${bucketName}`);
    return cos.listObjects(
        {Bucket: bucketName},
    ).promise()
    .then((data) => {
        if (data != null && data.Contents != null) {
            for (var i = 0; i < data.Contents.length; i++) {
                var itemKey = data.Contents[i].Key;
                var itemSize = data.Contents[i].Size;
                console.log(`Item: ${itemKey} (${itemSize} bytes).`)
            }
        }
    })
    .catch((e) => {
        console.error(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK リファレンス

特定の項目のファイル内容の取得

function getItem(bucketName, itemName) {
    console.log(`Retrieving item from bucket: ${bucketName}, key: ${itemName}`);
    return cos.getObject({
        Bucket: bucketName,
        Key: itemName
    }).promise()
    .then((data) => {
        if (data != null) {
            console.log('File Contents: ' + Buffer.from(data.Body).toString());
        }
    })
    .catch((e) => {
        console.error(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK リファレンス

バケットから項目を削除

function deleteItem(bucketName, itemName) {
    console.log(`Deleting item: ${itemName}`);
    return cos.deleteObject({
        Bucket: bucketName,
        Key: itemName
    }).promise()
    .then(() =>{
        console.log(`Item: ${itemName} deleted!`);
    })
    .catch((e) => {
        console.error(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK リファレンス

バケットから複数項目を削除

削除要求には、削除するキーを最大 1000 個含めることができます。 オブジェクトの削除をバッチで行うことは、要求ごとのオーバーヘッドを削減するのに非常に役立ちますが、多数のキーを削除すると要求が完了するまでにしばらく時間がかかる可能性があるので注意してください。 また、適切なパフォーマンスを確保するために、オブジェクトのサイズも考慮する。

function deleteItems(bucketName) {
    var deleteRequest = {
        "Objects": [
            { "Key": "deletetest/testfile1.txt" },
            { "Key": "deletetest/testfile2.txt" },
            { "Key": "deletetest/testfile3.txt" },
            { "Key": "deletetest/testfile4.txt" },
            { "Key": "deletetest/testfile5.txt" }
        ]
    }
    return cos.deleteObjects({
        Bucket: bucketName,
        Delete: deleteRequest
    }).promise()
    .then((data) => {
        console.log(`Deleted items for ${bucketName}`);
        console.log(data.Deleted);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK リファレンス

バケットの削除

function deleteBucket(bucketName) {
    console.log(`Deleting bucket: ${bucketName}`);
    return cos.deleteBucket({
        Bucket: bucketName
    }).promise()
    .then(() => {
        console.log(`Bucket: ${bucketName} deleted!`);
    })
    .catch((e) => {
        console.error(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK リファレンス

複数パーツ・アップロードの実行

function multiPartUpload(bucketName, itemName, filePath) {
    var uploadID = null;

    if (!fs.existsSync(filePath)) {
        log.error(new Error(`The file \'${filePath}\' does not exist or is not accessible.`));
        return;
    }

    console.log(`Starting multi-part upload for ${itemName} to bucket: ${bucketName}`);
    return cos.createMultipartUpload({
        Bucket: bucketName,
        Key: itemName
    }).promise()
    .then((data) => {
        uploadID = data.UploadId;

        //begin the file upload
        fs.readFile(filePath, (e, fileData) => {
            //min 5MB part
            var partSize = 1024 * 1024 * 5;
            var partCount = Math.ceil(fileData.length / partSize);

            async.timesSeries(partCount, (partNum, next) => {
                var start = partNum * partSize;
                var end = Math.min(start + partSize, fileData.length);

                partNum++;

                console.log(`Uploading to ${itemName} (part ${partNum} of ${partCount})`);

                cos.uploadPart({
                    Body: fileData.slice(start, end),
                    Bucket: bucketName,
                    Key: itemName,
                    PartNumber: partNum,
                    UploadId: uploadID
                }).promise()
                .then((data) => {
                    next(e, {ETag: data.ETag, PartNumber: partNum});
                })
                .catch((e) => {
                    cancelMultiPartUpload(bucketName, itemName, uploadID);
                    console.error(`ERROR: ${e.code} - ${e.message}\n`);
                });
            }, (e, dataPacks) => {
                cos.completeMultipartUpload({
                    Bucket: bucketName,
                    Key: itemName,
                    MultipartUpload: {
                        Parts: dataPacks
                    },
                    UploadId: uploadID
                }).promise()
                .then(console.log(`Upload of all ${partCount} parts of ${itemName} successful.`))
                .catch((e) => {
                    cancelMultiPartUpload(bucketName, itemName, uploadID);
                    console.error(`ERROR: ${e.code} - ${e.message}\n`);
                });
            });
        });
    })
    .catch((e) => {
        console.error(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

function cancelMultiPartUpload(bucketName, itemName, uploadID) {
    return cos.abortMultipartUpload({
        Bucket: bucketName,
        Key: itemName,
        UploadId: uploadID
    }).promise()
    .then(() => {
        console.log(`Multi-part upload aborted for ${itemName}`);
    })
    .catch((e)=>{
        console.error(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK リファレンス

バックアップ・ポリシーの作成

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config values
const apiKey = '<API_KEY>';
const sourceBucketName = '< SOURCE_BUCKET_NAME>';
const backupVaultCrn = '<BACKUP_VAULT_CRN>';
const policyName = '<BACKUP_POLICY_NAME>';

async function  createBackupPolicy () {
  try {
    // Authenticator and client setup
    const authenticator = new IamAuthenticator({ apikey: apiKey });
    const rcClient = new ResourceConfigurationV1({ authenticator });

    // Create backup policy
    const response = await rcClient.createBackupPolicy({
      bucket: sourceBucketName,
      policyName: policyName,
      targetBackupVaultCrn: backupVaultCrn,
      backupType: “continuous”,
      initialRetention: {delete_after_days:1},
    });

    console.log('Backup  policy created successfully: ‘, response.result);

  } catch (err) {
    console.error('Error:', err);
  }
}
// Run the function
createBackupPolicy ();

バックアップ・ポリシーのリスト

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config
const apiKey = '<API_KEY>';
const sourceBucketName = '<SOURCE_BUCKET_NAME>';

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });

async function listBackupPolicies() {
  try {

    // List all backup policies
    const listResponse = await rcClient.listBackupPolicies({
      bucket: sourceBucketName,
    });

    console.log('\n List of backup policies:');
    const policies = listResponse.result.backup_policies || [];
    policies.forEach(policy => console.log(policy));

  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the function
listBackupPolicies();

バックアップ・ポリシー

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config
const apiKey = '<API_KEY>';
const sourceBucketName = '<SOURCE_BUCKET_NAME>';
const policyId = '<POLICY_ID>'; // Policy ID to retrieve backup Policy

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });

async function fetchBackupPolicy () {
  try {
    // Fetch backup policy
    const getResponse = await rcClient.getBackupPolicy({
      bucket: sourceBucketName,
      policyId: policyId,
    });
    console.log('\nFetched Backup Policy Details:');
    console.log(getResponse.result);

  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the function
fetchBackupPolicy ();

バックアップポリシーの削除

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config
const apiKey = '<API_KEY>';
const sourceBucketName = '<SOURCE_BUCKET_NAME>';
const policyId = '<POLICY_ID_TO_DELETE>'; // Policy ID of the policy to be deleted

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });
async function deleteBackupPolicy() {
try {
    // Delete backup policy
    await rcClient.deleteBackupPolicy({
      bucket: sourceBucketName,
      policyId: policyId,
    });

    console.log(`Backup policy '${policyId}' deleted successfully.`);
  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the function
deleteBackupPolicy ();

バックアップ保管庫の作成

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config
const apiKey = '<API_KEY>';
const serviceInstanceId = '<SERVICE_INSTANCE_ID>';
const region = '<REGION>';
const backupVaultName = <BACKUP_VAULT_NAME>';

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });

async function createBackupVault() {
  try {

    const createResponse = await rcClient.createBackupVault({
      serviceInstanceId: serviceInstanceId,
      backupVaultName: backupVaultName,
      region: region,
    });

    console.log('Backup vault created:');
    console.log(createResponse.result);
  } catch (error) {
    console.error('Error creating backup vault:', error);
  }
}

// Run the function
createBackupVault();

バックアップ保管庫のリストアップ

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config
const apiKey = '<API_KEY>';
const serviceInstanceId = '<SERVICE_INSTANCE_ID>';

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });

async function listBackupVaults() {
  try {
    // List backup vaults
    const listResponse = await rcClient.listBackupVaults({
      serviceInstanceId: serviceInstanceId,
    });

    console.log('List of backup vaults:');
    console.log(listResponse.result);
  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the function
listBackupVaults ();

バックアップ保管庫の取得

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config
const apiKey = '<API_KEY>';
const backupVaultName = '<BACKUP_VAULT_NAME>'; // Name of the backup vault to fetch

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });

async function fetchBackupVault () {
  try {
    // Get backup vault
    const getResponse = await rcClient.getBackupVault({
      backupVaultName: backupVaultName,
    });

    console.log('Backup vault details:');
    console.log(getResponse.result);
  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the function
fetchBackupVault ();

バックアップ保管庫の更新

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1');

// Config
const apiKey = '<API_KEY>';
const backupVaultName = '<BACKUP_VAULT_NAME>'; // Keep consistent for create + update

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });

async function updateBackupVault() {
  try {
    // Update backup vault to disable tracking and monitoring
    const patch = {
      activity_tracking: {
        management_events: false,
      },
      metrics_monitoring: {
        usage_metrics_enabled: false,
      },
    };

    const updateResponse = await rcClient.updateBackupVault({
      backupVaultName: backupVaultName,
      backupVaultPatch: patch,
    });

    console.log(`Backup vault updated. Status code: ${updateResponse.status}`);
  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the function
updateBackupVault ();

バックアップ保管庫の削除

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config
const apiKey = '<API_KEY>';
const backupVaultName = '<BACKUP_VAULT_NAME>';

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });

async function deleteBackupVault() {
  try {
    // Delete the backup vault
    await rcClient.deleteBackupVault({
      backupVaultName: backupVaultName,
    });

    console.log(`Backup vault '${backupVaultName}' deleted successfully.`);
  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the function
deleteBackupVault();

リスト回復範囲

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config
const apiKey = '<API_KEY>';
const backupVaultName = '<BACKUP_VAULT_NAME>';

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });

async function listRecoveryRanges() {
  try {
    // List recovery ranges
    const recoveryRangesResponse = await rcClient.listRecoveryRanges({
      backupVaultName: backupVaultName,
    });

    console.log('Recovery Ranges:');
    console.log(recoveryRangesResponse.result);
  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the function
listRecoveryRanges();

回復範囲を得る

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config
const apiKey = '<API_KEY>';
const recoveryRangeId = '<RECOVERY_RANGE_ID>';
const backupVaultName = '<BACKUP_VAULT_NAME>';

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });

async function fetchRecoveryRangeInfo() {

try {
    // Fetch details of the recovery range
    const recoveryRangeId = createResponse.result.recovery_range_id;  // Assuming the recovery range info is part of the response
    const getRecoveryRangeResponse = await rcClient.getSourceResourceRecoveryRange({
      backupVaultName: backupVaultName,
      recoveryRangeId: recoveryRangeId,
    });

    console.log('Recovery Range Details:');
    console.log(getRecoveryRangeResponse.result);
  } catch (error) {
    console.error('Error:', error);
  }
}
// Run the function
fetchRecoveryRangeInfo();

回復範囲の更新

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1');

// Config
const apiKey = '<API_KEY>';
const backupVaultCrn = '<BACKUP_VAULT_CRN>';
const recoveryRangeId = '<RECOVERY_RANGE_ID>';
const policyId = '<POLICY_ID>';

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });

async function patchRecoveryRange() {
  try {
    // Patch the recovery range retention
    const patchResponse = await rcClient.patchSourceResourceRecoveryRange({
      backupVaultName: backupVaultName,
      recoveryRangeId: recoveryRangeId,
      retention: {
          delete_after_days: 99
        }
    });

    console.log('Recovery range updated successfully:');
    console.log(patchResponse.result);

  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the function
patchRecoveryRange ();

リストアの開始

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Configuration
const apiKey = '<API_KEY>';
const backupVaultName = '<BACKUP_VAULT_NAME>';
const recoveryRangeId = '<RECOVERY_RANGE_ID>';
const targetBucketCrn = '<TARGET_BUCKET_CRN>';
const restorePointInTime = '<RESTORE_POINT_TIME>';
const endpoint = '<COS_ENDPOINT>';

// Setup authenticator and clients
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });
rcClient.setServiceUrl("SERVICE_URL");

async function initiateRestore () {
  try {
    // Initiate restore
    const createRestoreResponse = await rcClient.createRestore({
      backupVaultName: backupVaultName,
      recoveryRangeId: recoveryRangeId,
      restoreType: 'in_place',
      restorePointInTime: restorePointInTime,
      targetResourceCrn: targetBucketCrn,
    });

    const restoreId = createRestoreResponse.result.restore_id;
    console.log(`Restore initiated with ID: ${restoreId}`);

  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the function
initiateRestore ();

リストア

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config
const apiKey = '<API_KEY>';
const backupVaultName = '<BACKUP_VAULT_NAME>';

// Auth & Clients
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });
rcClient.setServiceUrl("SERVICE_URL");

async function listRestore()  {
  try {
    // List restore operations
    const listRestoreResp = await rcClient.listRestores({
      backupVaultName: backupVaultName
    });

    console.log('Restore operations:', listRestoreResp.result);
  } catch (err) {
    console.error('Error occurred:', err);
  }
};

// Run the function
listRestore();

リストアの詳細

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')
// Configuration
const apiKey = '<API_KEY>';
const backupVaultName = '<BACKUP_VAULT_NAME>';
const restoreId = '<RESTORE_ID>';

const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });
rcClient.setServiceUrl("SERVICE_URL");

async function getRestore()  {
  try {
    // Get specific restore
    const restoreDetails = await rcClient.getRestore({
      backupVaultName: backupVaultName,
      restoreId: restoreId
    });
    console.log('Restore details:', restoreDetails.result);

  } catch (err) {
    console.error('Error:', err);
  }
}
getRestore();

Key Protect の使用

暗号鍵を管理するために、Key Protect をストレージ・バケットに追加できます。 IBM COS ではすべてのデータが暗号化されますが、Key Protect が提供するサービスは、集中型サービスを使用して暗号鍵を生成したり、ローテーションしたり、暗号鍵へのアクセスを制御したりするためのものです。

開始前に

Key-Protect を有効にしてバケツを作成するには、以下の項目が必要です:

ルート・キー CRN の取得

  1. Key Protect サービスのインスタンス ID を取得します。
  2. Key Protect API を使用して、すべての使用可能なキーを取得します。
    • curl コマンドまたは API REST クライアント (Postman など) のいずれかを使用して、Key Protect API にアクセスできます。
  3. バケットで Key Protect を有効にするために使用するルート・キーの CRN を取得します。 CRN は、下記のようになります。

crn:v1:bluemix:public:kms:us-south:a/3d624cd74a0dea86ed8efe3101341742:90b6a1db-0fe1-4fe9-b91e-962c327df531:key:0bg3e33e-a866-50f2-b715-5cba2bc93234

Key Protect が有効なバケットの作成

function createBucketKP(bucketName) {
    console.log(`Creating new encrypted bucket: ${bucketName}`);
    return cos.createBucket({
        Bucket: bucketName,
        CreateBucketConfiguration: {
          LocationConstraint: '<bucket-location>'
        },
        IBMSSEKPEncryptionAlgorithm: '<algorithm>',
        IBMSSEKPCustomerRootKeyCrn: '<root-key-crn>'
    }).promise()
    .then((() => {
        console.log(`Bucket: ${bucketName} created!`);
        logDone();
    }))
    .catch(logError);
}

キー値

  • <bucket-location>- バケツの地域または場所 ( Key Protect は特定の地域でのみ利用可能です。 ご使用のロケーションが Key Protect サービスと一致していることを確認してください。) LocationConstraint の有効なプロビジョニング・コードのリストについては、ストレージ・クラスのガイドを参照してください。
  • <algorithm>- バケツに追加された新しいオブジェクトに使用される暗号化アルゴリズム (デフォルトは AES256 )。
  • <root-key-crn>- Key Protect サービスから取得するルート鍵の CRN。

SDK リファレンス

アーカイブ機能の使用

アーカイブ層を使用することで、ユーザーは、失効したデータをアーカイブし、ストレージ・コストを削減できます。 アーカイブ・ポリシー (ライフサイクル構成 とも呼ばれます) は、バケットに対して作成され、ポリシーが作成された後にバケットに追加されるすべてのオブジェクトに適用されます。

バケットのライフサイクル構成の表示

function getLifecycleConfiguration(bucketName) {
    return cos.getBucketLifecycleConfiguration({
        Bucket: bucketName
    }).promise()
    .then((data) => {
        if (data != null) {
            console.log(`Retrieving bucket lifecycle config from: ${bucketName}`);
            console.log(JSON.stringify(data, null, 4));
        }
        else {
            console.log(`No lifecycle configuration for ${bucketName}`);
        }
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK リファレンス

ライフサイクル構成の作成

ライフサイクル構成ルールの構造について詳しくは、API リファレンスを参照してください。

function createLifecycleConfiguration(bucketName) {
    //
    var config = {
        Rules: [{
            Status: 'Enabled',
            ID: '<policy-id>',
            Filter: {
                Prefix: ''
            },
            Transitions: [{
                Days: <number-of-days>,
                StorageClass: 'GLACIER'
            }]
        }]
    };

    return cos.putBucketLifecycleConfiguration({
        Bucket: bucketName,
        LifecycleConfiguration: config
    }).promise()
    .then(() => {
        console.log(`Created bucket lifecycle config for: ${bucketName}`);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

キー値

  • <policy-id>- ライフサイクルポリシーの名前(一意でなければならない)
  • <number-of-days>- 復元ファイルの保存日数

SDK リファレンス

バケットのライフサイクル構成の削除

function deleteLifecycleConfiguration(bucketName) {
    return cos.deleteBucketLifecycle({
        Bucket: bucketName
    }).promise()
    .then(() => {
        console.log(`Deleted bucket lifecycle config from: ${bucketName}`);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK リファレンス

オブジェクトの一時的リストア

リストア要求のパラメーターについて詳しくは、API リファレンスを参照してください。

function restoreItem(bucketName, itemName) {
    var params = {
        Bucket: bucketName,
        Key: itemName,
        RestoreRequest: {
            Days: <number-of-days>,
            GlacierJobParameters: {
                Tier: 'Bulk'
            },
        }
    };

    return cos.restoreObject(params).promise()
    .then(() => {
        console.log(`Restoring item: ${itemName} from bucket: ${bucketName}`);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

キー値

  • <number-of-days>- 復元ファイルの保存日数

SDK リファレンス

オブジェクトの HEAD 情報の表示

function getHEADItem(bucketName, itemName) {
    return cos.headObject({
        Bucket: bucketName,
        Key: itemName
    }).promise()
    .then((data) => {
        console.log(`Retrieving HEAD for item: ${itemName} from bucket: ${bucketName}`);
        console.log(JSON.stringify(data, null, 4));
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK リファレンス

メタデータの更新

既存のオブジェクトのメタデータを更新する方法は、2 とおりあります。

  • 新しいメタデータと元のオブジェクト・コンテンツが指定された PUT 要求
  • 元のオブジェクトをコピー・ソースとして指定し、新しいメタデータを使用する COPY 要求の実行

PUT を使用したメタデータの更新

注: PUT のリクエストは、オブジェクトの既存のコンテンツを上書きするため、最初に新しいメタデータをダウンロードし、再アップロードする必要がある。

function updateMetadataPut(bucketName, itemName, metaValue) {
    console.log(`Updating metadata for item: ${itemName}`);

    //retrieve the existing item to reload the contents
    return cos.getObject({
        Bucket: bucketName,
        Key: itemName
    }).promise()
    .then((data) => {
        //set the new metadata
        var newMetadata = {
            newkey: metaValue
        };

        return cos.putObject({
            Bucket: bucketName,
            Key: itemName,
            Body: data.Body,
            Metadata: newMetadata
        }).promise()
        .then(() => {
            console.log(`Updated metadata for item: ${itemName} from bucket: ${bucketName}`);
        })
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

COPY を使用したメタデータの更新

function updateMetadataCopy(bucketName, itemName, metaValue) {
    console.log(`Updating metadata for item: ${itemName}`);

    //set the copy source to itself
    var copySource = bucketName + '/' + itemName;

    //set the new metadata
    var newMetadata = {
        newkey: metaValue
    };

    return cos.copyObject({
        Bucket: bucketName,
        Key: itemName,
        CopySource: copySource,
        Metadata: newMetadata,
        MetadataDirective: 'REPLACE'
    }).promise()
    .then((data) => {
        console.log(`Updated metadata for item: ${itemName} from bucket: ${bucketName}`);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

Immutable Object Storage の使用

既存のバケットへの保護構成の追加

保護対象のバケットに書き込まれたオブジェクトは、保護期間が満了し、オブジェクトに対するすべての法的保留が解除されるまで削除できません。 オブジェクトの作成時にオブジェクト固有の値が指定されない限り、バケットのデフォルトの保存期間値がオブジェクトにも適用されます。 保全の対象でなくなった保護対象バケット内のオブジェクト (保存期間が満了し、オブジェクトに法的保留が課せられていない) が上書きされた場合、そのオブジェクトは再度保全の対象になります。 新しい保存期間は、オブジェクト上書き要求の一部として指定できます。そうしない場合は、バケットのデフォルトの保存期間がオブジェクトに適用されます。

保存期間設定 MinimumRetentionDefaultRetention、および MaximumRetention でサポートされる最小値と最大値は、それぞれ 0 日と 365243 日 (1000 年) です。

function addProtectionConfigurationToBucket(bucketName) {
    console.log(`Adding protection to bucket ${bucketName}`);
    return cos.putBucketProtectionConfiguration({
        Bucket: bucketName,
        ProtectionConfiguration: {
            'Status': 'Retention',
            'MinimumRetention': {'Days': 10},
            'DefaultRetention': {'Days': 100},
            'MaximumRetention': {'Days': 1000}
        }
    }).promise()
    .then(() => {
        console.log(`Protection added to bucket ${bucketName}!`);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

バケットに対する保護のチェック

function getProtectionConfigurationOnBucket(bucketName) {
    console.log(`Retrieve the protection on bucket ${bucketName}`);
    return cos.getBucketProtectionConfiguration({
        Bucket: bucketName
    }).promise()
    .then((data) => {
        console.log(`Configuration on bucket ${bucketName}:`);
        console.log(data);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

保護オブジェクトのアップロード

保全の対象でなくなった保護対象バケット内のオブジェクト (保存期間が満了し、オブジェクトに法的保留が課せられていない) が上書きされた場合、そのオブジェクトは再度保全の対象になります。 新しい保存期間は、オブジェクト上書き要求の一部として指定できます。そうしない場合は、バケットのデフォルトの保存期間がオブジェクトに適用されます。

タイプ 説明
Retention-Period 負でない整数 (秒数) オブジェクトを保管する保存期間 (秒数)。 オブジェクトは、保存期間に指定された時間が経過するまで上書きも削除もできません。 このフィールドと Retention-Expiration-Date が指定された場合、400 エラーが返されます。 いずれも指定されない場合は、バケットの DefaultRetention 期間が使用されます。 ゼロ (0) は有効な値であり、バケットの最小保存期間も 0 であると想定されます。
Retention-expiration-date 日付 (ISO 8601 フォーマット) オブジェクトを合法的に削除または変更できるようになる日付。 これか Retention-Period ヘッダーのいずれかのみを指定できます。 両方が指定された場合は、400 エラーが返されます。 いずれも指定されない場合は、バケットの DefaultRetention 期間が使用されます。
Retention-legal-hold-id ストリング オブジェクトに適用される単一の法的保留。 法的保留とは、Y 文字の長さのストリングです。 オブジェクトに関連付けられたすべての法的保留が解除されるまで、オブジェクトは上書きも削除もできません。
function putObjectAddLegalHold(bucketName, objectName, legalHoldId) {
    console.log(`Add legal hold ${legalHoldId} to ${objectName} in bucket ${bucketName} with a putObject operation.`);
    return cos.putObject({
        Bucket: bucketName,
        Key: objectName,
        Body: 'body',
        RetentionLegalHoldId: legalHoldId
    }).promise()
    .then((data) => {
        console.log(`Legal hold ${legalHoldId} added to object ${objectName} in bucket ${bucketName}`);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

function copyProtectedObject(sourceBucketName, sourceObjectName, destinationBucketName, newObjectName, ) {
    console.log(`Copy protected object ${sourceObjectName} from bucket ${sourceBucketName} to ${destinationBucketName}/${newObjectName}.`);
    return cos.copyObject({
        Bucket: destinationBucketName,
        Key: newObjectName,
        CopySource: sourceBucketName + '/' + sourceObjectName,
        RetentionDirective: 'Copy'
    }).promise()
    .then((data) => {
        console.log(`Protected object copied from ${sourceBucketName}/${sourceObjectName} to ${destinationBucketName}/${newObjectName}`);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

保護オブジェクトの保存期間の延長

オブジェクトの保存期間は延長のみが可能です。 現在構成されている値から減らすことはできません。

保存延長値は次の 3 つの方法のいずれかで設定されます。

  • 現行値からの追加時間 (Additional-Retention-Period または同様のメソッド)
  • 新しい延長期間 (秒数) (Extend-Retention-From-Current-Time または同様のメソッド)
  • オブジェクトの新しい保存有効期限日付 (New-Retention-Expiration-Date または同様のメソッド)

オブジェクト・メタデータに保管されている現在の保存期間は、extendRetention 要求に設定されているパラメーターに応じて、指定された追加時間分増やされるか、新しい値に置き換えられます。 いずれの場合も、保存延長パラメーターは現在の保存期間に対して検査され、更新後の保存期間が現在の保存期間より大きい場合にのみ、延長パラメーターが受け入れられます。

保全の対象でなくなった保護対象バケット内のオブジェクト (保存期間が満了し、オブジェクトに法的保留が課せられていない) が上書きされた場合、そのオブジェクトは再度保全の対象になります。 新しい保存期間は、オブジェクト上書き要求の一部として指定できます。そうしない場合は、バケットのデフォルトの保存期間がオブジェクトに適用されます。

function extendRetentionPeriodOnObject(bucketName, objectName, additionalSeconds) {
    console.log(`Extend the retention period on ${objectName} in bucket ${bucketName} by ${additionalSeconds} seconds.`);
    return cos.extendObjectRetention({
        Bucket: bucketName,
        Key: objectName,
        AdditionalRetentionPeriod: additionalSeconds
    }).promise()
    .then((data) => {
        console.log(`New retention period on ${objectName} is ${data.RetentionPeriod}`);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

保護オブジェクトの法的保留のリスト

この操作で返される内容は以下のとおりです。

  • オブジェクト作成日
  • オブジェクト保存期間 (秒数)
  • 期間および作成日に基づいて計算された保存有効期限
  • 法的保留のリスト
  • 法的保留 ID
  • 法的保留が適用されたときのタイム・スタンプ

オブジェクトに法的保留がない場合は、空の LegalHoldSet が返されます。 オブジェクトに保存期間が指定されていない場合は、 404 エラーが返されます。

function listLegalHoldsOnObject(bucketName, objectName) {
    console.log(`List all legal holds on object ${objectName} in bucket ${bucketName}`);
    return cos.listLegalHolds({
        Bucket: bucketName,
        Key: objectId
    }).promise()
    .then((data) => {
        console.log(`Legal holds on bucket ${bucketName}: ${data}`);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

ホストされた静的 Web サイトの作成

通常、バケット所有者のみが静的 Web サイトをホストするようにバケットを構成することを許可されるため、この操作には許可が必要です。 これらのパラメーターは、サイトへの訪問者のデフォルトの接尾部と、オプションのエラー文書を決定します。

var websiteParams = {
  Bucket: "bucketName",
  WebsiteConfiguration: {
    ErrorDocument: {
      Key: "error.html"
    },
    IndexDocument: {
      Suffix: "index.html"
    }
  }
};
function putBucketWebsiteConfiguration(websiteParams) {
  return cos.putBucketWebsite({websiteParams}).promise()
    .then((data) => {
       console.log(`Website configured for ${bucketName}`);
    })
    .catch((e) => {
       console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

次のステップ

個々のメソッドおよびクラスについて詳しくは、 SDK の API 資料を参照してください。 GitHubでソース・コードを確認してください。