This guide shows you how to connect AWS Lambda to Microsoft SQL Server using PyODBC. Lambda doesn’t include ODBC drivers or the pyodbc library by default, so you need to package them yourself. We’ll cover two approaches: a Docker container image (recommended) and a Lambda layer.
Prerequisites
- Docker with Buildx installed locally (the examples use WSL2 Ubuntu on Windows)
- AWS CLI configured. see How to Install AWS CLI v2 on Ubuntu 22.04
- An Amazon ECR repository (for the container image approach)
- A SQL Server instance reachable from your Lambda’s VPC
- A Secrets Manager secret containing JSON fields
usernameandpassword, for a SQL Server login with only the permissions your application needs
For a private SQL Server, configure Lambda VPC subnets with a route to the database. Its execution role needs permissions to manage VPC network interfaces, commonly supplied by AWSLambdaVPCAccessExecutionRole. Allow database traffic on port 1433 between the relevant security groups. Secrets Manager also needs an HTTPS route: use a Secrets Manager interface VPC endpoint with private DNS and suitable security groups, or NAT access from the private subnet. See AWS’s VPC secret-access checklist.
What Gets Installed and Why
Connecting Lambda to SQL Server requires three components that aren’t included in the Lambda runtime:
- unixODBC. the ODBC driver manager for Linux. Installed from the Amazon Linux package repository.
- Microsoft ODBC Driver 18 for SQL Server (
msodbcsql18). the actual driver that speaks the SQL Server protocol. - pyodbc. the Python library that connects your code to the ODBC driver manager.
Method 1: Container Image (Recommended)
Container images are the simplest way to deploy Lambda functions with native dependencies. Everything is packaged in the Docker image. no layers to manage separately.
Dockerfile
This uses a multi-stage build to keep the final image small. The builder installs pyodbc and Microsoft’s driver. The final stage installs the runtime driver manager and receives the Python dependencies, Microsoft driver files, and driver registration.
Create a Dockerfile in your project root. Microsoft does not list Amazon Linux 2023 among its supported distributions. The RHEL 9 repository below is a compatibility workaround, so test it against your database before deployment. See Microsoft’s supported installation instructions.
FROM public.ecr.aws/lambda/python:3.12 AS builder
# Amazon Linux supplies the driver manager and Python's build dependencies.
RUN dnf install -y unixODBC unixODBC-devel gcc-c++ findutils \
&& dnf clean all
# Compatibility workaround: Microsoft does not list AL2023 as supported.
RUN curl -fsSL https://packages.microsoft.com/config/rhel/9/prod.repo \
-o /etc/yum.repos.d/mssql-release.repo \
&& ACCEPT_EULA=Y dnf install -y msodbcsql18 \
&& dnf clean all
RUN python -m pip install --no-cache-dir pyodbc boto3 -t /opt/python
# Resolve the installed library filename instead of guessing its version.
RUN driver=$(find /opt/microsoft/msodbcsql18/lib64 -name 'libmsodbcsql-18*.so*' -type f -print -quit) \
&& test -n "$driver" \
&& printf '[ODBC Driver 18 for SQL Server]\nDescription=Microsoft ODBC Driver 18 for SQL Server\nDriver=%s\nUsageCount=1\n' "$driver" > /opt/odbcinst.ini
FROM public.ecr.aws/lambda/python:3.12
RUN dnf install -y unixODBC openssl krb5-libs \
&& dnf clean all
COPY --from=builder /opt/python /opt/python
COPY --from=builder /opt/microsoft /opt/microsoft
COPY --from=builder /opt/odbcinst.ini /opt/odbcinst.ini
ENV PYTHONPATH=/opt/python
ENV ODBCSYSINI=/opt
# Fail the build if registration, imports, or native dependencies are missing.
RUN odbcinst -q -d -n 'ODBC Driver 18 for SQL Server' \
&& python -c "import pyodbc; assert 'ODBC Driver 18 for SQL Server' in pyodbc.drivers()" \
&& ! ldd /opt/microsoft/msodbcsql18/lib64/libmsodbcsql-18*.so* | grep 'not found'
COPY app.py ${LAMBDA_TASK_ROOT}/
CMD ["app.handler"]
The base image public.ecr.aws/lambda/python:3.12 uses Amazon Linux 2023, which uses dnf as its package manager. If you’re using Python 3.11 or earlier, the base image uses Amazon Linux 2 with yum instead. see Solve ‘yum: command not found’ in AWS Lambda Python 3.12 Base Image for details on this change.
Build and Deploy
Build the image, push it to ECR, and create or update the Lambda function:
docker buildx build --platform linux/amd64 --provenance=false --load -t lambda-pyodbc .
# Set these placeholders to your ECR registry and AWS Region.
ECR_REGISTRY=YOUR_ECR_REGISTRY
AWS_REGION=your-region
aws ecr get-login-password --region "$AWS_REGION" | \
docker login --username AWS --password-stdin "$ECR_REGISTRY"
docker tag lambda-pyodbc:latest "$ECR_REGISTRY/lambda-pyodbc:latest"
docker push "$ECR_REGISTRY/lambda-pyodbc:latest"
Replace YOUR_ECR_REGISTRY with your ECR registry hostname and your-region with your AWS Region. These commands push an image; create or update your Lambda function to use that image and select the x86_64 architecture.
Method 2: Lambda Layer
If you can’t use container images, package the dependencies as a Lambda layer. This approach builds the layer artifacts inside Docker and outputs a zip file you can upload to Lambda.
Use the same Python 3.12 runtime and x86_64 architecture for the image build, layer, and function. An arm64 function needs a separate build and compatible driver packages. Build Method 1’s image first, then create build-layer.sh:
#!/usr/bin/env bash
set -euo pipefail
mkdir -p output
# Build Method 1's Dockerfile first. Override Lambda's handler entrypoint.
docker run --rm --platform linux/amd64 --entrypoint /bin/bash \
-v "$(pwd)/output:/output" lambda-pyodbc -euo pipefail -c '
dnf install -y zip findutils
mkdir -p /opt/lib
# Bundle the native dependency closure, using the matching runtime glibc.
python - <<"PYTHON"
import glob
import os
import re
import shutil
import subprocess
queue = glob.glob("/opt/python/pyodbc*.so")
queue += glob.glob("/opt/microsoft/msodbcsql18/lib64/*.so*")
seen = set()
while queue:
library = queue.pop()
if library in seen:
continue
seen.add(library)
result = subprocess.run(["ldd", library], check=True, capture_output=True, text=True)
if "not found" in result.stdout:
raise RuntimeError(result.stdout)
for dependency in re.findall(r"=> (/\S+)", result.stdout):
owner = subprocess.check_output(
["rpm", "-qf", "--qf", "%{NAME}", dependency], text=True
).strip()
if owner == "glibc":
continue
shutil.copy2(dependency, "/opt/lib/" + os.path.basename(dependency))
queue.append(dependency)
PYTHON
export LD_LIBRARY_PATH="/opt/lib:${LD_LIBRARY_PATH:-}"
python -c "import pyodbc; assert \"ODBC Driver 18 for SQL Server\" in pyodbc.drivers()"
cd /opt
zip -r /output/pyodbc-layer.zip python lib microsoft odbcinst.ini
'
echo 'Layer built: output/pyodbc-layer.zip'
Run the script:
mkdir -p output
chmod +x build-layer.sh
./build-layer.sh
Upload the layer to AWS:
aws lambda publish-layer-version \
--layer-name pyodbc-mssql \
--zip-file fileb://output/pyodbc-layer.zip \
--compatible-runtimes python3.12 \
--compatible-architectures x86_64
Attach the layer to your Lambda function, and set these environment variables on the function:
LD_LIBRARY_PATH=/opt/lib:/var/lang/lib:/lib64:/usr/lib64:/var/runtime:/var/runtime/lib:/var/task:/var/task/lib
ODBCSYSINI=/opt
For more on building Lambda layers, see How to Build and Deploy Python Libraries for AWS Lambda Layers.
The Lambda Function
This function works with both the container image and layer approaches. It reads the server and database from environment variables, retrieves credentials from Secrets Manager, and runs a test query. Grant the execution role secretsmanager:GetSecretValue for that secret, plus kms:Decrypt if it uses a customer managed KMS key.
Create app.py:
import json
import os
import boto3
import pyodbc
secrets = boto3.client("secretsmanager")
def odbc_value(value):
# Braces keep semicolons and closing braces inside credential values.
return "{" + str(value).replace("}", "}}") + "}"
def handler(event, context):
response = secrets.get_secret_value(SecretId=os.environ["DB_SECRET_ID"])
credentials = json.loads(response["SecretString"])
conn_str = (
"DRIVER={ODBC Driver 18 for SQL Server};"
f"SERVER={odbc_value(os.environ['DB_SERVER'])};"
f"DATABASE={odbc_value(os.environ['DB_NAME'])};"
f"UID={odbc_value(credentials['username'])};"
f"PWD={odbc_value(credentials['password'])};"
"Encrypt=yes;TrustServerCertificate=no;"
)
conn = pyodbc.connect(conn_str, timeout=10)
try:
row = conn.cursor().execute("SELECT @@VERSION").fetchone()
return {"statusCode": 200, "body": row[0]}
finally:
conn.close()
Set these environment variables on your Lambda function:
| Variable | Example Value |
|---|---|
DB_SERVER |
sql.example.com,1433 |
DB_NAME |
mydb |
DB_SECRET_ID |
your-secret-name |
Store a least-privilege login such as lambda_reader in the secret, rather than sa. Keep its password out of code, environment variables, logs, and responses. The example validates the SQL Server certificate; its hostname must match DB_SERVER and its issuing CA must be trusted by the runtime.
Troubleshooting
Can’t find ODBC Driver 18
If you get Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 18 for SQL Server'"), check registration as well as dependencies. Confirm ODBCSYSINI=/opt, that /opt/odbcinst.ini names the installed driver library, and that /opt/microsoft/msodbcsql18/lib64/ exists. Use pyodbc.drivers() to inspect registration and ldd on the driver to find missing libraries. For a layer, preserve Lambda’s existing library search paths when adding /opt/lib.
Connection timeout
If the function times out, your Lambda likely can’t reach the SQL Server. Check that:
- The Lambda is deployed in a VPC with a subnet that can route to the SQL Server
- The security group allows outbound traffic on port 1433
- The SQL Server’s security group or firewall allows inbound from the Lambda’s security group
SSL/TLS errors
ODBC Driver 18 encrypts connections by default. Prefer Encrypt=yes;TrustServerCertificate=no; with a trusted certificate. For an isolated test with a self-signed certificate, Encrypt=yes;TrustServerCertificate=yes; encrypts traffic but skips server identity checks. It cannot make a server without TLS support accept TLS. Fix the server’s TLS configuration rather than disabling encryption for production.
yum: command not found (Python 3.12+)
Lambda base images for Python 3.12 and later use Amazon Linux 2023, which replaced yum with dnf. Replace all yum commands with dnf. Changing the package manager does not make a RHEL repository officially supported on AL2023; the compatibility caveat above still applies.
Conclusion
Your Lambda function can now query SQL Server using pyodbc. The container image approach is simpler to maintain since all dependencies live in the Docker image. The layer approach works when container images aren’t an option. If you’re building CI/CD pipelines to automate this, see Fix Docker Builds Hanging on the Microsoft GPG Key in GitLab CI/CD for common pipeline issues with this setup.


