github.com/peterbale/terraform@v0.9.0-beta2.0.20170315142748-5723acd55547/builtin/providers/icinga2/resource_icinga2_hostgroup.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 resourceIcinga2Hostgroup() *schema.Resource {
    11  
    12  	return &schema.Resource{
    13  		Create: resourceIcinga2HostgroupCreate,
    14  		Read:   resourceIcinga2HostgroupRead,
    15  		Delete: resourceIcinga2HostgroupDelete,
    16  		Schema: map[string]*schema.Schema{
    17  			"name": &schema.Schema{
    18  				Type:        schema.TypeString,
    19  				Required:    true,
    20  				Description: "name",
    21  				ForceNew:    true,
    22  			},
    23  			"display_name": &schema.Schema{
    24  				Type:        schema.TypeString,
    25  				Required:    true,
    26  				Description: "Display name of Host Group",
    27  				ForceNew:    true,
    28  			},
    29  		},
    30  	}
    31  }
    32  
    33  func resourceIcinga2HostgroupCreate(d *schema.ResourceData, meta interface{}) error {
    34  
    35  	client := meta.(*iapi.Server)
    36  
    37  	name := d.Get("name").(string)
    38  	displayName := d.Get("display_name").(string)
    39  
    40  	hostgroups, err := client.CreateHostgroup(name, displayName)
    41  	if err != nil {
    42  		return err
    43  	}
    44  
    45  	found := false
    46  	for _, hostgroup := range hostgroups {
    47  		if hostgroup.Name == name {
    48  			d.SetId(name)
    49  			found = true
    50  		}
    51  	}
    52  
    53  	if !found {
    54  		return fmt.Errorf("Failed to Create Hostgroup %s : %s", name, err)
    55  	}
    56  
    57  	return nil
    58  }
    59  
    60  func resourceIcinga2HostgroupRead(d *schema.ResourceData, meta interface{}) error {
    61  
    62  	client := meta.(*iapi.Server)
    63  	name := d.Get("name").(string)
    64  
    65  	hostgroups, err := client.GetHostgroup(name)
    66  	if err != nil {
    67  		return err
    68  	}
    69  
    70  	found := false
    71  	for _, hostgroup := range hostgroups {
    72  		if hostgroup.Name == name {
    73  			d.SetId(name)
    74  			d.Set("display_name", hostgroup.Attrs.DisplayName)
    75  			found = true
    76  		}
    77  	}
    78  
    79  	if !found {
    80  		return fmt.Errorf("Failed to Read Hostgroup %s : %s", name, err)
    81  	}
    82  
    83  	return nil
    84  }
    85  
    86  func resourceIcinga2HostgroupDelete(d *schema.ResourceData, meta interface{}) error {
    87  
    88  	client := meta.(*iapi.Server)
    89  	name := d.Get("name").(string)
    90  
    91  	err := client.DeleteHostgroup(name)
    92  	if err != nil {
    93  		return fmt.Errorf("Failed to Delete Hostgroup %s : %s", name, err)
    94  	}
    95  
    96  	return nil
    97  
    98  }