Skip to content

Instantly share code, notes, and snippets.

@jpalala
Created January 25, 2025 05:38
Show Gist options
  • Save jpalala/cca9f0f3368fd71af53f3bfbd6748419 to your computer and use it in GitHub Desktop.
Save jpalala/cca9f0f3368fd71af53f3bfbd6748419 to your computer and use it in GitHub Desktop.
poc java lambda writing to s3 file

Upload base64 encoded file to S3

  1. Encrypt the .env file locally (on linux / mac):
    base64 your-env-file.env > encrypted-env-file.env
  2. Upload the encrypted-env-file.env to S3 (via aws-cli)

Notes for Production

  1. IAM Role: Ensure the Lambda execution role has the s3:GetObject permission for the specific S3 bucket and file.
  2. Error Handling: Add better error handling for cases where the S3 object is unavailable.
  3. Testing: Test locally using AWS SAM or deploy the Lambda and test via API Gateway/CloudWatch logs.
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.Base64;
import java.util.concurrent.TimeUnit;
// AWS Lambda Handler
public class FeatureFlagHandler implements RequestHandler<Object, String> {
private static final String BUCKET_NAME = "your-s3-bucket";
private static final String FILE_KEY = "path/to/your/envfile.env";
private static final Cache<String, String> cache;
private final AmazonS3 s3Client;
static {
// Initialize cache with 30-second expiry
cache = CacheBuilder.newBuilder()
.expireAfterWrite(30, TimeUnit.SECONDS)
.build();
}
public FeatureFlagHandler() {
// Initialize S3 client
this.s3Client = AmazonS3ClientBuilder.defaultClient();
}
@Override
public String handleRequest(Object input, Context context) {
try {
return cache.get("featureFlags", this::fetchAndDecodeFeatureFlags);
} catch (Exception e) {
context.getLogger().log("Error fetching feature flags: " + e.getMessage());
return null;
}
}
// Fetch and decode feature flags from S3
private String fetchAndDecodeFeatureFlags() {
String encryptedData = s3Client.getObjectAsString(BUCKET_NAME, FILE_KEY);
return new String(Base64.getDecoder().decode(encryptedData));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment