>_ IzzyLab

Hands-on task

This task is step 3 of the course “Terraform and Ansible”

Terraform: three files via count

medium~15 min

In /root/tf describe a local_file resource with count = 3 that creates the files /opt/gen/file-0.txt, /opt/gen/file-1.txt, /opt/gen/file-2.txt (the index comes from count.index). Run apply. There's no internet in the sandbox: only the hashicorp/local provider is available (it sits in a local mirror, terraform init will find it on its own). Write the config in the Editor tab (the /root/tf directory is already created) and run terraform in the terminal.

What you'll practise:
  • terraform
  • count
  • count.index
  • interpolation
  • local_file

Topic breakdown

The count meta-argument in Terraform multiplies a single resource block into several instances instead of copy-pasting nearly identical descriptions. Inside such a resource the variable count.index is available — the sequence number of the copy (0, 1, 2…), by which instances differ from one another. To insert this value into a string (for example, into a file path) you use ${...} interpolation right inside the HCL string literal. After apply all created instances are visible in terraform state list.

What's checked

  1. all three files are created in /opt/gen/
  2. state has three local_file instances via count
  3. infrastructure matches the config (plan shows no changes)

What it looks like