(aws_elasticloadbalancingv2): (RuntimeError: Error: Region is required to enable ELBv2 access logging)
Describe the bug
When trying to enable access logs for a elbv2 application load balancer, I get the RunTimeError Error: Region is required to enable ELBv2 access logging I have confirmed that the region is set in my stack and I also have tried specifying it in the CLI but I get the same error. I am using the us-west-2 region.
My code to set it up is:
load_balancer = elb.ApplicationLoadBalancer(
self,
f"{stage_name}-LB",
load_balancer_name=f"{stage_name}-LB",
vpc=vpc,
internet_facing=True,
security_group=self.load_balancer_security_group,
idle_timeout=Duration.seconds(600),
vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
)
load_balancer.log_access_logs(
bucket=s3.Bucket.from_bucket_arn(
self, "AccessLogBucket", access_log_bucket.bucket_arn
)
)
Regression Issue
- [ ] Select this option if this issue appears to be a regression.
Last Known Working CDK Version
No response
Expected Behavior
This should be setting the region from either my stack env region or region in the CLI
Current Behavior
Here is the sanitized error:
jsii.errors.JavaScriptError:
@jsii/kernel.RuntimeError: Error: Region is required to enable ELBv2 access logging
at Kernel._Kernel_ensureSync (/tmp/tmpjgil7csr/lib/program.js:9511:23)
at Kernel.invoke (/tmp/tmpjgil7csr/lib/program.js:8874:102)
at KernelHost.processRequest (/tmp/tmpjgil7csr/lib/program.js:10718:36)
at KernelHost.run (/tmp/tmpjgil7csr/lib/program.js:10678:22)
at Immediate._onImmediate (/tmp/tmpjgil7csr/lib/program.js:10679:46)
at process.processImmediate (node:internal/timers:478:21)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<code_dir>/infrastructure/app.py", line 12, in <module>
DevStack(
~~~~~~~~^
app,
^^^^
...<4 lines>...
),
^^
)
^
File "<code_dir>/infrastructure/.venv/lib64/python3.13/site-packages/jsii/_runtime.py", line 118, in __call__
inst = super(JSIIMeta, cast(JSIIMeta, cls)).__call__(*args, **kwargs)
File "<code_dir>/infrastructure/infrastructure/infrastructure_stack.py", line 16, in __init__
self.load_balancer = LoadBalancer(
~~~~~~~~~~~~^
self,
^^^^^
"LoadBalancer",
^^^^^^^^^^^^^^^
vpc=self.network_stack.vpc,
^^^^^^^^^^^^^^^^^^^^^^^^^^^
)
^
File "<code_dir>/infrastructure/.venv/lib64/python3.13/site-packages/jsii/_runtime.py", line 118, in __call__
inst = super(JSIIMeta, cast(JSIIMeta, cls)).__call__(*args, **kwargs)
File "<code_dir>/infrastructure/infrastructure/load_balancer_stack.py", line 95, in __init__
load_balancer.log_access_logs(
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
bucket=s3.Bucket.from_bucket_arn(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
self, "AccessLogBucket", access_log_bucket.bucket_arn
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
)
^
)
^
File "<code_dir>/infrastructure/.venv/lib64/python3.13/site-packages/aws_cdk/aws_elasticloadbalancingv2/__init__.py", line 23355, in log_access_logs
return typing.cast(None, jsii.invoke(self, "logAccessLogs", [bucket, prefix]))
~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<code_dir>/infrastructure/.venv/lib64/python3.13/site-packages/jsii/_kernel/__init__.py", line 149, in wrapped
return _recursize_dereference(kernel, fn(kernel, *args, **kwargs))
~~^^^^^^^^^^^^^^^^^^^^^^^^^
File "<code_dir>/infrastructure/.venv/lib64/python3.13/site-packages/jsii/_kernel/__init__.py", line 399, in invoke
response = self.provider.invoke(
InvokeRequest(
...<3 lines>...
)
)
File "<code_dir>/infrastructure/.venv/lib64/python3.13/site-packages/jsii/_kernel/providers/process.py", line 380, in invoke
return self._process.send(request, InvokeResponse)
~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
File "<code_dir>/infrastructure/.venv/lib64/python3.13/site-packages/jsii/_kernel/providers/process.py", line 342, in send
raise RuntimeError(resp.error) from JavaScriptError(resp.stack)
RuntimeError: Error: Region is required to enable ELBv2 access logging
Subprocess exited with error 1
Reproduction Steps
This is the snippet of code I am using the create the load balancer and attach the access_logs bucket
load_balancer = elb.ApplicationLoadBalancer(
self,
f"{stage_name}-LB",
load_balancer_name=f"{stage_name}-LB",
vpc=vpc,
internet_facing=True,
security_group=self.load_balancer_security_group,
idle_timeout=Duration.seconds(600),
vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
)
load_balancer.log_access_logs(
bucket=s3.Bucket.from_bucket_arn(
self, "AccessLogBucket", access_log_bucket.bucket_arn
)
)
Possible Solution
No response
Additional Information/Context
No response
CDK CLI Version
2.173.4 (build 1dadd61)
Framework Version
No response
Node.js Version
v20.10.0
OS
Fedora Linux 41 (Workstation Edition)
Language
Python
Language Version
Python 3.13.1
Other information
There is a similar closed issue: https://github.com/aws/aws-cdk/issues/25007
Hey @tylerclair , thanks for reaching out.
Did you mention Environment variables in your /bin folder file like this -
env: { account: '123456789012', region: 'us-west-2' },
Hi @khushail,
I do have my environment specified in my app.py calling my stack
import os
import aws_cdk as cdk
from infrastructure.infrastructure_stack import DevStack
app = cdk.App()
DevStack(
app,
"DevStack",
env=cdk.Environment(
account=os.getenv("AWS_DEFAULT_ACCOUNT"),
region=os.getenv("AWS_DEFAULT_REGION", "us-west-2"),
),
)
app.synth()
I have also confirmed that the env variables for the account and region are properly set and can be retrieved.
@tylerclair , I tried to reproduce the error with the given code in Typescript and here is my observation -
code in /lib/load_balancer_issue-stack.ts -
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as elb from 'aws-cdk-lib/aws-elasticloadbalancingv2';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as s3 from 'aws-cdk-lib/aws-s3';
// import * as sqs from 'aws-cdk-lib/aws-sqs';
export class LoadBalancerIssueStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const vpc = new ec2.Vpc(this, 'VPC', {
maxAzs: 2,
});
const load_balancer_security_group = new ec2.SecurityGroup(this, 'LoadBalancerSecurityGroup', {
vpc: vpc,
allowAllOutbound: true,
});
const load_balancer = new elb.ApplicationLoadBalancer(this, 'LoadBalancer', {
vpc: vpc,
internetFacing: true,
securityGroup: load_balancer_security_group,
idleTimeout: cdk.Duration.seconds(600),
});
const accessLogsBucket = new s3.Bucket(this, 'LoadBalancerAccessLogsBucket', {
removalPolicy: cdk.RemovalPolicy.DESTROY,
});
load_balancer.logAccessLogs(accessLogsBucket, 'access_logs/');
}
}
Initial error produced with mentioning region/account -
^
Error: Region is required to enable ELBv2 access logging
at ApplicationLoadBalancer.resourcePolicyPrincipal (/Users/khushail/loadBalancerIssue/node_modules/aws-cdk-lib/aws-elasticloadbalancingv2/lib/shared/base-load-balancer.js:1:6204)
at ApplicationLoadBalancer.logAccessLogs (/Users/khushail/loadBalancerIssue/node_modules/aws-cdk-lib/aws-elasticloadbalancingv2/lib/alb/application-load-balancer.js:1:7586)
at new LoadBalancerIssueStack (/Users/khushail/loadBalancerIssue/lib/load_balancer_issue-stack.ts:32:19)
at Object.<anonymous> (/Users/khushail/loadBalancerIssue/bin/load_balancer_issue.ts:6:1)
at Module._compile (node:internal/modules/cjs/loader:1469:14)
at Module.m._compile (/Users/khushail/loadBalancerIssue/node_modules/ts-node/src/index.ts:1618:23)
at Module._extensions..js (node:internal/modules/cjs/loader:1548:10)
at Object.require.extensions.<computed> [as .ts] (/Users/khushail/loadBalancerIssue/node_modules/ts-node/src/index.ts:1621:12)
at Module.load (node:internal/modules/cjs/loader:1288:32)
at Function.Module._load (node:internal/modules/cjs/loader:1104:12)
Subprocess exited with error 1
but as soon as I mentioned this in the bin/load_balancer_issue.ts -
const app = new cdk.App();
new LoadBalancerIssueStack(app, 'LoadBalancerIssueStack', {
env: { account: '123456789012', region: 'us-east-2' },
});
the code successfully synthesized , sharing a snippet of synthesized template-
Same gets synthesized in Python as well -
Hope this would be helpful. Let me know if still having issues.
This issue has not received a response in a while. If you want to keep this issue open, please leave a comment below and auto-close will be canceled.
@khushail I was able to solve it by explicitly passing the environment to the stacks within my devstack. I worked with another developer who had the same issue and the way he solved it was along the same lines as what you had posted. I adapted it to Python in a slightly different way, not sure if its the right way but the error doesn't happen anymore.
Folder structure:
- app.py
- infrastructure
- compute_stack.py
- infrastructure_stack.py -- (main stack)
- load_balancer_stack.py
- network_stack.py
- redis_stack.py
I worked with another developer who had the same issue and the way he solved it was along the same lines as what you had posted. I adapted it to Python in a slightly different way.
my app.py file:
import os
import aws_cdk as cdk
from infrastructure.infrastructure_stack import DevStack
app = cdk.App()
DevStack(
app,
"DevStack",
env=cdk.Environment(
account=os.getenv("AWS_DEFAULT_ACCOUNT"),
region=os.getenv("AWS_DEFAULT_REGION"),
),
)
app.synth()
my infrastructure/infrastructure_stack.py:
import os
from aws_cdk import Stack
from constructs import Construct
from infrastructure.network_stack import NetworkStack
from infrastructure.compute_stack import ComputeStack
from infrastructure.load_balancer_stack import LoadBalancer
from infrastructure.redis_stack import RedisStack
class DevStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs):
super().__init__(scope, construct_id, **kwargs)
env = kwargs.get("env")
self.network_stack = NetworkStack(self, "NetworkStack", env=env)
self.load_balancer = LoadBalancer(
self, "LoadBalancer", vpc=self.network_stack.vpc, env=env
)
self.compute_stack = ComputeStack(
self,
"ComputeStack",
vpc=self.network_stack.vpc,
load_balancer_security_group=self.load_balancer.load_balancer_security_group,
load_balancer_security_group_usu=self.load_balancer.load_balancer_security_group_usu_traffic,
env=env,
)
self.redis_stack = RedisStack(
self,
"RedisStack",
vpc=self.network_stack.vpc,
ecs_security_group=self.compute_stack.ecs_security_group,
env=env,
)
my infrastucture/load_balancer.py:
class LoadBalancer(Stack):
def __init__(
self,
scope: Construct,
construct_id: str,
vpc: ec2.Vpc,
**kwargs,
):
super().__init__(scope, construct_id, **kwargs)
access_log_bucket = s3.Bucket(
self,
"LB-Logs",
bucket_name=f"{stage_name}-lb-logs",
versioned=False,
public_read_access=False,
removal_policy=RemovalPolicy.RETAIN,
)
access_log_bucket.add_to_resource_policy(
iam.PolicyStatement(
effect=iam.Effect.ALLOW,
principals=[iam.ArnPrincipal("arn:aws:iam::797873946194:root")],
actions=["s3:PutObject"],
resources=[f"{access_log_bucket.bucket_arn}/*"],
)
)
access_log_bucket.add_lifecycle_rule(expiration=Duration.days(30))
load_balancer = elb.ApplicationLoadBalancer(
self,
f"{stage_name}-LB",
load_balancer_name=f"{stage_name}-LB",
vpc=vpc,
internet_facing=True,
security_group=self.load_balancer_security_group,
idle_timeout=Duration.seconds(600),
vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
)
load_balancer.log_access_logs(
bucket=s3.Bucket.from_bucket_arn(
self, "AccessLogBucket", access_log_bucket.bucket_arn
)
)
@tylerclair , Since you are able to solve this, should this issue be closed ?
This issue has not received a response in a while. If you want to keep this issue open, please leave a comment below and auto-close will be canceled.
It did solve the issue, I will go ahead and close it. Thanks for your help!
Comments on closed issues and PRs are hard for our team to see. If you need help, please open a new issue that references this one.