From 6e02e44337abcface0265f2f2a0ab74204900b7c Mon Sep 17 00:00:00 2001 From: timgoud <46928143+timgoud@users.noreply.github.com> Date: Thu, 14 Jul 2022 12:17:26 +0200 Subject: [PATCH] Update resource_zabbix_host.go add marco function --- zabbix/resource_zabbix_host.go | 41 ++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/zabbix/resource_zabbix_host.go b/zabbix/resource_zabbix_host.go index e36c37af..47f7c101 100644 --- a/zabbix/resource_zabbix_host.go +++ b/zabbix/resource_zabbix_host.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "log" + "strings" "github.com/claranet/go-zabbix-api" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" @@ -103,6 +104,12 @@ func resourceZabbixHost() *schema.Resource { Elem: &schema.Schema{Type: schema.TypeString}, Optional: true, }, + "macro": &schema.Schema{ + Type: schema.TypeMap, + Elem: &schema.Schema{Type: schema.TypeString}, + Optional: true, + Description: "User macros for the host.", + }, }, } } @@ -267,6 +274,20 @@ func getTemplates(d *schema.ResourceData, api *zabbix.API) (zabbix.TemplateIDs, return hostTemplates, nil } +func getHostMacro(d *schema.ResourceData) zabbix.Macros { + var macros zabbix.Macros + + terraformMacros := d.Get("macro").(map[string]interface{}) + for i, terraformMacro := range terraformMacros { + macro := zabbix.Macro{ + MacroName: fmt.Sprintf("{$%s}", i), + Value: terraformMacro.(string), + } + macros = append(macros, macro) + } + return macros +} + func createHostObj(d *schema.ResourceData, api *zabbix.API) (*zabbix.Host, error) { host := zabbix.Host{ Host: d.Get("host").(string), @@ -302,6 +323,8 @@ func createHostObj(d *schema.ResourceData, api *zabbix.API) (*zabbix.Host, error } host.TemplateIDs = templates + host.UserMacros = getHostMacro(d) + return &host, nil } @@ -368,7 +391,25 @@ func resourceZabbixHostRead(d *schema.ResourceData, meta interface{}) error { } d.Set("templates", templateNames) + macros := make(map[string]interface{}, len(host.UserMacros)) + + for _, macro := range host.UserMacros { + var name string + if noPrefix := strings.Split(macro.MacroName, "{$"); len(noPrefix) == 2 { + name = noPrefix[1] + } else { + return fmt.Errorf("Invalid macro name \"%s\"", macro.MacroName) + } + if noSuffix := strings.Split(name, "}"); len(noSuffix) == 2 { + name = noSuffix[0] + } else { + return fmt.Errorf("Invalid macro name \"%s\"", macro.MacroName) + } + macros[name] = macro.Value + } + d.Set("macro", macros) + groups, err := api.HostGroupsGet(params) if err != nil {