How to check if retention tag is applied or not to S3 object, if applied don't apply tag again and if not applied apply the 10yearsretention tag to S3 object in CLI script

0

I tried with below command but it is not getting the results like if applied version Id of the tag if not applied not applying the tag to s3 object

Help me to write shell script

aws s3api get-object-tagging --bucket your-bucket --key your-object-key --query 'TagSet[?Key==retention && Value==10yearsretention || Value==6yearsretention]' >/dev/null 2>> error.log || aws s3api put-object-tagging --bucket your-bucket --key your-object-key --tagging 'TagSet=[{Key=retention,Value=10yearsretention}]' >> error.log

The above command not working properly, put-object command is working but not both commands correctly when combined

Results I am getting like [] when trying with aws s3api get-object-tagging --bucket your-bucket --key your-object-key --query 'TagSet[?Key==retention && Value==10yearsretention || Value==6yearsretention]'

2 Answers
0

try something like this.. pls check you key values accordingly


#!/bin/bash

# Set your AWS CLI profile, bucket name, and object key
AWS_PROFILE="your_aws_profile"
BUCKET_NAME="your_bucket_name"
OBJECT_KEY="your_object_key"

# Get the current object tagging
TAG_INFO=$(aws s3api get-object-tagging --bucket $BUCKET_NAME --key $OBJECT_KEY --profile $AWS_PROFILE --output json)

# Check if the desired retention tag is already applied
if [[ $TAG_INFO == *"\"Key\":\"retention\",\"Value\":\"10yearsretention\""* ]] || [[ $TAG_INFO == *"\"Key\":\"retention\",\"Value\":\"6yearsretention\""* ]]; then
    # Retention tag is already applied
    echo "Retention tag already applied to the S3 object. Skipping."
else
    # Retention tag not applied, apply the 10-year retention tag
    echo "Applying 10-year retention tag to the S3 object..."
    aws s3api put-object-tagging --bucket $BUCKET_NAME --key $OBJECT_KEY --tagging 'TagSet=[{Key=retention,Value=10yearsretention}]' --profile $AWS_PROFILE
    echo "Retention tag applied."
fi

AWS
answered a year ago
0

Thanks for your example @Tulasiram toorpu, I tried the above example, please check my observations below

I did like below: Manually i applied the retention tag to one S3 object and in the same folder other 3 objects are not having retention tag. So total 4 object only 1 is applied.

I ran the script for the first object it shows log like "Retention tag is already applied to specified S3 object. Skipping" Script completed

Second run, it is appling the retention tag to the already applied S3 object and not checking if that tag is already having key and value or not.

Third run, same thing happened likewise second run.

?

answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions