Variables in Terraform
- To make terraform templates dynamic we need to accept user input and we accept user inputs in terraform using variables
- Refer Here for official docs
- Refer Here for the changes done to add a variable for a region
-
Values to the variables can be passed by the user during terraform apply
- by using
teraform apply -var <variable-name-1>=<value-1> -var <variable-name-2>=<value-2>Refer Here - To handle multiple varibales terraform allows to create a file
.tfvarsextension where you can define variable values Refer Here
- by using
- Refer Here for the first version of variables
imporovement: avoid copy pastes
- Lets use count meta argument Refer Here
- Refer Here for the changes done
improvement: use functions
- use length function to determine number of resources to be created or passed to count
- Refer Here for the changes
- Use string interpolation. Refer Here
- Refer Here for using interpolation for dynamic cidr range calculation
Exercise
- Create a terraform template to
- create a network (vnet/vpc)
- with dynamic number of subnets based of cidr ranges
subnet_cidrs = ["192.168.0.0/24", "192.168.1.0/24"] - subnet names should be like
subnet0, subnet1 - note: use variables (tfvars)
