Chắc hẵn các bạn đã nghe qua terraform module, terraform module là những modun mà việc sử dụng lại module đó cho nhiều component khác nhau.
Ví dụ bạn muốn tạo nhiều keyvault khác nhau nhưng thay vì mỗi khi tạo keyvault bạn phải viết nguyên một cái resource dài nhằng, bạn có thể viết một module rồi phía ngoài bạn muốn tạo bao nhiêu keyvault khác nhau bạn chỉ cần khai báo tên và các parameter kèm theo của keyvault đó.
Vậy cấu trúc khi viết một mudun trong terraform như thế nào.
Hình trên là cấu trúc thư mục và file của một modun terraform điển hình.
Các file main.tf và variables.tf của modun được bỏ vào thư mục Modules và thư mục con là tên của một resource. Trong hình trên modun đó là Resource_Group trong Azure Cloud.
Vậy trong file main.tf có gì.
Trước tiên bạn muốn viết resource group có những parameter nào thì bạn lên trang terraform:
https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/resource_group
resource "azurerm_resource_group" "example_rg" {
name = var.resource_group_name
location = var.location
tags = var.tags
}
Trong đó biến name và location là bắt buộc, biến tags thì là option.
Như vậy 3 biến trên đều khai trong file variables.tf
variable "resource_group_name" {
description = "The name of the module demo resource group in which the resources will be created"
type = string
default = "example_module_rg"
}
variable "location" {
description = "The location where module demo resource group will be created"
type = string
default = "East Us"
}
variable "tags" {
description = "A map of the tags to use for the module demo resources that are deployed"
type = map(string)
default = {
environment = "Example"
Owner = "vcloud-lab.com"
}
}
Các giá trị type là phải khai báo trong file variables.tf của modun terraform.
Hai file main.tf và variables.tf trên được bỏ trong thư mục Modules > Resource_Group
Phía ngoài file main.tf mình khai báo trỏ vào thư mục module như sau:
# Configure the Microsoft Azure Provider
provider "azurerm" {
features {}
}
module "Demo_Azure_Module_RG" {
source = "./Modules/Resource_Group"
resource_group_name = "demo_RG"
location = "West US"
tags = {
environment = "DemoRG"
Owner = "http://vcloud-lab.com"
}
}
module "Demo_Azure_Module_RG_2" {
source = "./Modules/Resource_Group"
resource_group_name = "demo_RG_2"
location = "West US"
tags = {
environment = "DemoRG"
Owner = "http://devopstechhub.com"
}
}
Nhận xét
Đăng nhận xét