Skip to content

Commit 65cfc79

Browse files
authored
Better handle failures to connect to SSM (#6)
* Add timeout * Handle errors
1 parent 230aa1a commit 65cfc79

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

pydantic_ssm_settings/source.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
1+
import os
12
import logging
23
from pathlib import Path
34
from typing import TYPE_CHECKING, Any, Dict, Optional, Union
45

6+
from botocore.exceptions import ClientError
7+
from botocore.client import Config
58
import boto3
69

710
from pydantic import BaseSettings, typing
@@ -21,7 +24,12 @@ def __init__(self, ssm_prefix: Union[typing.StrPath, None]):
2124

2225
@property
2326
def client(self) -> "SSMClient":
24-
return boto3.client("ssm")
27+
return boto3.client("ssm", config=self.client_config)
28+
29+
@property
30+
def client_config(self):
31+
timeout = float(os.environ.get("SSM_TIMEOUT", 0.5))
32+
return Config(connect_timeout=timeout, read_timeout=timeout)
2533

2634
def __call__(self, settings: BaseSettings) -> Dict[str, Any]:
2735
"""
@@ -39,9 +47,13 @@ def __call__(self, settings: BaseSettings) -> Dict[str, Any]:
3947

4048
logger.debug(f"Building SSM settings with prefix of {secrets_path=}")
4149

42-
params = self.client.get_parameters_by_path(
43-
Path=str(secrets_path), WithDecryption=True
44-
)["Parameters"]
50+
try:
51+
params = self.client.get_parameters_by_path(
52+
Path=str(secrets_path), WithDecryption=True
53+
)["Parameters"]
54+
except ClientError:
55+
logger.exception("Failed to get parameters from %s", secrets_path)
56+
return {}
4557

4658
return {
4759
str(Path(param["Name"]).relative_to(secrets_path)): param["Value"]

0 commit comments

Comments
 (0)