AWS bucket with streamlit keys

I have entered my keys, secret ID and region associated with my AWS bucket and for some reason I am getting this error on my streamlit app when trying to get a list of the files in my bucket:

Error retrieving files: An error occurred (InvalidAccessKeyId) when calling the ListObjectsV2 operation: The AWS Access Key Id you provided does not exist in our records.

here’s my code:

import streamlit as st
import boto3
from botocore.exceptions import NoCredentialsError

# Retrieve AWS credentials and bucket info from secrets
aws_access_key_id = st.secrets["aws"]["access_key_id"]
aws_secret_access_key = st.secrets["aws"]["secret_access_key"]
region = st.secrets["aws"]["region"]
bucket_name = st.secrets["aws"]["bucket_name"]

# Function to list files in the S3 bucket
def list_s3_files():
    try:
        # Initialize a session using boto3 with AWS credentials from secrets
        s3_client = boto3.client(
            "s3",
            aws_access_key_id=aws_access_key_id,
            aws_secret_access_key=aws_secret_access_key,
            region_name=region
        )

        # List files in the specified S3 bucket
        response = s3_client.list_objects_v2(Bucket=bucket_name)

        # Check if there are any files in the bucket
        if 'Contents' in response:
            st.write(f"Files in S3 bucket '{bucket_name}':")
            for file in response['Contents']:
                st.write(f"- {file['Key']}")
        else:
            st.write(f"No files found in the bucket '{bucket_name}'.")
    except NoCredentialsError:
        st.error("Credentials not available.")
    except Exception as e:
        st.error(f"Error retrieving files: {e}")

# Display a button to trigger the file listing
if st.button("List S3 Bucket Files"):
    list_s3_files()

This error definitely means that the Access Key or any other credential is wrong.

I figured it out. It had to do with my conda virtual environment. I switched it and instead wrote the API keys to the .streamlit folder using the command: nano .streamlit/secrets.toml and my code worked fine

Great!

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.