Terraform 如何将地形代码重构为模块?
我从网络、虚拟机和数据库(在Azure中)的3个单独的terraform目录开始,我会在每个目录中应用Terraform 如何将地形代码重构为模块?,terraform,Terraform,我从网络、虚拟机和数据库(在Azure中)的3个单独的terraform目录开始,我会在每个目录中应用terraform terraform文件中存在一些重复,例如每个文件中的Azure资源组 # Create a resource group resource "azurerm_resource_group" "resource-group" { name = "terraform-rg" location = "eastus" } 因此,我现在想重新构造代码,以便从根目录下
terraform
terraform文件中存在一些重复,例如每个文件中的Azure资源组
# Create a resource group
resource "azurerm_resource_group" "resource-group" {
name = "terraform-rg"
location = "eastus"
}
因此,我现在想重新构造代码,以便从根目录下的单个main.tf
调用所有3个,并且我只执行terraform应用一次
但是,我对这一点还不熟悉,如果资源组位于根目录中,并且不再位于同一文件中,我不确定如何引用该资源组
例如,用于VM的vnet如下所示:
# Create a virtual network for the VM
resource "azurerm_virtual_network" "vm-vnet" {
name = "terraform-client1-vnet"
address_space = ["10.0.0.0/16"]
location = azurerm_resource_group.resource-group.location
resource_group_name = azurerm_resource_group.resource-group.name
}
location
和resource\u group\u name
不再解析,因为azurerm\u resource\u group.resource group
不再位于同一文件中,而是位于根目录下的main.tf
中
如何正确地重构它,从而解决所有问题
是否有import
语句?模块的工作方式如下
假设您有以下文件夹
modules
- resource-group
- networking
- vms
- databases
确保在模块资源组中设置正确的输出,如下所示
注意,在terraform版本v0.12+中,可能您不需要再设置输出变量,它应该可以直接工作,但我没有机会进行测试
在文件夹modules/resource group
下,您可以准备此文件main.tf
# Create a resource group
resource "azurerm_resource_group" "resource-group" {
name = "terraform-rg"
location = "eastus"
}
output "resource-group-location" {
value = azurerm_resource_group.resource-group.location
}
output "resource-group-name" {
value = azurerm_resource_group.resource-group.name
}
现在,您可以轻松地在其他模块中引用资源
module "resource-group"{
source = "../resource-group"
...
}
# Create a virtual network for the VM
resource "azurerm_virtual_network" "vm-vnet" {
name = "terraform-client1-vnet"
address_space = ["10.0.0.0/16"]
location = module.resource-group.resource-group-location
resource_group_name = module.resource-group.resource-group-name
}