masterforker
masterforker

Reputation: 2527

Getting specific version of file from S3 bucket

I have a file in a S3 bucket with versioning turned on. Using the aws-cli is there a way to copy a specific version of this file, rather than the latest version?

Upvotes: 23

Views: 22146

Answers (5)

Igor S.
Igor S.

Reputation: 446

if someone is struggling to find the answer related to SDK, so here is what I did

Note: last (latest) object version you retvive after that you uploaded the file using PutObjectCommand through s3client or getSignedUrl

const {
    S3Client,
    GetObjectCommand,
    ListObjectVersionsCommand
} = require('@aws-sdk/client-s3');
    
const s3Client = new S3Client({
    endpoint: process.env.SPACES_ENDPOINT
    region: process.env.SPACES_REGION,
    credentials: {
        accessKeyId: process.env.SPACES_ACCESS_KEY,
        secretAccessKey: process.env.SPACES_SECRET_KEY
    }
});

async getUploadedObjectVersion(filename) {
    const command = new ListObjectVersionsCommand({
        Bucket: 'bucketName',
        KeyMarker: filename  <--- response array will start from meta data of this key
    });
    const response = await s3Client.send(command);

    const lastVersionId = response.Versions.find(version => version.IsLatest === true && version.Key === filename)?.VersionId; //exactly what you mneed
},

Upvotes: 0

PersianIronwood
PersianIronwood

Reputation: 780

This is how I got an object in s3 for specific versionId :

  async function getObject() {
    try {
      const params = {
        Bucket: this.imageBucket,
        Key: `YOUR_PATH_TO_OBJECT?versionId=u_HtqVAVylAG2fk0tXOGoC6CdT4EtOV2`,
      };
      const data = await s3.getObject(params).promise();
      return data.Body.toString('utf-8');
    } catch (e) {
      throw new Error(`Could not retrieve file from S3: ${e.message}`);
    }
  }

Upvotes: 0

Beef Eater
Beef Eater

Reputation: 394

There is a very convenient tool, s3-pit-restore, that allows restoring a point-in-time version of a file or a prefix (a directory) from a versioned bucket. See Angelo's response to this question:

https://serverfault.com/questions/589713/restore-a-versioned-s3-bucket-to-a-particular-point-in-time

Upvotes: 0

Piyush Patil
Piyush Patil

Reputation: 14533

Yes you can do that see this example you will need the version ID for the object.

aws s3api get-object --bucket mybucket --key file1.txt --version-id Mj1.PcWG8e.C._7LhvFU131pXJ98abIl foo.txt

Also you can list the version for getting the version ID using this commands.

aws s3api list-object-versions --bucket mybucket

Upvotes: 37

Vor
Vor

Reputation: 35139

Yes, use aws s3api get-object and specify --version-id

More info here http://docs.aws.amazon.com/cli/latest/reference/s3api/get-object.html

Upvotes: 4

Related Questions