Get startedGet started for free

Meta-arguments for Resources

1. Meta-arguments for Resources

Let’s transition and examine resource meta-arguments. The Terraform language defines several meta-arguments, which can be used with any resource type to change the behavior of resources. Count creates multiple instances, depending on the value you define. for_each, creates multiple instances according to a map or set of strings. Depends_on is used to specify explicit dependencies. Lifecycle defines the lifecycle of a resource. With the lifecycle argument you can prevent destruction of a resource for compliance purposes, and create a resource before destroying the replaced resource. This approach is often used for high availability. Provider selects a non-default provider configuration. You can have multiple configurations for a provider, including default. This course covers count and for_each in detail. Let’s start with the count meta-argument. Perhaps you must deploy multiple VM instances. In the resource definition here, each Compute Engine instance is created with a separate google_compute_instance resource block. Writing code in this way is redundant. Instead, replace redundant code by adding the count argument at the beginning of the resource definition. The count argument tells Terraform to create three instances of the same kind. The expression on the second line, count.index, represents the index number of the current count loop. The count index starts at 0 and increments by 1 for each resource. Include the count index variable in strings using interpolation. When deployed, Terraform names the instances dev_VM1, dev_VM2, and dev_VM3. If your instances are almost identical, count is appropriate. If some of their arguments need distinct values that can't be directly derived from an integer, it's safer to use for_each. The for_each argument can be assigned to a string of values or a map. Terraform will create one instance for each member of the string. Consider a scenario where you need three similar instances configured in three specific zones and you want the names to have zones as prefixes for identification. Instead of writing lengthy repetitive code, you can use the for_each argument to assign specific values. The example code creates three instances in their respective zones: dev-us-central1-a, dev-asia-east1-b, and dev-europe-west4-a.

2. Let's practice!

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.