

# バケットでのバージョニングの有効化
<a name="manage-versioning-examples"></a>

S3 バージョニングを使用すると、1 つのバケットで複数バージョンのオブジェクトを維持できます。このセクションでは、コンソール、REST API、AWS SDK、AWS Command Line Interface (AWS CLI) を使って、バケットでバージョニングを有効にする方法の例を説明します。

**注記**  
バケットで初めてバージョニングを有効にしたときは、変更が S3 システム全体に完全に反映されるまでに、最長で 15 分かかることがあります。この間、バージョニングを有効にした後で作成または更新したオブジェクトへの `GET` リクエストは、`HTTP 404 NoSuchKey` エラーになる可能性があります。バケット内のオブジェクトへの書き込みオペレーション (`PUT` または `DELETE`) は、バージョニングを有効にした後で 15 分待ってから実行することをお勧めします。この待機時間は、オブジェクトの可視性とバージョンの追跡に伴う潜在的な問題を回避するのに役立ちます。

S3 バージョニングの詳細については、「[S3 バージョニングによる複数のバージョンのオブジェクトの保持](Versioning.md)」を参照してください。バージョニングが有効になっているバケットでの、オブジェクトの操作に関する詳細は、「[バージョニングが有効なバケットでのオブジェクトの操作](manage-objects-versioned-bucket.md)」を参照してください。

