github.com/vtorhonen/terraform@v0.9.0-beta2.0.20170307220345-5d894e4ffda7/builtin/providers/openstack/resource_openstack_networking_secgroup_v2.go (about)

     1  package openstack
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"time"
     7  
     8  	"github.com/hashicorp/terraform/helper/resource"
     9  	"github.com/hashicorp/terraform/helper/schema"
    10  
    11  	"github.com/gophercloud/gophercloud"
    12  	"github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/security/groups"
    13  	"github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/security/rules"
    14  )
    15  
    16  func resourceNetworkingSecGroupV2() *schema.Resource {
    17  	return &schema.Resource{
    18  		Create: resourceNetworkingSecGroupV2Create,
    19  		Read:   resourceNetworkingSecGroupV2Read,
    20  		Delete: resourceNetworkingSecGroupV2Delete,
    21  		Importer: &schema.ResourceImporter{
    22  			State: schema.ImportStatePassthrough,
    23  		},
    24  
    25  		Schema: map[string]*schema.Schema{
    26  			"region": &schema.Schema{
    27  				Type:        schema.TypeString,
    28  				Required:    true,
    29  				ForceNew:    true,
    30  				DefaultFunc: schema.EnvDefaultFunc("OS_REGION_NAME", ""),
    31  			},
    32  			"name": &schema.Schema{
    33  				Type:     schema.TypeString,
    34  				Required: true,
    35  				ForceNew: true,
    36  			},
    37  			"description": &schema.Schema{
    38  				Type:     schema.TypeString,
    39  				Optional: true,
    40  				ForceNew: true,
    41  				Computed: true,
    42  			},
    43  			"tenant_id": &schema.Schema{
    44  				Type:     schema.TypeString,
    45  				Optional: true,
    46  				ForceNew: true,
    47  				Computed: true,
    48  			},
    49  			"delete_default_rules": &schema.Schema{
    50  				Type:     schema.TypeBool,
    51  				Optional: true,
    52  				ForceNew: true,
    53  			},
    54  		},
    55  	}
    56  }
    57  
    58  func resourceNetworkingSecGroupV2Create(d *schema.ResourceData, meta interface{}) error {
    59  
    60  	config := meta.(*Config)
    61  	networkingClient, err := config.networkingV2Client(GetRegion(d))
    62  	if err != nil {
    63  		return fmt.Errorf("Error creating OpenStack networking client: %s", err)
    64  	}
    65  
    66  	opts := groups.CreateOpts{
    67  		Name:        d.Get("name").(string),
    68  		Description: d.Get("description").(string),
    69  		TenantID:    d.Get("tenant_id").(string),
    70  	}
    71  
    72  	log.Printf("[DEBUG] Create OpenStack Neutron Security Group: %#v", opts)
    73  
    74  	security_group, err := groups.Create(networkingClient, opts).Extract()
    75  	if err != nil {
    76  		return err
    77  	}
    78  
    79  	// Delete the default security group rules if it has been requested.
    80  	deleteDefaultRules := d.Get("delete_default_rules").(bool)
    81  	if deleteDefaultRules {
    82  		for _, rule := range security_group.Rules {
    83  			if err := rules.Delete(networkingClient, rule.ID).ExtractErr(); err != nil {
    84  				return fmt.Errorf(
    85  					"There was a problem deleting a default security group rule: %s", err)
    86  			}
    87  		}
    88  	}
    89  
    90  	log.Printf("[DEBUG] OpenStack Neutron Security Group created: %#v", security_group)
    91  
    92  	d.SetId(security_group.ID)
    93  
    94  	return resourceNetworkingSecGroupV2Read(d, meta)
    95  }
    96  
    97  func resourceNetworkingSecGroupV2Read(d *schema.ResourceData, meta interface{}) error {
    98  	log.Printf("[DEBUG] Retrieve information about security group: %s", d.Id())
    99  
   100  	config := meta.(*Config)
   101  	networkingClient, err := config.networkingV2Client(GetRegion(d))
   102  	if err != nil {
   103  		return fmt.Errorf("Error creating OpenStack networking client: %s", err)
   104  	}
   105  
   106  	security_group, err := groups.Get(networkingClient, d.Id()).Extract()
   107  
   108  	if err != nil {
   109  		return CheckDeleted(d, err, "OpenStack Neutron Security group")
   110  	}
   111  
   112  	d.Set("description", security_group.Description)
   113  	d.Set("tenant_id", security_group.TenantID)
   114  	d.Set("name", security_group.Name)
   115  	d.Set("region", GetRegion(d))
   116  
   117  	return nil
   118  }
   119  
   120  func resourceNetworkingSecGroupV2Delete(d *schema.ResourceData, meta interface{}) error {
   121  	log.Printf("[DEBUG] Destroy security group: %s", d.Id())
   122  
   123  	config := meta.(*Config)
   124  	networkingClient, err := config.networkingV2Client(GetRegion(d))
   125  	if err != nil {
   126  		return fmt.Errorf("Error creating OpenStack networking client: %s", err)
   127  	}
   128  
   129  	stateConf := &resource.StateChangeConf{
   130  		Pending:    []string{"ACTIVE"},
   131  		Target:     []string{"DELETED"},
   132  		Refresh:    waitForSecGroupDelete(networkingClient, d.Id()),
   133  		Timeout:    2 * time.Minute,
   134  		Delay:      5 * time.Second,
   135  		MinTimeout: 3 * time.Second,
   136  	}
   137  
   138  	_, err = stateConf.WaitForState()
   139  	if err != nil {
   140  		return fmt.Errorf("Error deleting OpenStack Neutron Security Group: %s", err)
   141  	}
   142  
   143  	d.SetId("")
   144  	return err
   145  }
   146  
   147  func waitForSecGroupDelete(networkingClient *gophercloud.ServiceClient, secGroupId string) resource.StateRefreshFunc {
   148  	return func() (interface{}, string, error) {
   149  		log.Printf("[DEBUG] Attempting to delete OpenStack Security Group %s.\n", secGroupId)
   150  
   151  		r, err := groups.Get(networkingClient, secGroupId).Extract()
   152  		if err != nil {
   153  			if _, ok := err.(gophercloud.ErrDefault404); ok {
   154  				log.Printf("[DEBUG] Successfully deleted OpenStack Neutron Security Group %s", secGroupId)
   155  				return r, "DELETED", nil
   156  			}
   157  			return r, "ACTIVE", err
   158  		}
   159  
   160  		err = groups.Delete(networkingClient, secGroupId).ExtractErr()
   161  		if err != nil {
   162  			if _, ok := err.(gophercloud.ErrDefault404); ok {
   163  				log.Printf("[DEBUG] Successfully deleted OpenStack Neutron Security Group %s", secGroupId)
   164  				return r, "DELETED", nil
   165  			}
   166  			return r, "ACTIVE", err
   167  		}
   168  
   169  		log.Printf("[DEBUG] OpenStack Neutron Security Group %s still active.\n", secGroupId)
   170  		return r, "ACTIVE", nil
   171  	}
   172  }