Trong terraform bạn định nghĩa các biến số bằng cách tạo một file variables.tf trong thư mục terraform.
File đó có dạng như sau :
variable "resource_group_name" { default = "myTFResourceGroup"}
Trong file này ta định nghĩa biến số là : resource_group_name có giá trị mặc định là: myTFResourceGroup. Giá trị của biến số đã được định nghĩa nên ta không cần phải nhập vào.
Bây giờ ta cập nhật cấu hình terraform của bạn với biến số của bạn định nghĩa ở trên.
resource "azurerm_resource_group" "rg" {+ name = var.resource_group_name- name = "myTFResourceGroup" location = "westus2" tags = { Environment = "Terraform Getting Started" Team = "DevOps" } }
Lúc này name của resource được lấy từ file variables.tf
Apply cấu hình terraform :
$ terraform apply Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions:##...Plan: 2 to add, 0 to change, 0 to destroy. Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value: yes azurerm_resource_group.rg: Creating...azurerm_resource_group.rg: Creation complete after 1s [id=/subscriptions/c9ed8610-47a3-4107-a2b2-a322114dfb29/resourceGroups/myTFResourceGroup]azurerm_virtual_network.vnet: Creating...azurerm_virtual_network.vnet: Creation complete after 7s [id=/subscriptions/c9ed8610-47a3-4107-a2b2-a322114dfb29/resourceGroups/myTFResourceGroup/providers/Microsoft.Network/virtualNetworks/myTFVnet] Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
Confirm YES khi đươc hỏi.
Trường hợp bây giờ bạn muốn ghi đè thông tin variable trên khi chạy terraform apply thì ta chạy như sau:
$ terraform apply -var "resource_group_name=myNewResourceGroupName"
Lúc này resource_group_name sẽ là myNew......
Chú ý là ghi đè giá trị của biến số khi chạy command line thì nó sẽ không lưu giá trị đó vào terraform.
Nhận xét
Đăng nhận xét