github.com/minamijoyo/terraform@v0.7.8-0.20161029001309-18b3736ba44b/builtin/providers/google/resource_container_cluster.go (about)

     1  package google
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"net"
     7  	"regexp"
     8  	"time"
     9  
    10  	"github.com/hashicorp/terraform/helper/resource"
    11  	"github.com/hashicorp/terraform/helper/schema"
    12  	"google.golang.org/api/container/v1"
    13  	"google.golang.org/api/googleapi"
    14  )
    15  
    16  func resourceContainerCluster() *schema.Resource {
    17  	return &schema.Resource{
    18  		Create: resourceContainerClusterCreate,
    19  		Read:   resourceContainerClusterRead,
    20  		Update: resourceContainerClusterUpdate,
    21  		Delete: resourceContainerClusterDelete,
    22  
    23  		Schema: map[string]*schema.Schema{
    24  			"initial_node_count": &schema.Schema{
    25  				Type:     schema.TypeInt,
    26  				Required: true,
    27  				ForceNew: true,
    28  			},
    29  
    30  			"master_auth": &schema.Schema{
    31  				Type:     schema.TypeList,
    32  				Required: true,
    33  				ForceNew: true,
    34  				Elem: &schema.Resource{
    35  					Schema: map[string]*schema.Schema{
    36  						"client_certificate": &schema.Schema{
    37  							Type:     schema.TypeString,
    38  							Computed: true,
    39  						},
    40  						"client_key": &schema.Schema{
    41  							Type:     schema.TypeString,
    42  							Computed: true,
    43  						},
    44  						"cluster_ca_certificate": &schema.Schema{
    45  							Type:     schema.TypeString,
    46  							Computed: true,
    47  						},
    48  						"password": &schema.Schema{
    49  							Type:     schema.TypeString,
    50  							Required: true,
    51  							ForceNew: true,
    52  						},
    53  						"username": &schema.Schema{
    54  							Type:     schema.TypeString,
    55  							Required: true,
    56  							ForceNew: true,
    57  						},
    58  					},
    59  				},
    60  			},
    61  
    62  			"name": &schema.Schema{
    63  				Type:     schema.TypeString,
    64  				Required: true,
    65  				ForceNew: true,
    66  				ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
    67  					value := v.(string)
    68  
    69  					if len(value) > 40 {
    70  						errors = append(errors, fmt.Errorf(
    71  							"%q cannot be longer than 40 characters", k))
    72  					}
    73  					if !regexp.MustCompile("^[a-z0-9-]+$").MatchString(value) {
    74  						errors = append(errors, fmt.Errorf(
    75  							"%q can only contain lowercase letters, numbers and hyphens", k))
    76  					}
    77  					if !regexp.MustCompile("^[a-z]").MatchString(value) {
    78  						errors = append(errors, fmt.Errorf(
    79  							"%q must start with a letter", k))
    80  					}
    81  					if !regexp.MustCompile("[a-z0-9]$").MatchString(value) {
    82  						errors = append(errors, fmt.Errorf(
    83  							"%q must end with a number or a letter", k))
    84  					}
    85  					return
    86  				},
    87  			},
    88  
    89  			"zone": &schema.Schema{
    90  				Type:     schema.TypeString,
    91  				Required: true,
    92  				ForceNew: true,
    93  			},
    94  
    95  			"cluster_ipv4_cidr": &schema.Schema{
    96  				Type:     schema.TypeString,
    97  				Optional: true,
    98  				Computed: true,
    99  				ForceNew: true,
   100  				ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
   101  					value := v.(string)
   102  					_, ipnet, err := net.ParseCIDR(value)
   103  
   104  					if err != nil || ipnet == nil || value != ipnet.String() {
   105  						errors = append(errors, fmt.Errorf(
   106  							"%q must contain a valid CIDR", k))
   107  					}
   108  					return
   109  				},
   110  			},
   111  
   112  			"description": &schema.Schema{
   113  				Type:     schema.TypeString,
   114  				Optional: true,
   115  				ForceNew: true,
   116  			},
   117  
   118  			"endpoint": &schema.Schema{
   119  				Type:     schema.TypeString,
   120  				Computed: true,
   121  			},
   122  
   123  			"instance_group_urls": &schema.Schema{
   124  				Type:     schema.TypeList,
   125  				Computed: true,
   126  				Elem:     &schema.Schema{Type: schema.TypeString},
   127  			},
   128  
   129  			"logging_service": &schema.Schema{
   130  				Type:     schema.TypeString,
   131  				Optional: true,
   132  				Computed: true,
   133  				ForceNew: true,
   134  			},
   135  
   136  			"monitoring_service": &schema.Schema{
   137  				Type:     schema.TypeString,
   138  				Optional: true,
   139  				Computed: true,
   140  				ForceNew: true,
   141  			},
   142  
   143  			"network": &schema.Schema{
   144  				Type:     schema.TypeString,
   145  				Optional: true,
   146  				Default:  "default",
   147  				ForceNew: true,
   148  			},
   149  			"subnetwork": &schema.Schema{
   150  				Type:     schema.TypeString,
   151  				Optional: true,
   152  				ForceNew: true,
   153  			},
   154  			"addons_config": &schema.Schema{
   155  				Type:     schema.TypeList,
   156  				Optional: true,
   157  				ForceNew: true,
   158  				MaxItems: 1,
   159  				Elem: &schema.Resource{
   160  					Schema: map[string]*schema.Schema{
   161  						"http_load_balancing": &schema.Schema{
   162  							Type:     schema.TypeList,
   163  							Optional: true,
   164  							ForceNew: true,
   165  							MaxItems: 1,
   166  							Elem: &schema.Resource{
   167  								Schema: map[string]*schema.Schema{
   168  									"disabled": &schema.Schema{
   169  										Type:     schema.TypeBool,
   170  										Optional: true,
   171  										ForceNew: true,
   172  									},
   173  								},
   174  							},
   175  						},
   176  						"horizontal_pod_autoscaling": &schema.Schema{
   177  							Type:     schema.TypeList,
   178  							Optional: true,
   179  							ForceNew: true,
   180  							MaxItems: 1,
   181  							Elem: &schema.Resource{
   182  								Schema: map[string]*schema.Schema{
   183  									"disabled": &schema.Schema{
   184  										Type:     schema.TypeBool,
   185  										Optional: true,
   186  										ForceNew: true,
   187  									},
   188  								},
   189  							},
   190  						},
   191  					},
   192  				},
   193  			},
   194  			"node_config": &schema.Schema{
   195  				Type:     schema.TypeList,
   196  				Optional: true,
   197  				Computed: true,
   198  				ForceNew: true,
   199  				Elem: &schema.Resource{
   200  					Schema: map[string]*schema.Schema{
   201  						"machine_type": &schema.Schema{
   202  							Type:     schema.TypeString,
   203  							Optional: true,
   204  							Computed: true,
   205  							ForceNew: true,
   206  						},
   207  
   208  						"disk_size_gb": &schema.Schema{
   209  							Type:     schema.TypeInt,
   210  							Optional: true,
   211  							Computed: true,
   212  							ForceNew: true,
   213  							ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
   214  								value := v.(int)
   215  
   216  								if value < 10 {
   217  									errors = append(errors, fmt.Errorf(
   218  										"%q cannot be less than 10", k))
   219  								}
   220  								return
   221  							},
   222  						},
   223  
   224  						"oauth_scopes": &schema.Schema{
   225  							Type:     schema.TypeList,
   226  							Elem:     &schema.Schema{Type: schema.TypeString},
   227  							Optional: true,
   228  							Computed: true,
   229  							ForceNew: true,
   230  						},
   231  					},
   232  				},
   233  			},
   234  
   235  			"node_version": &schema.Schema{
   236  				Type:     schema.TypeString,
   237  				Optional: true,
   238  				Computed: true,
   239  			},
   240  
   241  			"project": &schema.Schema{
   242  				Type:     schema.TypeString,
   243  				Optional: true,
   244  				ForceNew: true,
   245  			},
   246  		},
   247  	}
   248  }
   249  
   250  func resourceContainerClusterCreate(d *schema.ResourceData, meta interface{}) error {
   251  	config := meta.(*Config)
   252  
   253  	project, err := getProject(d, config)
   254  	if err != nil {
   255  		return err
   256  	}
   257  
   258  	zoneName := d.Get("zone").(string)
   259  	clusterName := d.Get("name").(string)
   260  
   261  	masterAuths := d.Get("master_auth").([]interface{})
   262  	if len(masterAuths) > 1 {
   263  		return fmt.Errorf("Cannot specify more than one master_auth.")
   264  	}
   265  	masterAuth := masterAuths[0].(map[string]interface{})
   266  
   267  	cluster := &container.Cluster{
   268  		MasterAuth: &container.MasterAuth{
   269  			Password: masterAuth["password"].(string),
   270  			Username: masterAuth["username"].(string),
   271  		},
   272  		Name:             clusterName,
   273  		InitialNodeCount: int64(d.Get("initial_node_count").(int)),
   274  	}
   275  
   276  	if v, ok := d.GetOk("cluster_ipv4_cidr"); ok {
   277  		cluster.ClusterIpv4Cidr = v.(string)
   278  	}
   279  
   280  	if v, ok := d.GetOk("description"); ok {
   281  		cluster.Description = v.(string)
   282  	}
   283  
   284  	if v, ok := d.GetOk("logging_service"); ok {
   285  		cluster.LoggingService = v.(string)
   286  	}
   287  
   288  	if v, ok := d.GetOk("monitoring_service"); ok {
   289  		cluster.MonitoringService = v.(string)
   290  	}
   291  
   292  	if _, ok := d.GetOk("network"); ok {
   293  		network, err := getNetworkName(d, "network")
   294  		if err != nil {
   295  			return err
   296  		}
   297  		cluster.Network = network
   298  	}
   299  
   300  	if v, ok := d.GetOk("subnetwork"); ok {
   301  		cluster.Subnetwork = v.(string)
   302  	}
   303  
   304  	if v, ok := d.GetOk("addons_config"); ok {
   305  		addonsConfig := v.([]interface{})[0].(map[string]interface{})
   306  		cluster.AddonsConfig = &container.AddonsConfig{}
   307  
   308  		if v, ok := addonsConfig["http_load_balancing"]; ok {
   309  			addon := v.([]interface{})[0].(map[string]interface{})
   310  			cluster.AddonsConfig.HttpLoadBalancing = &container.HttpLoadBalancing{
   311  				Disabled: addon["disabled"].(bool),
   312  			}
   313  		}
   314  
   315  		if v, ok := addonsConfig["horizontal_pod_autoscaling"]; ok {
   316  			addon := v.([]interface{})[0].(map[string]interface{})
   317  			cluster.AddonsConfig.HorizontalPodAutoscaling = &container.HorizontalPodAutoscaling{
   318  				Disabled: addon["disabled"].(bool),
   319  			}
   320  		}
   321  	}
   322  	if v, ok := d.GetOk("node_config"); ok {
   323  		nodeConfigs := v.([]interface{})
   324  		if len(nodeConfigs) > 1 {
   325  			return fmt.Errorf("Cannot specify more than one node_config.")
   326  		}
   327  		nodeConfig := nodeConfigs[0].(map[string]interface{})
   328  
   329  		cluster.NodeConfig = &container.NodeConfig{}
   330  
   331  		if v, ok = nodeConfig["machine_type"]; ok {
   332  			cluster.NodeConfig.MachineType = v.(string)
   333  		}
   334  
   335  		if v, ok = nodeConfig["disk_size_gb"]; ok {
   336  			cluster.NodeConfig.DiskSizeGb = int64(v.(int))
   337  		}
   338  
   339  		if v, ok := nodeConfig["oauth_scopes"]; ok {
   340  			scopesList := v.([]interface{})
   341  			scopes := []string{}
   342  			for _, v := range scopesList {
   343  				scopes = append(scopes, v.(string))
   344  			}
   345  
   346  			cluster.NodeConfig.OauthScopes = scopes
   347  		}
   348  	}
   349  
   350  	req := &container.CreateClusterRequest{
   351  		Cluster: cluster,
   352  	}
   353  
   354  	op, err := config.clientContainer.Projects.Zones.Clusters.Create(
   355  		project, zoneName, req).Do()
   356  	if err != nil {
   357  		return err
   358  	}
   359  
   360  	// Wait until it's created
   361  	wait := resource.StateChangeConf{
   362  		Pending:    []string{"PENDING", "RUNNING"},
   363  		Target:     []string{"DONE"},
   364  		Timeout:    30 * time.Minute,
   365  		MinTimeout: 3 * time.Second,
   366  		Refresh: func() (interface{}, string, error) {
   367  			resp, err := config.clientContainer.Projects.Zones.Operations.Get(
   368  				project, zoneName, op.Name).Do()
   369  			log.Printf("[DEBUG] Progress of creating GKE cluster %s: %s",
   370  				clusterName, resp.Status)
   371  			return resp, resp.Status, err
   372  		},
   373  	}
   374  
   375  	_, err = wait.WaitForState()
   376  	if err != nil {
   377  		return err
   378  	}
   379  
   380  	log.Printf("[INFO] GKE cluster %s has been created", clusterName)
   381  
   382  	d.SetId(clusterName)
   383  
   384  	return resourceContainerClusterRead(d, meta)
   385  }
   386  
   387  func resourceContainerClusterRead(d *schema.ResourceData, meta interface{}) error {
   388  	config := meta.(*Config)
   389  
   390  	project, err := getProject(d, config)
   391  	if err != nil {
   392  		return err
   393  	}
   394  
   395  	zoneName := d.Get("zone").(string)
   396  
   397  	cluster, err := config.clientContainer.Projects.Zones.Clusters.Get(
   398  		project, zoneName, d.Get("name").(string)).Do()
   399  	if err != nil {
   400  		if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == 404 {
   401  			log.Printf("[WARN] Removing Container Cluster %q because it's gone", d.Get("name").(string))
   402  			// The resource doesn't exist anymore
   403  			d.SetId("")
   404  
   405  			return nil
   406  		}
   407  
   408  		return err
   409  	}
   410  
   411  	d.Set("name", cluster.Name)
   412  	d.Set("zone", cluster.Zone)
   413  	d.Set("endpoint", cluster.Endpoint)
   414  
   415  	masterAuth := []map[string]interface{}{
   416  		map[string]interface{}{
   417  			"username":               cluster.MasterAuth.Username,
   418  			"password":               cluster.MasterAuth.Password,
   419  			"client_certificate":     cluster.MasterAuth.ClientCertificate,
   420  			"client_key":             cluster.MasterAuth.ClientKey,
   421  			"cluster_ca_certificate": cluster.MasterAuth.ClusterCaCertificate,
   422  		},
   423  	}
   424  	d.Set("master_auth", masterAuth)
   425  
   426  	d.Set("initial_node_count", cluster.InitialNodeCount)
   427  	d.Set("node_version", cluster.CurrentNodeVersion)
   428  	d.Set("cluster_ipv4_cidr", cluster.ClusterIpv4Cidr)
   429  	d.Set("description", cluster.Description)
   430  	d.Set("logging_service", cluster.LoggingService)
   431  	d.Set("monitoring_service", cluster.MonitoringService)
   432  	d.Set("network", d.Get("network").(string))
   433  	d.Set("subnetwork", cluster.Subnetwork)
   434  	d.Set("node_config", flattenClusterNodeConfig(cluster.NodeConfig))
   435  	d.Set("instance_group_urls", cluster.InstanceGroupUrls)
   436  
   437  	return nil
   438  }
   439  
   440  func resourceContainerClusterUpdate(d *schema.ResourceData, meta interface{}) error {
   441  	config := meta.(*Config)
   442  
   443  	project, err := getProject(d, config)
   444  	if err != nil {
   445  		return err
   446  	}
   447  
   448  	zoneName := d.Get("zone").(string)
   449  	clusterName := d.Get("name").(string)
   450  	desiredNodeVersion := d.Get("node_version").(string)
   451  
   452  	req := &container.UpdateClusterRequest{
   453  		Update: &container.ClusterUpdate{
   454  			DesiredNodeVersion: desiredNodeVersion,
   455  		},
   456  	}
   457  	op, err := config.clientContainer.Projects.Zones.Clusters.Update(
   458  		project, zoneName, clusterName, req).Do()
   459  	if err != nil {
   460  		return err
   461  	}
   462  
   463  	// Wait until it's updated
   464  	wait := resource.StateChangeConf{
   465  		Pending:    []string{"PENDING", "RUNNING"},
   466  		Target:     []string{"DONE"},
   467  		Timeout:    10 * time.Minute,
   468  		MinTimeout: 2 * time.Second,
   469  		Refresh: func() (interface{}, string, error) {
   470  			log.Printf("[DEBUG] Checking if GKE cluster %s is updated", clusterName)
   471  			resp, err := config.clientContainer.Projects.Zones.Operations.Get(
   472  				project, zoneName, op.Name).Do()
   473  			log.Printf("[DEBUG] Progress of updating GKE cluster %s: %s",
   474  				clusterName, resp.Status)
   475  			return resp, resp.Status, err
   476  		},
   477  	}
   478  
   479  	_, err = wait.WaitForState()
   480  	if err != nil {
   481  		return err
   482  	}
   483  
   484  	log.Printf("[INFO] GKE cluster %s has been updated to %s", d.Id(),
   485  		desiredNodeVersion)
   486  
   487  	return resourceContainerClusterRead(d, meta)
   488  }
   489  
   490  func resourceContainerClusterDelete(d *schema.ResourceData, meta interface{}) error {
   491  	config := meta.(*Config)
   492  
   493  	project, err := getProject(d, config)
   494  	if err != nil {
   495  		return err
   496  	}
   497  
   498  	zoneName := d.Get("zone").(string)
   499  	clusterName := d.Get("name").(string)
   500  
   501  	log.Printf("[DEBUG] Deleting GKE cluster %s", d.Get("name").(string))
   502  	op, err := config.clientContainer.Projects.Zones.Clusters.Delete(
   503  		project, zoneName, clusterName).Do()
   504  	if err != nil {
   505  		return err
   506  	}
   507  
   508  	// Wait until it's deleted
   509  	wait := resource.StateChangeConf{
   510  		Pending:    []string{"PENDING", "RUNNING"},
   511  		Target:     []string{"DONE"},
   512  		Timeout:    10 * time.Minute,
   513  		MinTimeout: 3 * time.Second,
   514  		Refresh: func() (interface{}, string, error) {
   515  			log.Printf("[DEBUG] Checking if GKE cluster %s is deleted", clusterName)
   516  			resp, err := config.clientContainer.Projects.Zones.Operations.Get(
   517  				project, zoneName, op.Name).Do()
   518  			log.Printf("[DEBUG] Progress of deleting GKE cluster %s: %s",
   519  				clusterName, resp.Status)
   520  			return resp, resp.Status, err
   521  		},
   522  	}
   523  
   524  	_, err = wait.WaitForState()
   525  	if err != nil {
   526  		return err
   527  	}
   528  
   529  	log.Printf("[INFO] GKE cluster %s has been deleted", d.Id())
   530  
   531  	d.SetId("")
   532  
   533  	return nil
   534  }
   535  
   536  func flattenClusterNodeConfig(c *container.NodeConfig) []map[string]interface{} {
   537  	config := []map[string]interface{}{
   538  		map[string]interface{}{
   539  			"machine_type": c.MachineType,
   540  			"disk_size_gb": c.DiskSizeGb,
   541  		},
   542  	}
   543  
   544  	if len(c.OauthScopes) > 0 {
   545  		config[0]["oauth_scopes"] = c.OauthScopes
   546  	}
   547  
   548  	return config
   549  }