terraform-provider-routeros icon indicating copy to clipboard operation
terraform-provider-routeros copied to clipboard

Additional info for easy import

Open cmdorexe opened this issue 1 year ago • 13 comments

as example i used "/ip fi ad" foreach i in=[/ip fi ad find dynamic=no] do={put [/ip fi ad get $i]} we get all we are needed out it to import_fw_addr_list.txt

Now we can export it to variable in default section to move.

.id=*1;address=192.168.88.11;comment=example 2;creation-time=1970-01-02 07:00:52;disabled=false;dynamic=false;list=srv
.id=*2;address=192.168.88.12;comment=example 2;creation-time=1970-01-02 07:00:52;disabled=false;dynamic=false;list=srv
.id=*3;address=192.168.88.1;comment=example;creation-time=1970-01-02 07:00:52;disabled=false;dynamic=false;list=routeros
cat ./import_fw_addr_list.txt | perl -pe 's/^\.id=(.*)\;address=((?>\d+\.\d+\.\d+.\d+)|(?>\d+\.\d+\.\d+.\d+\/\d+))(\;comment=(.*)|.?)\;.*\;.*\;.*\;.*list=(.*)$/{ address="\2", comment="\4", list="\5" },/g' > import_fw_addr_list.tf.txt
#!/bin/bash
findexes=$(cat ./import_fw_addr_list.txt | sed -r 's/.id=(.*).*/\U\1/g' | awk -F";" '{ print $1}')
i=0
for index in $findexes
do
idx=$(printf "%00004d" $i)
#remove idx
  bash -cv "tofu state rm 'module.dev-gw0.routeros_ip_firewall_addr_list.address_list[\"$idx\"]'"
  bash -cv "tofu import 'module.dev-gw0.routeros_ip_firewall_addr_list.address_list[\"$idx\"]' \"$index\""
  let i=${i}+1
done
variable "address_list" {
  type = list(object({
#    id = string
    address = string
    comment = optional(string)
    #    creation_time  = optional(string)
    disabled = optional(bool, false)
    dynamic  = optional(bool, false)
    list     = string
  }))

  default = [
    { address="192.168.88.11", comment="example 2", list="srv" },
    { address="192.168.88.12", comment="example 2", list="srv" },
    { address="192.168.88.1", comment="example", list="routeros" },
]

locals {
  # https://discuss.hashicorp.com/t/does-map-sort-keys/12056/2
  # Map keys are always iterated in lexicographical order!
  address_list_map = { for idx, rule in var.address_list : format("%00004d", idx) => rule }
}

resource "routeros_ip_firewall_addr_list" "address_list" {
  for_each = local.address_list_map
#  id       = each.value.id
  address  = each.value.address
  comment  = each.value.comment
  #  creation_time  = each.value.creation_time
  disabled = each.value.disabled
  list     = each.value.list
}

cmdorexe avatar Jun 07 '24 13:06 cmdorexe