joneshf / terraform-provider-openwrt

A Terraform provider for OpenWrt using LuCI's JSON-RPC API
https://registry.terraform.io/providers/joneshf/openwrt
Mozilla Public License 2.0
33 stars 8 forks source link

Modifying initial bridge - allow using 'name' for indexing collections #135

Open otopetrik opened 1 year ago

otopetrik commented 1 year ago

Default bridge in OpenWrt installation does not have an id set:

network.@device[0]=device
network.@device[0].name='br-lan'
network.@device[0].type='bridge'
network.@device[0].ports='eth0.1'

Therefore the following does not work

data "openwrt_network_device" "br_lan" {
  id = "br-lan"
}

fails with │ could not find section network.br-lan

Hacky workaround works:

data "openwrt_network_device" "br_lan" {
  id = "@device[0]"
}

That is unfortunate when using data, but it causes bigger issue when attempting to use resource, e.g.

resource "openwrt_network_device" "br_lan" {
  id = "br-lan"
  name = "br-lan"
  type = "bridge"
  ports = [ 
    "eth0"
  ]   
}

That fails with │ It is not currently known why this happens. It is unclear if this is a problem with the provider. Please double check the values provided are acceptable..

It looks like that the provider is attempting to create another bridge br-lan instead of modifying/replacing the existing bridge with the same name (because the initial br-lan has the name, but not have br-lan id).

Workaround is possible by manually importing the bridge terraform import openwrt_network_device.vrouter_br_lan '@device[0]', but it seems like an ugly workaround just to ensure that the initial bridge configuration can be modified from terraform.

Not sure what the cleanest solution is. Most terraform providers start with more or less clean slate (e.g. empty cloud provider environment). OpenWrt starts with the initial networking configuration, which cannot be removed before terraform run, because it would prevent terraform to connect... therefore it has to be modified or replaced (all without breaking connection).

It seems that name of the bridge has to be unique, so it should be to safe to fallback using name when there is no id match. And functionality to use unique attributes for automatic import might be useful for openwrt_dhcp_host when migrating from manual management to terraform (e.g. before creating new openwrt_dhcp_host, try auto-importing matching on mac, ip, name in that order).

Would it be possible to auto-import existing id-less bridge based on matching name and modify it to match terraform resource instead of creating new one ?

otopetrik commented 1 year ago

Never mind, it looks like setting id on imported resource does not work, terraform apply fails to change imported resource id to the one specified in .tf file. At the moment, it looks like that the best solution is to just run uci -X show network | grep "name='br-lan'" | cut -d. -f2 and use the resulting 'cfgXXXXXX' as terraform resource id.