すべてのプロダクト
Search
ドキュメントセンター

Object Storage Service:ライフサイクル管理 (Python SDK V2)

最終更新日:Mar 21, 2026

ライフサイクルルールを使用すると、Object Storage Service (OSS) は、オブジェクトの経過時間やアクセスパターンに基づいて、オブジェクトをより低コストのストレージクラスに自動的にトランジションしたり、オブジェクトを削除したりできます。手動介入は不要です。

OSS は 2 種類のルールをサポートしています。

  • 最終変更時間に基づくルール: 指定された日数変更されていないオブジェクトをトランジションまたは削除します。これらのルールを使用して、古いデータをクリーンアップしたり、めったに更新されないファイルをアーカイブしたりできます。

  • 最終アクセス時間に基づくルール: OSS はアクセスパターンをモニターし、コールドデータをより安価なストレージクラスに自動的に移動します。これにより、自動ストレージ階層化が実装され、時間の経過とともにストレージコストが削減されます。

前提条件

開始する前に、以下を確認してください。

このトピックのサンプルコードは、中国 (杭州) リージョン (cn-hangzhou) とパブリックエンドポイントを使用しています。同じリージョン の別の Alibaba Cloud サービスから OSS にアクセスするには、代わりに内部エンドポイントを使用してください。サポートされているリージョン とエンドポイントについては、「OSS リージョンとエンドポイント」をご参照ください。

ライフサイクルルールの設定

以下の 3 つのサンプルはすべて、client.put_bucket_lifecycle() を呼び出し、バケットに LifecycleConfiguration を適用します。各サンプルは、異なるフィルタリングとトランジションのシナリオを示しています。

既存のルールを 1 つ以上更新するには、「ライフサイクルルールを変更する方法」をご参照ください。

最終変更時間に基づいてオブジェクトを IA ストレージに移行

このサンプルでは、バケットに 2 つのルールを設定します。

  • rule1: プレフィックス foo/ とタグ k1:v1 を持つオブジェクトを、最終変更から 30 日後に低頻度アクセス (IA) ストレージにトランジションします。

  • rule2: バージョン管理が有効なバケット内のプレフィックス dir/ を持つオブジェクトの場合、期限切れの削除マーカーを自動的に削除し、10 日後に非現行バージョンを IA にトランジションし、30 日後に非現行バージョンを完全に削除します。

import argparse
import alibabacloud_oss_v2 as oss

parser = argparse.ArgumentParser(description="put bucket lifecycle sample")
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    args = parser.parse_args()

    # Load credentials from environment variables
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    client = oss.Client(cfg)

    result = client.put_bucket_lifecycle(oss.PutBucketLifecycleRequest(
        bucket=args.bucket,
        lifecycle_configuration=oss.LifecycleConfiguration(
            rules=[
                oss.LifecycleRule(
                    id='rule1',
                    status='Enabled',
                    prefix='foo/',
                    transitions=[oss.LifecycleRuleTransition(
                        days=30,
                        storage_class=oss.StorageClassType.IA,
                        is_access_time=False,  # Policy based on last modified time
                    )],
                    tags=[oss.Tag(
                        key='k1',
                        value='v1',
                    )],
                ),
                oss.LifecycleRule(
                    id='rule2',
                    status='Enabled',
                    prefix='dir/',
                    expiration=oss.LifecycleRuleExpiration(
                        days=10,
                        expired_object_delete_marker=True,  # Remove delete markers when no other versions exist
                    ),
                    noncurrent_version_expiration=oss.NoncurrentVersionExpiration(
                        noncurrent_days=30,
                    ),
                    noncurrent_version_transition=oss.NoncurrentVersionTransition(
                        noncurrent_days=10,
                        storage_class=oss.StorageClassType.IA,
                        is_access_time=False,  # Policy based on last modified time
                    ),
                ),
            ]
        ),
    ))

    print(f'status code: {result.status_code}, request id: {result.request_id}')


if __name__ == "__main__":
    main()

サイズでオブジェクトをフィルタリングし、特定のプレフィックスまたはタグを除外

このサンプルでは、プレフィックス logs/ を持つオブジェクトを、最終変更から 30 日後に低頻度アクセス (IA) ストレージにトランジションします。ただし、オブジェクトサイズが 500 バイトから 1,000 バイトの間である場合に限ります。プレフィックス logs/log とタグ key1:value1 にも一致するオブジェクトは除外されます。

import argparse
import alibabacloud_oss_v2 as oss

