///<summary>/// Set or modify a legal hold on an object in an S3 bucket.///</summary>///<param name="bucketName">The bucket of the object.</param>///<param name="objectKey">The key of the object.</param>///<param name="holdStatus">The On or Off status for the legal hold.</param>///<returns>True if successful.</returns>publicasync Task<bool> ModifyObjectLegalHold(string bucketName,
string objectKey, ObjectLockLegalHoldStatus holdStatus){try{var request = new PutObjectLegalHoldRequest()
{
BucketName = bucketName,
Key = objectKey,
LegalHold = new ObjectLockLegalHold()
{
Status = holdStatus
}
};
var response = await _amazonS3.PutObjectLegalHoldAsync(request);
Console.WriteLine($"\tModified legal hold for {objectKey} in {bucketName}.");
return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
}
catch (AmazonS3Exception ex)
{
Console.WriteLine($"\tError modifying legal hold: '{ex.Message}'");
returnfalse;
}
}
// Set or modify a legal hold on an object in an S3 bucket.publicvoidmodifyObjectLegalHold(String bucketName, String objectKey, boolean legalHoldOn){
ObjectLockLegalHold legalHold ;
if (legalHoldOn) {
legalHold = ObjectLockLegalHold.builder()
.status(ObjectLockLegalHoldStatus.ON)
.build();
} else{
legalHold = ObjectLockLegalHold.builder()
.status(ObjectLockLegalHoldStatus.OFF)
.build();
}
PutObjectLegalHoldRequest legalHoldRequest = PutObjectLegalHoldRequest.builder()
.bucket(bucketName)
.key(objectKey)
.legalHold(legalHold)
.build();
getClient().putObjectLegalHold(legalHoldRequest) ;
System.out.println("Modified legal hold for "+ objectKey +" in "+bucketName +".");
}
import{
PutObjectLegalHoldCommand,
S3Client,
S3ServiceException,
} from"@aws-sdk/client-s3";
/**
* Apply a legal hold configuration to the specified object.
* @param {{ bucketName: string, objectKey: string, legalHoldStatus: "ON" | "OFF" }}
*/exportconst main = async ({ bucketName, objectKey, legalHoldStatus }) => {if (!["OFF", "ON"].includes(legalHoldStatus.toUpperCase())) {thrownewError(
"Invalid parameter. legalHoldStatus must be 'ON' or 'OFF'.",
);
}
const client = new S3Client({});
const command = new PutObjectLegalHoldCommand({Bucket: bucketName,
Key: objectKey,
LegalHold: {// Set the status to 'ON' to place a legal hold on the object.// Set the status to 'OFF' to remove the legal hold.Status: legalHoldStatus,
},
});
try{await client.send(command);
console.log(
`Legal hold status set to "${legalHoldStatus}" for "${objectKey}" in "${bucketName}"`,
);
} catch (caught) {if (
caught instanceof S3ServiceException &&
caught.name === "NoSuchBucket"
) {console.error(
`Error from S3 while modifying legal hold status for "${objectKey}" in "${bucketName}". The bucket doesn't exist.`,
);
} elseif (caught instanceof S3ServiceException) {console.error(
`Error from S3 while modifying legal hold status for "${objectKey}" in "${bucketName}". ${caught.name}: ${caught.message}`,
);
} else{throw caught;
}
}
};
// Call function if run directlyimport{ parseArgs } from"node:util";
import{
isMain,
validateArgs,
} from"@aws-doc-sdk-examples/lib/utils/util-node.js";
const loadArgs = () =>{const options = {bucketName: {type: "string",
required: true,
},
objectKey: {type: "string",
required: true,
},
legalHoldStatus: {type: "string",
default: "ON",
},
};
const results = parseArgs({ options });
const{ errors } = validateArgs({ options }, results);
return{ errors, results };
};
if (isMain(import.meta.url)) {const{ errors, results } = loadArgs();
if (!errors) {
main(results.values);
} else{console.error(errors.join("\n"));
}
}
defset_legal_hold(s3_client, bucket: str, key: str) -> None:"""
Set a legal hold on a specific file in a bucket.
Args:
s3_client: Boto3 S3 client.
bucket: The name of the bucket containing the file.
key: The key of the file to set the legal hold on.
"""print()
logger.info("Setting legal hold on file [%s] in bucket [%s]", key, bucket)
try:
before_status = "OFF"
after_status = "ON"
s3_client.put_object_legal_hold(
Bucket=bucket, Key=key, LegalHold={"Status": after_status}
)
logger.debug(
"Legal hold set successfully on file [%s] in bucket [%s]", key, bucket
)
_print_legal_hold_update(bucket, key, before_status, after_status)
except Exception as e:
logger.error(
"Failed to set legal hold on file [%s] in bucket [%s]: %s", key, bucket, e
)
如需 API 詳細資訊,請參閱《適用於 AWS Python (Boto3) 的 SDK API 參考》中的 PutObjectLegalHold。
///<summary>/// Set or modify a legal hold on an object in an S3 bucket.///</summary>///<param name="bucketName">The bucket of the object.</param>///<param name="objectKey">The key of the object.</param>///<param name="holdStatus">The On or Off status for the legal hold.</param>///<returns>True if successful.</returns>publicasync Task<bool> ModifyObjectLegalHold(string bucketName,
string objectKey, ObjectLockLegalHoldStatus holdStatus){try{var request = new PutObjectLegalHoldRequest()
{
BucketName = bucketName,
Key = objectKey,
LegalHold = new ObjectLockLegalHold()
{
Status = holdStatus
}
};
var response = await _amazonS3.PutObjectLegalHoldAsync(request);
Console.WriteLine($"\tModified legal hold for {objectKey} in {bucketName}.");
return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
}
catch (AmazonS3Exception ex)
{
Console.WriteLine($"\tError modifying legal hold: '{ex.Message}'");
returnfalse;
}
}