github.com/turtlemonvh/terraform@v0.6.9-0.20151204001754-8e40b6b855e8/builtin/providers/google/resource_sql_database_instance.go (about)

     1  package google
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/hashicorp/terraform/helper/schema"
     7  
     8  	"google.golang.org/api/sqladmin/v1beta4"
     9  )
    10  
    11  func resourceSqlDatabaseInstance() *schema.Resource {
    12  	return &schema.Resource{
    13  		Create: resourceSqlDatabaseInstanceCreate,
    14  		Read:   resourceSqlDatabaseInstanceRead,
    15  		Update: resourceSqlDatabaseInstanceUpdate,
    16  		Delete: resourceSqlDatabaseInstanceDelete,
    17  
    18  		Schema: map[string]*schema.Schema{
    19  			"name": &schema.Schema{
    20  				Type:     schema.TypeString,
    21  				Required: true,
    22  				ForceNew: true,
    23  			},
    24  			"master_instance_name": &schema.Schema{
    25  				Type:     schema.TypeString,
    26  				Optional: true,
    27  				ForceNew: true,
    28  			},
    29  			"database_version": &schema.Schema{
    30  				Type:     schema.TypeString,
    31  				Optional: true,
    32  				Default:  "MYSQL_5_5",
    33  				ForceNew: true,
    34  			},
    35  			"region": &schema.Schema{
    36  				Type:     schema.TypeString,
    37  				Required: true,
    38  				ForceNew: true,
    39  			},
    40  			"self_link": &schema.Schema{
    41  				Type:     schema.TypeString,
    42  				Computed: true,
    43  			},
    44  			"settings": &schema.Schema{
    45  				Type:     schema.TypeList,
    46  				Required: true,
    47  				Elem: &schema.Resource{
    48  					Schema: map[string]*schema.Schema{
    49  						"version": &schema.Schema{
    50  							Type:     schema.TypeInt,
    51  							Computed: true,
    52  						},
    53  						"tier": &schema.Schema{
    54  							Type:     schema.TypeString,
    55  							Required: true,
    56  						},
    57  						"activation_policy": &schema.Schema{
    58  							Type:     schema.TypeString,
    59  							Optional: true,
    60  						},
    61  						"authorized_gae_applications": &schema.Schema{
    62  							Type:     schema.TypeList,
    63  							Optional: true,
    64  							Elem:     &schema.Schema{Type: schema.TypeString},
    65  						},
    66  						"backup_configuration": &schema.Schema{
    67  							Type:     schema.TypeList,
    68  							Optional: true,
    69  							Elem: &schema.Resource{
    70  								Schema: map[string]*schema.Schema{
    71  									"binary_log_enabled": &schema.Schema{
    72  										Type:     schema.TypeBool,
    73  										Optional: true,
    74  									},
    75  									"enabled": &schema.Schema{
    76  										Type:     schema.TypeBool,
    77  										Optional: true,
    78  									},
    79  									"start_time": &schema.Schema{
    80  										Type:     schema.TypeString,
    81  										Optional: true,
    82  									},
    83  								},
    84  							},
    85  						},
    86  						"crash_safe_replication": &schema.Schema{
    87  							Type:     schema.TypeBool,
    88  							Optional: true,
    89  						},
    90  						"database_flags": &schema.Schema{
    91  							Type:     schema.TypeList,
    92  							Optional: true,
    93  							Elem: &schema.Resource{
    94  								Schema: map[string]*schema.Schema{
    95  									"value": &schema.Schema{
    96  										Type:     schema.TypeString,
    97  										Optional: true,
    98  									},
    99  									"name": &schema.Schema{
   100  										Type:     schema.TypeString,
   101  										Optional: true,
   102  									},
   103  								},
   104  							},
   105  						},
   106  						"ip_configuration": &schema.Schema{
   107  							Type:     schema.TypeList,
   108  							Optional: true,
   109  							Elem: &schema.Resource{
   110  								Schema: map[string]*schema.Schema{
   111  									"authorized_networks": &schema.Schema{
   112  										Type:     schema.TypeList,
   113  										Optional: true,
   114  										Elem: &schema.Resource{
   115  											Schema: map[string]*schema.Schema{
   116  												"expiration_time": &schema.Schema{
   117  													Type:     schema.TypeString,
   118  													Optional: true,
   119  												},
   120  												"name": &schema.Schema{
   121  													Type:     schema.TypeString,
   122  													Optional: true,
   123  												},
   124  												"value": &schema.Schema{
   125  													Type:     schema.TypeString,
   126  													Optional: true,
   127  												},
   128  											},
   129  										},
   130  									},
   131  									"ipv4_enabled": &schema.Schema{
   132  										Type:     schema.TypeBool,
   133  										Optional: true,
   134  									},
   135  									"require_ssl": &schema.Schema{
   136  										Type:     schema.TypeBool,
   137  										Optional: true,
   138  									},
   139  								},
   140  							},
   141  						},
   142  						"location_preference": &schema.Schema{
   143  							Type:     schema.TypeList,
   144  							Optional: true,
   145  							Elem: &schema.Resource{
   146  								Schema: map[string]*schema.Schema{
   147  									"follow_gae_application": &schema.Schema{
   148  										Type:     schema.TypeString,
   149  										Optional: true,
   150  									},
   151  									"zone": &schema.Schema{
   152  										Type:     schema.TypeString,
   153  										Optional: true,
   154  									},
   155  								},
   156  							},
   157  						},
   158  						"pricing_plan": &schema.Schema{
   159  							Type:     schema.TypeString,
   160  							Optional: true,
   161  						},
   162  						"replication_type": &schema.Schema{
   163  							Type:     schema.TypeString,
   164  							Optional: true,
   165  						},
   166  					},
   167  				},
   168  			},
   169  			"replica_configuration": &schema.Schema{
   170  				Type:     schema.TypeList,
   171  				Optional: true,
   172  				Elem: &schema.Resource{
   173  					Schema: map[string]*schema.Schema{
   174  						"ca_certificate": &schema.Schema{
   175  							Type:     schema.TypeString,
   176  							Optional: true,
   177  							ForceNew: true,
   178  						},
   179  						"client_certificate": &schema.Schema{
   180  							Type:     schema.TypeString,
   181  							Optional: true,
   182  							ForceNew: true,
   183  						},
   184  						"client_key": &schema.Schema{
   185  							Type:     schema.TypeString,
   186  							Optional: true,
   187  							ForceNew: true,
   188  						},
   189  						"connect_retry_interval": &schema.Schema{
   190  							Type:     schema.TypeInt,
   191  							Optional: true,
   192  							ForceNew: true,
   193  						},
   194  						"dump_file_path": &schema.Schema{
   195  							Type:     schema.TypeString,
   196  							Optional: true,
   197  							ForceNew: true,
   198  						},
   199  						"master_heartbeat_period": &schema.Schema{
   200  							Type:     schema.TypeInt,
   201  							Optional: true,
   202  							ForceNew: true,
   203  						},
   204  						"password": &schema.Schema{
   205  							Type:     schema.TypeString,
   206  							Optional: true,
   207  							ForceNew: true,
   208  						},
   209  						"ssl_cipher": &schema.Schema{
   210  							Type:     schema.TypeString,
   211  							Optional: true,
   212  							ForceNew: true,
   213  						},
   214  						"username": &schema.Schema{
   215  							Type:     schema.TypeString,
   216  							Optional: true,
   217  							ForceNew: true,
   218  						},
   219  						"verify_server_certificate": &schema.Schema{
   220  							Type:     schema.TypeBool,
   221  							Optional: true,
   222  							ForceNew: true,
   223  						},
   224  					},
   225  				},
   226  			},
   227  		},
   228  	}
   229  }
   230  
   231  func resourceSqlDatabaseInstanceCreate(d *schema.ResourceData, meta interface{}) error {
   232  	config := meta.(*Config)
   233  
   234  	name := d.Get("name").(string)
   235  	region := d.Get("region").(string)
   236  	databaseVersion := d.Get("database_version").(string)
   237  
   238  	_settingsList := d.Get("settings").([]interface{})
   239  	if len(_settingsList) > 1 {
   240  		return fmt.Errorf("At most one settings block is allowed")
   241  	}
   242  
   243  	_settings := _settingsList[0].(map[string]interface{})
   244  	settings := &sqladmin.Settings{
   245  		Tier: _settings["tier"].(string),
   246  	}
   247  
   248  	if v, ok := _settings["activation_policy"]; ok {
   249  		settings.ActivationPolicy = v.(string)
   250  	}
   251  
   252  	if v, ok := _settings["authorized_gae_applications"]; ok {
   253  		settings.AuthorizedGaeApplications = make([]string, 0)
   254  		for _, app := range v.([]interface{}) {
   255  			settings.AuthorizedGaeApplications = append(settings.AuthorizedGaeApplications,
   256  				app.(string))
   257  		}
   258  	}
   259  
   260  	if v, ok := _settings["backup_configuration"]; ok {
   261  		_backupConfigurationList := v.([]interface{})
   262  		if len(_backupConfigurationList) > 1 {
   263  			return fmt.Errorf("At most one backup_configuration block is allowed")
   264  		}
   265  
   266  		if len(_backupConfigurationList) == 1 && _backupConfigurationList[0] != nil {
   267  			settings.BackupConfiguration = &sqladmin.BackupConfiguration{}
   268  			_backupConfiguration := _backupConfigurationList[0].(map[string]interface{})
   269  
   270  			if vp, okp := _backupConfiguration["binary_log_enabled"]; okp {
   271  				settings.BackupConfiguration.BinaryLogEnabled = vp.(bool)
   272  			}
   273  
   274  			if vp, okp := _backupConfiguration["enabled"]; okp {
   275  				settings.BackupConfiguration.Enabled = vp.(bool)
   276  			}
   277  
   278  			if vp, okp := _backupConfiguration["start_time"]; okp {
   279  				settings.BackupConfiguration.StartTime = vp.(string)
   280  			}
   281  		}
   282  	}
   283  
   284  	if v, ok := _settings["crash_safe_replication"]; ok {
   285  		settings.CrashSafeReplicationEnabled = v.(bool)
   286  	}
   287  
   288  	if v, ok := _settings["database_flags"]; ok {
   289  		settings.DatabaseFlags = make([]*sqladmin.DatabaseFlags, 0)
   290  		_databaseFlagsList := v.([]interface{})
   291  		for _, _flag := range _databaseFlagsList {
   292  			_entry := _flag.(map[string]interface{})
   293  			flag := &sqladmin.DatabaseFlags{}
   294  			if vp, okp := _entry["name"]; okp {
   295  				flag.Name = vp.(string)
   296  			}
   297  
   298  			if vp, okp := _entry["value"]; okp {
   299  				flag.Value = vp.(string)
   300  			}
   301  
   302  			settings.DatabaseFlags = append(settings.DatabaseFlags, flag)
   303  		}
   304  	}
   305  
   306  	if v, ok := _settings["ip_configuration"]; ok {
   307  		_ipConfigurationList := v.([]interface{})
   308  		if len(_ipConfigurationList) > 1 {
   309  			return fmt.Errorf("At most one ip_configuration block is allowed")
   310  		}
   311  
   312  		if len(_ipConfigurationList) == 1 && _ipConfigurationList[0] != nil {
   313  			settings.IpConfiguration = &sqladmin.IpConfiguration{}
   314  			_ipConfiguration := _ipConfigurationList[0].(map[string]interface{})
   315  
   316  			if vp, okp := _ipConfiguration["ipv4_enabled"]; okp {
   317  				settings.IpConfiguration.Ipv4Enabled = vp.(bool)
   318  			}
   319  
   320  			if vp, okp := _ipConfiguration["require_ssl"]; okp {
   321  				settings.IpConfiguration.RequireSsl = vp.(bool)
   322  			}
   323  
   324  			if vp, okp := _ipConfiguration["authorized_networks"]; okp {
   325  				settings.IpConfiguration.AuthorizedNetworks = make([]*sqladmin.AclEntry, 0)
   326  				_authorizedNetworksList := vp.([]interface{})
   327  				for _, _acl := range _authorizedNetworksList {
   328  					_entry := _acl.(map[string]interface{})
   329  					entry := &sqladmin.AclEntry{}
   330  
   331  					if vpp, okpp := _entry["expiration_time"]; okpp {
   332  						entry.ExpirationTime = vpp.(string)
   333  					}
   334  
   335  					if vpp, okpp := _entry["name"]; okpp {
   336  						entry.Name = vpp.(string)
   337  					}
   338  
   339  					if vpp, okpp := _entry["value"]; okpp {
   340  						entry.Value = vpp.(string)
   341  					}
   342  
   343  					settings.IpConfiguration.AuthorizedNetworks = append(
   344  						settings.IpConfiguration.AuthorizedNetworks, entry)
   345  				}
   346  			}
   347  		}
   348  	}
   349  
   350  	if v, ok := _settings["location_preference"]; ok {
   351  		_locationPreferenceList := v.([]interface{})
   352  		if len(_locationPreferenceList) > 1 {
   353  			return fmt.Errorf("At most one location_preference block is allowed")
   354  		}
   355  
   356  		if len(_locationPreferenceList) == 1 && _locationPreferenceList[0] != nil {
   357  			settings.LocationPreference = &sqladmin.LocationPreference{}
   358  			_locationPreference := _locationPreferenceList[0].(map[string]interface{})
   359  
   360  			if vp, okp := _locationPreference["follow_gae_application"]; okp {
   361  				settings.LocationPreference.FollowGaeApplication = vp.(string)
   362  			}
   363  
   364  			if vp, okp := _locationPreference["zone"]; okp {
   365  				settings.LocationPreference.Zone = vp.(string)
   366  			}
   367  		}
   368  	}
   369  
   370  	if v, ok := _settings["pricing_plan"]; ok {
   371  		settings.PricingPlan = v.(string)
   372  	}
   373  
   374  	if v, ok := _settings["replication_type"]; ok {
   375  		settings.ReplicationType = v.(string)
   376  	}
   377  
   378  	instance := &sqladmin.DatabaseInstance{
   379  		Name:            name,
   380  		Region:          region,
   381  		Settings:        settings,
   382  		DatabaseVersion: databaseVersion,
   383  	}
   384  
   385  	if v, ok := d.GetOk("replica_configuration"); ok {
   386  		_replicaConfigurationList := v.([]interface{})
   387  		if len(_replicaConfigurationList) > 1 {
   388  			return fmt.Errorf("Only one replica_configuration block may be defined")
   389  		}
   390  
   391  		if len(_replicaConfigurationList) == 1 && _replicaConfigurationList[0] != nil {
   392  			replicaConfiguration := &sqladmin.ReplicaConfiguration{}
   393  			mySqlReplicaConfiguration := &sqladmin.MySqlReplicaConfiguration{}
   394  			_replicaConfiguration := _replicaConfigurationList[0].(map[string]interface{})
   395  
   396  			if vp, okp := _replicaConfiguration["ca_certificate"]; okp {
   397  				mySqlReplicaConfiguration.CaCertificate = vp.(string)
   398  			}
   399  
   400  			if vp, okp := _replicaConfiguration["client_certificate"]; okp {
   401  				mySqlReplicaConfiguration.ClientCertificate = vp.(string)
   402  			}
   403  
   404  			if vp, okp := _replicaConfiguration["client_key"]; okp {
   405  				mySqlReplicaConfiguration.ClientKey = vp.(string)
   406  			}
   407  
   408  			if vp, okp := _replicaConfiguration["connect_retry_interval"]; okp {
   409  				mySqlReplicaConfiguration.ConnectRetryInterval = int64(vp.(int))
   410  			}
   411  
   412  			if vp, okp := _replicaConfiguration["dump_file_path"]; okp {
   413  				mySqlReplicaConfiguration.DumpFilePath = vp.(string)
   414  			}
   415  
   416  			if vp, okp := _replicaConfiguration["master_heartbeat_period"]; okp {
   417  				mySqlReplicaConfiguration.MasterHeartbeatPeriod = int64(vp.(int))
   418  			}
   419  
   420  			if vp, okp := _replicaConfiguration["password"]; okp {
   421  				mySqlReplicaConfiguration.Password = vp.(string)
   422  			}
   423  
   424  			if vp, okp := _replicaConfiguration["ssl_cipher"]; okp {
   425  				mySqlReplicaConfiguration.SslCipher = vp.(string)
   426  			}
   427  
   428  			if vp, okp := _replicaConfiguration["username"]; okp {
   429  				mySqlReplicaConfiguration.Username = vp.(string)
   430  			}
   431  
   432  			if vp, okp := _replicaConfiguration["verify_server_certificate"]; okp {
   433  				mySqlReplicaConfiguration.VerifyServerCertificate = vp.(bool)
   434  			}
   435  
   436  			replicaConfiguration.MysqlReplicaConfiguration = mySqlReplicaConfiguration
   437  			instance.ReplicaConfiguration = replicaConfiguration
   438  		}
   439  	}
   440  
   441  	if v, ok := d.GetOk("master_instance_name"); ok {
   442  		instance.MasterInstanceName = v.(string)
   443  	}
   444  
   445  	op, err := config.clientSqlAdmin.Instances.Insert(config.Project, instance).Do()
   446  	if err != nil {
   447  		return fmt.Errorf("Error, failed to create instance %s: %s", name, err)
   448  	}
   449  
   450  	err = sqladminOperationWait(config, op, "Create Instance")
   451  	if err != nil {
   452  		return err
   453  	}
   454  
   455  	return resourceSqlDatabaseInstanceRead(d, meta)
   456  }
   457  
   458  func resourceSqlDatabaseInstanceRead(d *schema.ResourceData, meta interface{}) error {
   459  	config := meta.(*Config)
   460  
   461  	instance, err := config.clientSqlAdmin.Instances.Get(config.Project,
   462  		d.Get("name").(string)).Do()
   463  
   464  	if err != nil {
   465  		return fmt.Errorf("Error retrieving instance %s: %s",
   466  			d.Get("name").(string), err)
   467  	}
   468  
   469  	_settingsList := d.Get("settings").([]interface{})
   470  	_settings := _settingsList[0].(map[string]interface{})
   471  
   472  	settings := instance.Settings
   473  	_settings["version"] = settings.SettingsVersion
   474  	_settings["tier"] = settings.Tier
   475  
   476  	// Take care to only update attributes that the user has defined explicitly
   477  	if v, ok := _settings["activation_policy"]; ok && len(v.(string)) > 0 {
   478  		_settings["activation_policy"] = settings.ActivationPolicy
   479  	}
   480  
   481  	if v, ok := _settings["authorized_gae_applications"]; ok && len(v.([]interface{})) > 0 {
   482  		_authorized_gae_applications := make([]interface{}, 0)
   483  		for _, app := range settings.AuthorizedGaeApplications {
   484  			_authorized_gae_applications = append(_authorized_gae_applications, app)
   485  		}
   486  		_settings["authorized_gae_applications"] = _authorized_gae_applications
   487  	}
   488  
   489  	if v, ok := _settings["backup_configuration"]; ok {
   490  		_backupConfigurationList := v.([]interface{})
   491  		if len(_backupConfigurationList) > 1 {
   492  			return fmt.Errorf("At most one backup_configuration block is allowed")
   493  		}
   494  
   495  		if len(_backupConfigurationList) == 1 && _backupConfigurationList[0] != nil {
   496  			_backupConfiguration := _backupConfigurationList[0].(map[string]interface{})
   497  
   498  			if vp, okp := _backupConfiguration["binary_log_enabled"]; okp && vp != nil {
   499  				_backupConfiguration["binary_log_enabled"] = settings.BackupConfiguration.BinaryLogEnabled
   500  			}
   501  
   502  			if vp, okp := _backupConfiguration["enabled"]; okp && vp != nil {
   503  				_backupConfiguration["enabled"] = settings.BackupConfiguration.Enabled
   504  			}
   505  
   506  			if vp, okp := _backupConfiguration["start_time"]; okp && vp != nil {
   507  				_backupConfiguration["start_time"] = settings.BackupConfiguration.StartTime
   508  			}
   509  
   510  			_backupConfigurationList[0] = _backupConfiguration
   511  			_settings["backup_configuration"] = _backupConfigurationList
   512  		}
   513  	}
   514  
   515  	if v, ok := _settings["crash_safe_replication"]; ok && v != nil {
   516  		_settings["crash_safe_replication"] = settings.CrashSafeReplicationEnabled
   517  	}
   518  
   519  	if v, ok := _settings["database_flags"]; ok && len(v.([]interface{})) > 0 {
   520  		_flag_map := make(map[string]string)
   521  		// First keep track of localy defined flag pairs
   522  		for _, _flag := range _settings["database_flags"].([]interface{}) {
   523  			_entry := _flag.(map[string]interface{})
   524  			_flag_map[_entry["name"].(string)] = _entry["value"].(string)
   525  		}
   526  
   527  		_database_flags := make([]interface{}, 0)
   528  		// Next read the flag pairs from the server, and reinsert those that
   529  		// correspond to ones defined locally
   530  		for _, entry := range settings.DatabaseFlags {
   531  			if _, okp := _flag_map[entry.Name]; okp {
   532  				_entry := make(map[string]interface{})
   533  				_entry["name"] = entry.Name
   534  				_entry["value"] = entry.Value
   535  				_database_flags = append(_database_flags, _entry)
   536  			}
   537  		}
   538  		_settings["database_flags"] = _database_flags
   539  	}
   540  
   541  	if v, ok := _settings["ip_configuration"]; ok {
   542  		_ipConfigurationList := v.([]interface{})
   543  		if len(_ipConfigurationList) > 1 {
   544  			return fmt.Errorf("At most one ip_configuration block is allowed")
   545  		}
   546  
   547  		if len(_ipConfigurationList) == 1 && _ipConfigurationList[0] != nil {
   548  			_ipConfiguration := _ipConfigurationList[0].(map[string]interface{})
   549  
   550  			if vp, okp := _ipConfiguration["ipv4_enabled"]; okp && vp != nil {
   551  				_ipConfiguration["ipv4_enabled"] = settings.IpConfiguration.Ipv4Enabled
   552  			}
   553  
   554  			if vp, okp := _ipConfiguration["require_ssl"]; okp && vp != nil {
   555  				_ipConfiguration["require_ssl"] = settings.IpConfiguration.RequireSsl
   556  			}
   557  
   558  			if vp, okp := _ipConfiguration["authorized_networks"]; okp && vp != nil {
   559  				_ipc_map := make(map[string]interface{})
   560  				// First keep track of localy defined ip configurations
   561  				for _, _ipc := range _ipConfigurationList {
   562  					_entry := _ipc.(map[string]interface{})
   563  					if _entry["value"] == nil {
   564  						continue
   565  					}
   566  					_value := make(map[string]interface{})
   567  					_value["name"] = _entry["name"]
   568  					_value["expiration_time"] = _entry["expiration_time"]
   569  					// We key on value, since that is the only required part of
   570  					// this 3-tuple
   571  					_ipc_map[_entry["value"].(string)] = _value
   572  				}
   573  				_authorized_networks := make([]interface{}, 0)
   574  				// Next read the network tuples from the server, and reinsert those that
   575  				// correspond to ones defined locally
   576  				for _, entry := range settings.IpConfiguration.AuthorizedNetworks {
   577  					if _, okp := _ipc_map[entry.Value]; okp {
   578  						_entry := make(map[string]interface{})
   579  						_entry["value"] = entry.Value
   580  						_entry["name"] = entry.Name
   581  						_entry["expiration_time"] = entry.ExpirationTime
   582  						_authorized_networks = append(_authorized_networks, _entry)
   583  					}
   584  				}
   585  				_ipConfiguration["authorized_networks"] = _authorized_networks
   586  			}
   587  			_ipConfigurationList[0] = _ipConfiguration
   588  			_settings["ip_configuration"] = _ipConfigurationList
   589  		}
   590  	}
   591  
   592  	if v, ok := _settings["location_preference"]; ok && len(v.([]interface{})) > 0 {
   593  		_locationPreferenceList := v.([]interface{})
   594  		if len(_locationPreferenceList) > 1 {
   595  			return fmt.Errorf("At most one location_preference block is allowed")
   596  		}
   597  
   598  		if len(_locationPreferenceList) == 1 && _locationPreferenceList[0] != nil &&
   599  			settings.LocationPreference != nil {
   600  			_locationPreference := _locationPreferenceList[0].(map[string]interface{})
   601  
   602  			if vp, okp := _locationPreference["follow_gae_application"]; okp && vp != nil {
   603  				_locationPreference["follow_gae_application"] =
   604  					settings.LocationPreference.FollowGaeApplication
   605  			}
   606  
   607  			if vp, okp := _locationPreference["zone"]; okp && vp != nil {
   608  				_locationPreference["zone"] = settings.LocationPreference.Zone
   609  			}
   610  
   611  			_locationPreferenceList[0] = _locationPreference
   612  			_settings["location_preference"] = _locationPreferenceList[0]
   613  		}
   614  	}
   615  
   616  	if v, ok := _settings["pricing_plan"]; ok && len(v.(string)) > 0 {
   617  		_settings["pricing_plan"] = settings.PricingPlan
   618  	}
   619  
   620  	if v, ok := _settings["replication_type"]; ok && len(v.(string)) > 0 {
   621  		_settings["replication_type"] = settings.ReplicationType
   622  	}
   623  
   624  	_settingsList[0] = _settings
   625  	d.Set("settings", _settingsList)
   626  
   627  	if v, ok := d.GetOk("replica_configuration"); ok && v != nil {
   628  		_replicaConfigurationList := v.([]interface{})
   629  		if len(_replicaConfigurationList) > 1 {
   630  			return fmt.Errorf("Only one replica_configuration block may be defined")
   631  		}
   632  
   633  		if len(_replicaConfigurationList) == 1 && _replicaConfigurationList[0] != nil {
   634  			mySqlReplicaConfiguration := instance.ReplicaConfiguration.MysqlReplicaConfiguration
   635  			_replicaConfiguration := _replicaConfigurationList[0].(map[string]interface{})
   636  
   637  			if vp, okp := _replicaConfiguration["ca_certificate"]; okp && vp != nil {
   638  				_replicaConfiguration["ca_certificate"] = mySqlReplicaConfiguration.CaCertificate
   639  			}
   640  
   641  			if vp, okp := _replicaConfiguration["client_certificate"]; okp && vp != nil {
   642  				_replicaConfiguration["client_certificate"] = mySqlReplicaConfiguration.ClientCertificate
   643  			}
   644  
   645  			if vp, okp := _replicaConfiguration["client_key"]; okp && vp != nil {
   646  				_replicaConfiguration["client_key"] = mySqlReplicaConfiguration.ClientKey
   647  			}
   648  
   649  			if vp, okp := _replicaConfiguration["connect_retry_interval"]; okp && vp != nil {
   650  				_replicaConfiguration["connect_retry_interval"] = mySqlReplicaConfiguration.ConnectRetryInterval
   651  			}
   652  
   653  			if vp, okp := _replicaConfiguration["dump_file_path"]; okp && vp != nil {
   654  				_replicaConfiguration["dump_file_path"] = mySqlReplicaConfiguration.DumpFilePath
   655  			}
   656  
   657  			if vp, okp := _replicaConfiguration["master_heartbeat_period"]; okp && vp != nil {
   658  				_replicaConfiguration["master_heartbeat_period"] = mySqlReplicaConfiguration.MasterHeartbeatPeriod
   659  			}
   660  
   661  			if vp, okp := _replicaConfiguration["password"]; okp && vp != nil {
   662  				_replicaConfiguration["password"] = mySqlReplicaConfiguration.Password
   663  			}
   664  
   665  			if vp, okp := _replicaConfiguration["ssl_cipher"]; okp && vp != nil {
   666  				_replicaConfiguration["ssl_cipher"] = mySqlReplicaConfiguration.SslCipher
   667  			}
   668  
   669  			if vp, okp := _replicaConfiguration["username"]; okp && vp != nil {
   670  				_replicaConfiguration["username"] = mySqlReplicaConfiguration.Username
   671  			}
   672  
   673  			if vp, okp := _replicaConfiguration["verify_server_certificate"]; okp && vp != nil {
   674  				_replicaConfiguration["verify_server_certificate"] = mySqlReplicaConfiguration.VerifyServerCertificate
   675  			}
   676  
   677  			_replicaConfigurationList[0] = _replicaConfiguration
   678  			d.Set("replica_configuration", _replicaConfigurationList)
   679  		}
   680  	}
   681  
   682  	if v, ok := d.GetOk("master_instance_name"); ok && v != nil {
   683  		d.Set("master_instance_name", instance.MasterInstanceName)
   684  	}
   685  
   686  	d.Set("self_link", instance.SelfLink)
   687  	d.SetId(instance.Name)
   688  
   689  	return nil
   690  }
   691  
   692  func resourceSqlDatabaseInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
   693  	config := meta.(*Config)
   694  	d.Partial(true)
   695  
   696  	instance, err := config.clientSqlAdmin.Instances.Get(config.Project,
   697  		d.Get("name").(string)).Do()
   698  
   699  	if err != nil {
   700  		return fmt.Errorf("Error retrieving instance %s: %s",
   701  			d.Get("name").(string), err)
   702  	}
   703  
   704  	if d.HasChange("settings") {
   705  		_oListCast, _settingsListCast := d.GetChange("settings")
   706  		_oList := _oListCast.([]interface{})
   707  		_o := _oList[0].(map[string]interface{})
   708  		_settingsList := _settingsListCast.([]interface{})
   709  		if len(_settingsList) > 1 {
   710  			return fmt.Errorf("At most one settings block is allowed")
   711  		}
   712  
   713  		_settings := _settingsList[0].(map[string]interface{})
   714  		settings := &sqladmin.Settings{
   715  			Tier:            _settings["tier"].(string),
   716  			SettingsVersion: instance.Settings.SettingsVersion,
   717  		}
   718  
   719  		if v, ok := _settings["activation_policy"]; ok {
   720  			settings.ActivationPolicy = v.(string)
   721  		}
   722  
   723  		if v, ok := _settings["authorized_gae_applications"]; ok {
   724  			settings.AuthorizedGaeApplications = make([]string, 0)
   725  			for _, app := range v.([]interface{}) {
   726  				settings.AuthorizedGaeApplications = append(settings.AuthorizedGaeApplications,
   727  					app.(string))
   728  			}
   729  		}
   730  
   731  		if v, ok := _settings["backup_configuration"]; ok {
   732  			_backupConfigurationList := v.([]interface{})
   733  			if len(_backupConfigurationList) > 1 {
   734  				return fmt.Errorf("At most one backup_configuration block is allowed")
   735  			}
   736  
   737  			if len(_backupConfigurationList) == 1 && _backupConfigurationList[0] != nil {
   738  				settings.BackupConfiguration = &sqladmin.BackupConfiguration{}
   739  				_backupConfiguration := _backupConfigurationList[0].(map[string]interface{})
   740  
   741  				if vp, okp := _backupConfiguration["binary_log_enabled"]; okp {
   742  					settings.BackupConfiguration.BinaryLogEnabled = vp.(bool)
   743  				}
   744  
   745  				if vp, okp := _backupConfiguration["enabled"]; okp {
   746  					settings.BackupConfiguration.Enabled = vp.(bool)
   747  				}
   748  
   749  				if vp, okp := _backupConfiguration["start_time"]; okp {
   750  					settings.BackupConfiguration.StartTime = vp.(string)
   751  				}
   752  			}
   753  		}
   754  
   755  		if v, ok := _settings["crash_safe_replication"]; ok {
   756  			settings.CrashSafeReplicationEnabled = v.(bool)
   757  		}
   758  
   759  		_oldDatabaseFlags := make([]interface{}, 0)
   760  		if ov, ook := _o["database_flags"]; ook {
   761  			_oldDatabaseFlags = ov.([]interface{})
   762  		}
   763  
   764  		if v, ok := _settings["database_flags"]; ok || len(_oldDatabaseFlags) > 0 {
   765  			oldDatabaseFlags := settings.DatabaseFlags
   766  			settings.DatabaseFlags = make([]*sqladmin.DatabaseFlags, 0)
   767  			_databaseFlagsList := make([]interface{}, 0)
   768  			if v != nil {
   769  				_databaseFlagsList = v.([]interface{})
   770  			}
   771  
   772  			_odbf_map := make(map[string]interface{})
   773  			for _, _dbf := range _oldDatabaseFlags {
   774  				_entry := _dbf.(map[string]interface{})
   775  				_odbf_map[_entry["name"].(string)] = true
   776  			}
   777  
   778  			// First read the flags from the server, and reinsert those that
   779  			// were not previously defined
   780  			for _, entry := range oldDatabaseFlags {
   781  				_, ok_old := _odbf_map[entry.Name]
   782  				if !ok_old {
   783  					settings.DatabaseFlags = append(
   784  						settings.DatabaseFlags, entry)
   785  				}
   786  			}
   787  			// finally, insert only those that were previously defined
   788  			// and are still defined.
   789  			for _, _flag := range _databaseFlagsList {
   790  				_entry := _flag.(map[string]interface{})
   791  				flag := &sqladmin.DatabaseFlags{}
   792  				if vp, okp := _entry["name"]; okp {
   793  					flag.Name = vp.(string)
   794  				}
   795  
   796  				if vp, okp := _entry["value"]; okp {
   797  					flag.Value = vp.(string)
   798  				}
   799  
   800  				settings.DatabaseFlags = append(settings.DatabaseFlags, flag)
   801  			}
   802  		}
   803  
   804  		if v, ok := _settings["ip_configuration"]; ok {
   805  			_ipConfigurationList := v.([]interface{})
   806  			if len(_ipConfigurationList) > 1 {
   807  				return fmt.Errorf("At most one ip_configuration block is allowed")
   808  			}
   809  
   810  			if len(_ipConfigurationList) == 1 && _ipConfigurationList[0] != nil {
   811  				settings.IpConfiguration = &sqladmin.IpConfiguration{}
   812  				_ipConfiguration := _ipConfigurationList[0].(map[string]interface{})
   813  
   814  				if vp, okp := _ipConfiguration["ipv4_enabled"]; okp {
   815  					settings.IpConfiguration.Ipv4Enabled = vp.(bool)
   816  				}
   817  
   818  				if vp, okp := _ipConfiguration["require_ssl"]; okp {
   819  					settings.IpConfiguration.RequireSsl = vp.(bool)
   820  				}
   821  
   822  				_oldAuthorizedNetworkList := make([]interface{}, 0)
   823  				if ov, ook := _o["ip_configuration"]; ook {
   824  					_oldIpConfList := ov.([]interface{})
   825  					if len(_oldIpConfList) > 0 {
   826  						_oldIpConf := _oldIpConfList[0].(map[string]interface{})
   827  						if ovp, ookp := _oldIpConf["authorized_networks"]; ookp {
   828  							_oldAuthorizedNetworkList = ovp.([]interface{})
   829  						}
   830  					}
   831  				}
   832  
   833  				if vp, okp := _ipConfiguration["authorized_networks"]; okp || len(_oldAuthorizedNetworkList) > 0 {
   834  					oldAuthorizedNetworks := settings.IpConfiguration.AuthorizedNetworks
   835  					settings.IpConfiguration.AuthorizedNetworks = make([]*sqladmin.AclEntry, 0)
   836  
   837  					_authorizedNetworksList := make([]interface{}, 0)
   838  					if vp != nil {
   839  						_authorizedNetworksList = vp.([]interface{})
   840  					}
   841  					_oipc_map := make(map[string]interface{})
   842  					for _, _ipc := range _oldAuthorizedNetworkList {
   843  						_entry := _ipc.(map[string]interface{})
   844  						_oipc_map[_entry["value"].(string)] = true
   845  					}
   846  					// Next read the network tuples from the server, and reinsert those that
   847  					// were not previously defined
   848  					for _, entry := range oldAuthorizedNetworks {
   849  						_, ok_old := _oipc_map[entry.Value]
   850  						if !ok_old {
   851  							settings.IpConfiguration.AuthorizedNetworks = append(
   852  								settings.IpConfiguration.AuthorizedNetworks, entry)
   853  						}
   854  					}
   855  					// finally, insert only those that were previously defined
   856  					// and are still defined.
   857  					for _, _ipc := range _authorizedNetworksList {
   858  						_entry := _ipc.(map[string]interface{})
   859  						if _, ok_old := _oipc_map[_entry["value"].(string)]; ok_old {
   860  							entry := &sqladmin.AclEntry{}
   861  
   862  							if vpp, okpp := _entry["expiration_time"]; okpp {
   863  								entry.ExpirationTime = vpp.(string)
   864  							}
   865  
   866  							if vpp, okpp := _entry["name"]; okpp {
   867  								entry.Name = vpp.(string)
   868  							}
   869  
   870  							if vpp, okpp := _entry["value"]; okpp {
   871  								entry.Value = vpp.(string)
   872  							}
   873  
   874  							settings.IpConfiguration.AuthorizedNetworks = append(
   875  								settings.IpConfiguration.AuthorizedNetworks, entry)
   876  						}
   877  					}
   878  				}
   879  			}
   880  		}
   881  
   882  		if v, ok := _settings["location_preference"]; ok {
   883  			_locationPreferenceList := v.([]interface{})
   884  			if len(_locationPreferenceList) > 1 {
   885  				return fmt.Errorf("At most one location_preference block is allowed")
   886  			}
   887  
   888  			if len(_locationPreferenceList) == 1 && _locationPreferenceList[0] != nil {
   889  				settings.LocationPreference = &sqladmin.LocationPreference{}
   890  				_locationPreference := _locationPreferenceList[0].(map[string]interface{})
   891  
   892  				if vp, okp := _locationPreference["follow_gae_application"]; okp {
   893  					settings.LocationPreference.FollowGaeApplication = vp.(string)
   894  				}
   895  
   896  				if vp, okp := _locationPreference["zone"]; okp {
   897  					settings.LocationPreference.Zone = vp.(string)
   898  				}
   899  			}
   900  		}
   901  
   902  		if v, ok := _settings["pricing_plan"]; ok {
   903  			settings.PricingPlan = v.(string)
   904  		}
   905  
   906  		if v, ok := _settings["replication_type"]; ok {
   907  			settings.ReplicationType = v.(string)
   908  		}
   909  
   910  		instance.Settings = settings
   911  	}
   912  
   913  	d.Partial(false)
   914  
   915  	op, err := config.clientSqlAdmin.Instances.Update(config.Project, instance.Name, instance).Do()
   916  	if err != nil {
   917  		return fmt.Errorf("Error, failed to update instance %s: %s", instance.Name, err)
   918  	}
   919  
   920  	err = sqladminOperationWait(config, op, "Create Instance")
   921  	if err != nil {
   922  		return err
   923  	}
   924  
   925  	return resourceSqlDatabaseInstanceRead(d, meta)
   926  }
   927  
   928  func resourceSqlDatabaseInstanceDelete(d *schema.ResourceData, meta interface{}) error {
   929  	config := meta.(*Config)
   930  
   931  	op, err := config.clientSqlAdmin.Instances.Delete(config.Project, d.Get("name").(string)).Do()
   932  
   933  	if err != nil {
   934  		return fmt.Errorf("Error, failed to delete instance %s: %s", d.Get("name").(string), err)
   935  	}
   936  
   937  	err = sqladminOperationWait(config, op, "Delete Instance")
   938  	if err != nil {
   939  		return err
   940  	}
   941  
   942  	return nil
   943  }