Unable to create EC2 with CDK using existing VPC in Python

Viewed 28

Trying to access VPC via CDK 2.0, using python


from constructs import Construct

dirname = os.path.dirname(__file__)


class EC2InstanceStack(Stack):

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

        vpc = ec2.Vpc.from_lookup(self, "vpc", vpc_id='vpc-0912xxxxxxx94647')

Getting below error, not sure how to pass the account and region in my code

Traceback (most recent call last):
  File "/Users/..../external/aws-cdk-examples/python/ec2/instance/app.py", line 86, in <module>
    EC2InstanceStack(app, "ec2-instance")
  File "/Users/...../projects/cdk_workshop/.venv/lib/python3.10/site-packages/jsii/_runtime.py", line 86, in __call__
    inst = super().__call__(*args, **kwargs)
  File "/Users/...../external/aws-cdk-examples/python/ec2/instance/app.py", line 49, in __init__
    vpc = ec2.Vpc.from_lookup(self, "vpc", vpc_id='vpc-091234581ee4994647')
  File "/Users/..../CDK/projects/cdk_workshop/.venv/lib/python3.10/site-packages/aws_cdk/aws_ec2/__init__.py", line 65179, in from_lookup
    return typing.cast(IVpc, jsii.sinvoke(cls, "fromLookup", [scope, id, options]))
  File "/Users/...../projects/cdk_workshop/.venv/lib/python3.10/site-packages/jsii/_kernel/__init__.py", line 148, in wrapped
    return _recursize_dereference(kernel, fn(kernel, *args, **kwargs))
  File "/Users/...../CDK/projects/cdk_workshop/.venv/lib/python3.10/site-packages/jsii/_kernel/__init__.py", line 405, in sinvoke
    response = self.provider.sinvoke(
  File "/Users/..../CDK/projects/cdk_workshop/.venv/lib/python3.10/site-packages/jsii/_kernel/providers/process.py", line 365, in sinvoke
    return self._process.send(request, InvokeResponse)
  File "/Users/..../CDK/projects/cdk_workshop/.venv/lib/python3.10/site-packages/jsii/_kernel/providers/process.py", line 329, in send
    raise JSIIError(resp.error) from JavaScriptError(resp.stack)
jsii.errors.JSIIError: Cannot retrieve value from context provider vpc-provider since account/region are not specified at the stack level. Configure "env" with an account and region when you define your stack.See https://docs.aws.amazon.com/cdk/latest/guide/environments.html for more details.

Any idea ??

1 Answers

Looks like the answer is in your error message :)

jsii.errors.JSIIError: Cannot retrieve value from context provider vpc-provider since account/region are not specified at the stack level. Configure "env" with an account and region when you define your stack.See https://docs.aws.amazon.com/cdk/latest/guide/environments.html for more details.
Related