parser = argparse.ArgumentParser(description="put bucket lifecycle sample")
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    args = parser.parse_args()

    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    client = oss.Client(cfg)

    result = client.put_bucket_lifecycle(oss.PutBucketLifecycleRequest(
        bucket=args.bucket,
        lifecycle_configuration=oss.LifecycleConfiguration(
            rules=[
                oss.LifecycleRule(
                    id='rule1',
                    status='Enabled',
                    prefix='logs/',
                    transitions=[oss.LifecycleRuleTransition(
                        days=30,
                        storage_class=oss.StorageClassType.IA,
                        is_access_time=False,  # Policy based on last modified time
                    )],
                    filter=oss.LifecycleRuleFilter(
                        object_size_greater_than=500,   # Minimum object size in bytes
                        object_size_less_than=1000,     # Maximum object size in bytes
                        filter_not=[oss.LifecycleRuleNot(
                            prefix='logs/log',          # Exclude this prefix
                            tag={
                                'key': 'key1',
                                'value': 'value1',
                            },
                        )],
                    ),
                ),
            ]
        ),
    ))

    print(f'status code: {result.status_code}, request id: {result.request_id}')


if __name__ == "__main__":
    main()

アクセスパターンに基づいてコールドデータを移動

このサンプルでは、最終変更時間ではなく最終アクセス時間に基づいてオブジェクトをトランジションする 2 つのルールを設定します。どちらのルールも is_access_time=Truereturn_to_std_when_visit=False を使用します。

  • rule1: プレフィックス data/ を持つオブジェクトを、200 日間の非アクティブ状態の後、低頻度アクセス (IA) にトランジションします。

  • rule2: プレフィックス log/ を持つオブジェクトを、120 日間の非アクティブ状態の後 IA にトランジションし、その後 250 日後にアーカイブにトランジションします。

import argparse
import alibabacloud_oss_v2 as oss

parser = argparse.ArgumentParser(description="put bucket lifecycle sample")
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    args = parser.parse_args()

    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    client = oss.Client(cfg)

    result = client.put_bucket_lifecycle(oss.PutBucketLifecycleRequest(
        bucket=args.bucket,
        lifecycle_configuration=oss.LifecycleConfiguration(
            rules=[
                oss.LifecycleRule(
                    id='rule1',
                    status='Enabled',
                    prefix='data/',
                    transitions=[oss.LifecycleRuleTransition(
                        days=200,
                        storage_class=oss.StorageClassType.IA,
                        is_access_time=True,               # Policy based on last access time
                        return_to_std_when_visit=False,    # Stay in IA when accessed again
                    )],
                ),
                oss.LifecycleRule(
                    id='rule2',
                    status='Enabled',
                    prefix='log/',
                    transitions=[
                        oss.LifecycleRuleTransition(
                            days=120,
                            storage_class=oss.StorageClassType.IA,
                            is_access_time=True,
                            return_to_std_when_visit=False,
                        ),
                        oss.LifecycleRuleTransition(
                            days=250,
                            storage_class=oss.StorageClassType.ARCHIVE,
                            is_access_time=True,
                            return_to_std_when_visit=False,
                        ),
                    ],
                ),
            ]
        ),
    ))

    print(f'status code: {result.status_code}, request id: {result.request_id}')


if __name__ == "__main__":
    main()

ライフサイクルルールの表示

client.get_bucket_lifecycle() を使用して、バケットに構成されているすべてのライフサイクルルールを取得します。結果には、完全なルール定義を含む lifecycle_configuration.rules リストが含まれます。

import argparse
import alibabacloud_oss_v2 as oss

parser = argparse.ArgumentParser(description="get bucket lifecycle sample")
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    args = parser.parse_args()

    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    client = oss.Client(cfg)

    result = client.get_bucket_lifecycle(
        oss.GetBucketLifecycleRequest(
            bucket=args.bucket,
        )
    )

    print(f'status code: {result.status_code}, request id: {result.request_id}')

    if result.lifecycle_configuration.rules:
        for r in result.lifecycle_configuration.rules:
            print(f'rule: {r}')


if __name__ == "__main__":
    main()

すべてのライフサイクルルールの削除

client.delete_bucket_lifecycle() は、バケットからすべてのライフサイクルルールを削除します。個別のルールを削除するには、「特定のライフサイクルルールを削除する方法」をご参照ください。

import argparse
import alibabacloud_oss_v2 as oss

parser = argparse.ArgumentParser(description="delete bucket lifecycle sample")
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    args = parser.parse_args()

    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    client = oss.Client(cfg)

    result = client.delete_bucket_lifecycle(
        oss.DeleteBucketLifecycleRequest(
            bucket=args.bucket,
        )
    )

    print(f'status code: {result.status_code}, request id: {result.request_id}')


if __name__ == "__main__":
    main()

参照