[英]Create Terraform Cloudwatch Dashboards dynamically
Overview概述
Currently, dashboards are being deployed via Terraform using values from a dictionary in locals.tf:目前,仪表板正在通过 Terraform 使用 locals.tf 中字典中的值进行部署:
resource "aws_cloudwatch_dashboard" "my_alb" {
for_each = local.env_mapping[var.env]
dashboard_name = "${each.key}_alb_web_operational"
dashboard_body = templatefile("templates/alb_ops.tpl", {
environment = each.value.env,
account = each.value.account,
region = each.value.region,
alb = each.value.alb
tg = each.value.alb_tg
}
This leads to fragility because the values of AWS infrastructure resources like the ALB and ALB target group are hard coded.这会导致脆弱性,因为 AWS 基础设施资源(如 ALB 和 ALB 目标组)的值是硬编码的。 Sometimes when applying updates AWS resources are destroyed and recreated.
有时,在应用更新时,AWS 资源会被销毁并重新创建。
Question问题
What's the best approach to get these values dynamically?动态获取这些值的最佳方法是什么? For example, this could be achieved by writing a Python/Boto3 Lambda, which looks up these values and then passes them to Terraform as env variables.
例如,这可以通过编写 Python/Boto3 Lambda 来实现,它查找这些值,然后将它们作为环境变量传递给 Terraform。 Are there any other recommended ways to achieve the same?
还有其他推荐的方法可以达到同样的目的吗?
It depends on how much environment is dynamical .这取决于有多少环境是动态的。 But sounds like Terraformdata sources is what you are looking for.
但听起来 Terraform数据源就是你要找的。
Usually, loadbalancer names are fixed or generated by some rule and should be known before creating dashboard.通常,负载均衡器的名称是固定的或由某些规则生成的,在创建仪表板之前应该知道。
Let's suppose that names are fixed, and names are:假设名称是固定的,名称是:
variable "loadbalancers" {
type = object
default = {
alb01 = "alb01",
alb02 = "alb02"
}
}
In this case loadbalancers may be taken by:在这种情况下, 负载均衡器可能由以下人员承担:
data "aws_lb" "albs" {
for_each = var.loadbalancers
name = each.value # or each.key
}
And after that you will be able to get dynamically generated parameters:之后你将能够获得动态生成的参数:
If loadbalancer names are generated by some rule, you should use aws cli
or aws cdk
to get all names, or just generate names by same rule as it was generated inside AWS environment and pass inside Terraform variable.如果负载均衡器名称是由某些规则生成的,您应该使用
aws cli
或aws cdk
来获取所有名称,或者只按照与在 AWS 环境中生成的规则相同的规则生成名称,并在 Terraform 变量中传递。
Notice: terraform plan (apply, destroy)
will raise error if you pass non-existent name.注意:
terraform plan (apply, destroy)
如果传递不存在的名字会报错。 You should check if LB with provided name exists.您应该检查是否存在具有提供名称的 LB。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.