《Windows Azure Platform 系列文章目錄》
熟悉Azure Template的讀者都知道:Azure ARM (5) ARM Template初探 - 本地JSON Template文件(1)
Azure Template分為兩種類型的文件,資源和變量
(1)Template:資源文件,表示我們需要創建的資源是什么,比如Azure VM,Azure Storage
(2)Parameter:變量文件,表示資源所使用到的參數,比如虛擬機的名字,登陸虛擬機所需要的用戶名和密碼。存儲名稱等等。
在使用Terraform時,也會有兩種類型的文件。我們以Terraform例子為例:
Terraform 運行時會讀取工作目錄中所有的 *.tf, *.tfvars 文件,所以我們不必把所有的東西都寫在單個文件中去,應按職責分列在不同的文件中,例如:
provider.tf -- provider 配置
terraform.tfvars -- 配置 provider 要用到的變量
varable.tf -- 通用變量
resource.tf -- 資源定義
data.tf -- 包文件定義
output.tf -- 輸出
provider "azurerm" { features {} } resource "azurerm_resource_group" "example" { #這里會讀取variables.tf文件 name = "${var.prefix}-resources" location = "${var.location}" }
上面的var.prefix和var.location,會讀取到變量文件
具體的變量內容,在這里被定義:https://github.com/terraform-providers/terraform-provider-azurerm/blob/master/examples/virtual-networks/multiple-subnets/variables.tf
variable "prefix" { description = "The prefix used for all resources in this example" } variable "location" { description = "The Azure location where all resources in this example should be created" }
好了,現在我們用兩種方式執行Terraform
第一種:通過讀取variable.tf中的變量值,來創建Azure資源
第二種:通過執行terraform -apply 過程中,直接設置變量值
我們開始第一種方法:通過讀取variable.tf中的變量值,來創建Azure資源
1.修改varible.tf文件,設置default值。在Terraform執行過程中
我們可以在variable.tf中,設置default值,定義這些變量值。
variable "prefix" { default="leizha" description = "The prefix used for all resources in this example" } variable "location" { default="chinaeast2" description = "The Azure location where all resources in this example should be created" }
2.terraform init,初始化工作目錄:
terraform init
Terraform init做的事情就像是git init加上npm install,執行完trraform init之后,會在當前目錄中生成.terraform目錄,並依照*.tf文件中的執行下載相應的插件
3.terraform plan
該命令讓terraform在正式執行之前,提供了預覽執行計划的機會,讓我們清楚的了解將要做什么
4.terraform apply
這句語句就是真正執行terraform,並顯示結果。
terraform apply -auto-approve
注意:上面的auto-approve是跳過交互式批准流程。
因為我們在步驟1中,設置了prefix值,則我們在terraform執行完畢后,通過讀取variable.tf中prefix值,創建相應的資源。
執行的結果如下:
第二種:通過執行terraform apply 過程中,直接設置變量值
1.首先我們把上面已經創建的Azure資源刪除。圖略。
2.觀察variable.tf中,設置default值,定義這些變量值。
variable "prefix" { default="leizha" description = "The prefix used for all resources in this example" } variable "location" { default="chinaeast2" description = "The Azure location where all resources in this example should be created" }
3.在terraform apply中,直接設置變量值
下面的-var里面,分別設置了prefix的值和location的值
terraform apply -var 'prefix=contoso' -var 'location=chinaeast2'
4.執行結果:
可以看到,雖然我們在variable.tf中,設置default值。但是在terraform apply中,直接設置了變量值,所以會顯示不一樣的結果:
var.prefix