sfgroups
sfgroups

Reputation: 19099

Terrafrom reading yaml file and assign local varible

I am trying to read the yaml file and assign value to local variable, below code giving `Invalid index' error. how to fix this error message?

YAML file server.yaml

vm:
  - name: vmingd25
  - system_cores: 4

Code block

locals {
        vm_raw = yamldecode(file("server.yaml"))["vm"]
        vm_name=  local.vm_raw["name"]
        vm_cpu = local.vm_raw["system_cores"]
}

Error message

╷
│ Error: Invalid index
│
│   on main.tf line 16, in locals:
│   16:         vm_name=  local.vm_raw["name"]
│     ├────────────────
│     │ local.vm_raw is tuple with 10 elements
│
│ The given key does not identify an element in this collection value: a number is required.
╵
╷
│ Error: Invalid index
│
│   on main.tf line 17, in locals:
│   17:         vm_cpu = local.vm_raw["system_cores"]
│     ├────────────────
│     │ local.vm_raw is tuple with 10 elements
│
│ The given key does not identify an element in this collection value: a number is required.

Upvotes: 1

Views: 775

Answers (1)

George Richardson
George Richardson

Reputation: 1268

Your YAML is equivalent to the following JSON:

{
  "vm": [
    {
      "name": "vmingd25"
    },
    {
      "system_cores": 4
    }
  ]
}

As you can see the vm element is a list of objects because you are using the - character. This means you need to either:

  • Change you YAML to remove the - list definition. e.g.
    vm:
      name: vmingd25
      system_cores: 4
    
    This would turn the list into a dictionary so you could index with the keys as you have done in your question. OR
  • If you cannot change the YAML then you will need to index with an integer. This might work if your YAML never changes but is definitely not recommended.

Upvotes: 3

Related Questions