Tag an Object
Components
- Credentials
- Bucket Name
- Object Name
- Tag
- .NET
- PHP
- Python
- Javascript
- GO
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace PutObjectTags
{
class PutObjectTags
{
private const string bucketName = "<BUCKET_NAME>";
private const string objectName = "<OBJECT_NAME>";
private static IAmazonS3 _s3Client;
public static void Main()
{
var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("<ACCESS-KEY>", "<SECRET-KEY>");
var config = new AmazonS3Config { ServiceURL = "<ENDPOINT>" };
_s3Client = new AmazonS3Client(awsCredentials, config);
PutObjectTagsAsync().Wait();
}
private static async Task PutObjectTagsAsync()
{
try
{
var tagging = new Tagging
{
TagSet = new List<Tag>
{
new Tag
{
Key = "key1",
Value = "value1"
}
}
};
// Set a new Tag set for object.
PutObjectTaggingResponse response = await _s3Client.PutObjectTaggingAsync(new PutObjectTaggingRequest
{
BucketName = bucketName,
Key = objectName,
Tagging = tagging
});
Console.WriteLine($"Tag set added to {objectName} object");
}
catch (AmazonS3Exception amazonS3Exception)
{
Console.WriteLine("An AmazonS3Exception was thrown. Exception: " + amazonS3Exception.ToString());
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.ToString());
}
}
}
}
<?php
require('client.php');
$bucket = '<BUCKET_NAME>';
$params = [
'Bucket' => $bucket,
'ContentMD5' => '<string>',
'ExpectedBucketOwner' => '<string>',
'Key' => '<OBJECT_NAME>', // REQUIRED
'RequestPayer' => 'requester',
'Tagging' => [ // REQUIRED
'TagSet' => [ // REQUIRED
[
'Key' => '<string>', // REQUIRED
'Value' => '<string>', // REQUIRED
],
],
],
'VersionId' => '<string>',
];
try {
$resp = $client->putObjectTagging($params);
var_dump($resp);
} catch (AwsException $e) {
// Display error message
echo $e->getMessage();
echo "\n";
}
import boto3
import logging
from botocore.exceptions import ClientError
logging.basicConfig(level=logging.INFO)
try:
s3_client = boto3.client(
's3',
endpoint_url='<ENDPOINT>',
aws_access_key_id='<ACCESS-KEY>',
aws_secret_access_key='<SECRET-KEY>'
)
except Exception as exc:
logging.error(exc)
else:
try:
response = s3_client.put_object_tagging(
Bucket='<BUCKET_NAME>',
Key='<OBJECT_NAME>',
VersionId='string',
ContentMD5='string',
Tagging={
'TagSet': [
{
'Key': 'string',
'Value': 'string'
},
]
},
ExpectedBucketOwner='string',
RequestPayer='requester'
)
logging.info(response)
except ClientError as exc:
logging.error(exc)
// Import required AWS SDK clients and commands for Node.js
const { S3Client, PutObjectTaggingCommand } = require("@aws-sdk/client-s3");
// Create an S3 client service object
const s3 = new S3Client({
region: "default",
endpoint: "<ENDPOINT_URL>",
credentials: {
accessKeyId: "<ACCESS_KEY>",
secretAccessKey:
"<SECRET_KEY>",
},
});
const BUCKET_NAME = "<BUCKET_NAME>";
const run = async () => {
try {
const response = await s3.send(
new PutObjectTaggingCommand({
Bucket: BUCKET_NAME,
Key: "<OBJECT_NAME>",
Tagging: {
TagSet: [
{
Key: "key",
Value: "value",
},
],
},
})
);
console.log("Success", response);
} catch (err) {
console.log("Error", err);
}
};
run();
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
)
// Allows person with EMAIL address PERMISSION access to BUCKET OBJECT
// If PERMISSION is missing, they get READ access.
//
// Usage:
// go run s3_put_bucket_acl.go BUCKET OBJECT ACL
func main() {
if len(os.Args) < 3 {
exitErrorf("Bucket name and object name: go run", os.Args[0], "BUCKET OBJECT")
}
bucket := os.Args[1]
key := os.Args[2]
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
Credentials: credentials.NewStaticCredentials("<ACCESS-KEY>", "<SECRET-KEY>", ""),
})
svc := s3.New(sess, &aws.Config{
Region: aws.String("default"),
Endpoint: aws.String("<ENDPOINT>"),
})
params := &s3.PutObjectTaggingInput{
Bucket: &bucket,
Key: &key,
Tagging: &s3.Tagging{
TagSet: []*s3.Tag{
{
Key: aws.String("Key3"),
Value: aws.String("Value3"),
},
{
Key: aws.String("Key4"),
Value: aws.String("Value4"),
},
},
},
}
// Set bucket ACL
_, err = svc.PutObjectTagging(params)
if err != nil {
exitErrorf(err.Error())
}
fmt.Println("Congratulations. You put tags on object")
}
func exitErrorf(msg string, args ...interface{}) {
fmt.Fprintf(os.Stderr, msg+"\n", args...)
os.Exit(1)
}
The following command can be used to execute the aforementioned code, presuming the code file is called s3_put_object_tagging.go:
go run s3_put_object_tagging.go BUCKET OBJECT