Dit deel is nog niet vertaald. Je ziet de Engelse tekst.
$ als gewone gebruiker# als root (of met sudo)
Vaardigheden in dit hoofdstuk
- resource- en data-blokken, verwijzingen, variabelen en outputs
Use resource and data blocks
A resource is managed by Terraform (created, changed, deleted). A data source only reads something that already exists.
data "azurerm_client_config" "current" {}
data "azurerm_resource_group" "shared" {
name = "rg-shared"
}
resource "azurerm_virtual_network" "app" {
name = "vnet-app-${var.env}"
location = data.azurerm_resource_group.shared.location
resource_group_name = data.azurerm_resource_group.shared.name
address_space = ["10.30.0.0/16"]
}| Block | Address in code | Managed by Terraform |
|---|---|---|
resource "TYPE" "NAME" | TYPE.NAME | Yes |
data "TYPE" "NAME" | data.TYPE.NAME | No, read only |
Reference attributes across resources
Use one resource's attributes in another: TYPE.NAME.ATTRIBUTE. The reference also tells Terraform the order.
resource "azurerm_subnet" "web" {
name = "snet-web"
resource_group_name = azurerm_virtual_network.app.resource_group_name
virtual_network_name = azurerm_virtual_network.app.name
address_prefixes = ["10.30.1.0/24"]
}
resource "azurerm_network_interface" "web" {
name = "nic-web1"
location = azurerm_virtual_network.app.location
resource_group_name = azurerm_virtual_network.app.resource_group_name
ip_configuration {
name = "ipconfig1"
subnet_id = azurerm_subnet.web.id
private_ip_address_allocation = "Dynamic"
}
}Declare input variables
A variable is a parameter of the configuration, with a type, a default, a description and optional validation.
variable "env" {
type = string
description = "Environment name: dev, test or prod"
validation {
condition = contains(["dev", "test", "prod"], var.env)
error_message = "env must be dev, test or prod."
}
}
variable "vm_count" {
type = number
default = 2
}
variable "admin_ip" {
type = string
sensitive = true
}Give values to variables
Values come from several places. Later ones in this list win.
| Source (low → high priority) | Example |
|---|---|
default in the variable | default = 2 |
| Environment variable | export TF_VAR_env=dev |
terraform.tfvars, *.auto.tfvars | env = "dev" |
-var-file=FILE | terraform plan -var-file=prod.tfvars |
-var on the command line | terraform plan -var env=prod |
env = "prod"
vm_count = 3Return values with outputs
Outputs print values after apply, and pass values from a module to its caller.
Name repeated values with locals
Locals give a name to an expression used many times — common tags, name prefixes.
locals {
prefix = "shop-${var.env}"
tags = {
env = var.env
owner = "it"
managed = "terraform"
}
}
resource "azurerm_resource_group" "app" {
name = "rg-${local.prefix}"
location = "westeurope"
tags = local.tags
}Onthoud
var. = input from outside, local. = computed inside, output = returned to the outside.