Skip to content

Commit 70e59bc

Browse files
author
Mike Shultz
authored
Merge pull request #10 from ApeWorX/feat/ecs-creds
feat: adds force_ecs_container_credentials kwarg to broker
2 parents d1907ca + cd535ac commit 70e59bc

2 files changed

Lines changed: 38 additions & 1 deletion

File tree

taskiq_sqs/aws.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import json
2+
import os
3+
4+
import urllib3 # boto3 peer dep (v1)
5+
6+
ECS_CONTAINER_METADATA_URI = "http://169.254.170.2"
7+
8+
9+
class InvalidEnvironment(Exception):
10+
pass
11+
12+
13+
def get_container_credentials():
14+
"""Fetches the ECS task role credentials provided by the metadata service"""
15+
if not (relative_uri := os.environ.get("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI")):
16+
raise InvalidEnvironment(
17+
"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI not defined. This may not be an ECS container."
18+
)
19+
20+
http = urllib3.PoolManager()
21+
resp = http.request("GET", f"{ECS_CONTAINER_METADATA_URI}{relative_uri}")
22+
return json.loads(resp.data)

taskiq_sqs/broker.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
from taskiq.exceptions import BrokerError
1717
from taskiq.message import BrokerMessage
1818

19+
from taskiq_sqs.aws import get_container_credentials
20+
1921
if TYPE_CHECKING:
2022
from mypy_boto3_sqs.service_resource import Queue, SQSServiceResource
2123

@@ -37,15 +39,28 @@ def __init__(
3739
result_backend: Optional[AsyncResultBackend] = None,
3840
task_id_generator: Optional[Callable[[], str]] = None,
3941
sqs_region_override: str | None = None,
42+
force_ecs_container_credentials=False,
4043
) -> None:
4144
super().__init__(result_backend, task_id_generator)
4245

4346
if not sqs_queue_url or not sqs_queue_url.startswith("http"):
4447
raise BrokerError("A valid SQS Queue URL is required")
4548

49+
creds = dict()
50+
# NOTE: This bypasses the normal order of operations for boto3 auth and
51+
# goes straight to using the ECS role creds from the metadata
52+
# service. This can be useful in edge cases where there are higher
53+
# priority credentials you do not want to use for this service.
54+
if force_ecs_container_credentials:
55+
creds = get_container_credentials()
56+
4657
self.sqs_queue_url = sqs_queue_url
4758
self._sqs: SQSServiceResource = boto3.resource(
48-
"sqs", region_name=sqs_region_override
59+
"sqs",
60+
region_name=sqs_region_override,
61+
aws_access_key_id=creds.get("AccessKeyId"),
62+
aws_secret_access_key=creds.get("SecretAccessKey"),
63+
aws_session_token=creds.get("Token"),
4964
)
5065
self._sqs_queue: Optional[Queue] = None
5166

0 commit comments

Comments
 (0)