source = "terraform-aws-modules/security-group/aws//modules/web" version = "3.17.0"
- name = "lb-sg-{var.resource_tags["environment"]}"
- name = "lb-sg-${local.name_suffix}"
...
}
module "elb_http" { source = "terraform-aws-modules/elb/aws" version = "2.4.0"
Ensure load balancer name is unique
- name = "lb-{var.resource_tags["project"]}-${var.resource_tags["environment"]}"
- name = "lb-{local.name_suffix}"
...
}
>
> * 请注意,负载均衡器名称**包含一个随机字符串**,以便这些**名称是唯一的**,这是 AWS 中**负载均衡器名称的要求**。
> * **应用配置以验证名称的值是否未更改**。
>
>
> + **`terraform apply`**
>
>
>
---
#### 将变量与局部值组合
>
> * 与**变量值不同**,**局部值可以使用动态表达式和资源参数**。
> * 许多项目要求以**某种方式标记所有资源以跟踪它们**。要**强制实施此要求**,请将**本地值与变量结合使用**,以便**分配给资源的标签至少包括项目名称和环境**。
> * 将以下**新变量定义**添加到**`variables.tf`**。
>
>
>
variable "project_name" { description = "Name of the project." type = string default = "my-project" }
variable "environment" { description = "Name of the environment." type = string default = "dev" }
>
> * 接下来,将**变量`resource_tags`的默认值更改为空映射**。
>
>
>
variable "resource_tags" { description = "Tags to set for all resources" type = map(string)
- default = {
-
project = "my-project", -
environment = "dev" - }
- default = { } }
>
> * 添加**新块`locals`以创建所需标签和用户定义标签组合**。
>
>
>
locals { required_tags = { project = var.project_name, environment = var.environment } tags = merge(var.resource_tags, local.required_tags) }
>
> * 可以在**单个块中定义配置本地值**,**也可以使用多个`locals`块**。
> * 更新**局部变量的定义以使用新变量**。
>
>
>
locals {
- name_suffix = "{var.resource_tags["environment"]}"
- name_suffix = "{var.environment}" }
>
> * 然后,**更新`main.tf`中的`tags`引用**,以**使用新的本地值**。
>
>
>
- tags = var.resource_tags
- tags = local.tags
... replace all five occurrences of tags = var.resource_tags
>
> * 最后,向**`output.tf`文件添加一个名为`tags`的输出**。此**输出将显示您在此配置中使用的标签**。
>
>
>
output "tags" { value = local.tags }
>
> * 现在,**应用这些更改以查看每个资源的标签**。
>
>
> + **`terraform apply`**
> * 接下来,**运行另一个 apply**,这次**将环境更改为`prod`**。
>
>
> + **`terraform apply -var "environment=prod"`**


**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**
**了解详情》docs.qq.com/doc/DSlVlZExWQ0FRSE9H**