“botocore.exceptions.NoRegionError:您必须指定一个区域。” 部署到 ECR 时

Drk*_*Str 4 amazon-web-services amazon-ecs boto3 aws-cdk

我按照教程使用 CDK 部署到 ECS,但是当我部署时,部署后出现此错误

botocore.exceptions.NoRegionError: You must specify a region.
Run Code Online (Sandbox Code Playgroud)

这是我正在部署的内容。

应用程序.py

#!/usr/bin/env python3
from os import environ

from aws_cdk import core as cdk

from ecs_test.ecs_test_stack import EcsTestStack

_env=cdk.Environment(account=environ["CDK_DEFAULT_ACCOUNT"], region='ap-southeast-2')
app = cdk.App()
EcsTestStack(app, "EcsTestStackV3", env=_env)
app.synth()
Run Code Online (Sandbox Code Playgroud)

ecs_test_stack.py

from aws_cdk import core, aws_ecs_patterns, aws_ec2, aws_ecs


class EcsTestStack(core.Stack):

def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
    super().__init__(scope, construct_id, **kwargs)

    _container_image = aws_ecs.ContainerImage.from_asset(
        directory=".",
        file='Dockerfile.ECS_Test',
        exclude=["cdk.out"]
    )

    vpc = aws_ec2.Vpc(self, "ecs-test-vpc-v3", max_azs=3)

    cluster = aws_ecs.Cluster(self, "ecs-test-cluster-v3", vpc=vpc)

    cluster.add_capacity("ecs-autoscaling-capacity-v3",
                         instance_type=aws_ec2.InstanceType("t2.small"),
                         min_capacity=1,
                         max_capacity=3)

    self.ecs_test = aws_ecs_patterns.QueueProcessingEc2Service(
        self,
        "ECS_Test_Pattern_v3",
        cluster=cluster,
        cpu=512,
        memory_limit_mib=512,
        image=_container_image,
        min_scaling_capacity=1,
        max_scaling_capacity=5
    )
Run Code Online (Sandbox Code Playgroud)

Dockerfile.ECS_测试

from alpine:3.8

RUN apk add -U python3 py3-pip && pip3 install awscli boto3

COPY ./ecs_test/queue_service.py /queue_service.py

CMD ["/queue_service.py","receive"]
Run Code Online (Sandbox Code Playgroud)

队列服务.py

#!/usr/bin/env python3

from boto3 import resource
from os import getenv
from time import sleep
from random import randrange
from sys import argv


def get_queue_details():
    sqs = resource('sqs')
    print(getenv('QUEUE_NAME'))
    return sqs.get_queue_by_name(QueueName=getenv('QUEUE_NAME'))


def receive():
    queue = get_queue_details()
    while True:
        for message in queue.receive_messages():
            print("MESSAGE CONSUMED: {}".format(message.body))
            print(message.delete())
            sleep(1)


def send(num_messages=100):
    queue = get_queue_details()
    for _num in range(num_messages):
        _rand = randrange(1000)
        print(queue.send_message(MessageBody=str(_rand)))


if __name__ == '__main__':
    try:
        if argv[1] == 'send':
            send()
        if argv[1] == 'receive':
            receive()
    except IndexError as I:
        print("Please pass either send or receive.\n./queue_service.py <send> <receive>")
        exit(200)
Run Code Online (Sandbox Code Playgroud)

queue_service.py 在我的系统上本地运行时运行良好,但是当我使用 CDK 进行部署并填满队列时,我收到错误botocore.exceptions.NoRegionError: You must specify a region.

问:如何设置ECS的地域?

Jyo*_*r S 12

您必须告知 Boto3 您要在哪个区域使用 sqs 资源。

在queue_service.py中为sqs资源设置region_name

sqs = resource('sqs', region_name='us-west-2')
Run Code Online (Sandbox Code Playgroud)

或者

AWS_DEFAULT_REGION在queue_service.py中设置环境变量

os.environ['AWS_DEFAULT_REGION'] = 'us-west-2'
Run Code Online (Sandbox Code Playgroud)

或者

设置AWS_DEFAULT_REGION环境变量Dockerfile

ENV AWS_DEFAULT_REGION=us-west-2
Run Code Online (Sandbox Code Playgroud)

或者

设置环境变量ECS task definition