github.com/vtorhonen/terraform@v0.9.0-beta2.0.20170307220345-5d894e4ffda7/builtin/providers/icinga2/resource_icinga2_host.go (about) 1 package icinga2 2 3 import ( 4 "fmt" 5 6 "github.com/hashicorp/terraform/helper/schema" 7 "github.com/lrsmith/go-icinga2-api/iapi" 8 ) 9 10 func resourceIcinga2Host() *schema.Resource { 11 12 return &schema.Resource{ 13 Create: resourceIcinga2HostCreate, 14 Read: resourceIcinga2HostRead, 15 Delete: resourceIcinga2HostDelete, 16 Schema: map[string]*schema.Schema{ 17 "hostname": &schema.Schema{ 18 Type: schema.TypeString, 19 Required: true, 20 Description: "Hostname", 21 ForceNew: true, 22 }, 23 "address": &schema.Schema{ 24 Type: schema.TypeString, 25 Required: true, 26 ForceNew: true, 27 }, 28 "check_command": &schema.Schema{ 29 Type: schema.TypeString, 30 Required: true, 31 ForceNew: true, 32 }, 33 "vars": &schema.Schema{ 34 Type: schema.TypeMap, 35 Optional: true, 36 ForceNew: true, 37 }, 38 }, 39 } 40 } 41 42 func resourceIcinga2HostCreate(d *schema.ResourceData, meta interface{}) error { 43 44 client := meta.(*iapi.Server) 45 46 hostname := d.Get("hostname").(string) 47 address := d.Get("address").(string) 48 checkCommand := d.Get("check_command").(string) 49 50 vars := make(map[string]string) 51 52 // Normalize from map[string]interface{} to map[string]string 53 iterator := d.Get("vars").(map[string]interface{}) 54 for key, value := range iterator { 55 vars[key] = value.(string) 56 } 57 58 // Call CreateHost with normalized data 59 hosts, err := client.CreateHost(hostname, address, checkCommand, vars) 60 if err != nil { 61 return err 62 } 63 64 found := false 65 for _, host := range hosts { 66 if host.Name == hostname { 67 d.SetId(hostname) 68 found = true 69 } 70 } 71 72 if !found { 73 return fmt.Errorf("Failed to Create Host %s : %s", hostname, err) 74 } 75 76 return nil 77 } 78 79 func resourceIcinga2HostRead(d *schema.ResourceData, meta interface{}) error { 80 81 client := meta.(*iapi.Server) 82 83 hostname := d.Get("hostname").(string) 84 85 hosts, err := client.GetHost(hostname) 86 if err != nil { 87 return err 88 } 89 90 found := false 91 for _, host := range hosts { 92 if host.Name == hostname { 93 d.SetId(hostname) 94 d.Set("hostname", host.Name) 95 d.Set("address", host.Attrs.Address) 96 d.Set("check_command", host.Attrs.CheckCommand) 97 d.Set("vars", host.Attrs.Vars) 98 found = true 99 } 100 } 101 102 if !found { 103 return fmt.Errorf("Failed to Read Host %s : %s", hostname, err) 104 } 105 106 return nil 107 } 108 109 func resourceIcinga2HostDelete(d *schema.ResourceData, meta interface{}) error { 110 111 client := meta.(*iapi.Server) 112 hostname := d.Get("hostname").(string) 113 114 err := client.DeleteHost(hostname) 115 if err != nil { 116 return fmt.Errorf("Failed to Delete Host %s : %s", hostname, err) 117 } 118 119 return nil 120 121 }