【发布时间】:2022-02-08 14:06:46
【问题描述】:
我正在学习 AWS CDK,这是一个我似乎无法弄清楚的问题。 JS/Node 不是我经常使用的语言,所以如果有一些明显的原生我遗漏的东西,请不要太苛刻。我正在尝试将容器部署到现有 VPC/新 ECS 集群。下面的代码不是我的整个脚本,而是一个重要的部分。希望它能给出我想要做什么的想法。
//import everything first
stack_name = "frontend";
class Frontend extends core.Stack {
constructor(scope, id, props = {}) {
super(scope, id);
console.log("env variable " + JSON.stringify(props));
const base_platform = new BasePlatform(this, id, props);
//this bit doesn't matter, I'm just showing the functions I'm calling to set everything up
const fargate_load_balanced_service = ecs_patterns.ApplicationLoadBalancedFargateService();
this.fargate_load_balanced_service.taskDefinition.addToTaskRolePolicy();
this.fargate_load_balanced_service.service.connections.allowTo();
const autoscale = this.fargate_load_balanced_service.service.autoScaleTaskCount({});
this.autoscale.scale_on_cpu_utilization();
}
}
class BasePlatform extends core.Construct {
constructor(scope, id, props = {}) {
super(scope, id);
this.environment_name="frontend";
console.log("environment variables " + JSON.stringify(process.env));
//This bit is my problem child
const vpc = ec2.Vpc.fromLookup(
this, "VPC",{
vpcId: 'vpc-##########'
});
//this bit doesn't matter, I'm just showing the functions I'm calling to set everything up
const sd_namespace = service_discovery.PrivateDnsNamespace.from_private_dns_namespace_attributes();
const ecs_cluster = ecs.Cluster.from_cluster_attributes();
const services_sec_grp = ec2.SecurityGroup.from_security_group_id();
}
}
const app = new core.App();
_env = {account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION };
new Frontend(app, stack_name, {env: _env});
app.synth();
当我运行 CDK 合成器时,它会吐出:
错误:无法从上下文提供程序 vpc-provider 检索值,因为未在堆栈级别指定帐户/区域。在定义堆栈时使用显式帐户和区域配置“env”,或使用环境变量“CDK_DEFAULT_ACCOUNT”和“CDK_DEFAULT_REGION”从 CLI 继承环境信息(不建议用于生产堆栈)
但我不知道为什么。我在这里的用法适合 Stackoverflow 对类似问题的其他几个答案,它不像 AWS 文档中的示例,当我使用 console.log(process.env) 时,它会吐出 CDK_DEFAULT_REGION 和 CDK_DEFAULT_ACCOUNT 的正确/预期值。当我记录“env”时,它也会吐出预期值。
所以我的问题是,如何配置我的环境以便 ec2.Vpc.fromLookup 知道我的帐户信息,或者如何将值正确传递给“env”?
【问题讨论】:
-
@Mithilesh_Kunal 虽然设置了环境变量。当我注销
process.env时,它们就在那里。那么为什么ec2.Vpc.fromLookup会抛出一个抱怨它们的错误呢?它们已设置。
标签: javascript node.js amazon-web-services aws-cdk