首页 > 解决方案 > 从运行 ECS 任务的容器中检索元数据时出现连接错误

问题描述

我正在尝试检索在容器中运行 ECS 任务的实例所在的实际区域。容器运行一个 python 脚本,第一个任务是获取区域,以便我可以使用 boto3 方法sqs.get_queue_by_name(),例如需要设置区域的方法。为此,我尝试让该地区与

meta = requests.get('http://169.254.169.254/latest/dynamic/instance-identity/document', timeout=1).json()
os.environ["AWS_DEFAULT_REGION"] = meta.get("region")

但我遇到了连接错误。

当我手动构建堆栈时,没有问题,但是当堆栈由 CDK 部署时(相同的安全组、角色等),我得到了错误

requests.exceptions.ConnectionError: HTTPConnectionPool(host='169.254.169.254', port=80): Max retries exceeded with url: /latest/dynamic/instance-identity/document (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fe3d62491f0>: Failed to establish a new connection: [Errno 22] Invalid argument'))

我可以看到解决此问题的两种不同途径:

[编辑]

在容器内部(实例运行时我可以登录到容器),我可以 ping 说 google.com,但不能 ping 实例元数据 URI:

import requests
requests.get("https://www.google.com", timeout=1) ---> Response200
requests.get("http://169.254.169.254/latest/meta-data/", timeout=1) ---> ConnectTimeout Exception

[解决方案]

重复相关的问题?

标签: dockernetworkingboto3amazon-ecsaws-cdk

解决方案


推荐阅读