S3 Check If File Exist By Getting Metadata

- 1 answer

I am trying to check if file exists in s3 bucket using AWS javascript sdk. I have defined my policy to Allow HeadBucket for my s3 bucket.

    "Version": "2012-10-17",
    "Statement": [
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "s3:HeadBucket",
            "Resource": "*"

I have attached the above policy to a user and I am using that user in setting up the config for the s3 as follows:


    "user1": {
        "bucket": "my-bucket",
        "region": "us-east-2",
        "accessKey": "********",
        "secretKey": "*********"

In my node.js code, I am trying to use headObject to get the meta data for the object as follows:

var AWS = require('aws-sdk');
var s3Config = require("../data/aws-config.json").user1;
var s3 = new AWS.S3;

var params = {
    Bucket: "my-bucket",
    Key: "mykey.PNG"
s3.headObject(params, function (err, metadata) {

This is giving me 403 Forbidden error. I have tried everything from changing AWS policy to allow all s3 operations to allow access to all resources, nothing seems to work.


I checked the AWS.config.credentials and it is loading some random accessKey and secretKey and not from my config file. I am not sure why this is happening.



You are trying to HEAD object. There's no HEAD bucket operation which is what your IAM policy grants.

To do HEAD operation on an object, you need s3:GetObject permission.

See docs for more information.