S3 バージョニングを使用してデータを保護する方法の詳細については、「[Tutorial: Protecting data on Amazon S3 against accidental deletion or application bugs using S3 Versioning, S3 Object Lock, and S3 Replication](https://aws.amazon.com/getting-started/hands-on/protect-data-on-amazon-s3/?ref=docs_gateway/amazons3/manage-versioning-examples.html)」(チュートリアル: S3 バージョニング、S3 オブジェクトロック、S3 レプリケーションを使用して、Amazon S3 上のデータを予期しない削除やアプリケーションのバグから保護する) を参照してください。

作成する各 S3 バケットには、それに関連付けられた*バージョニング*のサブリソースがあります。(詳しくは、[汎用バケットの設定オプション](UsingBucket.md#bucket-config-options-intro) を参照してください)。デフォルトでは、バケットの*バージョニングは無効*で、バージョニングのサブリソースには、以下のとおり、空のバージョニング設定が保存されます。

```
<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> 
</VersioningConfiguration>
```

バージョニングを有効にするには、状態を含むバージョニング設定を使用して、Amazon S3 にリクエストを送信します。

```
<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> 
  <Status>Enabled</Status> 
</VersioningConfiguration>
```

バージョニングを停止するには、ステータス値を `Suspended` に設定します。

バケット所有者とすべての承認されたユーザーは、バージョニングを有効にすることができます。バケット所有者は、バケットを作成した AWS アカウント (ルートアカウント) です。 権限の詳細については、 を参照してください[Amazon S3 用 Identity and Access Management](security-iam.md)

以下のセクションでは、コンソール、AWS CLI、AWS SDK を使って S3 バージョニングを有効にする方法の詳細を説明します。

## S3 コンソールの使用
<a name="enable-versioning"></a>

AWS マネジメントコンソール を使用して、S3 バケットでバージョニングを有効にするには、次の手順に従います。

**S3 汎用バケットのバージョニングを有効または無効にするには**

1. AWS マネジメントコンソール にサインインし、Amazon S3 コンソール [https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/) を開きます。

1. 左のナビゲーションペインで、**[汎用バケット]** を選択します。

1. バケットリストで、バージョニングを有効にするバケットの名前を選択します。

1. [**プロパティ**] を選択します。

1. [**バケットのバージョニング**] で [**編集**] を選択します。

1. [**中断**] または [**有効化**] を選択し、[**変更を保存**] を選択します。

**注記**  
バージョニングで AWS 多要素認証 (MFA) を使用できます。バージョニングに MFA を使用しているときに、オブジェクトバージョンを完全に削除したり、バージョニングを停止または再有効化したりする場合は、AWS アカウント のアクセスキーと有効なコードを、アカウントの MFA デバイスから指定することが必要になります。  
バージョニングで MFA を使用するには、`MFA Delete` を有効にします。ただし、AWS マネジメントコンソール を使用して `MFA Delete` を有効にすることはできません。AWS Command Line Interface (AWS CLI) または API を使用する必要があります。詳細については、「[MFA 削除の設定](MultiFactorAuthenticationDelete.md)」を参照してください。

## AWS CLI の使用
<a name="manage-versioning-examples-cli"></a>

次の例では、S3 汎用バケットでバージョニングを有効にします。

```
aws s3api put-bucket-versioning --bucket amzn-s3-demo-bucket1 --versioning-configuration Status=Enabled
```

次の例では、物理的な MFA デバイスのバケットで S3 バージョニングと多要素認証 (MFA) 削除を有効にします。物理的な MFA デバイスの場合、`--mfa` パラメータで、MFA デバイスのシリアル番号、スペース文字、および認証デバイスに表示される値の連結を渡します。

```
aws s3api put-bucket-versioning --bucket amzn-s3-demo-bucket1 --versioning-configuration Status=Enabled,MFADelete=Enabled --mfa "SerialNumber 123456"
```

次の例では、仮想 MFA デバイスのバケットで S3 バージョニングと多要素認証 (MFA) 削除を有効にします。仮想 MFA デバイスの場合、`--mfa` パラメータで、MFA デバイスの ARN、スペース文字、および認証デバイスに表示される値の連結を渡します。

```
aws s3api put-bucket-versioning --bucket amzn-s3-demo-bucket1 --versioning-configuration Status=Enabled,MFADelete=Enabled --mfa "arn:aws:iam::account-id:mfa/root-account-mfa-device 123789"
```

**注記**  
MFA 削除を使用するときは、承認済みの物理または仮想の認証デバイスが必要です。Amazon S3 での MFA 削除の使用に関する詳細は、「[MFA 削除の設定](MultiFactorAuthenticationDelete.md)」を参照してください。

AWS CLI を使用したバージョニングの有効化に関する詳細は、*AWS CLI CLI コマンドリファレンス*の「[put-bucket-versioning](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-versioning.html)」を参照してください。

## AWS SDK の使用
<a name="manage-versioning-examples-sdk"></a>

次の例では、バケットでバージョニングを有効にし、AWS SDK for Java と AWS SDK for .NET を使ってバージョニングの状態を復元します。他の AWS SDK の使用の詳細については、「[AWS デベロッパーセンター](https://aws.amazon.com/code/)」を参照してください。

------
#### [ .NET ]

コード例を設定および実行する方法の詳細については、「*AWS SDK for .NET デベロッパーガイド*」の「[AWS SDK for .NET の開始方法](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/net-dg-setup.html)」 を参照してください。

```
using System;
using Amazon.S3;
using Amazon.S3.Model;

namespace s3.amazon.com.rproxy.goskope.com.docsamples
{
    class BucketVersioningConfiguration
    {
        static string bucketName = "*** bucket name ***";

        public static void Main(string[] args)
        {
            using (var client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1))
            {
                try
                {
                    EnableVersioningOnBucket(client);
                    string bucketVersioningStatus = RetrieveBucketVersioningConfiguration(client);
                }
                catch (AmazonS3Exception amazonS3Exception)
                {
                    if (amazonS3Exception.ErrorCode != null &&
                        (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                        ||
                        amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                    {
                        Console.WriteLine("Check the provided AWS Credentials.");
                        Console.WriteLine(
                        "To sign up for service, go to http://aws.amazon.com/s3");
                    }
                    else
                    {
                        Console.WriteLine(
                         "Error occurred. Message:'{0}' when listing objects",
                         amazonS3Exception.Message);
                    }
                }
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }

        static void EnableVersioningOnBucket(IAmazonS3 client)
        {

                PutBucketVersioningRequest request = new PutBucketVersioningRequest
                {
                    BucketName = bucketName,
                    VersioningConfig = new S3BucketVersioningConfig 
                    {
                        Status = VersionStatus.Enabled
                    }
                };

                PutBucketVersioningResponse response = client.PutBucketVersioning(request);
        }


        static string RetrieveBucketVersioningConfiguration(IAmazonS3 client)
        {
                GetBucketVersioningRequest request = new GetBucketVersioningRequest
                {
                    BucketName = bucketName
                };
 
                GetBucketVersioningResponse response = client.GetBucketVersioning(request);
                return response.VersioningConfig.Status;
            }
    }
}
```

------
#### [ Java ]

作業サンプルの作成方法およびテスト方法については、「AWS SDK for Java のデベロッパーガイド」の「[使用開始](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/getting-started.html)」を参照してください。

```
import java.io.IOException;

import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.BucketVersioningConfiguration;
import com.amazonaws.services.s3.model.SetBucketVersioningConfigurationRequest;

public class BucketVersioningConfigurationExample {
    public static String bucketName = "*** bucket name ***"; 
    public static AmazonS3Client s3Client;

    public static void main(String[] args) throws IOException {
        s3Client = new AmazonS3Client(new ProfileCredentialsProvider());
        s3Client.setRegion(Region.getRegion(Regions.US_EAST_1));
        try {

            // 1. Enable versioning on the bucket.
        	BucketVersioningConfiguration configuration = 
        			new BucketVersioningConfiguration().withStatus("Enabled");
            
			SetBucketVersioningConfigurationRequest setBucketVersioningConfigurationRequest = 
					new SetBucketVersioningConfigurationRequest(bucketName,configuration);
			
			s3Client.setBucketVersioningConfiguration(setBucketVersioningConfigurationRequest);
			
			// 2. Get bucket versioning configuration information.
			BucketVersioningConfiguration conf = s3Client.getBucketVersioningConfiguration(bucketName);
			 System.out.println("bucket versioning configuration status:    " + conf.getStatus());

        } catch (AmazonS3Exception amazonS3Exception) {
            System.out.format("An Amazon S3 error occurred. Exception: %s", amazonS3Exception.toString());
        } catch (Exception ex) {
            System.out.format("Exception: %s", ex.toString());
        }        
    }
}
```

------
#### [ Python ]

次の Python コードの例では、Amazon S3 バケットを作成し、バージョニング用に有効にして、オブジェクトの最新ではないバージョンが 7 日後に失効するライフサイクルを設定しています。

```
def create_versioned_bucket(bucket_name, prefix):
    """
    Creates an Amazon S3 bucket, enables it for versioning, and configures a lifecycle
    that expires noncurrent object versions after 7 days.

    Adding a lifecycle configuration to a versioned bucket is a best practice.
    It helps prevent objects in the bucket from accumulating a large number of
    noncurrent versions, which can slow down request performance.

    Usage is shown in the usage_demo_single_object function at the end of this module.

    :param bucket_name: The name of the bucket to create.
    :param prefix: Identifies which objects are automatically expired under the
                   configured lifecycle rules.
    :return: The newly created bucket.
    """
    try:
        bucket = s3.create_bucket(
            Bucket=bucket_name,
            CreateBucketConfiguration={
                "LocationConstraint": s3.meta.client.meta.region_name
            },
        )
        logger.info("Created bucket %s.", bucket.name)
    except ClientError as error:
        if error.response["Error"]["Code"] == "BucketAlreadyOwnedByYou":
            logger.warning("Bucket %s already exists! Using it.", bucket_name)
            bucket = s3.Bucket(bucket_name)
        else:
            logger.exception("Couldn't create bucket %s.", bucket_name)
            raise

    try:
        bucket.Versioning().enable()
        logger.info("Enabled versioning on bucket %s.", bucket.name)
    except ClientError:
        logger.exception("Couldn't enable versioning on bucket %s.", bucket.name)
        raise

    try:
        expiration = 7
        bucket.LifecycleConfiguration().put(
            LifecycleConfiguration={
                "Rules": [
                    {
                        "Status": "Enabled",
                        "Prefix": prefix,
                        "NoncurrentVersionExpiration": {"NoncurrentDays": expiration},
                    }
                ]
            }
        )
        logger.info(
            "Configured lifecycle to expire noncurrent versions after %s days "
            "on bucket %s.",
            expiration,
            bucket.name,
        )
    except ClientError as error:
        logger.warning(
            "Couldn't configure lifecycle on bucket %s because %s. "
            "Continuing anyway.",
            bucket.name,
            error,
        )

    return bucket
```

------