Skip to content

Instantly share code, notes, and snippets.

@decagondev
Created December 26, 2024 22:28
Show Gist options
  • Save decagondev/779c0a9fe7793c2822bce27d131f5fba to your computer and use it in GitHub Desktop.
Save decagondev/779c0a9fe7793c2822bce27d131f5fba to your computer and use it in GitHub Desktop.
import subprocess
import json
import os
import time
from pathlib import Path
def run_command(command, shell=True):
"""Execute a shell command and return the output"""
try:
result = subprocess.run(command, shell=shell, check=True, capture_output=True, text=True)
return result.stdout.strip()
except subprocess.CalledProcessError as e:
print(f"Error executing command: {command}")
print(f"Error message: {e.stderr}")
raise
def get_user_input(prompt, default=None):
"""Get user input with an optional default value"""
if default:
response = input(f"{prompt} [{default}]: ").strip()
return response if response else default
return input(f"{prompt}: ").strip()
def validate_jar_file(jar_path):
"""Validate that the JAR file exists"""
return os.path.exists(jar_path)
def main():
print("AWS Lambda Deployment Script")
print("===========================")
project_name = get_user_input("Enter project name")
region = get_user_input("Enter AWS region", "us-east-1")
account_id = get_user_input("Enter AWS account ID")
role_name = get_user_input("Enter IAM role name for Lambda execution")
handler_path = get_user_input(
"Enter Lambda handler path",
"com.example.lambda.PostRequestHandler::handleRequest"
)
print("\nBuilding project with Gradle...")
try:
run_command("gradle clean build")
except subprocess.CalledProcessError:
print("Failed to build project. Please ensure Gradle is installed and the build is configured correctly.")
return
build_dir = Path("build/libs")
jar_files = list(build_dir.glob("*.jar"))
if not jar_files:
print("No JAR files found in build/libs directory")
return
jar_file = jar_files[0]
print(f"Found JAR file: {jar_file}")
zip_filename = "function.zip"
print(f"\nCreating zip file: {zip_filename}")
run_command(f"zip {zip_filename} {jar_file}")
print("\nCreating Lambda function...")
lambda_create_command = f"""
aws lambda create-function \
--function-name {project_name} \
--runtime java11 \
--role arn:aws:iam::{account_id}:role/{role_name} \
--handler {handler_path} \
--timeout 15 \
--memory-size 512 \
--zip-file fileb://{zip_filename}
"""
lambda_response = json.loads(run_command(lambda_create_command))
function_arn = lambda_response["FunctionArn"]
print("\nCreating API Gateway...")
api_create_command = """
aws apigatewayv2 create-api \
--name "{project_name}API" \
--protocol-type "HTTP"
"""
api_response = json.loads(run_command(api_create_command))
api_id = api_response["ApiId"]
print("\nCreating Lambda integration...")
integration_command = f"""
aws apigatewayv2 create-integration \
--api-id {api_id} \
--integration-type AWS_PROXY \
--integration-uri {function_arn}
"""
run_command(integration_command)
print("\nCreating API route...")
route_command = f"""
aws apigatewayv2 create-route \
--api-id {api_id} \
--route-key "POST /post"
"""
run_command(route_command)
print("\nDeploying API...")
deploy_command = f"""
aws apigatewayv2 create-deployment \
--api-id {api_id}
"""
run_command(deploy_command)
print("\nAdding Lambda permissions...")
permission_command = f"""
aws lambda add-permission \
--function-name {project_name} \
--statement-id ApiGatewayInvokePermission \
--action lambda:InvokeFunction \
--principal apigateway.amazonaws.com \
--source-arn arn:aws:execute-api:{region}:{account_id}:{api_id}/*/POST/post
"""
run_command(permission_command)
api_endpoint = f"https://{api_id}.execute-api.{region}.amazonaws.com/post"
print("\nDeployment Complete!")
print("===================")
print(f"API Endpoint: {api_endpoint}")
print("\nTest your API with:")
print(f'curl -X POST -H "Content-Type: application/json" -d \'{"name":"test"}\' {api_endpoint}')
deployment_info = {
"project_name": project_name,
"function_arn": function_arn,
"api_id": api_id,
"api_endpoint": api_endpoint,
"region": region
}
with open("deployment_info.json", "w") as f:
json.dump(deployment_info, f, indent=2)
print("\nDeployment information saved to deployment_info.json")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment