diff --git a/common/common_volcengine_version.go b/common/common_volcengine_version.go index aace74f3..b33d1c6d 100644 --- a/common/common_volcengine_version.go +++ b/common/common_volcengine_version.go @@ -2,5 +2,5 @@ package common const ( TerraformProviderName = "terraform-provider-volcengine" - TerraformProviderVersion = "0.0.50" + TerraformProviderVersion = "0.0.51" ) diff --git a/docgen/main.go b/docgen/main.go index 0b02ad99..2b76cf0e 100644 --- a/docgen/main.go +++ b/docgen/main.go @@ -128,6 +128,7 @@ var resourceKeys = map[string]string{ "cen": "CEN(BETA)", "vpn": "VPN(BETA)", "autoscaling": "AUTOSCALING", + "mongodb": "MONGODB", } type Products struct { diff --git a/example/dataMongoDBAccounts/main.tf b/example/dataMongoDBAccounts/main.tf new file mode 100644 index 00000000..3b6d1bc6 --- /dev/null +++ b/example/dataMongoDBAccounts/main.tf @@ -0,0 +1,3 @@ +data "volcengine_mongodb_accounts" "default"{ + instance_id = "mongo-replica-xxx" +} \ No newline at end of file diff --git a/example/dataMongoDBAllowLists/main.tf b/example/dataMongoDBAllowLists/main.tf new file mode 100644 index 00000000..e44d610d --- /dev/null +++ b/example/dataMongoDBAllowLists/main.tf @@ -0,0 +1,5 @@ +data "volcengine_mongodb_allow_lists" "default"{ + region_id = "cn-xxx" + instance_id="mongo-replica-xxx" + allow_list_ids=["acl-2ecfc3318fd24bfab6xxx","acl-ada659ab83e941d6adc2xxxf"] +} \ No newline at end of file diff --git a/example/dataMongoDBInstanceParameterLogs/main.tf b/example/dataMongoDBInstanceParameterLogs/main.tf new file mode 100644 index 00000000..89d37590 --- /dev/null +++ b/example/dataMongoDBInstanceParameterLogs/main.tf @@ -0,0 +1,5 @@ +data "volcengine_mongodb_instance_parameter_logs" "foo"{ + instance_id="mongo-replica-xxx" + start_time="2022-11-14 00:00Z" + end_time="2022-11-14 18:15Z" +} \ No newline at end of file diff --git a/example/dataMongoDBInstanceParameters/main.tf b/example/dataMongoDBInstanceParameters/main.tf new file mode 100644 index 00000000..867f12a9 --- /dev/null +++ b/example/dataMongoDBInstanceParameters/main.tf @@ -0,0 +1,3 @@ +data "volcengine_mongodb_instance_parameters" "foo"{ + instance_id="mongo-replica-xxx" +} \ No newline at end of file diff --git a/example/dataMongoDBRegions/main.tf b/example/dataMongoDBRegions/main.tf new file mode 100644 index 00000000..81eab57b --- /dev/null +++ b/example/dataMongoDBRegions/main.tf @@ -0,0 +1,2 @@ +data "volcengine_mongodb_regions" "default"{ +} \ No newline at end of file diff --git a/example/dataMongoDBSSLStates/main.tf b/example/dataMongoDBSSLStates/main.tf new file mode 100644 index 00000000..d981b607 --- /dev/null +++ b/example/dataMongoDBSSLStates/main.tf @@ -0,0 +1,3 @@ +data "volcengine_mongodb_ssl_states" "foo"{ + instance_id="mongo-shard-xxx" +} \ No newline at end of file diff --git a/example/dataMongoDBSpecs/main.tf b/example/dataMongoDBSpecs/main.tf new file mode 100644 index 00000000..04c27c60 --- /dev/null +++ b/example/dataMongoDBSpecs/main.tf @@ -0,0 +1,3 @@ +data "volcengine_mongodb_specs" "foo"{ + region_id="cn-xxx" +} \ No newline at end of file diff --git a/example/dataMongoDBZones/main.tf b/example/dataMongoDBZones/main.tf new file mode 100644 index 00000000..f306a55c --- /dev/null +++ b/example/dataMongoDBZones/main.tf @@ -0,0 +1,3 @@ +data "volcengine_mongodb_zones" "default"{ + region_id = "XXX" +} \ No newline at end of file diff --git a/example/dataMongodbEndpoints/main.tf b/example/dataMongodbEndpoints/main.tf new file mode 100644 index 00000000..33576feb --- /dev/null +++ b/example/dataMongodbEndpoints/main.tf @@ -0,0 +1,3 @@ +data "volcengine_mongodb_endpoints" "foo"{ + instance_id="mongo-shard-xxx" +} \ No newline at end of file diff --git a/example/dataMongodbInstances/main.tf b/example/dataMongodbInstances/main.tf new file mode 100644 index 00000000..926fdeb3 --- /dev/null +++ b/example/dataMongodbInstances/main.tf @@ -0,0 +1,3 @@ +data "volcengine_mongodb_instances" "foo"{ + instance_id="mongo-replica-xxx" +} \ No newline at end of file diff --git a/example/mongoDBAllowList/main.tf b/example/mongoDBAllowList/main.tf new file mode 100644 index 00000000..a23ad1e2 --- /dev/null +++ b/example/mongoDBAllowList/main.tf @@ -0,0 +1,6 @@ +resource "volcengine_mongodb_allow_list" "foo"{ + allow_list_name="tf-test" + allow_list_desc="test" + allow_list_type="IPv4" + allow_list="10.1.1.1,10.1.1.2,10.1.1.3,10.2.3.0/24" +} \ No newline at end of file diff --git a/example/mongoDBAllowListAssociate/main.tf b/example/mongoDBAllowListAssociate/main.tf new file mode 100644 index 00000000..4f7ce64e --- /dev/null +++ b/example/mongoDBAllowListAssociate/main.tf @@ -0,0 +1,4 @@ +resource "volcengine_mongodb_allow_list_associate" "foo"{ + instance_id="mongo-replica-b2xxx" + allow_list_id="acl-4d66bec945d14fa48xxx" +} \ No newline at end of file diff --git a/example/mongoDBEndpoint/main.tf b/example/mongoDBEndpoint/main.tf new file mode 100644 index 00000000..917343ec --- /dev/null +++ b/example/mongoDBEndpoint/main.tf @@ -0,0 +1,6 @@ +resource "volcengine_mongodb_endpoint" "foo"{ + instance_id="mongo-shard-xxx" + object_id="mongo-shard-xxx-s1" + network_type="Public" + eip_ids=["eip-xx","eip-xx"] +} \ No newline at end of file diff --git a/example/mongoDBEndpointImport/main.tf b/example/mongoDBEndpointImport/main.tf new file mode 100644 index 00000000..298aeedc --- /dev/null +++ b/example/mongoDBEndpointImport/main.tf @@ -0,0 +1,5 @@ +resource "volcengine_mongodb_endpoint" "foo"{ + instance_id="mongo-shard-9e031cea119b" + object_id="mongo-shard-9e031cea119b-s0" + network_type="Private" +} \ No newline at end of file diff --git a/example/mongoDBInstance/main.tf b/example/mongoDBInstance/main.tf new file mode 100644 index 00000000..ca1af9d9 --- /dev/null +++ b/example/mongoDBInstance/main.tf @@ -0,0 +1,15 @@ +resource "volcengine_mongodb_instance" "foo"{ + zone_id="cn-xxx" + instance_type="ShardedCluster" + node_spec="mongo.xxx" + mongos_node_spec="mongo.mongos.xxx" + shard_number=3 + storage_space_gb=100 + subnet_id="subnet-2d6pxxu" + instance_name="tf-test" + charge_type="PostPaid" + # period_unit="Month" + # period=1 + # auto_renew=false + # ssl_action="Close" +} \ No newline at end of file diff --git a/example/mongoDBInstanceParameter/main.tf b/example/mongoDBInstanceParameter/main.tf new file mode 100644 index 00000000..bd4468ae --- /dev/null +++ b/example/mongoDBInstanceParameter/main.tf @@ -0,0 +1,6 @@ +resource "volcengine_mongodb_instance_parameter" "foo"{ + instance_id="mongo-replica-b2xxx" + parameter_name="connPoolMaxConnsPerHost" + parameter_role="Node" + parameter_value="800" +} \ No newline at end of file diff --git a/example/mongoDBSSLState/main.tf b/example/mongoDBSSLState/main.tf new file mode 100644 index 00000000..3c8f4efe --- /dev/null +++ b/example/mongoDBSSLState/main.tf @@ -0,0 +1,4 @@ +resource "volcengine_mongodb_ssl_state" "foo"{ + instance_id="mongo-shard-xxx" + ssl_action="Update" +} \ No newline at end of file diff --git a/example/mongodb/import/main.tf b/example/mongodb/import/main.tf new file mode 100644 index 00000000..3578269f --- /dev/null +++ b/example/mongodb/import/main.tf @@ -0,0 +1,15 @@ +resource "volcengine_mongodb_instance" "foo"{ + # region_id="cn-xxx" + # zone_ids=["cn-xxx"] + # instance_name="test-22" + # sharded_cluster=0 + # password="1qaz!QAZ" + # node_number=2 + # shard_capacity=1024 + # engine_version="5.0" + # vpc_id="vpc-274d24a6ece807fap8***" + # subnet_id="subnet-274o6znje5iww7fa***" + # charge_type="PrePaid" + # purchase_months=1 + # auto_renew=false +} \ No newline at end of file diff --git a/logger/logger.go b/logger/logger.go index 45ec7d0f..ca37128e 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -33,14 +33,14 @@ func Debug(format string, action string, req interface{}, v ...interface{}) { message := fmt.Sprintf("[DEBUG] {(t-%v):%v:%v}", GetGID(), file, line) log.Printf(message+format, action, req, v) } -func DebugInfo(format string, info interface{}) { +func DebugInfo(format string, info ...interface{}) { _, file, line, _ := runtime.Caller(skip) start := strings.LastIndex(file, "/") if start != -1 { file = file[start+1:] } message := fmt.Sprintf("[DEBUG] {%v:%v}", file, line) - log.Printf(message+format, info) + log.Printf(message+format, info...) } func Info(format string, v ...interface{}) { diff --git a/volcengine/escloud/zone/data_source_volcengine_zones.go b/volcengine/escloud/zone/data_source_volcengine_escloud_zones.go similarity index 100% rename from volcengine/escloud/zone/data_source_volcengine_zones.go rename to volcengine/escloud/zone/data_source_volcengine_escloud_zones.go diff --git a/volcengine/escloud/zone/service_volcengine_zone.go b/volcengine/escloud/zone/service_volcengine_escloud_zone.go similarity index 100% rename from volcengine/escloud/zone/service_volcengine_zone.go rename to volcengine/escloud/zone/service_volcengine_escloud_zone.go diff --git a/volcengine/mongodb/account/data_source_volcengine_mongodb_accounts.go b/volcengine/mongodb/account/data_source_volcengine_mongodb_accounts.go new file mode 100644 index 00000000..80ea6562 --- /dev/null +++ b/volcengine/mongodb/account/data_source_volcengine_mongodb_accounts.go @@ -0,0 +1,80 @@ +package account + +import ( + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + ve "github.com/volcengine/terraform-provider-volcengine/common" +) + +func DataSourceVolcengineMongoDBAccounts() *schema.Resource { + return &schema.Resource{ + Read: dataSourceVolcengineAccountsRead, + Schema: map[string]*schema.Schema{ + "instance_id": { + Type: schema.TypeString, + Required: true, + // ForceNew: true, + Description: "Target query mongo instance id.", + }, + "account_name": { + Type: schema.TypeString, + Optional: true, + Description: "The name of account, current support only `root`.", + ValidateFunc: validation.StringInSlice([]string{"root"}, false), + }, + "output_file": { + Type: schema.TypeString, + Optional: true, + Description: "File name where to save data source results.", + }, + "total_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The total count of accounts query.", + }, + "accounts": { + Description: "The collection of accounts query.", + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "account_name": { + Type: schema.TypeString, + Computed: true, + Description: "The name of account.", + }, + "account_type": { + Type: schema.TypeString, + Computed: true, + Description: "The type of account.", + }, + "account_privileges": { + Type: schema.TypeList, + Computed: true, + Description: "The privilege info of mongo instance.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "db_name": { + Type: schema.TypeString, + Computed: true, + Description: "The Name of DB.", + }, + "role_name": { + Type: schema.TypeString, + Computed: true, + Description: "The Name of role.", + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func dataSourceVolcengineAccountsRead(d *schema.ResourceData, meta interface{}) error { + regionService := NewMongoDBAccountService(meta.(*ve.SdkClient)) + return regionService.Dispatcher.Data(regionService, d, DataSourceVolcengineMongoDBAccounts()) +} diff --git a/volcengine/mongodb/account/service_volcengine_mongodb_account.go b/volcengine/mongodb/account/service_volcengine_mongodb_account.go new file mode 100644 index 00000000..80155313 --- /dev/null +++ b/volcengine/mongodb/account/service_volcengine_mongodb_account.go @@ -0,0 +1,186 @@ +package account + +import ( + "errors" + "fmt" + "strings" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" + "github.com/volcengine/terraform-provider-volcengine/logger" +) + +type VolcengineMongoDBAccountService struct { + Client *ve.SdkClient + Dispatcher *ve.Dispatcher +} + +func NewMongoDBAccountService(c *ve.SdkClient) *VolcengineMongoDBAccountService { + return &VolcengineMongoDBAccountService{ + Client: c, + Dispatcher: &ve.Dispatcher{}, + } +} + +func (s *VolcengineMongoDBAccountService) GetClient() *ve.SdkClient { + return s.Client +} + +func getUniversalInfo(actionName string) ve.UniversalInfo { + return ve.UniversalInfo{ + ServiceName: "mongodb", + Version: "2022-01-01", + HttpMethod: ve.POST, + ContentType: ve.ApplicationJSON, + Action: actionName, + } +} + +func (s *VolcengineMongoDBAccountService) ReadResources(condition map[string]interface{}) ([]interface{}, error) { + return ve.WithPageNumberQuery(condition, "PageSize", "PageNumber", 10, 1, func(condition map[string]interface{}) ([]interface{}, error) { + var ( + resp *map[string]interface{} + results interface{} + ok bool + err error + data []interface{} + ) + + action := "DescribeDBAccounts" + logger.Debug(logger.ReqFormat, action, condition) + if condition == nil { + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), nil) + } else { + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), &condition) + } + if err != nil { + return nil, err + } + + logger.Debug(logger.RespFormat, action, condition, *resp) + + results, err = ve.ObtainSdkValue("Result.Accounts", *resp) + if err != nil { + return data, err + } + if results == nil { + results = []interface{}{} + } + if data, ok = results.([]interface{}); !ok { + return data, errors.New("Result.Accounts is not Slice") + } + return data, err + }) +} + +func (s *VolcengineMongoDBAccountService) ReadResource(resourceData *schema.ResourceData, id string) (data map[string]interface{}, err error) { + var ( + results []interface{} + ok bool + ) + if id == "" { + id = s.ReadResourceId(resourceData.Id()) + } + + items := strings.Split(id, ":") + if len(items) != 2 { + return data, fmt.Errorf("the format of import id must be 'instanceId:accountName'") + } + + req := map[string]interface{}{ + "InstanceId": items[0], + "AccountName": items[1], + } + results, err = s.ReadResources(req) + if err != nil { + return data, err + } + for _, v := range results { + if data, ok = v.(map[string]interface{}); !ok { + return data, errors.New("value is not map") + } + } + if len(data) == 0 { + return data, fmt.Errorf("instance %s is not exist", id) + } + + return data, err +} + +func (s *VolcengineMongoDBAccountService) RefreshResourceState(resourceData *schema.ResourceData, target []string, timeout time.Duration, id string) *resource.StateChangeConf { + return nil +} + +func (s *VolcengineMongoDBAccountService) WithResourceResponseHandlers(account map[string]interface{}) []ve.ResourceResponseHandler { + handler := func() (map[string]interface{}, map[string]ve.ResponseConvert, error) { + return account, map[string]ve.ResponseConvert{ + "DBName": { + TargetField: "db_name", + }, + }, nil + } + return []ve.ResourceResponseHandler{handler} + +} + +func (s *VolcengineMongoDBAccountService) CreateResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + callback := ve.Callback{ + Call: ve.SdkCall{ + Action: "ResetDBAccount", + ConvertMode: ve.RequestConvertAll, + ContentType: ve.ContentTypeJson, + ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) { + logger.Debug(logger.ReqFormat, call.Action, call.SdkParam) + return s.Client.UniversalClient.DoCall(getUniversalInfo(call.Action), call.SdkParam) + }, + }, + } + return []ve.Callback{callback} +} + +func (s *VolcengineMongoDBAccountService) ModifyResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + callback := ve.Callback{ + Call: ve.SdkCall{ + Action: "ResetDBAccount", + ConvertMode: ve.RequestConvertIgnore, + ContentType: ve.ContentTypeJson, + BeforeCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (bool, error) { + items := strings.Split(d.Id(), ":") + if len(items) != 2 { + return false, fmt.Errorf("the format of import id must be 'instanceId:accountName'") + } + (*call.SdkParam)["InstanceId"] = items[0] + (*call.SdkParam)["AccountName"] = items[1] + (*call.SdkParam)["AccountPassword"] = d.Get("account_password") + return true, nil + }, + ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) { + logger.Debug(logger.ReqFormat, call.Action, call.SdkParam) + return s.Client.UniversalClient.DoCall(getUniversalInfo(call.Action), call.SdkParam) + }, + }, + } + return []ve.Callback{callback} +} + +func (s *VolcengineMongoDBAccountService) RemoveResource(resourceData *schema.ResourceData, r *schema.Resource) []ve.Callback { + return []ve.Callback{} +} + +func (s *VolcengineMongoDBAccountService) DatasourceResources(data *schema.ResourceData, resource *schema.Resource) ve.DataSourceInfo { + return ve.DataSourceInfo{ + NameField: "AccountName", + CollectField: "accounts", + ResponseConverts: map[string]ve.ResponseConvert{ + "DBName": { + TargetField: "db_name", + }, + }, + } +} + +func (s *VolcengineMongoDBAccountService) ReadResourceId(id string) string { + return id +} diff --git a/volcengine/mongodb/allow_list/data_source_volcengine_mongodb_allow_lists.go b/volcengine/mongodb/allow_list/data_source_volcengine_mongodb_allow_lists.go new file mode 100644 index 00000000..4f9179cb --- /dev/null +++ b/volcengine/mongodb/allow_list/data_source_volcengine_mongodb_allow_lists.go @@ -0,0 +1,105 @@ +package allow_list + +import ( + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" +) + +func DataSourceVolcengineMongoDBAllowLists() *schema.Resource { + return &schema.Resource{ + Read: dataSourceVolcengineMongoDBAllowListsRead, + Schema: map[string]*schema.Schema{ + "region_id": { + Type: schema.TypeString, + Required: true, + Description: "The region ID.", + }, + "instance_id": { + Type: schema.TypeString, + Optional: true, + Description: "The instance ID to query.", + }, + "allow_list_ids": { + Type: schema.TypeList, + Optional: true, + Description: "The allow list IDs to query.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "allow_lists": { + Description: "The collection of mongodb allow list query.", + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "allow_list_desc": { + Type: schema.TypeString, + Computed: true, + Description: "The description of allow list.", + }, + "allow_list_id": { + Type: schema.TypeString, + Computed: true, + Description: "The ID of allow list.", + }, + "allow_list_name": { + Type: schema.TypeString, + Computed: true, + Description: "The allow list name.", + }, + "allow_list_ip_num": { + Type: schema.TypeInt, + Computed: true, + Description: "The number of allow list IPs.", + }, + "allow_list_type": { + Type: schema.TypeString, + Computed: true, + Description: "The IP address type in allow list.", + }, + "associated_instance_num": { + Type: schema.TypeInt, + Computed: true, + Description: "The total number of instances bound under the allow list.", + }, + "allow_list": { + Type: schema.TypeString, + Computed: true, + Description: "The list of IP address in allow list.", + }, + "associated_instances": { + Type: schema.TypeList, + Computed: true, + Description: "The list of associated instances.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "instance_id": { + Type: schema.TypeString, + Computed: true, + Description: "The instance id that bound to the allow list.", + }, + "instance_name": { + Type: schema.TypeString, + Computed: true, + Description: "The instance name that bound to the allow list.", + }, + "vpc": { + Type: schema.TypeString, + Computed: true, + Description: "The VPC ID.", + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func dataSourceVolcengineMongoDBAllowListsRead(d *schema.ResourceData, meta interface{}) error { + service := NewMongoDBAllowListService(meta.(*ve.SdkClient)) + return service.Dispatcher.Data(service, d, DataSourceVolcengineMongoDBAllowLists()) +} diff --git a/volcengine/mongodb/allow_list/resource_volcengine_mongodb_allow_list.go b/volcengine/mongodb/allow_list/resource_volcengine_mongodb_allow_list.go new file mode 100644 index 00000000..d8384f9f --- /dev/null +++ b/volcengine/mongodb/allow_list/resource_volcengine_mongodb_allow_list.go @@ -0,0 +1,109 @@ +package allow_list + +import ( + "fmt" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + ve "github.com/volcengine/terraform-provider-volcengine/common" +) + +/* + +Import +mongosdb allow list can be imported using the allowListId, e.g. +``` +$ terraform import volcengine_mongosdb_allow_list.default acl-d1fd76693bd54e658912e7337d5b**** +``` + +*/ + +func ResourceVolcengineMongoDBAllowList() *schema.Resource { + resource := &schema.Resource{ + Create: resourceVolcengineMongoDBAllowListCreate, + Read: resourceVolcengineMongoDBAllowListRead, + Update: resourceVolcengineMongoDBAllowListUpdate, + Delete: resourceVolcengineMongoDBAllowListDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Schema: map[string]*schema.Schema{ + "allow_list_name": { + Type: schema.TypeString, + Required: true, + Description: "The name of allow list.", + }, + "allow_list_desc": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "The description of allow list.", + }, + "allow_list_type": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{"IPv4"}, false), + Description: "The IP address type of allow list,valid value contains `IPv4`.", + }, + "allow_list": { + Type: schema.TypeString, + Required: true, + Description: "IP address or IP address segment in CIDR format.", + }, + "modify_mode": { + Type: schema.TypeString, + Optional: true, + DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { + return d.Id() == "" + }, + Default: "Cover", + ValidateFunc: validation.StringInSlice([]string{"Cover", "Append", "Delete"}, false), + Description: "The modify mode.", + }, + //"apply_instance_num": { + // Type: schema.TypeInt, + // Optional: true, + // DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { + // return d.Id() == "" + // }, + // Description: "The instance number bound to the allow list,this parameter is required if you need to modify `AllowList`.", + //}, + }, + } + return resource +} + +func resourceVolcengineMongoDBAllowListCreate(d *schema.ResourceData, meta interface{}) (err error) { + service := NewMongoDBAllowListService(meta.(*ve.SdkClient)) + err = service.Dispatcher.Create(service, d, ResourceVolcengineMongoDBAllowList()) + if err != nil { + return fmt.Errorf("Error on creating instance %q,%s", d.Id(), err) + } + return resourceVolcengineMongoDBAllowListRead(d, meta) +} + +func resourceVolcengineMongoDBAllowListUpdate(d *schema.ResourceData, meta interface{}) (err error) { + service := NewMongoDBAllowListService(meta.(*ve.SdkClient)) + err = service.Dispatcher.Update(service, d, ResourceVolcengineMongoDBAllowList()) + if err != nil { + return fmt.Errorf("error on updating instance %q, %s", d.Id(), err) + } + return resourceVolcengineMongoDBAllowListRead(d, meta) +} + +func resourceVolcengineMongoDBAllowListDelete(d *schema.ResourceData, meta interface{}) (err error) { + service := NewMongoDBAllowListService(meta.(*ve.SdkClient)) + err = service.Dispatcher.Delete(service, d, ResourceVolcengineMongoDBAllowList()) + if err != nil { + return fmt.Errorf("error on deleting instance %q, %s", d.Id(), err) + } + return err +} + +func resourceVolcengineMongoDBAllowListRead(d *schema.ResourceData, meta interface{}) (err error) { + service := NewMongoDBAllowListService(meta.(*ve.SdkClient)) + err = service.Dispatcher.Read(service, d, ResourceVolcengineMongoDBAllowList()) + if err != nil { + return fmt.Errorf("Error on reading instance %q,%s", d.Id(), err) + } + return err +} diff --git a/volcengine/mongodb/allow_list/service_volcengine_mongodb_allow_list.go b/volcengine/mongodb/allow_list/service_volcengine_mongodb_allow_list.go new file mode 100644 index 00000000..b33b032c --- /dev/null +++ b/volcengine/mongodb/allow_list/service_volcengine_mongodb_allow_list.go @@ -0,0 +1,271 @@ +package allow_list + +import ( + "errors" + "fmt" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" + "github.com/volcengine/terraform-provider-volcengine/logger" +) + +type VolcengineMongoDBAllowListService struct { + Client *ve.SdkClient + Dispatcher *ve.Dispatcher +} + +func NewMongoDBAllowListService(c *ve.SdkClient) *VolcengineMongoDBAllowListService { + return &VolcengineMongoDBAllowListService{ + Client: c, + Dispatcher: &ve.Dispatcher{}, + } +} + +func (s *VolcengineMongoDBAllowListService) GetClient() *ve.SdkClient { + return s.Client +} + +func (s *VolcengineMongoDBAllowListService) readAllowListDetails(allowListId string) (allowList interface{}, err error) { + var ( + resp *map[string]interface{} + //ok bool + ) + action := "DescribeAllowListDetail" + cond := map[string]interface{}{ + "AllowListId": allowListId, + } + logger.Debug(logger.RespFormat, action, cond) + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), &cond) + if err != nil { + return allowList, err + } + logger.Debug(logger.RespFormat, action, resp) + + allowList, err = ve.ObtainSdkValue("Result", *resp) + if err != nil { + return allowList, err + } + return allowList, err +} + +func (s *VolcengineMongoDBAllowListService) DatasourceResources(data *schema.ResourceData, resource *schema.Resource) ve.DataSourceInfo { + return ve.DataSourceInfo{ + IdField: "AllowListId", + NameField: "AllowListName", + CollectField: "allow_lists", + ContentType: ve.ContentTypeJson, + RequestConverts: map[string]ve.RequestConvert{ + "allow_list_ids": { + TargetField: "AllowListIds", + }, + }, + ResponseConverts: map[string]ve.ResponseConvert{ + "AllowListIPNum": { + TargetField: "allow_list_ip_num", + }, + "VPC": { + TargetField: "vpc", + }, + }, + } +} + +func (s *VolcengineMongoDBAllowListService) ReadResources(condition map[string]interface{}) (data []interface{}, err error) { + var ( + resp *map[string]interface{} + results interface{} + ) + + if allowListIds, ok := condition["AllowListIds"]; ok { + for _, allowListId := range allowListIds.([]interface{}) { + detail, err := s.readAllowListDetails(allowListId.(string)) + if err != nil { + logger.DebugInfo("read allow list %s detail failed,err:%v.", allowListId, err) + continue + } + data = append(data, detail) + } + //detail, err := s.readAllowListDetails(allowListId.(string)) + //if err != nil { + // logger.DebugInfo("read allow list %s detail failed,err:%v.", allowListId, err) + // return nil, err + //} + return data, nil + } + + action := "DescribeAllowLists" + logger.Debug(logger.ReqFormat, action, condition) + if condition == nil { + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), nil) + if err != nil { + return data, err + } + } else { + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), &condition) + if err != nil { + return data, err + } + } + logger.Debug(logger.RespFormat, action, condition, *resp) + results, err = ve.ObtainSdkValue("Result.AllowLists", *resp) + if err != nil { + logger.DebugInfo("ve.ObtainSdkValue return :%v", err) + return data, err + } + if results == nil { + results = []interface{}{} + } + allowLists, ok := results.([]interface{}) + if !ok { + return data, fmt.Errorf("DescribeAllowLists responsed instances is not a slice") + } + + for _, ele := range allowLists { + allowList := ele.(map[string]interface{}) + id := allowList["AllowListId"].(string) + + detail, err := s.readAllowListDetails(id) + if err != nil { + logger.DebugInfo("read allow list %s detail failed,err:%v.", id, err) + data = append(data, ele) + continue + } + allowList["AllowList"] = detail.(map[string]interface{})["AllowList"] + allowList["AssociatedInstances"] = detail.(map[string]interface{})["AssociatedInstances"] + + data = append(data, allowList) + } + return data, nil +} + +func (s *VolcengineMongoDBAllowListService) ReadResource(resourceData *schema.ResourceData, id string) (data map[string]interface{}, err error) { + var ( + results []interface{} + ok bool + ) + if id == "" { + id = s.ReadResourceId(resourceData.Id()) + } + req := map[string]interface{}{ + "AllowListIds": []interface{}{id}, + } + results, err = s.ReadResources(req) + if err != nil { + return data, err + } + for _, v := range results { + if data, ok = v.(map[string]interface{}); !ok { + return data, errors.New("value is not map") + } + } + if len(data) == 0 { + return data, fmt.Errorf("allowlist %s is not exist", id) + } + return data, err +} + +func (s *VolcengineMongoDBAllowListService) RefreshResourceState(resourceData *schema.ResourceData, target []string, timeout time.Duration, id string) *resource.StateChangeConf { + return &resource.StateChangeConf{} +} + +func (s *VolcengineMongoDBAllowListService) WithResourceResponseHandlers(instance map[string]interface{}) []ve.ResourceResponseHandler { + handler := func() (map[string]interface{}, map[string]ve.ResponseConvert, error) { + return instance, nil, nil + } + return []ve.ResourceResponseHandler{handler} +} + +func (s *VolcengineMongoDBAllowListService) CreateResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + callback := ve.Callback{ + Call: ve.SdkCall{ + Action: "CreateAllowList", + ConvertMode: ve.RequestConvertAll, + ContentType: ve.ContentTypeJson, + ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) { + logger.Debug(logger.ReqFormat, call.Action, call.SdkParam) + return s.Client.UniversalClient.DoCall(getUniversalInfo(call.Action), call.SdkParam) + }, + AfterCall: func(d *schema.ResourceData, client *ve.SdkClient, resp *map[string]interface{}, call ve.SdkCall) error { + logger.Debug(logger.RespFormat, call.Action, call.SdkParam, resp) + id, _ := ve.ObtainSdkValue("Result.AllowListId", *resp) + d.SetId(id.(string)) + return nil + }, + }, + } + return []ve.Callback{callback} +} + +func (s *VolcengineMongoDBAllowListService) ModifyResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + callback := ve.Callback{ + Call: ve.SdkCall{ + Action: "ModifyAllowList", + ConvertMode: ve.RequestConvertAll, + BeforeCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (bool, error) { + (*call.SdkParam)["AllowListId"] = d.Id() + (*call.SdkParam)["AllowListName"] = resourceData.Get("allow_list_name") + + if resourceData.HasChange("allow_list") { + //describe allow list, get instance num + var applyInstanceNum int + detail, err := s.readAllowListDetails(d.Id()) + if err != nil { + return false, fmt.Errorf("read allow list detail faield") + } + if associatedInstances, ok := detail.(map[string]interface{})["AssociatedInstances"]; !ok { + return false, fmt.Errorf("read AssociatedInstances failed") + } else { + applyInstanceNum = len(associatedInstances.([]interface{})) + } + + //num, ok := resourceData.GetOkExists("apply_instance_num") + //if !ok { + // return false, fmt.Errorf("apply_instance_num is required if you need to modify allow_list") + //} + (*call.SdkParam)["ApplyInstanceNum"] = applyInstanceNum + } + return true, nil + }, + ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) { + logger.Debug(logger.ReqFormat, call.Action, call.SdkParam) + return s.Client.UniversalClient.DoCall(getUniversalInfo(call.Action), call.SdkParam) + }, + }, + } + + return []ve.Callback{callback} +} + +func (s *VolcengineMongoDBAllowListService) RemoveResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + callback := ve.Callback{ + Call: ve.SdkCall{ + Action: "DeleteAllowList", + ConvertMode: ve.RequestConvertIgnore, + BeforeCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (bool, error) { + (*call.SdkParam)["AllowListId"] = d.Id() + return true, nil + }, + ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) { + logger.Debug(logger.ReqFormat, call.Action, call.SdkParam) + return s.Client.UniversalClient.DoCall(getUniversalInfo(call.Action), call.SdkParam) + }, + }, + } + return []ve.Callback{callback} +} + +func (s *VolcengineMongoDBAllowListService) ReadResourceId(id string) string { + return id +} + +func getUniversalInfo(actionName string) ve.UniversalInfo { + return ve.UniversalInfo{ + ServiceName: "mongodb", + Action: actionName, + Version: "2022-01-01", + HttpMethod: ve.POST, + ContentType: ve.ApplicationJSON, + } +} diff --git a/volcengine/mongodb/allow_list_associate/common_volcengine_mongodb_allow_list_associate.go b/volcengine/mongodb/allow_list_associate/common_volcengine_mongodb_allow_list_associate.go new file mode 100644 index 00000000..adf88d3e --- /dev/null +++ b/volcengine/mongodb/allow_list_associate/common_volcengine_mongodb_allow_list_associate.go @@ -0,0 +1,22 @@ +package allow_list_associate + +import ( + "fmt" + "strings" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +var mongodbAllowListAssociateImporter = func(data *schema.ResourceData, i interface{}) ([]*schema.ResourceData, error) { + items := strings.Split(data.Id(), ":") + if len(items) != 2 { + return []*schema.ResourceData{data}, fmt.Errorf("import id must split with ':'") + } + if err := data.Set("instance_id", items[0]); err != nil { + return []*schema.ResourceData{data}, err + } + if err := data.Set("allow_list_id", items[1]); err != nil { + return []*schema.ResourceData{data}, err + } + return []*schema.ResourceData{data}, nil +} diff --git a/volcengine/mongodb/allow_list_associate/resource_volcengine_mongodb_allow_list_associate.go b/volcengine/mongodb/allow_list_associate/resource_volcengine_mongodb_allow_list_associate.go new file mode 100644 index 00000000..0495af22 --- /dev/null +++ b/volcengine/mongodb/allow_list_associate/resource_volcengine_mongodb_allow_list_associate.go @@ -0,0 +1,71 @@ +package allow_list_associate + +import ( + "fmt" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" +) + +/* + +Import +mongosdb allow list associate can be imported using the instanceId:allowListId, e.g. +``` +$ terraform import volcengine_mongosdb_allow_list_associate.default mongo-replica-e405f8e2****:acl-d1fd76693bd54e658912e7337d5b**** +``` + +*/ + +func ResourceVolcengineMongodbAllowListAssociate() *schema.Resource { + resource := &schema.Resource{ + Read: resourceVolcengineMongodbAllowListAssociateRead, + Create: resourceVolcengineMongodbAllowListAssociateCreate, + Delete: resourceVolcengineMongodbAllowListAssociateDelete, + Importer: &schema.ResourceImporter{ + State: mongodbAllowListAssociateImporter, + }, + Schema: map[string]*schema.Schema{ + "instance_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "Id of instance to associate.", + }, + "allow_list_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "Id of allow list to associate.", + }, + }, + } + return resource +} + +func resourceVolcengineMongodbAllowListAssociateRead(d *schema.ResourceData, meta interface{}) (err error) { + service := NewMongodbAllowListAssociateService(meta.(*ve.SdkClient)) + err = service.Dispatcher.Read(service, d, ResourceVolcengineMongodbAllowListAssociate()) + if err != nil { + return fmt.Errorf("error on reading association %v, %v", d.Id(), err) + } + return err +} + +func resourceVolcengineMongodbAllowListAssociateCreate(d *schema.ResourceData, meta interface{}) (err error) { + service := NewMongodbAllowListAssociateService(meta.(*ve.SdkClient)) + err = service.Dispatcher.Create(service, d, ResourceVolcengineMongodbAllowListAssociate()) + if err != nil { + return fmt.Errorf("error on creating mongodb allow list association %v, %v", d.Id(), err) + } + return err +} + +func resourceVolcengineMongodbAllowListAssociateDelete(d *schema.ResourceData, meta interface{}) (err error) { + service := NewMongodbAllowListAssociateService(meta.(*ve.SdkClient)) + err = service.Dispatcher.Delete(service, d, ResourceVolcengineMongodbAllowListAssociate()) + if err != nil { + return fmt.Errorf("error on deleting mongodb allow list association %v, %v", d.Id(), err) + } + return err +} diff --git a/volcengine/mongodb/allow_list_associate/service_volcengine_mongodb_allow_list_associate.go b/volcengine/mongodb/allow_list_associate/service_volcengine_mongodb_allow_list_associate.go new file mode 100644 index 00000000..bcdc039b --- /dev/null +++ b/volcengine/mongodb/allow_list_associate/service_volcengine_mongodb_allow_list_associate.go @@ -0,0 +1,232 @@ +package allow_list_associate + +import ( + "errors" + "fmt" + "strings" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" + "github.com/volcengine/terraform-provider-volcengine/logger" +) + +type VolcengineMongodbAllowListAssociateService struct { + Client *ve.SdkClient + Dispatcher *ve.Dispatcher +} + +const ( + ActionAssociateAllowList = "AssociateAllowList" + ActionDisassociateAllowList = "DisassociateAllowList" + ActionDescribeDBInstanceDetail = "DescribeDBInstanceDetail" +) + +func NewMongodbAllowListAssociateService(c *ve.SdkClient) *VolcengineMongodbAllowListAssociateService { + return &VolcengineMongodbAllowListAssociateService{ + Client: c, + Dispatcher: &ve.Dispatcher{}, + } +} + +func (s *VolcengineMongodbAllowListAssociateService) GetClient() *ve.SdkClient { + return s.Client +} + +func (s *VolcengineMongodbAllowListAssociateService) ReadResources(m map[string]interface{}) (data []interface{}, err error) { + return nil, nil +} + +func (s *VolcengineMongodbAllowListAssociateService) ReadResource(resourceData *schema.ResourceData, tmpId string) (data map[string]interface{}, err error) { + var ( + ids []string + instanceId string + req map[string]interface{} + output *map[string]interface{} + results interface{} + ok bool + ) + if tmpId == "" { + tmpId = s.ReadResourceId(resourceData.Id()) + } + ids = strings.Split(tmpId, ":") + if len(ids) != 2 { + return data, fmt.Errorf("invalid id") + } + instanceId = ids[0] + req = map[string]interface{}{ + "InstanceId": instanceId, + } + + logger.Debug(logger.ReqFormat, ActionDescribeDBInstanceDetail, req) + output, err = s.Client.UniversalClient.DoCall(getUniversalInfo(ActionDescribeDBInstanceDetail), &req) + logger.Debug(logger.RespFormat, ActionDescribeDBInstanceDetail, req, *output) + + if err != nil { + return data, err + } + results, err = ve.ObtainSdkValue("Result.DBInstance", *output) + if err != nil { + return data, err + } + if data, ok = results.(map[string]interface{}); !ok { + return data, errors.New("value is not map") + } + if len(data) == 0 { + return data, fmt.Errorf("instance(%v) is not existed", instanceId) + } + return data, nil +} + +func (s *VolcengineMongodbAllowListAssociateService) RefreshResourceState(resourceData *schema.ResourceData, target []string, timeout time.Duration, id string) *resource.StateChangeConf { + return &resource.StateChangeConf{ + Delay: time.Second, + Pending: []string{}, + Target: target, + Timeout: timeout, + MinTimeout: time.Second, + + Refresh: func() (result interface{}, state string, err error) { + logger.DebugInfo("Refresh status", 0) + var failStatus []string + failStatus = append(failStatus, "CreateFailed") + + output, err := s.ReadResource(resourceData, id) + if err != nil { + logger.DebugInfo("ActionDescribeDBInstanceDetail failed", 0) + return nil, "", err + } + var status interface{} + status, err = ve.ObtainSdkValue("InstanceStatus", output) + if err != nil { + logger.DebugInfo("ObtainSdkValue InstanceStatus failed", 0) + return nil, "", err + } + statusStr, ok := status.(string) + if !ok { + logger.DebugInfo("Type of InstanceStatus is not string", 0) + return nil, "", fmt.Errorf("type of status if not string") + } + for _, v := range failStatus { + if v == statusStr { + return nil, "", fmt.Errorf("instance status error,status %s", status.(string)) + } + } + return output, statusStr, nil + }, + } +} + +func (s *VolcengineMongodbAllowListAssociateService) WithResourceResponseHandlers(association map[string]interface{}) []ve.ResourceResponseHandler { + handler := func() (map[string]interface{}, map[string]ve.ResponseConvert, error) { + return association, map[string]ve.ResponseConvert{}, nil + } + return []ve.ResourceResponseHandler{handler} +} + +func (s *VolcengineMongodbAllowListAssociateService) CreateResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + callback := ve.Callback{ + Call: ve.SdkCall{ + Action: ActionAssociateAllowList, + ContentType: ve.ContentTypeJson, + Convert: map[string]ve.RequestConvert{}, + ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) { + var ( + output *map[string]interface{} + req map[string]interface{} + err error + ok bool + instanceIdInter interface{} + allowListIdInter interface{} + instanceId string + allowListId string + ) + logger.Debug(logger.ReqFormat, call.Action, *call.SdkParam) + instanceIdInter, ok = (*call.SdkParam)["InstanceId"] + if !ok { + return output, fmt.Errorf("please input instance_id") + } + instanceId, ok = instanceIdInter.(string) + if !ok { + return output, fmt.Errorf("type of instanceIdInter is not string") + } + allowListIdInter, ok = (*call.SdkParam)["AllowListId"] + if !ok { + return output, fmt.Errorf("please input allow_list_id") + } + allowListId, ok = allowListIdInter.(string) + if !ok { + return output, fmt.Errorf("type of allowListIdInter is not string") + } + req = make(map[string]interface{}) + req["InstanceIds"] = []string{instanceId} + req["AllowListIds"] = []string{allowListId} + output, err = s.Client.UniversalClient.DoCall(getUniversalInfo(call.Action), &req) + logger.Debug(logger.RespFormat, call.Action, *call.SdkParam, *output) + return output, err + }, + AfterCall: func(d *schema.ResourceData, client *ve.SdkClient, resp *map[string]interface{}, call ve.SdkCall) error { + d.SetId(fmt.Sprint((*call.SdkParam)["InstanceId"], ":", (*call.SdkParam)["AllowListId"])) + return nil + }, + Refresh: &ve.StateRefresh{ + Target: []string{"Running"}, + Timeout: resourceData.Timeout(schema.TimeoutCreate), + }, + }, + } + return []ve.Callback{callback} +} + +func (s *VolcengineMongodbAllowListAssociateService) ModifyResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + return []ve.Callback{} +} + +func (s *VolcengineMongodbAllowListAssociateService) RemoveResource(resourceData *schema.ResourceData, r *schema.Resource) []ve.Callback { + callback := ve.Callback{ + Call: ve.SdkCall{ + Action: ActionDisassociateAllowList, + ContentType: ve.ContentTypeJson, + ConvertMode: ve.RequestConvertIgnore, + BeforeCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (bool, error) { + id := s.ReadResourceId(d.Id()) + ids := strings.Split(id, ":") + instanceId := ids[0] + allowListId := ids[1] + (*call.SdkParam)["InstanceIds"] = []string{instanceId} + (*call.SdkParam)["AllowListIds"] = []string{allowListId} + return true, nil + }, + ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) { + logger.Debug(logger.ReqFormat, call.Action, *call.SdkParam) + return s.Client.UniversalClient.DoCall(getUniversalInfo(call.Action), call.SdkParam) + }, + Refresh: &ve.StateRefresh{ + Target: []string{"Running"}, + Timeout: resourceData.Timeout(schema.TimeoutDelete), + }, + }, + } + return []ve.Callback{callback} +} + +func (s *VolcengineMongodbAllowListAssociateService) DatasourceResources(data *schema.ResourceData, resource2 *schema.Resource) ve.DataSourceInfo { + return ve.DataSourceInfo{ + ContentType: ve.ContentTypeJson, + } +} + +func (s *VolcengineMongodbAllowListAssociateService) ReadResourceId(id string) string { + return id +} + +func getUniversalInfo(actionName string) ve.UniversalInfo { + return ve.UniversalInfo{ + ServiceName: "mongodb", + Action: actionName, + Version: "2022-01-01", + HttpMethod: ve.POST, + ContentType: ve.ApplicationJSON, + } +} diff --git a/volcengine/mongodb/endpoint/common_volcengine_mongodb_endpoint.go b/volcengine/mongodb/endpoint/common_volcengine_mongodb_endpoint.go new file mode 100644 index 00000000..7af9d1bf --- /dev/null +++ b/volcengine/mongodb/endpoint/common_volcengine_mongodb_endpoint.go @@ -0,0 +1,48 @@ +package endpoint + +import ( + "fmt" + "strings" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" + "github.com/volcengine/terraform-provider-volcengine/logger" +) + +func mongoDBEndpointImporter(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { + items := strings.Split(d.Id(), ":") + if len(items) != 2 { + return []*schema.ResourceData{d}, fmt.Errorf("the format of import id must be 'instanceId:endpointId'") + } + instanceId := items[0] + endpointId := items[1] + d.Set("endpoint_id", endpointId) + d.Set("instance_id", instanceId) + + endpointService := NewMongoDBEndpointService(m.(*ve.SdkClient)) + endpoint, err := endpointService.GetEndpoint(instanceId, endpointId, "", "") + if err != nil { + return []*schema.ResourceData{d}, err + } + if objectId, ok := endpoint["ObjectId"]; ok { + d.Set("object_id", objectId.(string)) + } + if networkType, ok := endpoint["NetworkType"]; ok { + d.Set("network_type", networkType) + } + nodeIds := make([]string, 0) + eipIds := make([]string, 0) + for _, address := range endpoint["DBAddresses"].([]interface{}) { + logger.DebugInfo("address %v :", address) + if nodeId, ok := address.(map[string]interface{})["NodeId"]; ok { + nodeIds = append(nodeIds, nodeId.(string)) + } + if eipId, ok := address.(map[string]interface{})["EipId"]; ok { + eipIds = append(eipIds, eipId.(string)) + } + } + d.Set("mongos_node_ids", nodeIds) + d.Set("eip_ids", eipIds) + + return []*schema.ResourceData{d}, nil +} diff --git a/volcengine/mongodb/endpoint/data_source_volcengine_mongodb_endpoints.go b/volcengine/mongodb/endpoint/data_source_volcengine_mongodb_endpoints.go new file mode 100644 index 00000000..7c7aaa71 --- /dev/null +++ b/volcengine/mongodb/endpoint/data_source_volcengine_mongodb_endpoints.go @@ -0,0 +1,117 @@ +package endpoint + +import ( + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" +) + +func DataSourceVolcengineMongoDBEndpoints() *schema.Resource { + return &schema.Resource{ + Read: dataSourceVolcengineMongoDBEndpointsRead, + Schema: map[string]*schema.Schema{ + "instance_id": { + Type: schema.TypeString, + Optional: true, + Description: "The instance ID to query.", + }, + "output_file": { + Type: schema.TypeString, + Optional: true, + Description: "File name where to save data source results.", + }, + "total_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The total count of mongodb endpoint query.", + }, + "endpoints": { + Description: "The collection of mongodb endpoints query.", + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "db_addresses": { + Type: schema.TypeList, + Computed: true, + Description: "The list of mongodb addresses.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "address_domain": { + Type: schema.TypeString, + Computed: true, + Description: "The domain of mongodb connection.", + }, + "address_ip": { + Type: schema.TypeString, + Computed: true, + Description: "The IP of mongodb connection.", + }, + "address_port": { + Type: schema.TypeString, + Computed: true, + Description: "The port of mongodb connection.", + }, + "address_type": { + Type: schema.TypeString, + Computed: true, + Description: "The connection type of mongodb.", + }, + "eip_id": { + Type: schema.TypeString, + Computed: true, + Description: "The EIP ID bound to the instance's public network address.", + }, + "node_id": { + Type: schema.TypeString, + Computed: true, + Description: "The node ID.", + }, + }, + }, + }, + "endpoint_id": { + Type: schema.TypeString, + Computed: true, + Description: "The ID of endpoint.", + }, + "endpoint_str": { + Type: schema.TypeString, + Computed: true, + Description: "The endpoint information.", + }, + "endpoint_type": { + Type: schema.TypeString, + Computed: true, + Description: "The node type corresponding to the endpoint.", + }, + "network_type": { + Type: schema.TypeString, + Computed: true, + Description: "The network type of endpoint.", + }, + "object_id": { + Type: schema.TypeString, + Computed: true, + Description: "The object ID corresponding to the endpoint.", + }, + "subnet_id": { + Type: schema.TypeString, + Computed: true, + Description: "The subnet ID.", + }, + "vpc_id": { + Type: schema.TypeString, + Computed: true, + Description: "The VPC ID.", + }, + }, + }, + }, + }, + } +} + +func dataSourceVolcengineMongoDBEndpointsRead(d *schema.ResourceData, meta interface{}) error { + service := NewMongoDBEndpointService(meta.(*ve.SdkClient)) + return service.Dispatcher.Data(service, d, DataSourceVolcengineMongoDBEndpoints()) +} diff --git a/volcengine/mongodb/endpoint/resource_volcengine_mongodb_endpoint.go b/volcengine/mongodb/endpoint/resource_volcengine_mongodb_endpoint.go new file mode 100644 index 00000000..8d5f95b5 --- /dev/null +++ b/volcengine/mongodb/endpoint/resource_volcengine_mongodb_endpoint.go @@ -0,0 +1,107 @@ +package endpoint + +import ( + "fmt" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + ve "github.com/volcengine/terraform-provider-volcengine/common" +) + +/* + +Import +mongodb endpoint can be imported using the instanceId:endpointId +`instanceId`: represents the instance that endpoint related to. +`endpointId`: the id of endpoint. +e.g. +``` +$ terraform import volcengine_mongodb_endpoint.default mongo-replica-e405f8e2****:BRhFA0pDAk0XXkxCZQ +``` + +*/ + +func ResourceVolcengineMongoDBEndpoint() *schema.Resource { + resource := &schema.Resource{ + Create: resourceVolcengineMongoDBEndpointCreate, + Read: resourceVolcengineMongoDBEndpointRead, + Update: resourceVolcengineMongoDBEndpointUpdate, + Delete: resourceVolcengineMongoDBEndpointDelete, + Importer: &schema.ResourceImporter{ + State: mongoDBEndpointImporter, + }, + Schema: map[string]*schema.Schema{ + "instance_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: "The instance where the endpoint resides.", + }, + "object_id": { + Type: schema.TypeString, + Optional: true, + Description: "The object ID corresponding to the endpoint.", + }, + "network_type": { + Type: schema.TypeString, + Optional: true, + Default: "Private", + Description: "The network type of endpoint.", + ValidateFunc: validation.StringInSlice([]string{"Private", "Public"}, false), + }, + "mongos_node_ids": { + Type: schema.TypeSet, + Optional: true, + Description: "A list of the Mongos node that needs to apply for the endpoint.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "eip_ids": { + Type: schema.TypeSet, + Optional: true, + Description: "A list of EIP IDs that need to be bound when applying for endpoint.", + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Set: schema.HashString, + }, + "endpoint_id": { + Type: schema.TypeString, + Computed: true, + Description: "The id of endpoint.", + }, + }, + } + return resource +} + +func resourceVolcengineMongoDBEndpointCreate(d *schema.ResourceData, meta interface{}) (err error) { + service := NewMongoDBEndpointService(meta.(*ve.SdkClient)) + err = service.Dispatcher.Create(service, d, ResourceVolcengineMongoDBEndpoint()) + if err != nil { + return fmt.Errorf("Error on creating endpoint %q,%s", d.Id(), err) + } + return resourceVolcengineMongoDBEndpointRead(d, meta) +} + +func resourceVolcengineMongoDBEndpointUpdate(d *schema.ResourceData, meta interface{}) (err error) { + return fmt.Errorf("mongodb endpoint does not support update") +} + +func resourceVolcengineMongoDBEndpointDelete(d *schema.ResourceData, meta interface{}) (err error) { + service := NewMongoDBEndpointService(meta.(*ve.SdkClient)) + err = service.Dispatcher.Delete(service, d, ResourceVolcengineMongoDBEndpoint()) + if err != nil { + return fmt.Errorf("error on deleting endpoint %q, %s", d.Id(), err) + } + return err +} + +func resourceVolcengineMongoDBEndpointRead(d *schema.ResourceData, meta interface{}) (err error) { + service := NewMongoDBEndpointService(meta.(*ve.SdkClient)) + err = service.Dispatcher.Read(service, d, ResourceVolcengineMongoDBEndpoint()) + if err != nil { + return fmt.Errorf("Error on reading endpoint %q,%s", d.Id(), err) + } + return err +} diff --git a/volcengine/mongodb/endpoint/service_volcengine_mongodb_endpoint.go b/volcengine/mongodb/endpoint/service_volcengine_mongodb_endpoint.go new file mode 100644 index 00000000..0ff225e4 --- /dev/null +++ b/volcengine/mongodb/endpoint/service_volcengine_mongodb_endpoint.go @@ -0,0 +1,249 @@ +package endpoint + +import ( + "errors" + "fmt" + "time" + + mongodbInstance "github.com/volcengine/terraform-provider-volcengine/volcengine/mongodb/instance" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" + "github.com/volcengine/terraform-provider-volcengine/logger" +) + +type VolcengineMongoDBEndpointService struct { + Client *ve.SdkClient + Dispatcher *ve.Dispatcher +} + +func NewMongoDBEndpointService(c *ve.SdkClient) *VolcengineMongoDBEndpointService { + return &VolcengineMongoDBEndpointService{ + Client: c, + Dispatcher: &ve.Dispatcher{}, + } +} + +func (s *VolcengineMongoDBEndpointService) GetClient() *ve.SdkClient { + return s.Client +} + +func (s *VolcengineMongoDBEndpointService) ReadResources(condition map[string]interface{}) (data []interface{}, err error) { + var ( + resp *map[string]interface{} + results interface{} + ok bool + ) + action := "DescribeDBEndpoint" + + logger.Debug(logger.ReqFormat, action, condition) + if condition == nil { + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), nil) + if err != nil { + return data, err + } + } else { + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), &condition) + if err != nil { + return data, err + } + } + + logger.Debug(logger.RespFormat, action, resp) + results, err = ve.ObtainSdkValue("Result.DBEndpoints", *resp) + if err != nil { + return data, err + } + if results == nil { + results = []interface{}{} + } + if data, ok = results.([]interface{}); !ok { + return data, errors.New("Result.DBEndpoints is not Slice") + } + return data, err +} + +func (s *VolcengineMongoDBEndpointService) GetEndpoint(instanceId, endpointId, networkType, objectId string) (endpoint map[string]interface{}, err error) { + req := map[string]interface{}{ + "InstanceId": instanceId, + } + results, err := s.ReadResources(req) + if err != nil { + return nil, err + } + for _, v := range results { + dbEndpoint, ok := v.(map[string]interface{}) + if !ok { + return nil, fmt.Errorf("dbEndpoint value is not map") + } + if endpointId != "" && endpointId == dbEndpoint["EndpointId"].(string) { + return dbEndpoint, nil + } + if networkType == dbEndpoint["NetworkType"].(string) { // private or public + if objectId == "" || (objectId != "" && objectId == dbEndpoint["ObjectId"].(string)) { //endpointType is ReplicaSet if objectId is empty + return dbEndpoint, nil + } + } + } + return nil, fmt.Errorf("the endpoint not found") +} + +func (s *VolcengineMongoDBEndpointService) ReadResource(resourceData *schema.ResourceData, id string) (data map[string]interface{}, err error) { + return data, err +} + +func (s *VolcengineMongoDBEndpointService) RefreshResourceState(resourceData *schema.ResourceData, target []string, timeout time.Duration, id string) *resource.StateChangeConf { + return &resource.StateChangeConf{} +} + +func (s *VolcengineMongoDBEndpointService) WithResourceResponseHandlers(instance map[string]interface{}) []ve.ResourceResponseHandler { + handler := func() (map[string]interface{}, map[string]ve.ResponseConvert, error) { + return instance, nil, nil + } + return []ve.ResourceResponseHandler{handler} +} + +func (s *VolcengineMongoDBEndpointService) CreateResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + instanceId := resourceData.Get("instance_id").(string) + callback := ve.Callback{ + Call: ve.SdkCall{ + Action: "CreateDBEndpoint", + ConvertMode: ve.RequestConvertAll, + ContentType: ve.ContentTypeJson, + Convert: map[string]ve.RequestConvert{ + "eip_ids": { + ConvertType: ve.ConvertJsonArray, + }, + "mongos_node_ids": { + ConvertType: ve.ConvertJsonArray, + }, + }, + BeforeCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (bool, error) { + networkType := d.Get("network_type") + eipIds := d.Get("eip_ids") + if networkType != nil && networkType.(string) == "Public" { + if eipIds == nil { + return false, fmt.Errorf("eip_ids is required when network_type is 'Public'") + } + } + return true, nil + }, + ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) { + logger.Debug(logger.ReqFormat, call.Action, call.SdkParam) + return s.Client.UniversalClient.DoCall(getUniversalInfo(call.Action), call.SdkParam) + }, + ExtraRefresh: map[ve.ResourceService]*ve.StateRefresh{ + mongodbInstance.NewMongoDBInstanceService(s.Client): { + Target: []string{"Running"}, + Timeout: resourceData.Timeout(schema.TimeoutCreate), + ResourceId: instanceId, + }, + }, + LockId: func(d *schema.ResourceData) string { + logger.Debug("lock instance id:%s", instanceId, "") + return instanceId + }, + }, + } + obtainEndpointIdCallback := ve.Callback{ + Call: ve.SdkCall{ + ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) { + networkType := "Private" + if a, ok := d.GetOkExists("network_type"); ok { + networkType = a.(string) + } + objectId := "" + if a, ok := d.GetOkExists("object_id"); ok { + objectId = a.(string) + } + endpoint, err := s.GetEndpoint(instanceId, "", networkType, objectId) + if err != nil { + return nil, err + } + endpointId := endpoint["EndpointId"].(string) + d.Set("endpoint_id", endpointId) + d.SetId(fmt.Sprintf("%s:%s", instanceId, endpointId)) + return nil, nil + }, + }, + } + + return []ve.Callback{callback, obtainEndpointIdCallback} +} + +func (s *VolcengineMongoDBEndpointService) ModifyResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + return []ve.Callback{} +} + +func (s *VolcengineMongoDBEndpointService) RemoveResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + instanceId := resourceData.Get("instance_id").(string) + callback := ve.Callback{ + Call: ve.SdkCall{ + Action: "DeleteDBEndpoint", + ConvertMode: ve.RequestConvertIgnore, + BeforeCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (bool, error) { + // DescribeDBEndpoint : obtain EndpointId + (*call.SdkParam)["InstanceId"] = instanceId + (*call.SdkParam)["EndpointId"] = d.Get("endpoint_id") + if d.Get("mongos_node_id") != nil { + (*call.SdkParam)["MongosNodeIds"] = []interface{}{d.Get("mongos_node_id")} + } + return true, nil + }, + ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) { + logger.Debug(logger.ReqFormat, call.Action, call.SdkParam) + return s.Client.UniversalClient.DoCall(getUniversalInfo(call.Action), call.SdkParam) + }, + ExtraRefresh: map[ve.ResourceService]*ve.StateRefresh{ + mongodbInstance.NewMongoDBInstanceService(s.Client): { + Target: []string{"Running"}, + Timeout: resourceData.Timeout(schema.TimeoutCreate), + ResourceId: instanceId, + }, + }, + LockId: func(d *schema.ResourceData) string { + return instanceId + }, + }, + } + return []ve.Callback{callback} +} + +func (s *VolcengineMongoDBEndpointService) DatasourceResources(data *schema.ResourceData, resource *schema.Resource) ve.DataSourceInfo { + return ve.DataSourceInfo{ + RequestConverts: map[string]ve.RequestConvert{ + "db_engine": { + TargetField: "DBEngine", + }, + "db_engine_version": { + TargetField: "DBEngineVersion", + }, + }, + IdField: "EndpointId", + CollectField: "endpoints", + ContentType: ve.ContentTypeJson, + ResponseConverts: map[string]ve.ResponseConvert{ + "DBAddresses": { + TargetField: "db_addresses", + }, + "AddressIP": { + TargetField: "address_ip", + }, + }, + } +} + +func (s *VolcengineMongoDBEndpointService) ReadResourceId(id string) string { + return id +} + +func getUniversalInfo(actionName string) ve.UniversalInfo { + return ve.UniversalInfo{ + ServiceName: "mongodb", + Action: actionName, + Version: "2022-01-01", + HttpMethod: ve.POST, + ContentType: ve.ApplicationJSON, + } +} diff --git a/volcengine/mongodb/instance/data_source_volcengine_mongodb_instances.go b/volcengine/mongodb/instance/data_source_volcengine_mongodb_instances.go new file mode 100644 index 00000000..2d15fdff --- /dev/null +++ b/volcengine/mongodb/instance/data_source_volcengine_mongodb_instances.go @@ -0,0 +1,454 @@ +package instance + +import ( + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + ve "github.com/volcengine/terraform-provider-volcengine/common" +) + +func DataSourceVolcengineMongoDBInstances() *schema.Resource { + return &schema.Resource{ + Read: dataSourceVolcengineMongoDBInstancesRead, + Schema: map[string]*schema.Schema{ + "zone_id": { + Type: schema.TypeString, + Optional: true, + Description: "The zone ID to query.", + }, + "instance_id": { + Type: schema.TypeString, + Optional: true, + Description: "The instance ID to query.", + }, + "instance_name": { + Type: schema.TypeString, + Optional: true, + Description: "The instance name to query.", + }, + "instance_type": { + Type: schema.TypeString, + Optional: true, + Description: "The type of instance to query,the valid value contains `ReplicaSet` or `ShardedCluster`.", + ValidateFunc: validation.StringInSlice([]string{"ReplicaSet", "ShardedCluster"}, false), + }, + "instance_status": { + Type: schema.TypeString, + Optional: true, + Description: "The instance status to query.", + }, + "db_engine": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{"MongoDB"}, false), + Description: "The db engine to query,valid value contains `MongoDB`.", + }, + "db_engine_version": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{"MongoDB_4_0"}, false), + Description: "The version of db engine to query,valid value contains `MongoDB_4_0`.", + }, + "create_start_time": { + Type: schema.TypeString, + Optional: true, + Description: "The start time of creation to query.", + }, + "create_end_time": { + Type: schema.TypeString, + Optional: true, + Description: "The end time of creation to query.", + }, + "update_start_time": { + Type: schema.TypeString, + Optional: true, + Description: "The start time of update to query.", + }, + "update_end_time": { + Type: schema.TypeString, + Optional: true, + Description: "The end time of update to query.", + }, + "vpc_id": { + Type: schema.TypeString, + Optional: true, + Description: "The vpc id of instance to query.", + }, + "output_file": { + Type: schema.TypeString, + Optional: true, + Description: "File name where to save data source results.", + }, + "total_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The total count of mongodb instances query.", + }, + "instances": { + Description: "The collection of mongodb instances query.", + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "auto_renew": { + Type: schema.TypeBool, + Computed: true, + Description: "Whether to enable automatic renewal.", + }, + "charge_status": { + Type: schema.TypeString, + Computed: true, + Description: "The charge status.", + }, + "charge_type": { + Type: schema.TypeString, + Computed: true, + Description: "The charge type of instance.", + }, + "closed_time": { + Type: schema.TypeString, + Computed: true, + Description: "The planned close time.", + }, + "config_servers": { + Type: schema.TypeList, + Computed: true, + Description: "The list of config servers.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "config_server_node_id": { + Type: schema.TypeString, + Computed: true, + Description: "The config server node ID.", + }, + "node_role": { + Type: schema.TypeString, + Computed: true, + Description: "The config server node role.", + }, + "node_status": { + Type: schema.TypeString, + Computed: true, + Description: "The config server node status.", + }, + "total_memory_gb": { + Type: schema.TypeFloat, + Computed: true, + Description: "The total memory in GB.", + }, + "total_vcpu": { + Type: schema.TypeFloat, + Computed: true, + Description: "The total vCPU.", + }, + "used_memory_gb": { + Type: schema.TypeFloat, + Computed: true, + Description: "The used memory in GB.", + }, + "used_vcpu": { + Type: schema.TypeFloat, + Computed: true, + Description: "The used vCPU.", + }, + }, + }, + }, + "config_servers_id": { + Type: schema.TypeString, + Computed: true, + Description: "The ID of config servers.", + }, + "create_time": { + Type: schema.TypeString, + Computed: true, + Description: "The creation time of instance.", + }, + "db_engine": { + Type: schema.TypeString, + Computed: true, + Description: "The db engine.", + }, + "db_engine_version": { + Type: schema.TypeString, + Computed: true, + Description: "The version of database engine.", + }, + "db_engine_version_str": { + Type: schema.TypeString, + Computed: true, + Description: "The version string of database engine.", + }, + "expired_time": { + Type: schema.TypeString, + Computed: true, + Description: "The expired time of instance.", + }, + "instance_id": { + Type: schema.TypeString, + Computed: true, + Description: "The instance ID.", + }, + "instance_name": { + Type: schema.TypeString, + Computed: true, + Description: "The instance name.", + }, + "instance_status": { + Type: schema.TypeString, + Computed: true, + Description: "The instance status.", + }, + "instance_type": { + Type: schema.TypeString, + Computed: true, + Description: "The instance type.", + }, + "nodes": { + Type: schema.TypeList, + Computed: true, + Description: "The node information.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "node_delay_time": { + Type: schema.TypeInt, + Computed: true, + Description: "The master-slave delay time.", + }, + "node_id": { + Type: schema.TypeString, + Computed: true, + Description: "The node ID.", + }, + "node_role": { + Type: schema.TypeString, + Computed: true, + Description: "The nod role.", + }, + "node_spec": { + Type: schema.TypeString, + Computed: true, + Description: "The node spec.", + }, + "node_status": { + Type: schema.TypeString, + Computed: true, + Description: "The node status.", + }, + "total_memory_gb": { + Type: schema.TypeFloat, + Computed: true, + Description: "The total memory in GB.", + }, + "total_storage_gb": { + Type: schema.TypeFloat, + Computed: true, + Description: "The total storage in GB.", + }, + "total_vcpu": { + Type: schema.TypeFloat, + Computed: true, + Description: "The total vCPU.", + }, + "used_memory_gb": { + Type: schema.TypeFloat, + Computed: true, + Description: "The used memory in GB.", + }, + "used_storage_gb": { + Type: schema.TypeFloat, + Computed: true, + Description: "The used storage in GB.", + }, + "used_vcpu": { + Type: schema.TypeFloat, + Computed: true, + Description: "The used vCPU.", + }, + }, + }, + }, + "mongos": { + Type: schema.TypeList, + Computed: true, + Description: "The list of mongos.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "mongos_node_id": { + Type: schema.TypeString, + Computed: true, + Description: "The mongos node ID.", + }, + "node_spec": { + Type: schema.TypeString, + Computed: true, + Description: "The node spec.", + }, + "node_status": { + Type: schema.TypeString, + Computed: true, + Description: "The node status.", + }, + "total_memory_gb": { + Type: schema.TypeFloat, + Computed: true, + Description: "The total memory in GB.", + }, + "total_vcpu": { + Type: schema.TypeFloat, + Computed: true, + Description: "The total vCPU.", + }, + "used_memory_gb": { + Type: schema.TypeFloat, + Computed: true, + Description: "The used memory in GB.", + }, + "used_vcpu": { + Type: schema.TypeFloat, + Computed: true, + Description: "The used vCPU.", + }, + }, + }, + }, + + "project_name": { + Type: schema.TypeString, + Computed: true, + Description: "The project name to which the instance belongs.", + }, + "mongos_id": { + Type: schema.TypeString, + Computed: true, + Description: "The ID of mongos.", + }, + "reclaim_time": { + Type: schema.TypeString, + Computed: true, + Description: "The planned reclaim time of instance.", + }, + "shards": { + Type: schema.TypeList, + Computed: true, + Description: "The list of shards.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "nodes": { + Type: schema.TypeList, + Computed: true, + Description: "The node information.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "node_delay_time": { + Type: schema.TypeInt, + Computed: true, + Description: "The master-slave delay time.", + }, + "node_id": { + Type: schema.TypeString, + Computed: true, + Description: "The node ID.", + }, + "node_role": { + Type: schema.TypeString, + Computed: true, + Description: "The nod role.", + }, + "node_spec": { + Type: schema.TypeString, + Computed: true, + Description: "The node spec.", + }, + "node_status": { + Type: schema.TypeString, + Computed: true, + Description: "The node status.", + }, + "total_memory_gb": { + Type: schema.TypeFloat, + Computed: true, + Description: "The total memory in GB.", + }, + "total_storage_gb": { + Type: schema.TypeFloat, + Computed: true, + Description: "The total storage in GB.", + }, + "total_vcpu": { + Type: schema.TypeFloat, + Computed: true, + Description: "The total vCPU.", + }, + "used_memory_gb": { + Type: schema.TypeFloat, + Computed: true, + Description: "The used memory in GB.", + }, + "used_storage_gb": { + Type: schema.TypeFloat, + Computed: true, + Description: "The used storage in GB.", + }, + "used_vcpu": { + Type: schema.TypeFloat, + Computed: true, + Description: "The used vCPU.", + }, + }, + }, + }, + "shard_id": { + Type: schema.TypeString, + Computed: true, + Description: "The shard ID.", + }, + }, + }, + }, + "vpc_id": { + Type: schema.TypeString, + Computed: true, + Description: "The vpc ID.", + }, + "subnet_id": { + Type: schema.TypeString, + Computed: true, + Description: "The subnet id of instance.", + }, + "update_time": { + Type: schema.TypeString, + Computed: true, + Description: "The update time of instance.", + }, + "zone_id": { + Type: schema.TypeString, + Computed: true, + ForceNew: true, + Description: "The zone ID of instance.", + }, + "ssl_enable": { + Type: schema.TypeBool, + Computed: true, + Description: "Whether ssl enabled.", + }, + "ssl_is_valid": { + Type: schema.TypeBool, + Computed: true, + Description: "Whether ssl is valid.", + }, + "ssl_expire_time": { + Type: schema.TypeString, + Computed: true, + Description: "The ssl expire time.", + }, + }, + }, + }, + }, + } +} + +func dataSourceVolcengineMongoDBInstancesRead(d *schema.ResourceData, meta interface{}) error { + service := NewMongoDBInstanceService(meta.(*ve.SdkClient)) + return service.Dispatcher.Data(service, d, DataSourceVolcengineMongoDBInstances()) +} diff --git a/volcengine/mongodb/instance/resource_volcengine_mongodb_instance.go b/volcengine/mongodb/instance/resource_volcengine_mongodb_instance.go new file mode 100644 index 00000000..df487be3 --- /dev/null +++ b/volcengine/mongodb/instance/resource_volcengine_mongodb_instance.go @@ -0,0 +1,199 @@ +package instance + +import ( + "fmt" + + "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" +) + +/* + +Import +mongosdb instance can be imported using the id, e.g. +``` +$ terraform import volcengine_mongosdb_instance.default mongo-replica-e405f8e2**** +``` + +*/ + +func ResourceVolcengineMongoDBInstance() *schema.Resource { + resource := &schema.Resource{ + Create: resourceVolcengineMongoDBInstanceCreate, + Read: resourceVolcengineMongoDBInstanceRead, + Update: resourceVolcengineMongoDBInstanceUpdate, + Delete: resourceVolcengineMongoDBInstanceDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Schema: map[string]*schema.Schema{ + "zone_id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "The zone ID of instance.", + }, + // "db_engine": { + // Type: schema.TypeString, + // Optional: true, + // Computed: true, + // ValidateFunc: validation.StringInSlice([]string{"MongoDB"}, false), + // Description: "The db engine,valid value contains `MongoDB`.", + // }, + // "db_engine_version": { + // Type: schema.TypeString, + // Optional: true, + // Computed: true, + // ValidateFunc: validation.StringInSlice([]string{"MongoDB_4_0"}, false), + // Description: "The version of db engine,valid value contains `MongoDB_4_0`.", + // }, + "node_spec": { + Type: schema.TypeString, + Required: true, + Description: "The spec of node.", + }, + // "node_number": { + // Type: schema.TypeInt, + // Optional: true, + // Computed: true, + // Description: "If `InstanceType` is `ReplicaSet`,this parameter indicates the number of compute nodes of the replica set instance,if `InstanceType` is `ShardedCluster`,this parameter indicates the number of nodes in each shard.", + // }, + "instance_type": { + Type: schema.TypeString, + Optional: true, + Computed: true, + //Default: "ReplicaSet", + Description: "The type of instance,the valid value contains `ReplicaSet` or `ShardedCluster`.", + ValidateFunc: validation.StringInSlice([]string{"ReplicaSet", "ShardedCluster"}, false), + }, + "mongos_node_spec": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "The mongos node spec of shard cluster,this parameter is required when `InstanceType` is `ShardedCluster`.", + }, + "mongos_node_number": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "The mongos node number of shard cluster,value range is `2~23`,this parameter is required when `InstanceType` is `ShardedCluster`.", + }, + "shard_number": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "The number of shards in shard cluster,value range is `2~23`,this parameter is required when `InstanceType` is `ShardedCluster`.", + }, + "storage_space_gb": { + Type: schema.TypeInt, + Required: true, + Description: "The total storage space of a replica set instance, or the storage space of a single shard in a sharded cluster, in GiB.", + }, + "vpc_id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "The vpc ID.", + }, + "subnet_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: func(i interface{}, s string) ([]string, []error) { + return validation.StringIsNotEmpty(i, s) + }, + Description: "The subnet id of instance.", + }, + // "super_account_name": { + // Type: schema.TypeString, + // Required: true, + // ValidateFunc: validation.StringInSlice([]string{"root"}, false), + // Description: "The name of database account,must be `root`.", + // }, + "super_account_password": { + Type: schema.TypeString, + Required: true, + Sensitive: true, + Description: "The password of database account.", + }, + "instance_name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "The instance name.", + }, + "charge_type": { + Type: schema.TypeString, + Optional: true, + Computed: true, + //Default: "PostPaid", + ValidateFunc: validation.StringInSlice([]string{"Prepaid", "PostPaid"}, false), + Description: "The charge type of instance,valid value contains `Prepaid` or `PostPaid`.", + }, + "auto_renew": { + Type: schema.TypeBool, + Optional: true, + Computed: true, + Description: "Whether to enable automatic renewal.", + }, + "period_unit": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "The period unit,valid value contains `Year` or `Month`,this parameter is required when `ChargeType` is `Prepaid`.", + ValidateFunc: validation.StringInSlice([]string{"Year", "Month"}, false), + }, + "period": { + Type: schema.TypeInt, + Optional: true, + Computed: true, + Description: "The instance purchase duration,the value range is `1~3` when `PeriodUtil` is `Year`,the value range is `1~9` when `PeriodUtil` is `Month`,this parameter is required when `ChargeType` is `Prepaid`.", + }, + "project_name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "The project name to which the instance belongs.", + }, + }, + } + return resource +} + +func resourceVolcengineMongoDBInstanceCreate(d *schema.ResourceData, meta interface{}) (err error) { + service := NewMongoDBInstanceService(meta.(*ve.SdkClient)) + err = service.Dispatcher.Create(service, d, ResourceVolcengineMongoDBInstance()) + if err != nil { + return fmt.Errorf("Error on creating instance %q,%s", d.Id(), err) + } + return resourceVolcengineMongoDBInstanceRead(d, meta) +} + +func resourceVolcengineMongoDBInstanceUpdate(d *schema.ResourceData, meta interface{}) (err error) { + service := NewMongoDBInstanceService(meta.(*ve.SdkClient)) + err = service.Dispatcher.Update(service, d, ResourceVolcengineMongoDBInstance()) + if err != nil { + return fmt.Errorf("error on updating instance %q, %s", d.Id(), err) + } + return resourceVolcengineMongoDBInstanceRead(d, meta) +} + +func resourceVolcengineMongoDBInstanceDelete(d *schema.ResourceData, meta interface{}) (err error) { + service := NewMongoDBInstanceService(meta.(*ve.SdkClient)) + err = service.Dispatcher.Delete(service, d, ResourceVolcengineMongoDBInstance()) + if err != nil { + return fmt.Errorf("error on deleting instance %q, %s", d.Id(), err) + } + return err +} + +func resourceVolcengineMongoDBInstanceRead(d *schema.ResourceData, meta interface{}) (err error) { + service := NewMongoDBInstanceService(meta.(*ve.SdkClient)) + err = service.Dispatcher.Read(service, d, ResourceVolcengineMongoDBInstance()) + if err != nil { + return fmt.Errorf("Error on reading instance %q,%s", d.Id(), err) + } + return err +} diff --git a/volcengine/mongodb/instance/service_volcengine_mongodb_instance.go b/volcengine/mongodb/instance/service_volcengine_mongodb_instance.go new file mode 100644 index 00000000..78972293 --- /dev/null +++ b/volcengine/mongodb/instance/service_volcengine_mongodb_instance.go @@ -0,0 +1,572 @@ +package instance + +import ( + "errors" + "fmt" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" + "github.com/volcengine/terraform-provider-volcengine/logger" +) + +type VolcengineMongoDBInstanceService struct { + Client *ve.SdkClient + Dispatcher *ve.Dispatcher +} + +func NewMongoDBInstanceService(c *ve.SdkClient) *VolcengineMongoDBInstanceService { + return &VolcengineMongoDBInstanceService{ + Client: c, + Dispatcher: &ve.Dispatcher{}, + } +} + +func (s *VolcengineMongoDBInstanceService) GetClient() *ve.SdkClient { + return s.Client +} + +func (s *VolcengineMongoDBInstanceService) ReadInstanceDetails(id string) (instance interface{}, err error) { + var ( + resp *map[string]interface{} + ) + action := "DescribeDBInstanceDetail" + cond := map[string]interface{}{ + "InstanceId": id, + } + logger.Debug(logger.RespFormat, action, cond) + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), &cond) + if err != nil { + return instance, err + } + logger.Debug(logger.RespFormat, action, resp) + + instance, err = ve.ObtainSdkValue("Result.DBInstance", *resp) + if err != nil { + return instance, err + } + + return instance, err +} + +func (s *VolcengineMongoDBInstanceService) readSSLDetails(id string) (ssl interface{}, err error) { + var ( + resp *map[string]interface{} + ) + action := "DescribeDBInstanceSSL" + cond := map[string]interface{}{ + "InstanceId": id, + } + logger.Debug(logger.RespFormat, action, cond) + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), &cond) + if err != nil { + return ssl, err + } + logger.Debug(logger.RespFormat, action, resp) + + return ve.ObtainSdkValue("Result", *resp) +} + +func (s *VolcengineMongoDBInstanceService) ReadResources(condition map[string]interface{}) (data []interface{}, err error) { + var ( + resp *map[string]interface{} + results interface{} + ) + withoutDetail, containWithoutDetail := condition["WithoutDetail"] + if !containWithoutDetail { + withoutDetail = false + } + return ve.WithPageNumberQuery(condition, "PageSize", "PageNumber", 20, 1, func(m map[string]interface{}) ([]interface{}, error) { + action := "DescribeDBInstances" + logger.Debug(logger.ReqFormat, action, condition) + if condition == nil { + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), nil) + if err != nil { + return data, err + } + } else { + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), &condition) + if err != nil { + return data, err + } + } + logger.Debug(logger.RespFormat, action, condition, *resp) + results, err = ve.ObtainSdkValue("Result.DBInstances", *resp) + if err != nil { + logger.DebugInfo("ve.ObtainSdkValue return :%v", err) + return data, err + } + if results == nil { + results = []interface{}{} + } + instances, ok := results.([]interface{}) + if !ok { + return data, fmt.Errorf("DescribeDBInstances responsed instances is not a slice") + } + + for _, ele := range instances { + ins := ele.(map[string]interface{}) + instanceId := ins["InstanceId"].(string) + + // do not get detail when refresh status + if withoutDetail.(bool) { + data = append(data, ins) + continue + } + + detail, err := s.ReadInstanceDetails(instanceId) + if err != nil { + logger.DebugInfo("read instance %s detail failed,err:%v.", instanceId, err) + data = append(data, ele) + continue + } + ssl, err := s.readSSLDetails(instanceId) + if err != nil { + logger.DebugInfo("read instance ssl information of %s failed,err:%v.", instanceId, err) + data = append(data, ele) + continue + } + ins["ConfigServers"] = detail.(map[string]interface{})["ConfigServers"] + ins["Nodes"] = detail.(map[string]interface{})["Nodes"] + ins["Mongos"] = detail.(map[string]interface{})["Mongos"] + ins["Shards"] = detail.(map[string]interface{})["Shards"] + + ins["SSLEnable"] = ssl.(map[string]interface{})["SSLEnable"] + ins["SSLIsValid"] = ssl.(map[string]interface{})["IsValid"] + ins["SSLExpiredTime"] = ssl.(map[string]interface{})["SSLExpiredTime"] + data = append(data, ins) + } + return data, nil + }) +} + +func (s *VolcengineMongoDBInstanceService) ReadResource(resourceData *schema.ResourceData, id string) (data map[string]interface{}, err error) { + var ( + results []interface{} + ok bool + ) + if id == "" { + id = s.ReadResourceId(resourceData.Id()) + } + + req := map[string]interface{}{ + "InstanceId": id, + "withoutDetail": true, + } + results, err = s.ReadResources(req) + if err != nil { + return data, err + } + for _, v := range results { + if data, ok = v.(map[string]interface{}); !ok { + return data, errors.New("value is not map") + } + } + if len(data) == 0 { + return data, fmt.Errorf("instance %s is not exist", id) + } + + // import时设置默认值 + if _, ok := resourceData.GetOkExists("ssl_action"); !ok { + data["SslAction"] = "-" + } + if _, ok := resourceData.GetOkExists("restart_instance"); !ok { + data["RestartInstance"] = false + } + + if data["InstanceType"].(string) == "ReplicaSet" { + if temp, ok := data["Nodes"]; ok && temp != nil { + nodes := temp.([]interface{}) + data["NodeNumber"] = len(nodes) + data["NodeSpec"] = nodes[0].(map[string]interface{})["NodeSpec"] + } else { + data["NodeNumber"] = 0 + } + } + if data["InstanceType"].(string) == "ShardedCluster" { + if temp, ok := data["Mongos"]; ok && temp != nil { + mongos := temp.([]interface{}) + data["MongosNodeNumber"] = len(mongos) + data["MongosNodeSpec"] = mongos[0].(map[string]interface{})["NodeSpec"] + } else { + data["MongosNodeNumber"] = 0 + } + if temp, ok := data["Shards"]; ok && temp != nil { + shards := temp.([]interface{}) + data["ShardNumber"] = len(shards) + if tmp, ok := shards[0].(map[string]interface{})["Nodes"]; ok { + nodes := tmp.([]interface{}) + data["StorageSpaceGb"] = nodes[0].(map[string]interface{})["TotalStorageGB"] + data["NodeSpec"] = nodes[0].(map[string]interface{})["NodeSpec"] + data["NodeNumber"] = len(nodes) + } + } else { + data["ShardNumber"] = 0 + data["StorageSpaceGb"] = 0 + } + } + return data, err +} + +func (s *VolcengineMongoDBInstanceService) RefreshResourceState(resourceData *schema.ResourceData, target []string, timeout time.Duration, id string) *resource.StateChangeConf { + return &resource.StateChangeConf{ + Delay: 1 * time.Second, + Pending: []string{}, + Target: target, + Timeout: timeout, + MinTimeout: 1 * time.Second, + + Refresh: func() (result interface{}, state string, err error) { + var ( + instance map[string]interface{} + status interface{} + failStates []string + ) + failStates = append(failStates, "CreateFailed", "Failed") + + logger.DebugInfo("start refresh :%s", id) + instance, err = s.ReadResource(resourceData, id) + if err != nil { + return nil, "", err + } + logger.DebugInfo("Refresh instance status resp: %v", instance) + + status, err = ve.ObtainSdkValue("InstanceStatus", instance) + if err != nil { + return nil, "", err + } + for _, v := range failStates { + if v == status.(string) { + return nil, "", fmt.Errorf("instance status error,status %s", status.(string)) + } + } + logger.DebugInfo("refresh status:%v", status) + return instance, status.(string), err + }, + } +} + +func (s *VolcengineMongoDBInstanceService) WithResourceResponseHandlers(instance map[string]interface{}) []ve.ResourceResponseHandler { + handler := func() (map[string]interface{}, map[string]ve.ResponseConvert, error) { + return instance, map[string]ve.ResponseConvert{ + "DBEngine": { + TargetField: "db_ending", + }, + "DBEngineVersion": { + TargetField: "db_engine_version", + }, + "DBEngineVersionStr": { + TargetField: "db_engine_version_str", + }, + }, nil + } + return []ve.ResourceResponseHandler{handler} +} + +func (s *VolcengineMongoDBInstanceService) getVpcIdAndZoneIdBySubnet(subnetId string) (vpcId, zoneId string, err error) { + // describe subnet + req := map[string]interface{}{ + "SubnetIds.1": subnetId, + } + action := "DescribeSubnets" + resp, err := s.Client.VpcClient.DescribeSubnetsCommon(&req) + if err != nil { + return "", "", err + } + logger.Debug(logger.RespFormat, action, req, *resp) + results, err := ve.ObtainSdkValue("Result.Subnets", *resp) + if err != nil { + return "", "", err + } + if results == nil { + results = []interface{}{} + } + subnets, ok := results.([]interface{}) + if !ok { + return "", "", errors.New("Result.Subnets is not Slice") + } + if len(subnets) == 0 { + return "", "", fmt.Errorf("subnet %s not exist", subnetId) + } + vpcId = subnets[0].(map[string]interface{})["VpcId"].(string) + zoneId = subnets[0].(map[string]interface{})["ZoneId"].(string) + return vpcId, zoneId, nil +} + +func (s *VolcengineMongoDBInstanceService) CreateResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + callback := ve.Callback{ + Call: ve.SdkCall{ + Action: "CreateDBInstance", + ConvertMode: ve.RequestConvertAll, + ContentType: ve.ContentTypeJson, + Convert: map[string]ve.RequestConvert{ + // "db_engine": { + // TargetField: "DBEngine", + // }, + // "db_engine_version": { + // TargetField: "DBEngineVersion", + // }, + "storage_space_gb": { + TargetField: "StorageSpaceGB", + }, + }, + BeforeCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (bool, error) { + // describe subnet + subnetId := d.Get("subnet_id") + vpcId, zoneId, err := s.getVpcIdAndZoneIdBySubnet(subnetId.(string)) + if err != nil { + return false, fmt.Errorf("get vpc ID by subnet ID %s failed", subnetId) + } + // check custom + if vpcIdCustom, ok := (*call.SdkParam)["VpcId"]; ok { + if vpcIdCustom.(string) != vpcId { + return false, fmt.Errorf("vpc ID does not match") + } + } + if zoneIdCustom, ok := (*call.SdkParam)["ZoneId"]; ok { + if zoneIdCustom.(string) != zoneId { + return false, fmt.Errorf("zone ID does not match") + } + } + (*call.SdkParam)["VpcId"] = vpcId + (*call.SdkParam)["ZoneId"] = zoneId + // (*call.SdkParam)["DBEngine"] = "MongoDB" + // (*call.SdkParam)["DBEngineVersion"] = "MongoDB_4_0" + // (*call.SdkParam)["NodeNumber"] = 3 + // (*call.SdkParam)["SuperAccountName"] = "root" + return true, nil + }, + ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) { + logger.Debug(logger.ReqFormat, call.Action, call.SdkParam) + return s.Client.UniversalClient.DoCall(getUniversalInfo(call.Action), call.SdkParam) + }, + AfterCall: func(d *schema.ResourceData, client *ve.SdkClient, resp *map[string]interface{}, call ve.SdkCall) error { + logger.Debug(logger.RespFormat, call.Action, call.SdkParam, resp) + id, _ := ve.ObtainSdkValue("Result.InstanceId", *resp) + d.SetId(id.(string)) + time.Sleep(time.Second * 10) //如果创建之后立即refresh,DescribeDBInstances会查找不到这个实例直接返回错误.. + return nil + }, + Refresh: &ve.StateRefresh{ + Target: []string{"Running"}, + Timeout: resourceData.Timeout(schema.TimeoutCreate), + }, + }, + } + return []ve.Callback{callback} +} + +func (s *VolcengineMongoDBInstanceService) ModifyResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + callbacks := make([]ve.Callback, 0) + + if resourceData.HasChange("instance_name") { + callback := ve.Callback{ + Call: ve.SdkCall{ + Action: "ModifyDBInstanceName", + ConvertMode: ve.RequestConvertIgnore, + BeforeCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (bool, error) { + (*call.SdkParam)["InstanceId"] = d.Id() + (*call.SdkParam)["InstanceNewName"] = d.Get("instance_name") + return true, nil + }, + ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) { + logger.Debug(logger.ReqFormat, call.Action, call.SdkParam) + return s.Client.UniversalClient.DoCall(getUniversalInfo(call.Action), call.SdkParam) + }, + }, + } + callbacks = append(callbacks, callback) + } + + if resourceData.HasChange("instance_type") || resourceData.HasChange("node_spec") || + resourceData.HasChange("mongos_node_spec") || resourceData.HasChange("shard_number") || + resourceData.HasChange("mongos_node_number") || resourceData.HasChange("storage_space_gb") { + callback := ve.Callback{ + Call: ve.SdkCall{ + Action: "ModifyDBInstanceSpec", + ConvertMode: ve.RequestConvertIgnore, + BeforeCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (bool, error) { + (*call.SdkParam)["InstanceId"] = d.Id() + (*call.SdkParam)["InstanceType"] = d.Get("instance_type") + if resourceData.HasChange("node_spec") { + (*call.SdkParam)["NodeSpec"] = d.Get("node_spec") + } + if resourceData.HasChange("mongos_node_spec") { + (*call.SdkParam)["MongosNodeSpec"] = d.Get("mongos_node_spec") + } + if resourceData.HasChange("shard_number") { + (*call.SdkParam)["ShardNumber"] = d.Get("shard_number") + } + if resourceData.HasChange("mongos_node_number") { + (*call.SdkParam)["MongosNodeNumber"] = d.Get("mongos_node_number") + } + if resourceData.HasChange("storage_space_gb") { + (*call.SdkParam)["StorageSpaceGB"] = d.Get("storage_space_gb") + } + return true, nil + }, + ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) { + logger.Debug(logger.ReqFormat, call.Action, call.SdkParam) + return s.Client.UniversalClient.DoCall(getUniversalInfo(call.Action), call.SdkParam) + }, + AfterCall: func(d *schema.ResourceData, client *ve.SdkClient, resp *map[string]interface{}, call ve.SdkCall) error { + time.Sleep(time.Second * 10) //变更之后立即refresh,实例状态还是Running将立即返回.. + return nil + }, + Refresh: &ve.StateRefresh{ + Target: []string{"Running"}, + Timeout: resourceData.Timeout(schema.TimeoutCreate), + }, + }, + } + callbacks = append(callbacks, callback) + } + + if resourceData.HasChange("charge_type") { + callback := ve.Callback{ + Call: ve.SdkCall{ + Action: "ModifyDBInstanceChargeType", + ConvertMode: ve.RequestConvertIgnore, + ContentType: ve.ContentTypeJson, + BeforeCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (bool, error) { + (*call.SdkParam)["InstanceIds"] = []interface{}{d.Id()} + chargeType := d.Get("charge_type") + if chargeType.(string) != "Prepaid" { + return false, fmt.Errorf("only supports PostPaid to PrePaid currently") + } + (*call.SdkParam)["ChargeType"] = chargeType + (*call.SdkParam)["PeriodUnit"] = d.Get("period_unit") + (*call.SdkParam)["Period"] = d.Get("period") + (*call.SdkParam)["AutoRenew"] = d.Get("auto_renew") + return true, nil + }, + ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) { + logger.Debug(logger.ReqFormat, call.Action, call.SdkParam) + return s.Client.UniversalClient.DoCall(getUniversalInfo(call.Action), call.SdkParam) + }, + Refresh: &ve.StateRefresh{ + Target: []string{"Running"}, + Timeout: resourceData.Timeout(schema.TimeoutCreate), + }, + }, + } + callbacks = append(callbacks, callback) + } + if resourceData.HasChange("super_account_password") { + callback := ve.Callback{ + Call: ve.SdkCall{ + Action: "ResetDBAccount", + ConvertMode: ve.RequestConvertIgnore, + ContentType: ve.ContentTypeJson, + BeforeCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (bool, error) { + (*call.SdkParam)["InstanceId"] = d.Get("instance_id") + (*call.SdkParam)["AccountName"] = d.Get("super_account_name") + (*call.SdkParam)["AccountPassword"] = d.Get("super_account_password") + return true, nil + }, + ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) { + logger.Debug(logger.ReqFormat, call.Action, call.SdkParam) + return s.Client.UniversalClient.DoCall(getUniversalInfo(call.Action), call.SdkParam) + }, + Refresh: &ve.StateRefresh{ + Target: []string{"Running"}, + Timeout: resourceData.Timeout(schema.TimeoutCreate), + }, + }, + } + callbacks = append(callbacks, callback) + } + + return callbacks +} + +func (s *VolcengineMongoDBInstanceService) RemoveResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + callback := ve.Callback{ + Call: ve.SdkCall{ + Action: "DeleteDBInstance", + ConvertMode: ve.RequestConvertIgnore, + BeforeCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (bool, error) { + (*call.SdkParam)["InstanceId"] = d.Id() + return true, nil + }, + ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) { + logger.Debug(logger.ReqFormat, call.Action, call.SdkParam) + return s.Client.UniversalClient.DoCall(getUniversalInfo(call.Action), call.SdkParam) + }, + AfterCall: func(d *schema.ResourceData, client *ve.SdkClient, resp *map[string]interface{}, call ve.SdkCall) error { + return ve.CheckResourceUtilRemoved(d, s.ReadResource, 3*time.Minute) + }, + }, + } + return []ve.Callback{callback} +} + +func (s *VolcengineMongoDBInstanceService) DatasourceResources(data *schema.ResourceData, resource *schema.Resource) ve.DataSourceInfo { + return ve.DataSourceInfo{ + RequestConverts: map[string]ve.RequestConvert{ + "db_engine": { + TargetField: "DBEngine", + }, + "db_engine_version": { + TargetField: "DBEngineVersion", + }, + }, + IdField: "InstanceId", + NameField: "InstanceName", + CollectField: "instances", + ContentType: ve.ContentTypeJson, + ResponseConverts: map[string]ve.ResponseConvert{ + "DBEngine": { + TargetField: "db_engine", + }, + "DBEngineVersion": { + TargetField: "db_engine_version", + }, + "DBEngineVersionStr": { + TargetField: "db_engine_version_str", + }, + "TotalMemoryGB": { + TargetField: "total_memory_gb", + }, + "TotalvCPU": { + TargetField: "total_vcpu", + }, + "UsedMemoryGB": { + TargetField: "used_memory_gb", + }, + "UsedvCPU": { + TargetField: "used_vcpu", + }, + "TotalStorageGB": { + TargetField: "total_storage_gb", + }, + "UsedStorageGB": { + TargetField: "used_storage_gb", + }, + "SSLEnable": { + TargetField: "ssl_enable", + }, + "SSLIsValid": { + TargetField: "ssl_is_valid", + }, + "SSLExpireTime": { + TargetField: "ssl_expire_time", + }, + }, + } +} + +func (s *VolcengineMongoDBInstanceService) ReadResourceId(id string) string { + return id +} + +func getUniversalInfo(actionName string) ve.UniversalInfo { + return ve.UniversalInfo{ + ServiceName: "mongodb", + Action: actionName, + Version: "2022-01-01", + HttpMethod: ve.POST, + ContentType: ve.ApplicationJSON, + } +} diff --git a/volcengine/mongodb/instance_parameter/data_source_volcengine_mongodb_instance_parameters.go b/volcengine/mongodb/instance_parameter/data_source_volcengine_mongodb_instance_parameters.go new file mode 100644 index 00000000..6df1be37 --- /dev/null +++ b/volcengine/mongodb/instance_parameter/data_source_volcengine_mongodb_instance_parameters.go @@ -0,0 +1,130 @@ +package instance_parameter + +import ( + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + ve "github.com/volcengine/terraform-provider-volcengine/common" +) + +func DataSourceVolcengineMongoDBInstanceParameters() *schema.Resource { + return &schema.Resource{ + Read: dataSourceVolcengineMongoDBInstanceParametersRead, + Schema: map[string]*schema.Schema{ + "output_file": { + Type: schema.TypeString, + Optional: true, + Description: "File name where to save data source results.", + }, + "total_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The total count of mongodb instance parameter query.", + }, + "instance_id": { + Type: schema.TypeString, + Required: true, + Description: "The instance ID to query.", + }, + "parameter_role": { + Type: schema.TypeString, + Optional: true, + Description: "The node type of instance parameter,valid value contains `Node`,`Shard`,`ConfigServer`,`Mongos`.", + ValidateFunc: validation.StringInSlice([]string{"Node", "Shard", "ConfigServer", "Mongos"}, false), + }, + "parameter_names": { + Type: schema.TypeString, + Optional: true, + Description: "The parameter names,support fuzzy query, case insensitive.", + }, + "parameters": { + Type: schema.TypeList, + MaxItems: 1, + Computed: true, + Description: "The collection of parameter query.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "db_engine": { + Type: schema.TypeString, + Computed: true, + Description: "The database engine.", + }, + "db_engine_version": { + Type: schema.TypeString, + Computed: true, + Description: "The database engine version.", + }, + "instance_id": { + Type: schema.TypeString, + Computed: true, + Description: "The instance ID.", + }, + "total": { + Type: schema.TypeString, + Computed: true, + Description: "The total parameters queried.", + }, + "instance_parameters": { + Type: schema.TypeList, + Computed: true, + Description: "The list of parameters.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "checking_code": { + Type: schema.TypeString, + Computed: true, + Description: "The checking code of parameter.", + }, + "force_modify": { + Type: schema.TypeBool, + Computed: true, + Description: "Whether the parameter supports modifying.", + }, + "force_restart": { + Type: schema.TypeBool, + Computed: true, + Description: "Does the new parameter value need to restart the instance to take effect after modification.", + }, + "parameter_default_value": { + Type: schema.TypeString, + Computed: true, + Description: "The default value of parameter.", + }, + "parameter_description": { + Type: schema.TypeString, + Computed: true, + Description: "The description of parameter.", + }, + "parameter_name": { + Type: schema.TypeString, + Computed: true, + Description: "The name of parameter.", + }, + "parameter_role": { + Type: schema.TypeString, + Computed: true, + Description: "The node type to which the parameter belongs.", + }, + "parameter_type": { + Type: schema.TypeString, + Computed: true, + Description: "The type of parameter value.", + }, + "parameter_value": { + Type: schema.TypeString, + Computed: true, + Description: "The value of parameter.", + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func dataSourceVolcengineMongoDBInstanceParametersRead(d *schema.ResourceData, meta interface{}) error { + service := NewMongoDBInstanceParameterService(meta.(*ve.SdkClient)) + return service.Dispatcher.Data(service, d, DataSourceVolcengineMongoDBInstanceParameters()) +} diff --git a/volcengine/mongodb/instance_parameter/resource_volcengine_mongodb_instance_parameter.go b/volcengine/mongodb/instance_parameter/resource_volcengine_mongodb_instance_parameter.go new file mode 100644 index 00000000..d669f38d --- /dev/null +++ b/volcengine/mongodb/instance_parameter/resource_volcengine_mongodb_instance_parameter.go @@ -0,0 +1,115 @@ +package instance_parameter + +import ( + "fmt" + "strings" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" +) + +/* + +Import +mongosdb parameter can be imported using the param:instanceId:parameterName, e.g. +``` +$ terraform import volcengine_mongodb_instance_parameter.default param:mongo-replica-e405f8e2****:connPoolMaxConnsPerHost +``` + +*/ + +func mongoDBParameterImporter(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) { + items := strings.Split(d.Id(), ":") + if len(items) != 3 || items[0] != "param" { + return []*schema.ResourceData{d}, fmt.Errorf("the format of import id must be 'param:instanceId:parameterName'") + } + d.Set("instance_id", items[1]) + d.Set("parameter_name", items[2]) + return []*schema.ResourceData{d}, nil +} + +func ResourceVolcengineMongoDBInstanceParameter() *schema.Resource { + resource := &schema.Resource{ + Create: resourceVolcengineMongoDBInstanceParameterCreate, + Read: resourceVolcengineMongoDBInstanceParameterRead, + Update: resourceVolcengineMongoDBInstanceParameterUpdate, + Delete: resourceVolcengineMongoDBInstanceParameterDelete, + Importer: &schema.ResourceImporter{ + State: mongoDBParameterImporter, + }, + Schema: map[string]*schema.Schema{ + "instance_id": { + Type: schema.TypeString, + Required: true, + Description: "The instance ID.", + }, + "parameter_name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Description: "The name of parameter.", + }, + "parameter_role": { + Type: schema.TypeString, + Required: true, + Description: "The node type to which the parameter belongs.", + }, + "parameter_value": { + Type: schema.TypeString, + Required: true, + Description: "The value of parameter.", + }, + //"parameters_object": { + // Type: schema.TypeList, + // Optional: true, + // Description: "The parameters to modify.", + // Elem: &schema.Resource{ + // Schema: map[string]*schema.Schema{ + // "parameter_name": { + // Type: schema.TypeString, + // Required: true, + // Description: "The name of parameter.", + // }, + // "parameter_role": { + // Type: schema.TypeString, + // Required: true, + // Description: "The node type to which the parameter belongs.", + // }, + // "parameter_value": { + // Type: schema.TypeString, + // Required: true, + // Description: "The value of parameter.", + // }, + // }, + // }, + //}, + }, + } + return resource +} + +func resourceVolcengineMongoDBInstanceParameterCreate(d *schema.ResourceData, meta interface{}) (err error) { + return fmt.Errorf("mongodb instance parameter not allow creating,please import first") +} + +func resourceVolcengineMongoDBInstanceParameterUpdate(d *schema.ResourceData, meta interface{}) (err error) { + service := NewMongoDBInstanceParameterService(meta.(*ve.SdkClient)) + err = service.Dispatcher.Update(service, d, ResourceVolcengineMongoDBInstanceParameter()) + if err != nil { + return fmt.Errorf("error on updating instance %q, %s", d.Id(), err) + } + return resourceVolcengineMongoDBInstanceParameterRead(d, meta) +} + +func resourceVolcengineMongoDBInstanceParameterDelete(d *schema.ResourceData, meta interface{}) (err error) { + return nil +} + +func resourceVolcengineMongoDBInstanceParameterRead(d *schema.ResourceData, meta interface{}) (err error) { + service := NewMongoDBInstanceParameterService(meta.(*ve.SdkClient)) + err = service.Dispatcher.Read(service, d, ResourceVolcengineMongoDBInstanceParameter()) + if err != nil { + return fmt.Errorf("Error on reading instance %q,%s", d.Id(), err) + } + return err +} diff --git a/volcengine/mongodb/instance_parameter/service_volcengine_mongodb_instance_parameter.go b/volcengine/mongodb/instance_parameter/service_volcengine_mongodb_instance_parameter.go new file mode 100644 index 00000000..2a9ab91e --- /dev/null +++ b/volcengine/mongodb/instance_parameter/service_volcengine_mongodb_instance_parameter.go @@ -0,0 +1,188 @@ +package instance_parameter + +import ( + "errors" + "fmt" + mongodbInstance "github.com/volcengine/terraform-provider-volcengine/volcengine/mongodb/instance" + "strings" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" + "github.com/volcengine/terraform-provider-volcengine/logger" +) + +type VolcengineMongoDBInstanceParameterService struct { + Client *ve.SdkClient + Dispatcher *ve.Dispatcher +} + +func NewMongoDBInstanceParameterService(c *ve.SdkClient) *VolcengineMongoDBInstanceParameterService { + return &VolcengineMongoDBInstanceParameterService{ + Client: c, + Dispatcher: &ve.Dispatcher{}, + } +} + +func (s *VolcengineMongoDBInstanceParameterService) GetClient() *ve.SdkClient { + return s.Client +} + +func (s *VolcengineMongoDBInstanceParameterService) ReadResources(condition map[string]interface{}) (data []interface{}, err error) { + var ( + resp *map[string]interface{} + results interface{} + ) + action := "DescribeDBInstanceParameters" + + logger.Debug(logger.ReqFormat, action, condition) + if condition == nil { + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), nil) + if err != nil { + return data, err + } + } else { + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), &condition) + if err != nil { + return data, err + } + } + + logger.Debug(logger.RespFormat, action, resp) + results, err = ve.ObtainSdkValue("Result", *resp) + if err != nil { + return data, err + } + data = []interface{}{results} + return data, err +} + +func (s *VolcengineMongoDBInstanceParameterService) ReadResource(resourceData *schema.ResourceData, id string) (data map[string]interface{}, err error) { + var ( + results []interface{} + ok bool + ) + if id == "" { + id = s.ReadResourceId(resourceData.Id()) + } + parts := strings.Split(id, ":") + if len(parts) != 3 { + return data, fmt.Errorf("the format of import id must be 'endpoint:instanceId:parameterName'") + } + req := map[string]interface{}{ + "InstanceId": parts[1], + "ParameterNames": parts[2], + } + results, err = s.ReadResources(req) + if err != nil { + return data, err + } + for _, v := range results { + if data, ok = v.(map[string]interface{}); !ok { + return data, errors.New("value is not map") + } + } + if len(data) == 0 { + return data, fmt.Errorf("parameters of instance %s is not exist", id) + } + params, ok := data["InstanceParameters"] + if !ok || len(params.([]interface{})) == 0 { + return data, fmt.Errorf("parameters is empty") + } + param := params.([]interface{})[0] + return map[string]interface{}{ + "ParameterName": param.(map[string]interface{})["ParameterNames"], + "ParameterRole": param.(map[string]interface{})["ParameterRole"], + "ParameterValue": param.(map[string]interface{})["ParameterValue"], + }, err + +} + +func (s *VolcengineMongoDBInstanceParameterService) RefreshResourceState(resourceData *schema.ResourceData, target []string, timeout time.Duration, id string) *resource.StateChangeConf { + return &resource.StateChangeConf{} +} + +func (s *VolcengineMongoDBInstanceParameterService) WithResourceResponseHandlers(instance map[string]interface{}) []ve.ResourceResponseHandler { + handler := func() (map[string]interface{}, map[string]ve.ResponseConvert, error) { + return instance, nil, nil + } + return []ve.ResourceResponseHandler{handler} +} + +func (s *VolcengineMongoDBInstanceParameterService) CreateResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + return []ve.Callback{} +} + +func (s *VolcengineMongoDBInstanceParameterService) ModifyResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + id := s.ReadResourceId(resourceData.Id()) + parts := strings.Split(id, ":") + instanceId := parts[1] + callback := ve.Callback{ + Call: ve.SdkCall{ + Action: "ModifyDBInstanceParameters", + ConvertMode: ve.RequestConvertIgnore, + BeforeCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (bool, error) { + (*call.SdkParam)["InstanceId"] = instanceId + (*call.SdkParam)["ParametersObject"] = map[string]interface{}{ + "ParameterName": parts[2], + "ParameterRole": d.Get("parameter_role"), + "ParameterValue": d.Get("parameter_value"), + } + return true, nil + }, + ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) { + logger.Debug(logger.ReqFormat, call.Action, call.SdkParam) + return s.Client.UniversalClient.DoCall(getUniversalInfo(call.Action), call.SdkParam) + }, + ExtraRefresh: map[ve.ResourceService]*ve.StateRefresh{ + mongodbInstance.NewMongoDBInstanceService(s.Client): { + Target: []string{"Running"}, + Timeout: resourceData.Timeout(schema.TimeoutCreate), + ResourceId: instanceId, + }, + }, + LockId: func(d *schema.ResourceData) string { + return instanceId + }, + }, + } + return []ve.Callback{callback} +} + +func (s *VolcengineMongoDBInstanceParameterService) RemoveResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + return []ve.Callback{} +} + +func (s *VolcengineMongoDBInstanceParameterService) DatasourceResources(data *schema.ResourceData, resource *schema.Resource) ve.DataSourceInfo { + return ve.DataSourceInfo{ + IdField: "InstanceId", + CollectField: "parameters", + ContentType: ve.ContentTypeJson, + ResponseConverts: map[string]ve.ResponseConvert{ + "DBEngine": { + TargetField: "db_engine", + }, + "DBEngineVersion": { + TargetField: "db_engine_version", + }, + "ParameterNames": { + TargetField: "parameter_name", + }, + }, + } +} + +func (s *VolcengineMongoDBInstanceParameterService) ReadResourceId(id string) string { + return id +} + +func getUniversalInfo(actionName string) ve.UniversalInfo { + return ve.UniversalInfo{ + ServiceName: "mongodb", + Action: actionName, + Version: "2022-01-01", + HttpMethod: ve.POST, + ContentType: ve.ApplicationJSON, + } +} diff --git a/volcengine/mongodb/instance_parameter_log/data_source_volcengine_mongodb_instance_parameter_logs.go b/volcengine/mongodb/instance_parameter_log/data_source_volcengine_mongodb_instance_parameter_logs.go new file mode 100644 index 00000000..f5de9793 --- /dev/null +++ b/volcengine/mongodb/instance_parameter_log/data_source_volcengine_mongodb_instance_parameter_logs.go @@ -0,0 +1,84 @@ +package instance_parameter_log + +import ( + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" +) + +func DataSourceVolcengineMongoDBInstanceParameterLogs() *schema.Resource { + return &schema.Resource{ + Read: dataSourceVolcengineMongoDBInstanceParameterLogsRead, + Schema: map[string]*schema.Schema{ + "output_file": { + Type: schema.TypeString, + Optional: true, + Description: "File name where to save data source results.", + }, + "total_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The total count of mongodb instance parameter log query.", + }, + "instance_id": { + Type: schema.TypeString, + Required: true, + Description: "The instance ID to query.", + }, + "start_time": { + Type: schema.TypeString, + Optional: true, + Description: "The start time to query.", + }, + "end_time": { + Type: schema.TypeString, + Optional: true, + Description: "The end time to query.", + }, + "parameter_change_logs": { + Type: schema.TypeList, + MaxItems: 1, + Computed: true, + Description: "The collection of parameter change log query.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "modify_time": { + Type: schema.TypeString, + Computed: true, + Description: "The modifying time of parameter.", + }, + "new_parameter_value": { + Type: schema.TypeString, + Computed: true, + Description: "The new parameter value.", + }, + "old_parameter_value": { + Type: schema.TypeString, + Computed: true, + Description: "The old parameter value.", + }, + "parameter_name": { + Type: schema.TypeString, + Computed: true, + Description: "The parameter name.", + }, + "parameter_role": { + Type: schema.TypeString, + Computed: true, + Description: "The node type to which the parameter belongs.", + }, + "parameter_status": { + Type: schema.TypeString, + Computed: true, + Description: "The status of parameter change.", + }, + }, + }, + }, + }, + } +} + +func dataSourceVolcengineMongoDBInstanceParameterLogsRead(d *schema.ResourceData, meta interface{}) error { + service := NewMongoDBInstanceParameterLogService(meta.(*ve.SdkClient)) + return service.Dispatcher.Data(service, d, DataSourceVolcengineMongoDBInstanceParameterLogs()) +} diff --git a/volcengine/mongodb/instance_parameter_log/service_volcengine_mongodb_instance_parameter_log.go b/volcengine/mongodb/instance_parameter_log/service_volcengine_mongodb_instance_parameter_log.go new file mode 100644 index 00000000..64211638 --- /dev/null +++ b/volcengine/mongodb/instance_parameter_log/service_volcengine_mongodb_instance_parameter_log.go @@ -0,0 +1,111 @@ +package instance_parameter_log + +import ( + "fmt" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" + "github.com/volcengine/terraform-provider-volcengine/logger" +) + +type VolcengineMongoDBInstanceParameterLogService struct { + Client *ve.SdkClient + Dispatcher *ve.Dispatcher +} + +func NewMongoDBInstanceParameterLogService(c *ve.SdkClient) *VolcengineMongoDBInstanceParameterLogService { + return &VolcengineMongoDBInstanceParameterLogService{ + Client: c, + Dispatcher: &ve.Dispatcher{}, + } +} + +func (s *VolcengineMongoDBInstanceParameterLogService) GetClient() *ve.SdkClient { + return s.Client +} + +func (s *VolcengineMongoDBInstanceParameterLogService) ReadResources(condition map[string]interface{}) (data []interface{}, err error) { + var ( + resp *map[string]interface{} + results interface{} + ok bool + ) + return ve.WithPageNumberQuery(condition, "PageSize", "PageNumber", 100, 1, func(m map[string]interface{}) ([]interface{}, error) { + action := "DescribeDBInstanceParametersLog" + logger.Debug(logger.ReqFormat, action, condition) + if condition == nil { + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), nil) + if err != nil { + return data, err + } + } else { + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), &condition) + if err != nil { + return data, err + } + } + logger.Debug(logger.RespFormat, action, condition, *resp) + results, err = ve.ObtainSdkValue("Result.ParameterChangeLog", *resp) + if err != nil { + return data, err + } + if results == nil { + results = []interface{}{} + } + data, ok = results.([]interface{}) + if !ok { + return data, fmt.Errorf("DescribeDBInstanceParametersLog responsed is not a slice") + } + return data, nil + }) +} + +func (s *VolcengineMongoDBInstanceParameterLogService) ReadResource(resourceData *schema.ResourceData, id string) (data map[string]interface{}, err error) { + return data, err +} + +func (s *VolcengineMongoDBInstanceParameterLogService) RefreshResourceState(resourceData *schema.ResourceData, target []string, timeout time.Duration, id string) *resource.StateChangeConf { + return &resource.StateChangeConf{} +} + +func (s *VolcengineMongoDBInstanceParameterLogService) WithResourceResponseHandlers(instance map[string]interface{}) []ve.ResourceResponseHandler { + handler := func() (map[string]interface{}, map[string]ve.ResponseConvert, error) { + return instance, nil, nil + } + return []ve.ResourceResponseHandler{handler} +} + +func (s *VolcengineMongoDBInstanceParameterLogService) CreateResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + return []ve.Callback{} +} + +func (s *VolcengineMongoDBInstanceParameterLogService) ModifyResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + return []ve.Callback{} +} + +func (s *VolcengineMongoDBInstanceParameterLogService) RemoveResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + return []ve.Callback{} +} + +func (s *VolcengineMongoDBInstanceParameterLogService) DatasourceResources(data *schema.ResourceData, resource *schema.Resource) ve.DataSourceInfo { + return ve.DataSourceInfo{ + CollectField: "parameter_change_logs", + ContentType: ve.ContentTypeJson, + } +} + +func (s *VolcengineMongoDBInstanceParameterLogService) ReadResourceId(id string) string { + return id +} + +func getUniversalInfo(actionName string) ve.UniversalInfo { + return ve.UniversalInfo{ + ServiceName: "mongodb", + Action: actionName, + Version: "2022-01-01", + HttpMethod: ve.POST, + ContentType: ve.ApplicationJSON, + } +} diff --git a/volcengine/mongodb/region/data_source_volcengine_mongodb_regions.go b/volcengine/mongodb/region/data_source_volcengine_mongodb_regions.go new file mode 100644 index 00000000..e8bd54f8 --- /dev/null +++ b/volcengine/mongodb/region/data_source_volcengine_mongodb_regions.go @@ -0,0 +1,48 @@ +package region + +import ( + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" +) + +func DataSourceVolcengineMongoDBRegions() *schema.Resource { + return &schema.Resource{ + Read: dataSourceVolcengineRegionsRead, + Schema: map[string]*schema.Schema{ + "output_file": { + Type: schema.TypeString, + Optional: true, + Description: "File name where to save data source results.", + }, + "total_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The total count of region query.", + }, + "regions": { + Description: "The collection of region query.", + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "region_id": { + Type: schema.TypeString, + Computed: true, + Description: "The id of the region.", + }, + "region_name": { + Type: schema.TypeString, + Computed: true, + Description: "The name of region.", + }, + }, + }, + }, + }, + } +} + +func dataSourceVolcengineRegionsRead(d *schema.ResourceData, meta interface{}) error { + regionService := NewRegionService(meta.(*ve.SdkClient)) + return regionService.Dispatcher.Data(regionService, d, DataSourceVolcengineMongoDBRegions()) +} diff --git a/volcengine/mongodb/region/service_volcengine_mongodb_region.go b/volcengine/mongodb/region/service_volcengine_mongodb_region.go new file mode 100644 index 00000000..d5e8275d --- /dev/null +++ b/volcengine/mongodb/region/service_volcengine_mongodb_region.go @@ -0,0 +1,120 @@ +package region + +import ( + "errors" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" + "github.com/volcengine/terraform-provider-volcengine/logger" +) + +type VolcengineMongoRegionService struct { + Client *ve.SdkClient + Dispatcher *ve.Dispatcher +} + +func NewRegionService(c *ve.SdkClient) *VolcengineMongoRegionService { + return &VolcengineMongoRegionService{ + Client: c, + Dispatcher: &ve.Dispatcher{}, + } +} + +func (s *VolcengineMongoRegionService) GetClient() *ve.SdkClient { + return s.Client +} + +func getUniversalInfo(actionName string) ve.UniversalInfo { + return ve.UniversalInfo{ + ServiceName: "mongodb", + Version: "2022-01-01", + HttpMethod: ve.POST, + ContentType: ve.ApplicationJSON, + Action: actionName, + } +} + +func (s *VolcengineMongoRegionService) ReadResources(condition map[string]interface{}) ([]interface{}, error) { + var ( + resp *map[string]interface{} + results interface{} + ok bool + err error + data []interface{} + ) + action := "DescribeRegions" + logger.Debug(logger.ReqFormat, action, condition) + if condition == nil { + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), nil) + } else { + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), &condition) + } + if err != nil { + return nil, err + } + logger.Debug(logger.RespFormat, action, condition, *resp) + + results, err = ve.ObtainSdkValue("Result.Regions", *resp) + if err != nil { + return nil, err + } + if results == nil { + results = make([]interface{}, 0) + } + + if data, ok = results.([]interface{}); !ok { + return nil, errors.New("Result.Regions is not Slice") + } + + return data, nil +} + +func (s *VolcengineMongoRegionService) ReadResource(resourceData *schema.ResourceData, id string) (data map[string]interface{}, err error) { + return nil, nil +} + +func (s *VolcengineMongoRegionService) RefreshResourceState(resourceData *schema.ResourceData, target []string, timeout time.Duration, id string) *resource.StateChangeConf { + return &resource.StateChangeConf{ + Pending: []string{}, + Delay: 5 * time.Second, + MinTimeout: 5 * time.Second, + Target: target, + Timeout: timeout, + Refresh: func() (result interface{}, state string, err error) { + return nil, "", err + }, + } +} + +func (s *VolcengineMongoRegionService) WithResourceResponseHandlers(zone map[string]interface{}) []ve.ResourceResponseHandler { + handler := func() (map[string]interface{}, map[string]ve.ResponseConvert, error) { + return zone, nil, nil + } + return []ve.ResourceResponseHandler{handler} +} + +func (s *VolcengineMongoRegionService) CreateResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + return []ve.Callback{} +} + +func (s *VolcengineMongoRegionService) ModifyResource(resourceData *schema.ResourceData, resource *schema.Resource) (callbacks []ve.Callback) { + return callbacks +} + +func (s *VolcengineMongoRegionService) RemoveResource(resourceData *schema.ResourceData, r *schema.Resource) []ve.Callback { + return []ve.Callback{} +} + +func (s *VolcengineMongoRegionService) DatasourceResources(data *schema.ResourceData, resource *schema.Resource) ve.DataSourceInfo { + return ve.DataSourceInfo{ + NameField: "RegionId", + IdField: "RegionId", + CollectField: "regions", + } +} + +func (s *VolcengineMongoRegionService) ReadResourceId(id string) string { + return id +} diff --git a/volcengine/mongodb/spec/data_source_volcengine_mongodb_specs.go b/volcengine/mongodb/spec/data_source_volcengine_mongodb_specs.go new file mode 100644 index 00000000..bec9abdb --- /dev/null +++ b/volcengine/mongodb/spec/data_source_volcengine_mongodb_specs.go @@ -0,0 +1,142 @@ +package spec + +import ( + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" +) + +func DataSourceVolcengineMongoDBSpecs() *schema.Resource { + return &schema.Resource{ + Read: dataSourceVolcengineSpecsRead, + Schema: map[string]*schema.Schema{ + "output_file": { + Type: schema.TypeString, + Optional: true, + Description: "File name where to save data source results.", + }, + "total_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The total count of region query.", + }, + "region_id": { + Type: schema.TypeString, + Required: true, + Description: "The region ID to query.", + }, + "specs": { + Description: "The collection of mongos spec query.", + Type: schema.TypeList, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "mongos_node_specs": { + Type: schema.TypeList, + Computed: true, + Description: "The collection of mongos node specs.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu_num": { + Type: schema.TypeFloat, + Computed: true, + Description: "The max cpu cores.", + }, + "max_conn": { + Type: schema.TypeInt, + Computed: true, + Description: "The max connections.", + }, + "mem_in_gb": { + Type: schema.TypeFloat, + Computed: true, + Description: "The memory in GB.", + }, + "spec_name": { + Type: schema.TypeString, + Computed: true, + Description: "The mongos node spec name.", + }, + }, + }, + }, + + "node_specs": { + Type: schema.TypeList, + Computed: true, + Description: "The collection of node specs.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu_num": { + Type: schema.TypeFloat, + Computed: true, + Description: "The cpu cores.", + }, + "max_conn": { + Type: schema.TypeInt, + Computed: true, + Description: "The max connections.", + }, + "max_storage": { + Type: schema.TypeInt, + Computed: true, + Description: "The max storage.", + }, + "mem_in_db": { + Type: schema.TypeFloat, + Computed: true, + Description: "The memory in GB.", + }, + "spec_name": { + Type: schema.TypeString, + Computed: true, + Description: "The node spec name.", + }, + }, + }, + }, + "shard_node_specs": { + Type: schema.TypeList, + Computed: true, + Description: "The collection of shard node specs.", + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cpu_num": { + Type: schema.TypeFloat, + Computed: true, + Description: "The cpu cores.", + }, + "max_conn": { + Type: schema.TypeInt, + Computed: true, + Description: "The max connections.", + }, + "max_storage": { + Type: schema.TypeInt, + Computed: true, + Description: "The max storage.", + }, + "mem_in_gb": { + Type: schema.TypeInt, + Computed: true, + Description: "The memory in GB.", + }, + "spec_name": { + Type: schema.TypeString, + Computed: true, + Description: "The shard node spec name.", + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func dataSourceVolcengineSpecsRead(d *schema.ResourceData, meta interface{}) error { + service := NewSpecService(meta.(*ve.SdkClient)) + return service.Dispatcher.Data(service, d, DataSourceVolcengineMongoDBSpecs()) +} diff --git a/volcengine/mongodb/spec/service_volcengine_mongodb_spec.go b/volcengine/mongodb/spec/service_volcengine_mongodb_spec.go new file mode 100644 index 00000000..f8f0c710 --- /dev/null +++ b/volcengine/mongodb/spec/service_volcengine_mongodb_spec.go @@ -0,0 +1,100 @@ +package spec + +import ( + "time" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" + "github.com/volcengine/terraform-provider-volcengine/logger" +) + +type VolcengineMongoSpecService struct { + Client *ve.SdkClient + Dispatcher *ve.Dispatcher +} + +func NewSpecService(c *ve.SdkClient) *VolcengineMongoSpecService { + return &VolcengineMongoSpecService{ + Client: c, + Dispatcher: &ve.Dispatcher{}, + } +} + +func (s *VolcengineMongoSpecService) GetClient() *ve.SdkClient { + return s.Client +} + +func getUniversalInfo(actionName string) ve.UniversalInfo { + return ve.UniversalInfo{ + ServiceName: "mongodb", + Version: "2022-01-01", + HttpMethod: ve.POST, + ContentType: ve.ApplicationJSON, + Action: actionName, + } +} + +func (s *VolcengineMongoSpecService) ReadResources(condition map[string]interface{}) ([]interface{}, error) { + var ( + resp *map[string]interface{} + results interface{} + err error + data []interface{} + ) + action := "DescribeNodeSpecs" + logger.Debug(logger.ReqFormat, action, condition) + if condition == nil { + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), nil) + } else { + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), &condition) + } + if err != nil { + return nil, err + } + logger.Debug(logger.RespFormat, action, condition, *resp) + + results, err = ve.ObtainSdkValue("Result", *resp) + if err != nil { + return nil, err + } + if results == nil { + results = make([]interface{}, 0) + } + data = append(data, results) + return data, nil +} + +func (s *VolcengineMongoSpecService) ReadResource(resourceData *schema.ResourceData, id string) (data map[string]interface{}, err error) { + return nil, nil +} + +func (s *VolcengineMongoSpecService) RefreshResourceState(resourceData *schema.ResourceData, target []string, timeout time.Duration, id string) *resource.StateChangeConf { + return nil +} + +func (s *VolcengineMongoSpecService) WithResourceResponseHandlers(zone map[string]interface{}) []ve.ResourceResponseHandler { + return []ve.ResourceResponseHandler{} +} + +func (s *VolcengineMongoSpecService) CreateResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + return []ve.Callback{} +} + +func (s *VolcengineMongoSpecService) ModifyResource(resourceData *schema.ResourceData, resource *schema.Resource) (callbacks []ve.Callback) { + return callbacks +} + +func (s *VolcengineMongoSpecService) RemoveResource(resourceData *schema.ResourceData, r *schema.Resource) []ve.Callback { + return []ve.Callback{} +} + +func (s *VolcengineMongoSpecService) DatasourceResources(data *schema.ResourceData, resource *schema.Resource) ve.DataSourceInfo { + return ve.DataSourceInfo{ + CollectField: "specs", + } +} + +func (s *VolcengineMongoSpecService) ReadResourceId(id string) string { + return id +} diff --git a/volcengine/mongodb/ssl_state/data_source_volcengine_mongodb_ssl_states.go b/volcengine/mongodb/ssl_state/data_source_volcengine_mongodb_ssl_states.go new file mode 100644 index 00000000..5674fac3 --- /dev/null +++ b/volcengine/mongodb/ssl_state/data_source_volcengine_mongodb_ssl_states.go @@ -0,0 +1,53 @@ +package ssl_state + +import ( + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" +) + +func DataSourceVolcengineMongoDBSSLStates() *schema.Resource { + return &schema.Resource{ + Read: dataSourceVolcengineMongoDBSSLStatesRead, + Schema: map[string]*schema.Schema{ + "instance_id": { + Type: schema.TypeString, + Optional: true, + Description: "The mongodb instance ID to query.", + }, + "ssl_state": { + Description: "The collection of mongodb ssl state query.", + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "instance_id": { + Type: schema.TypeString, + Computed: true, + Description: "The mongodb instance id.", + }, + "ssl_enable": { + Type: schema.TypeBool, + Computed: true, + Description: "Whether SSL is enabled.", + }, + "is_valid": { + Type: schema.TypeBool, + Computed: true, + Description: "Whetehr SSL is valid.", + }, + "ssl_expired_time": { + Type: schema.TypeString, + Computed: true, + Description: "The expire time of SSL.", + }, + }, + }, + }, + }, + } +} + +func dataSourceVolcengineMongoDBSSLStatesRead(d *schema.ResourceData, meta interface{}) error { + service := NewMongoDBSSLStateService(meta.(*ve.SdkClient)) + return service.Dispatcher.Data(service, d, DataSourceVolcengineMongoDBSSLStates()) +} diff --git a/volcengine/mongodb/ssl_state/resource_volcengine_mongodb_ssl_state.go b/volcengine/mongodb/ssl_state/resource_volcengine_mongodb_ssl_state.go new file mode 100644 index 00000000..2e0c1d50 --- /dev/null +++ b/volcengine/mongodb/ssl_state/resource_volcengine_mongodb_ssl_state.go @@ -0,0 +1,83 @@ +package ssl_state + +import ( + "fmt" + + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" +) + +/* + +Import +mongosdb ssl state can be imported using the ssl:instanceId, e.g. +set `ssl_action` to `Update` will update ssl always when terraform apply. +``` +$ terraform import volcengine_mongosdb_ssl_state.default ssl:mongo-shard-d050db19xxx +``` + +*/ + +func ResourceVolcengineMongoDBSSLState() *schema.Resource { + resource := &schema.Resource{ + Create: resourceVolcengineMongoDBSSLStateCreate, + Read: resourceVolcengineMongoDBSSLStateRead, + Update: resourceVolcengineMongoDBSSLStateUpdate, + Delete: resourceVolcengineMongoDBSSLStateDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Schema: map[string]*schema.Schema{ + "instance_id": { + Type: schema.TypeString, + Required: true, + Description: "The ID of mongodb instance.", + }, + "ssl_action": { + Type: schema.TypeString, + Optional: true, + DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { + return d.Id() == "" + }, + Description: "The action of ssl,valid value contains `Update`.", + }, + }, + } + return resource +} + +func resourceVolcengineMongoDBSSLStateCreate(d *schema.ResourceData, meta interface{}) (err error) { + service := NewMongoDBSSLStateService(meta.(*ve.SdkClient)) + err = service.Dispatcher.Create(service, d, ResourceVolcengineMongoDBSSLState()) + if err != nil { + return fmt.Errorf("Error on open ssl %q,%s", d.Id(), err) + } + return resourceVolcengineMongoDBSSLStateRead(d, meta) +} + +func resourceVolcengineMongoDBSSLStateUpdate(d *schema.ResourceData, meta interface{}) (err error) { + service := NewMongoDBSSLStateService(meta.(*ve.SdkClient)) + err = service.Dispatcher.Update(service, d, ResourceVolcengineMongoDBSSLState()) + if err != nil { + return fmt.Errorf("error on updating ssl %q, %s", d.Id(), err) + } + return resourceVolcengineMongoDBSSLStateRead(d, meta) +} + +func resourceVolcengineMongoDBSSLStateDelete(d *schema.ResourceData, meta interface{}) (err error) { + service := NewMongoDBSSLStateService(meta.(*ve.SdkClient)) + err = service.Dispatcher.Delete(service, d, ResourceVolcengineMongoDBSSLState()) + if err != nil { + return fmt.Errorf("error on close ssl %q, %s", d.Id(), err) + } + return err +} + +func resourceVolcengineMongoDBSSLStateRead(d *schema.ResourceData, meta interface{}) (err error) { + service := NewMongoDBSSLStateService(meta.(*ve.SdkClient)) + err = service.Dispatcher.Read(service, d, ResourceVolcengineMongoDBSSLState()) + if err != nil { + return fmt.Errorf("Error on reading ssl state %q,%s", d.Id(), err) + } + return err +} diff --git a/volcengine/mongodb/ssl_state/service_volcengine_mongodb_ssl_state.go b/volcengine/mongodb/ssl_state/service_volcengine_mongodb_ssl_state.go new file mode 100644 index 00000000..53a227bc --- /dev/null +++ b/volcengine/mongodb/ssl_state/service_volcengine_mongodb_ssl_state.go @@ -0,0 +1,237 @@ +package ssl_state + +import ( + "errors" + "fmt" + mongodbInstance "github.com/volcengine/terraform-provider-volcengine/volcengine/mongodb/instance" + "strings" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" + "github.com/volcengine/terraform-provider-volcengine/logger" +) + +type VolcengineMongoDBSSLStateService struct { + Client *ve.SdkClient + Dispatcher *ve.Dispatcher +} + +func NewMongoDBSSLStateService(c *ve.SdkClient) *VolcengineMongoDBSSLStateService { + return &VolcengineMongoDBSSLStateService{ + Client: c, + Dispatcher: &ve.Dispatcher{}, + } +} + +func (s *VolcengineMongoDBSSLStateService) GetClient() *ve.SdkClient { + return s.Client +} + +func (s *VolcengineMongoDBSSLStateService) DatasourceResources(data *schema.ResourceData, resource *schema.Resource) ve.DataSourceInfo { + return ve.DataSourceInfo{ + CollectField: "ssl_state", + ContentType: ve.ContentTypeJson, + ResponseConverts: map[string]ve.ResponseConvert{ + "SSLEnable": { + TargetField: "ssl_enable", + }, + "SSLExpiredTime": { + TargetField: "ssl_expired_time", + }, + }, + } +} + +func (s *VolcengineMongoDBSSLStateService) ReadResources(condition map[string]interface{}) (data []interface{}, err error) { + var ( + resp *map[string]interface{} + results interface{} + ) + action := "DescribeDBInstanceSSL" + logger.Debug(logger.ReqFormat, action, condition) + if condition == nil { + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), nil) + if err != nil { + return data, err + } + } else { + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), &condition) + if err != nil { + return data, err + } + } + logger.Debug(logger.RespFormat, action, condition, *resp) + + results, err = ve.ObtainSdkValue("Result", *resp) + if err != nil { + logger.DebugInfo("ve.ObtainSdkValue return :%v", err) + return data, err + } + if results == nil { + results = []interface{}{} + } + return []interface{}{results}, nil +} + +func (s *VolcengineMongoDBSSLStateService) ReadResource(resourceData *schema.ResourceData, id string) (data map[string]interface{}, err error) { + var ( + results []interface{} + ok bool + ) + resourceId := resourceData.Id() + parts := strings.Split(resourceId, ":") + instanceId := parts[1] + + req := map[string]interface{}{ + "InstanceId": instanceId, + } + results, err = s.ReadResources(req) + if err != nil { + return data, err + } + for _, v := range results { + if data, ok = v.(map[string]interface{}); !ok { + return data, errors.New("value is not map") + } + } + if len(data) == 0 { + return data, fmt.Errorf("SSLState %s is not exist", id) + } + return data, err +} + +func (s *VolcengineMongoDBSSLStateService) RefreshResourceState(resourceData *schema.ResourceData, target []string, timeout time.Duration, id string) *resource.StateChangeConf { + return &resource.StateChangeConf{} +} + +func (s *VolcengineMongoDBSSLStateService) WithResourceResponseHandlers(instance map[string]interface{}) []ve.ResourceResponseHandler { + handler := func() (map[string]interface{}, map[string]ve.ResponseConvert, error) { + return instance, nil, nil + } + return []ve.ResourceResponseHandler{handler} +} + +func (s *VolcengineMongoDBSSLStateService) CreateResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + instanceId := resourceData.Get("instance_id").(string) + callback := ve.Callback{ + Call: ve.SdkCall{ + Action: "ModifyDBInstanceSSL", + ConvertMode: ve.RequestConvertIgnore, + ContentType: ve.ContentTypeJson, + SdkParam: &map[string]interface{}{ + "InstanceId": resourceData.Get("instance_id"), + "SSLAction": "Open", + }, + ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) { + logger.Debug(logger.ReqFormat, call.Action, call.SdkParam) + return s.Client.UniversalClient.DoCall(getUniversalInfo(call.Action), call.SdkParam) + }, + AfterCall: func(d *schema.ResourceData, client *ve.SdkClient, resp *map[string]interface{}, call ve.SdkCall) error { + logger.Debug(logger.RespFormat, call.Action, call.SdkParam, resp) + d.SetId(fmt.Sprintf("ssl:%s", d.Get("instance_id"))) + return nil + }, + ExtraRefresh: map[ve.ResourceService]*ve.StateRefresh{ + mongodbInstance.NewMongoDBInstanceService(s.Client): { + Target: []string{"Running"}, + Timeout: resourceData.Timeout(schema.TimeoutCreate), + ResourceId: instanceId, + }, + }, + LockId: func(d *schema.ResourceData) string { + logger.Debug("lock instance id:%s", instanceId, "") + return instanceId + }, + }, + } + return []ve.Callback{callback} +} + +func (s *VolcengineMongoDBSSLStateService) ModifyResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + instanceId := resourceData.Get("instance_id").(string) + callback := ve.Callback{ + Call: ve.SdkCall{ + Action: "ModifyDBInstanceSSL", + ConvertMode: ve.RequestConvertIgnore, + ContentType: ve.ContentTypeJson, + SdkParam: &map[string]interface{}{ + "InstanceId": resourceData.Get("instance_id"), + "SSLAction": "Update", + }, + ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) { + logger.Debug(logger.ReqFormat, call.Action, call.SdkParam) + return s.Client.UniversalClient.DoCall(getUniversalInfo(call.Action), call.SdkParam) + }, + AfterCall: func(d *schema.ResourceData, client *ve.SdkClient, resp *map[string]interface{}, call ve.SdkCall) error { + logger.Debug(logger.RespFormat, call.Action, call.SdkParam, resp) + d.SetId(fmt.Sprintf("ssl:%s", d.Get("instance_id"))) + d.Set("ssl_action", "noupdate") + return nil + }, + ExtraRefresh: map[ve.ResourceService]*ve.StateRefresh{ + mongodbInstance.NewMongoDBInstanceService(s.Client): { + Target: []string{"Running"}, + Timeout: resourceData.Timeout(schema.TimeoutCreate), + ResourceId: instanceId, + }, + }, + LockId: func(d *schema.ResourceData) string { + logger.Debug("lock instance id:%s", instanceId, "") + return instanceId + }, + }, + } + return []ve.Callback{callback} +} + +func (s *VolcengineMongoDBSSLStateService) RemoveResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + instanceId := resourceData.Get("instance_id").(string) + callback := ve.Callback{ + Call: ve.SdkCall{ + Action: "ModifyDBInstanceSSL", + ConvertMode: ve.RequestConvertIgnore, + ContentType: ve.ContentTypeJson, + SdkParam: &map[string]interface{}{ + "InstanceId": resourceData.Get("instance_id"), + "SSLAction": "Close", + }, + ExecuteCall: func(d *schema.ResourceData, client *ve.SdkClient, call ve.SdkCall) (*map[string]interface{}, error) { + logger.Debug(logger.ReqFormat, call.Action, call.SdkParam) + return s.Client.UniversalClient.DoCall(getUniversalInfo(call.Action), call.SdkParam) + }, + AfterCall: func(d *schema.ResourceData, client *ve.SdkClient, resp *map[string]interface{}, call ve.SdkCall) error { + logger.Debug(logger.RespFormat, call.Action, call.SdkParam, resp) + d.SetId(fmt.Sprintf("ssl:%s", d.Get("instance_id"))) + return nil + }, + ExtraRefresh: map[ve.ResourceService]*ve.StateRefresh{ + mongodbInstance.NewMongoDBInstanceService(s.Client): { + Target: []string{"Running"}, + Timeout: resourceData.Timeout(schema.TimeoutCreate), + ResourceId: instanceId, + }, + }, + LockId: func(d *schema.ResourceData) string { + logger.Debug("lock instance id:%s", instanceId, "") + return instanceId + }, + }, + } + return []ve.Callback{callback} +} + +func (s *VolcengineMongoDBSSLStateService) ReadResourceId(id string) string { + return id +} + +func getUniversalInfo(actionName string) ve.UniversalInfo { + return ve.UniversalInfo{ + ServiceName: "mongodb", + Action: actionName, + Version: "2022-01-01", + HttpMethod: ve.POST, + ContentType: ve.ApplicationJSON, + } +} diff --git a/volcengine/mongodb/zone/data_source_volcengine_mongodb_zones.go b/volcengine/mongodb/zone/data_source_volcengine_mongodb_zones.go new file mode 100644 index 00000000..e0cc7e9d --- /dev/null +++ b/volcengine/mongodb/zone/data_source_volcengine_mongodb_zones.go @@ -0,0 +1,58 @@ +package zone + +import ( + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" +) + +func DataSourceVolcengineMongoDBZones() *schema.Resource { + return &schema.Resource{ + Read: dataSourceVolcengineMongoDBZonesRead, + Schema: map[string]*schema.Schema{ + "region_id": { + Type: schema.TypeString, + Required: true, + Description: "The Id of Region.", + }, + "output_file": { + Type: schema.TypeString, + Optional: true, + Description: "File name where to save data source results.", + }, + "total_count": { + Type: schema.TypeInt, + Computed: true, + Description: "The total count of zone query.", + }, + "zones": { + Description: "The collection of zone query.", + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "id": { + Type: schema.TypeString, + Computed: true, + Description: "The id of the zone.", + }, + "zone_id": { + Type: schema.TypeString, + Computed: true, + Description: "The id of the zone.", + }, + "zone_name": { + Type: schema.TypeString, + Computed: true, + Description: "The name of the zone.", + }, + }, + }, + }, + }, + } +} + +func dataSourceVolcengineMongoDBZonesRead(d *schema.ResourceData, meta interface{}) error { + zoneService := NewZoneService(meta.(*ve.SdkClient)) + return zoneService.Dispatcher.Data(zoneService, d, DataSourceVolcengineMongoDBZones()) +} diff --git a/volcengine/mongodb/zone/service_volcengine_mongodb_zone.go b/volcengine/mongodb/zone/service_volcengine_mongodb_zone.go new file mode 100644 index 00000000..0acd7e49 --- /dev/null +++ b/volcengine/mongodb/zone/service_volcengine_mongodb_zone.go @@ -0,0 +1,126 @@ +package zone + +import ( + "errors" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + ve "github.com/volcengine/terraform-provider-volcengine/common" + "github.com/volcengine/terraform-provider-volcengine/logger" +) + +type VolcengineZoneService struct { + Client *ve.SdkClient + Dispatcher *ve.Dispatcher +} + +func NewZoneService(c *ve.SdkClient) *VolcengineZoneService { + return &VolcengineZoneService{ + Client: c, + Dispatcher: &ve.Dispatcher{}, + } +} + +func (s *VolcengineZoneService) GetClient() *ve.SdkClient { + return s.Client +} + +func getUniversalInfo(actionName string) ve.UniversalInfo { + return ve.UniversalInfo{ + ServiceName: "mongodb", + Version: "2022-01-01", + HttpMethod: ve.POST, + ContentType: ve.ApplicationJSON, + Action: actionName, + } +} + +func (s *VolcengineZoneService) ReadResources(condition map[string]interface{}) ([]interface{}, error) { + var ( + resp *map[string]interface{} + results interface{} + ok bool + err error + data []interface{} + ) + action := "DescribeAvailabilityZones" + logger.Debug(logger.ReqFormat, action, condition) + if condition == nil { + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), nil) + } else { + resp, err = s.Client.UniversalClient.DoCall(getUniversalInfo(action), &condition) + } + if err != nil { + return nil, err + } + logger.Debug(logger.RespFormat, action, condition, *resp) + + results, err = ve.ObtainSdkValue("Result.Zones", *resp) + if err != nil { + return nil, err + } + if results == nil { + results = make([]interface{}, 0) + } + + if data, ok = results.([]interface{}); !ok { + return nil, errors.New("Result.Zones is not Slice") + } + + return data, nil +} + +func (s *VolcengineZoneService) ReadResource(resourceData *schema.ResourceData, id string) (data map[string]interface{}, err error) { + return nil, nil +} + +func (s *VolcengineZoneService) RefreshResourceState(resourceData *schema.ResourceData, target []string, timeout time.Duration, id string) *resource.StateChangeConf { + return &resource.StateChangeConf{ + Pending: []string{}, + Delay: 5 * time.Second, + MinTimeout: 5 * time.Second, + Target: target, + Timeout: timeout, + Refresh: func() (result interface{}, state string, err error) { + return nil, "", err + }, + } +} + +func (s *VolcengineZoneService) WithResourceResponseHandlers(zone map[string]interface{}) []ve.ResourceResponseHandler { + handler := func() (map[string]interface{}, map[string]ve.ResponseConvert, error) { + return zone, nil, nil + } + return []ve.ResourceResponseHandler{handler} +} + +func (s *VolcengineZoneService) CreateResource(resourceData *schema.ResourceData, resource *schema.Resource) []ve.Callback { + return []ve.Callback{} +} + +func (s *VolcengineZoneService) ModifyResource(resourceData *schema.ResourceData, resource *schema.Resource) (callbacks []ve.Callback) { + return callbacks +} + +func (s *VolcengineZoneService) RemoveResource(resourceData *schema.ResourceData, r *schema.Resource) []ve.Callback { + return []ve.Callback{} +} + +func (s *VolcengineZoneService) DatasourceResources(data *schema.ResourceData, resource *schema.Resource) ve.DataSourceInfo { + return ve.DataSourceInfo{ + NameField: "ZoneId", + IdField: "ZoneId", + CollectField: "zones", + ResponseConverts: map[string]ve.ResponseConvert{ + "ZoneId": { + TargetField: "id", + KeepDefault: true, + }, + }, + } +} + +func (s *VolcengineZoneService) ReadResourceId(id string) string { + return id +} diff --git a/volcengine/provider.go b/volcengine/provider.go index 07cbc6e2..3c11876c 100644 --- a/volcengine/provider.go +++ b/volcengine/provider.go @@ -3,6 +3,10 @@ package volcengine import ( "strings" + "github.com/volcengine/terraform-provider-volcengine/volcengine/mongodb/ssl_state" + + "github.com/volcengine/terraform-provider-volcengine/volcengine/mongodb/spec" + "github.com/volcengine/terraform-provider-volcengine/volcengine/vke/kubeconfig" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" @@ -62,6 +66,15 @@ import ( "github.com/volcengine/terraform-provider-volcengine/volcengine/iam/iam_role_policy_attachment" "github.com/volcengine/terraform-provider-volcengine/volcengine/iam/iam_user" "github.com/volcengine/terraform-provider-volcengine/volcengine/iam/iam_user_policy_attachment" + "github.com/volcengine/terraform-provider-volcengine/volcengine/mongodb/account" + "github.com/volcengine/terraform-provider-volcengine/volcengine/mongodb/allow_list" + "github.com/volcengine/terraform-provider-volcengine/volcengine/mongodb/allow_list_associate" + "github.com/volcengine/terraform-provider-volcengine/volcengine/mongodb/endpoint" + mongodbInstance "github.com/volcengine/terraform-provider-volcengine/volcengine/mongodb/instance" + "github.com/volcengine/terraform-provider-volcengine/volcengine/mongodb/instance_parameter" + "github.com/volcengine/terraform-provider-volcengine/volcengine/mongodb/instance_parameter_log" + mongodbRegion "github.com/volcengine/terraform-provider-volcengine/volcengine/mongodb/region" + mongodbZone "github.com/volcengine/terraform-provider-volcengine/volcengine/mongodb/zone" "github.com/volcengine/terraform-provider-volcengine/volcengine/nat/dnat_entry" "github.com/volcengine/terraform-provider-volcengine/volcengine/nat/nat_gateway" "github.com/volcengine/terraform-provider-volcengine/volcengine/nat/snat_entry" @@ -267,6 +280,17 @@ func Provider() terraform.ResourceProvider { "volcengine_veenedge_instance_types": instance_types.DataSourceVolcengineInstanceTypes(), "volcengine_veenedge_available_resources": available_resource.DataSourceVolcengineAvailableResources(), "volcengine_veenedge_vpcs": veVpc.DataSourceVolcengineVpcs(), + // ================ MongoDB ============= + "volcengine_mongodb_instances": mongodbInstance.DataSourceVolcengineMongoDBInstances(), + "volcengine_mongodb_endpoints": endpoint.DataSourceVolcengineMongoDBEndpoints(), + "volcengine_mongodb_allow_lists": allow_list.DataSourceVolcengineMongoDBAllowLists(), + "volcengine_mongodb_instance_parameters": instance_parameter.DataSourceVolcengineMongoDBInstanceParameters(), + "volcengine_mongodb_instance_parameter_logs": instance_parameter_log.DataSourceVolcengineMongoDBInstanceParameterLogs(), + "volcengine_mongodb_regions": mongodbRegion.DataSourceVolcengineMongoDBRegions(), + "volcengine_mongodb_zones": mongodbZone.DataSourceVolcengineMongoDBZones(), + "volcengine_mongodb_accounts": account.DataSourceVolcengineMongoDBAccounts(), + "volcengine_mongodb_specs": spec.DataSourceVolcengineMongoDBSpecs(), + "volcengine_mongodb_ssl_states": ssl_state.DataSourceVolcengineMongoDBSSLStates(), }, ResourcesMap: map[string]*schema.Resource{ "volcengine_vpc": vpc.ResourceVolcengineVpc(), @@ -385,6 +409,13 @@ func Provider() terraform.ResourceProvider { "volcengine_veenedge_cloud_server": cloud_server.ResourceVolcengineCloudServer(), "volcengine_veenedge_instance": veInstance.ResourceVolcengineInstance(), "volcengine_veenedge_vpc": veVpc.ResourceVolcengineVpc(), + // ================ MongoDB ================ + "volcengine_mongodb_instance": mongodbInstance.ResourceVolcengineMongoDBInstance(), + "volcengine_mongodb_endpoint": endpoint.ResourceVolcengineMongoDBEndpoint(), + "volcengine_mongodb_allow_list": allow_list.ResourceVolcengineMongoDBAllowList(), + "volcengine_mongodb_instance_parameter": instance_parameter.ResourceVolcengineMongoDBInstanceParameter(), + "volcengine_mongodb_allow_list_associate": allow_list_associate.ResourceVolcengineMongodbAllowListAssociate(), + "volcengine_mongodb_ssl_state": ssl_state.ResourceVolcengineMongoDBSSLState(), }, ConfigureFunc: ProviderConfigure, } diff --git a/website/docs/d/escloud_zones.html.markdown b/website/docs/d/escloud_zones.html.markdown new file mode 100644 index 00000000..960f6f9b --- /dev/null +++ b/website/docs/d/escloud_zones.html.markdown @@ -0,0 +1,30 @@ +--- +subcategory: "ESCLOUD" +layout: "volcengine" +page_title: "Volcengine: volcengine_escloud_zones" +sidebar_current: "docs-volcengine-datasource-escloud_zones" +description: |- + Use this data source to query detailed information of escloud zones +--- +# volcengine_escloud_zones +Use this data source to query detailed information of escloud zones +## Example Usage +```hcl +data "volcengine_escloud_zones" "default" { + region_id = "xxx" +} +``` +## Argument Reference +The following arguments are supported: +* `region_id` - (Required) The Id of Region. +* `output_file` - (Optional) File name where to save data source results. + +## Attributes Reference +In addition to all arguments above, the following attributes are exported: +* `total_count` - The total count of zone query. +* `zones` - The collection of zone query. + * `id` - The id of the zone. + * `zone_id` - The id of the zone. + * `zone_name` - The name of the zone. + + diff --git a/website/docs/d/mongodb_accounts.html.markdown b/website/docs/d/mongodb_accounts.html.markdown new file mode 100644 index 00000000..ec4c6916 --- /dev/null +++ b/website/docs/d/mongodb_accounts.html.markdown @@ -0,0 +1,33 @@ +--- +subcategory: "MONGODB" +layout: "volcengine" +page_title: "Volcengine: volcengine_mongodb_accounts" +sidebar_current: "docs-volcengine-datasource-mongodb_accounts" +description: |- + Use this data source to query detailed information of mongodb accounts +--- +# volcengine_mongodb_accounts +Use this data source to query detailed information of mongodb accounts +## Example Usage +```hcl +data "volcengine_mongodb_accounts" "default" { + instance_id = "mongo-replica-xxx" +} +``` +## Argument Reference +The following arguments are supported: +* `instance_id` - (Required) Target query mongo instance id. +* `account_name` - (Optional) The name of account, current support only `root`. +* `output_file` - (Optional) File name where to save data source results. + +## Attributes Reference +In addition to all arguments above, the following attributes are exported: +* `accounts` - The collection of accounts query. + * `account_name` - The name of account. + * `account_privileges` - The privilege info of mongo instance. + * `db_name` - The Name of DB. + * `role_name` - The Name of role. + * `account_type` - The type of account. +* `total_count` - The total count of accounts query. + + diff --git a/website/docs/d/mongodb_allow_lists.html.markdown b/website/docs/d/mongodb_allow_lists.html.markdown new file mode 100644 index 00000000..15b9d20e --- /dev/null +++ b/website/docs/d/mongodb_allow_lists.html.markdown @@ -0,0 +1,40 @@ +--- +subcategory: "MONGODB" +layout: "volcengine" +page_title: "Volcengine: volcengine_mongodb_allow_lists" +sidebar_current: "docs-volcengine-datasource-mongodb_allow_lists" +description: |- + Use this data source to query detailed information of mongodb allow lists +--- +# volcengine_mongodb_allow_lists +Use this data source to query detailed information of mongodb allow lists +## Example Usage +```hcl +data "volcengine_mongodb_allow_lists" "default" { + region_id = "cn-xxx" + instance_id = "mongo-replica-xxx" + allow_list_ids = ["acl-2ecfc3318fd24bfab6xxx", "acl-ada659ab83e941d6adc2xxxf"] +} +``` +## Argument Reference +The following arguments are supported: +* `region_id` - (Required) The region ID. +* `allow_list_ids` - (Optional) The allow list IDs to query. +* `instance_id` - (Optional) The instance ID to query. + +## Attributes Reference +In addition to all arguments above, the following attributes are exported: +* `allow_lists` - The collection of mongodb allow list query. + * `allow_list_desc` - The description of allow list. + * `allow_list_id` - The ID of allow list. + * `allow_list_ip_num` - The number of allow list IPs. + * `allow_list_name` - The allow list name. + * `allow_list_type` - The IP address type in allow list. + * `allow_list` - The list of IP address in allow list. + * `associated_instance_num` - The total number of instances bound under the allow list. + * `associated_instances` - The list of associated instances. + * `instance_id` - The instance id that bound to the allow list. + * `instance_name` - The instance name that bound to the allow list. + * `vpc` - The VPC ID. + + diff --git a/website/docs/d/mongodb_endpoints.html.markdown b/website/docs/d/mongodb_endpoints.html.markdown new file mode 100644 index 00000000..319fb751 --- /dev/null +++ b/website/docs/d/mongodb_endpoints.html.markdown @@ -0,0 +1,41 @@ +--- +subcategory: "MONGODB" +layout: "volcengine" +page_title: "Volcengine: volcengine_mongodb_endpoints" +sidebar_current: "docs-volcengine-datasource-mongodb_endpoints" +description: |- + Use this data source to query detailed information of mongodb endpoints +--- +# volcengine_mongodb_endpoints +Use this data source to query detailed information of mongodb endpoints +## Example Usage +```hcl +data "volcengine_mongodb_endpoints" "foo" { + instance_id = "mongo-shard-xxx" +} +``` +## Argument Reference +The following arguments are supported: +* `instance_id` - (Optional) The instance ID to query. +* `output_file` - (Optional) File name where to save data source results. + +## Attributes Reference +In addition to all arguments above, the following attributes are exported: +* `endpoints` - The collection of mongodb endpoints query. + * `db_addresses` - The list of mongodb addresses. + * `address_domain` - The domain of mongodb connection. + * `address_ip` - The IP of mongodb connection. + * `address_port` - The port of mongodb connection. + * `address_type` - The connection type of mongodb. + * `eip_id` - The EIP ID bound to the instance's public network address. + * `node_id` - The node ID. + * `endpoint_id` - The ID of endpoint. + * `endpoint_str` - The endpoint information. + * `endpoint_type` - The node type corresponding to the endpoint. + * `network_type` - The network type of endpoint. + * `object_id` - The object ID corresponding to the endpoint. + * `subnet_id` - The subnet ID. + * `vpc_id` - The VPC ID. +* `total_count` - The total count of mongodb endpoint query. + + diff --git a/website/docs/d/mongodb_instance_parameter_logs.html.markdown b/website/docs/d/mongodb_instance_parameter_logs.html.markdown new file mode 100644 index 00000000..30072797 --- /dev/null +++ b/website/docs/d/mongodb_instance_parameter_logs.html.markdown @@ -0,0 +1,37 @@ +--- +subcategory: "MONGODB" +layout: "volcengine" +page_title: "Volcengine: volcengine_mongodb_instance_parameter_logs" +sidebar_current: "docs-volcengine-datasource-mongodb_instance_parameter_logs" +description: |- + Use this data source to query detailed information of mongodb instance parameter logs +--- +# volcengine_mongodb_instance_parameter_logs +Use this data source to query detailed information of mongodb instance parameter logs +## Example Usage +```hcl +data "volcengine_mongodb_instance_parameter_logs" "foo" { + instance_id = "mongo-replica-xxx" + start_time = "2022-11-14 00:00Z" + end_time = "2022-11-14 18:15Z" +} +``` +## Argument Reference +The following arguments are supported: +* `instance_id` - (Required) The instance ID to query. +* `end_time` - (Optional) The end time to query. +* `output_file` - (Optional) File name where to save data source results. +* `start_time` - (Optional) The start time to query. + +## Attributes Reference +In addition to all arguments above, the following attributes are exported: +* `parameter_change_logs` - The collection of parameter change log query. + * `modify_time` - The modifying time of parameter. + * `new_parameter_value` - The new parameter value. + * `old_parameter_value` - The old parameter value. + * `parameter_name` - The parameter name. + * `parameter_role` - The node type to which the parameter belongs. + * `parameter_status` - The status of parameter change. +* `total_count` - The total count of mongodb instance parameter log query. + + diff --git a/website/docs/d/mongodb_instance_parameters.html.markdown b/website/docs/d/mongodb_instance_parameters.html.markdown new file mode 100644 index 00000000..a71be65c --- /dev/null +++ b/website/docs/d/mongodb_instance_parameters.html.markdown @@ -0,0 +1,43 @@ +--- +subcategory: "MONGODB" +layout: "volcengine" +page_title: "Volcengine: volcengine_mongodb_instance_parameters" +sidebar_current: "docs-volcengine-datasource-mongodb_instance_parameters" +description: |- + Use this data source to query detailed information of mongodb instance parameters +--- +# volcengine_mongodb_instance_parameters +Use this data source to query detailed information of mongodb instance parameters +## Example Usage +```hcl +data "volcengine_mongodb_instance_parameters" "foo" { + instance_id = "mongo-replica-xxx" +} +``` +## Argument Reference +The following arguments are supported: +* `instance_id` - (Required) The instance ID to query. +* `output_file` - (Optional) File name where to save data source results. +* `parameter_names` - (Optional) The parameter names,support fuzzy query, case insensitive. +* `parameter_role` - (Optional) The node type of instance parameter,valid value contains `Node`,`Shard`,`ConfigServer`,`Mongos`. + +## Attributes Reference +In addition to all arguments above, the following attributes are exported: +* `parameters` - The collection of parameter query. + * `db_engine_version` - The database engine version. + * `db_engine` - The database engine. + * `instance_id` - The instance ID. + * `instance_parameters` - The list of parameters. + * `checking_code` - The checking code of parameter. + * `force_modify` - Whether the parameter supports modifying. + * `force_restart` - Does the new parameter value need to restart the instance to take effect after modification. + * `parameter_default_value` - The default value of parameter. + * `parameter_description` - The description of parameter. + * `parameter_name` - The name of parameter. + * `parameter_role` - The node type to which the parameter belongs. + * `parameter_type` - The type of parameter value. + * `parameter_value` - The value of parameter. + * `total` - The total parameters queried. +* `total_count` - The total count of mongodb instance parameter query. + + diff --git a/website/docs/d/mongodb_instances.html.markdown b/website/docs/d/mongodb_instances.html.markdown new file mode 100644 index 00000000..65b5e974 --- /dev/null +++ b/website/docs/d/mongodb_instances.html.markdown @@ -0,0 +1,104 @@ +--- +subcategory: "MONGODB" +layout: "volcengine" +page_title: "Volcengine: volcengine_mongodb_instances" +sidebar_current: "docs-volcengine-datasource-mongodb_instances" +description: |- + Use this data source to query detailed information of mongodb instances +--- +# volcengine_mongodb_instances +Use this data source to query detailed information of mongodb instances +## Example Usage +```hcl +data "volcengine_mongodb_instances" "foo" { + instance_id = "mongo-replica-xxx" +} +``` +## Argument Reference +The following arguments are supported: +* `create_end_time` - (Optional) The end time of creation to query. +* `create_start_time` - (Optional) The start time of creation to query. +* `db_engine_version` - (Optional) The version of db engine to query,valid value contains `MongoDB_4_0`. +* `db_engine` - (Optional) The db engine to query,valid value contains `MongoDB`. +* `instance_id` - (Optional) The instance ID to query. +* `instance_name` - (Optional) The instance name to query. +* `instance_status` - (Optional) The instance status to query. +* `instance_type` - (Optional) The type of instance to query,the valid value contains `ReplicaSet` or `ShardedCluster`. +* `output_file` - (Optional) File name where to save data source results. +* `update_end_time` - (Optional) The end time of update to query. +* `update_start_time` - (Optional) The start time of update to query. +* `vpc_id` - (Optional) The vpc id of instance to query. +* `zone_id` - (Optional) The zone ID to query. + +## Attributes Reference +In addition to all arguments above, the following attributes are exported: +* `instances` - The collection of mongodb instances query. + * `auto_renew` - Whether to enable automatic renewal. + * `charge_status` - The charge status. + * `charge_type` - The charge type of instance. + * `closed_time` - The planned close time. + * `config_servers_id` - The ID of config servers. + * `config_servers` - The list of config servers. + * `config_server_node_id` - The config server node ID. + * `node_role` - The config server node role. + * `node_status` - The config server node status. + * `total_memory_gb` - The total memory in GB. + * `total_vcpu` - The total vCPU. + * `used_memory_gb` - The used memory in GB. + * `used_vcpu` - The used vCPU. + * `create_time` - The creation time of instance. + * `db_engine_version_str` - The version string of database engine. + * `db_engine_version` - The version of database engine. + * `db_engine` - The db engine. + * `expired_time` - The expired time of instance. + * `instance_id` - The instance ID. + * `instance_name` - The instance name. + * `instance_status` - The instance status. + * `instance_type` - The instance type. + * `mongos_id` - The ID of mongos. + * `mongos` - The list of mongos. + * `mongos_node_id` - The mongos node ID. + * `node_spec` - The node spec. + * `node_status` - The node status. + * `total_memory_gb` - The total memory in GB. + * `total_vcpu` - The total vCPU. + * `used_memory_gb` - The used memory in GB. + * `used_vcpu` - The used vCPU. + * `nodes` - The node information. + * `node_delay_time` - The master-slave delay time. + * `node_id` - The node ID. + * `node_role` - The nod role. + * `node_spec` - The node spec. + * `node_status` - The node status. + * `total_memory_gb` - The total memory in GB. + * `total_storage_gb` - The total storage in GB. + * `total_vcpu` - The total vCPU. + * `used_memory_gb` - The used memory in GB. + * `used_storage_gb` - The used storage in GB. + * `used_vcpu` - The used vCPU. + * `project_name` - The project name to which the instance belongs. + * `reclaim_time` - The planned reclaim time of instance. + * `shards` - The list of shards. + * `nodes` - The node information. + * `node_delay_time` - The master-slave delay time. + * `node_id` - The node ID. + * `node_role` - The nod role. + * `node_spec` - The node spec. + * `node_status` - The node status. + * `total_memory_gb` - The total memory in GB. + * `total_storage_gb` - The total storage in GB. + * `total_vcpu` - The total vCPU. + * `used_memory_gb` - The used memory in GB. + * `used_storage_gb` - The used storage in GB. + * `used_vcpu` - The used vCPU. + * `shard_id` - The shard ID. + * `ssl_enable` - Whether ssl enabled. + * `ssl_expire_time` - The ssl expire time. + * `ssl_is_valid` - Whether ssl is valid. + * `subnet_id` - The subnet id of instance. + * `update_time` - The update time of instance. + * `vpc_id` - The vpc ID. + * `zone_id` - The zone ID of instance. +* `total_count` - The total count of mongodb instances query. + + diff --git a/website/docs/d/mongodb_regions.html.markdown b/website/docs/d/mongodb_regions.html.markdown new file mode 100644 index 00000000..cc96b90a --- /dev/null +++ b/website/docs/d/mongodb_regions.html.markdown @@ -0,0 +1,27 @@ +--- +subcategory: "MONGODB" +layout: "volcengine" +page_title: "Volcengine: volcengine_mongodb_regions" +sidebar_current: "docs-volcengine-datasource-mongodb_regions" +description: |- + Use this data source to query detailed information of mongodb regions +--- +# volcengine_mongodb_regions +Use this data source to query detailed information of mongodb regions +## Example Usage +```hcl +data "volcengine_mongodb_regions" "default" { +} +``` +## Argument Reference +The following arguments are supported: +* `output_file` - (Optional) File name where to save data source results. + +## Attributes Reference +In addition to all arguments above, the following attributes are exported: +* `regions` - The collection of region query. + * `region_id` - The id of the region. + * `region_name` - The name of region. +* `total_count` - The total count of region query. + + diff --git a/website/docs/d/mongodb_specs.html.markdown b/website/docs/d/mongodb_specs.html.markdown new file mode 100644 index 00000000..7e301f8a --- /dev/null +++ b/website/docs/d/mongodb_specs.html.markdown @@ -0,0 +1,44 @@ +--- +subcategory: "MONGODB" +layout: "volcengine" +page_title: "Volcengine: volcengine_mongodb_specs" +sidebar_current: "docs-volcengine-datasource-mongodb_specs" +description: |- + Use this data source to query detailed information of mongodb specs +--- +# volcengine_mongodb_specs +Use this data source to query detailed information of mongodb specs +## Example Usage +```hcl +data "volcengine_mongodb_specs" "foo" { + region_id = "cn-xxx" +} +``` +## Argument Reference +The following arguments are supported: +* `region_id` - (Required) The region ID to query. +* `output_file` - (Optional) File name where to save data source results. + +## Attributes Reference +In addition to all arguments above, the following attributes are exported: +* `specs` - The collection of mongos spec query. + * `mongos_node_specs` - The collection of mongos node specs. + * `cpu_num` - The max cpu cores. + * `max_conn` - The max connections. + * `mem_in_gb` - The memory in GB. + * `spec_name` - The mongos node spec name. + * `node_specs` - The collection of node specs. + * `cpu_num` - The cpu cores. + * `max_conn` - The max connections. + * `max_storage` - The max storage. + * `mem_in_db` - The memory in GB. + * `spec_name` - The node spec name. + * `shard_node_specs` - The collection of shard node specs. + * `cpu_num` - The cpu cores. + * `max_conn` - The max connections. + * `max_storage` - The max storage. + * `mem_in_gb` - The memory in GB. + * `spec_name` - The shard node spec name. +* `total_count` - The total count of region query. + + diff --git a/website/docs/d/mongodb_ssl_states.html.markdown b/website/docs/d/mongodb_ssl_states.html.markdown new file mode 100644 index 00000000..fd13306f --- /dev/null +++ b/website/docs/d/mongodb_ssl_states.html.markdown @@ -0,0 +1,29 @@ +--- +subcategory: "MONGODB" +layout: "volcengine" +page_title: "Volcengine: volcengine_mongodb_ssl_states" +sidebar_current: "docs-volcengine-datasource-mongodb_ssl_states" +description: |- + Use this data source to query detailed information of mongodb ssl states +--- +# volcengine_mongodb_ssl_states +Use this data source to query detailed information of mongodb ssl states +## Example Usage +```hcl +data "volcengine_mongodb_ssl_states" "foo" { + instance_id = "mongo-shard-xxx" +} +``` +## Argument Reference +The following arguments are supported: +* `instance_id` - (Optional) The mongodb instance ID to query. + +## Attributes Reference +In addition to all arguments above, the following attributes are exported: +* `ssl_state` - The collection of mongodb ssl state query. + * `instance_id` - The mongodb instance id. + * `is_valid` - Whetehr SSL is valid. + * `ssl_enable` - Whether SSL is enabled. + * `ssl_expired_time` - The expire time of SSL. + + diff --git a/website/docs/d/mongodb_zones.html.markdown b/website/docs/d/mongodb_zones.html.markdown new file mode 100644 index 00000000..ca56e7ca --- /dev/null +++ b/website/docs/d/mongodb_zones.html.markdown @@ -0,0 +1,30 @@ +--- +subcategory: "MONGODB" +layout: "volcengine" +page_title: "Volcengine: volcengine_mongodb_zones" +sidebar_current: "docs-volcengine-datasource-mongodb_zones" +description: |- + Use this data source to query detailed information of mongodb zones +--- +# volcengine_mongodb_zones +Use this data source to query detailed information of mongodb zones +## Example Usage +```hcl +data "volcengine_mongodb_zones" "default" { + region_id = "XXX" +} +``` +## Argument Reference +The following arguments are supported: +* `region_id` - (Required) The Id of Region. +* `output_file` - (Optional) File name where to save data source results. + +## Attributes Reference +In addition to all arguments above, the following attributes are exported: +* `total_count` - The total count of zone query. +* `zones` - The collection of zone query. + * `id` - The id of the zone. + * `zone_id` - The id of the zone. + * `zone_name` - The name of the zone. + + diff --git a/website/docs/d/zones.html.markdown b/website/docs/d/zones.html.markdown index ebcd2dfb..4739a8d2 100644 --- a/website/docs/d/zones.html.markdown +++ b/website/docs/d/zones.html.markdown @@ -1,5 +1,5 @@ --- -subcategory: "ESCLOUD" +subcategory: "ECS" layout: "volcengine" page_title: "Volcengine: volcengine_zones" sidebar_current: "docs-volcengine-datasource-zones" diff --git a/website/docs/r/mongodb_allow_list.html.markdown b/website/docs/r/mongodb_allow_list.html.markdown new file mode 100644 index 00000000..7cd8aa71 --- /dev/null +++ b/website/docs/r/mongodb_allow_list.html.markdown @@ -0,0 +1,39 @@ +--- +subcategory: "MONGODB" +layout: "volcengine" +page_title: "Volcengine: volcengine_mongodb_allow_list" +sidebar_current: "docs-volcengine-resource-mongodb_allow_list" +description: |- + Provides a resource to manage mongodb allow list +--- +# volcengine_mongodb_allow_list +Provides a resource to manage mongodb allow list +## Example Usage +```hcl +resource "volcengine_mongodb_allow_list" "foo" { + allow_list_name = "tf-test" + allow_list_desc = "test" + allow_list_type = "IPv4" + allow_list = "10.1.1.1,10.1.1.2,10.1.1.3,10.2.3.0/24" +} +``` +## Argument Reference +The following arguments are supported: +* `allow_list_name` - (Required) The name of allow list. +* `allow_list` - (Required) IP address or IP address segment in CIDR format. +* `allow_list_desc` - (Optional) The description of allow list. +* `allow_list_type` - (Optional) The IP address type of allow list,valid value contains `IPv4`. +* `modify_mode` - (Optional) The modify mode. + +## Attributes Reference +In addition to all arguments above, the following attributes are exported: +* `id` - ID of the resource. + + + +## Import +mongosdb allow list can be imported using the allowListId, e.g. +``` +$ terraform import volcengine_mongosdb_allow_list.default acl-d1fd76693bd54e658912e7337d5b**** +``` + diff --git a/website/docs/r/mongodb_allow_list_associate.html.markdown b/website/docs/r/mongodb_allow_list_associate.html.markdown new file mode 100644 index 00000000..d15a81f0 --- /dev/null +++ b/website/docs/r/mongodb_allow_list_associate.html.markdown @@ -0,0 +1,34 @@ +--- +subcategory: "MONGODB" +layout: "volcengine" +page_title: "Volcengine: volcengine_mongodb_allow_list_associate" +sidebar_current: "docs-volcengine-resource-mongodb_allow_list_associate" +description: |- + Provides a resource to manage mongodb allow list associate +--- +# volcengine_mongodb_allow_list_associate +Provides a resource to manage mongodb allow list associate +## Example Usage +```hcl +resource "volcengine_mongodb_allow_list_associate" "foo" { + instance_id = "mongo-replica-b2xxx" + allow_list_id = "acl-4d66bec945d14fa48xxx" +} +``` +## Argument Reference +The following arguments are supported: +* `allow_list_id` - (Required, ForceNew) Id of allow list to associate. +* `instance_id` - (Required, ForceNew) Id of instance to associate. + +## Attributes Reference +In addition to all arguments above, the following attributes are exported: +* `id` - ID of the resource. + + + +## Import +mongosdb allow list associate can be imported using the instanceId:allowListId, e.g. +``` +$ terraform import volcengine_mongosdb_allow_list_associate.default mongo-replica-e405f8e2****:acl-d1fd76693bd54e658912e7337d5b**** +``` + diff --git a/website/docs/r/mongodb_endpoint.html.markdown b/website/docs/r/mongodb_endpoint.html.markdown new file mode 100644 index 00000000..9b34b832 --- /dev/null +++ b/website/docs/r/mongodb_endpoint.html.markdown @@ -0,0 +1,42 @@ +--- +subcategory: "MONGODB" +layout: "volcengine" +page_title: "Volcengine: volcengine_mongodb_endpoint" +sidebar_current: "docs-volcengine-resource-mongodb_endpoint" +description: |- + Provides a resource to manage mongodb endpoint +--- +# volcengine_mongodb_endpoint +Provides a resource to manage mongodb endpoint +## Example Usage +```hcl +resource "volcengine_mongodb_endpoint" "foo" { + instance_id = "mongo-shard-xxx" + object_id = "mongo-shard-xxx-s1" + network_type = "Public" + eip_ids = ["eip-xx", "eip-xx"] +} +``` +## Argument Reference +The following arguments are supported: +* `instance_id` - (Required, ForceNew) The instance where the endpoint resides. +* `eip_ids` - (Optional) A list of EIP IDs that need to be bound when applying for endpoint. +* `mongos_node_ids` - (Optional) A list of the Mongos node that needs to apply for the endpoint. +* `network_type` - (Optional) The network type of endpoint. +* `object_id` - (Optional) The object ID corresponding to the endpoint. + +## Attributes Reference +In addition to all arguments above, the following attributes are exported: +* `id` - ID of the resource. +* `endpoint_id` - The id of endpoint. + + +## Import +mongodb endpoint can be imported using the instanceId:endpointId +`instanceId`: represents the instance that endpoint related to. +`endpointId`: the id of endpoint. +e.g. +``` +$ terraform import volcengine_mongodb_endpoint.default mongo-replica-e405f8e2****:BRhFA0pDAk0XXkxCZQ +``` + diff --git a/website/docs/r/mongodb_instance.html.markdown b/website/docs/r/mongodb_instance.html.markdown new file mode 100644 index 00000000..76b1dfea --- /dev/null +++ b/website/docs/r/mongodb_instance.html.markdown @@ -0,0 +1,59 @@ +--- +subcategory: "MONGODB" +layout: "volcengine" +page_title: "Volcengine: volcengine_mongodb_instance" +sidebar_current: "docs-volcengine-resource-mongodb_instance" +description: |- + Provides a resource to manage mongodb instance +--- +# volcengine_mongodb_instance +Provides a resource to manage mongodb instance +## Example Usage +```hcl +resource "volcengine_mongodb_instance" "foo" { + zone_id = "cn-xxx" + instance_type = "ShardedCluster" + node_spec = "mongo.xxx" + mongos_node_spec = "mongo.mongos.xxx" + shard_number = 3 + storage_space_gb = 100 + subnet_id = "subnet-2d6pxxu" + instance_name = "tf-test" + charge_type = "PostPaid" + # period_unit="Month" + # period=1 + # auto_renew=false + # ssl_action="Close" +} +``` +## Argument Reference +The following arguments are supported: +* `node_spec` - (Required) The spec of node. +* `storage_space_gb` - (Required) The total storage space of a replica set instance, or the storage space of a single shard in a sharded cluster, in GiB. +* `subnet_id` - (Required, ForceNew) The subnet id of instance. +* `super_account_password` - (Required) The password of database account. +* `auto_renew` - (Optional) Whether to enable automatic renewal. +* `charge_type` - (Optional) The charge type of instance,valid value contains `Prepaid` or `PostPaid`. +* `instance_name` - (Optional) The instance name. +* `instance_type` - (Optional) The type of instance,the valid value contains `ReplicaSet` or `ShardedCluster`. +* `mongos_node_number` - (Optional) The mongos node number of shard cluster,value range is `2~23`,this parameter is required when `InstanceType` is `ShardedCluster`. +* `mongos_node_spec` - (Optional) The mongos node spec of shard cluster,this parameter is required when `InstanceType` is `ShardedCluster`. +* `period_unit` - (Optional) The period unit,valid value contains `Year` or `Month`,this parameter is required when `ChargeType` is `Prepaid`. +* `period` - (Optional) The instance purchase duration,the value range is `1~3` when `PeriodUtil` is `Year`,the value range is `1~9` when `PeriodUtil` is `Month`,this parameter is required when `ChargeType` is `Prepaid`. +* `project_name` - (Optional) The project name to which the instance belongs. +* `shard_number` - (Optional) The number of shards in shard cluster,value range is `2~23`,this parameter is required when `InstanceType` is `ShardedCluster`. +* `vpc_id` - (Optional) The vpc ID. +* `zone_id` - (Optional) The zone ID of instance. + +## Attributes Reference +In addition to all arguments above, the following attributes are exported: +* `id` - ID of the resource. + + + +## Import +mongosdb instance can be imported using the id, e.g. +``` +$ terraform import volcengine_mongosdb_instance.default mongo-replica-e405f8e2**** +``` + diff --git a/website/docs/r/mongodb_instance_parameter.html.markdown b/website/docs/r/mongodb_instance_parameter.html.markdown new file mode 100644 index 00000000..22dbfb2a --- /dev/null +++ b/website/docs/r/mongodb_instance_parameter.html.markdown @@ -0,0 +1,38 @@ +--- +subcategory: "MONGODB" +layout: "volcengine" +page_title: "Volcengine: volcengine_mongodb_instance_parameter" +sidebar_current: "docs-volcengine-resource-mongodb_instance_parameter" +description: |- + Provides a resource to manage mongodb instance parameter +--- +# volcengine_mongodb_instance_parameter +Provides a resource to manage mongodb instance parameter +## Example Usage +```hcl +resource "volcengine_mongodb_instance_parameter" "foo" { + instance_id = "mongo-replica-b2xxx" + parameter_name = "connPoolMaxConnsPerHost" + parameter_role = "Node" + parameter_value = "800" +} +``` +## Argument Reference +The following arguments are supported: +* `instance_id` - (Required) The instance ID. +* `parameter_role` - (Required) The node type to which the parameter belongs. +* `parameter_value` - (Required) The value of parameter. +* `parameter_name` - (Optional) The name of parameter. + +## Attributes Reference +In addition to all arguments above, the following attributes are exported: +* `id` - ID of the resource. + + + +## Import +mongosdb parameter can be imported using the param:instanceId:parameterName, e.g. +``` +$ terraform import volcengine_mongodb_instance_parameter.default param:mongo-replica-e405f8e2****:connPoolMaxConnsPerHost +``` + diff --git a/website/docs/r/mongodb_ssl_state.html.markdown b/website/docs/r/mongodb_ssl_state.html.markdown new file mode 100644 index 00000000..44d73e5a --- /dev/null +++ b/website/docs/r/mongodb_ssl_state.html.markdown @@ -0,0 +1,35 @@ +--- +subcategory: "MONGODB" +layout: "volcengine" +page_title: "Volcengine: volcengine_mongodb_ssl_state" +sidebar_current: "docs-volcengine-resource-mongodb_ssl_state" +description: |- + Provides a resource to manage mongodb ssl state +--- +# volcengine_mongodb_ssl_state +Provides a resource to manage mongodb ssl state +## Example Usage +```hcl +resource "volcengine_mongodb_ssl_state" "foo" { + instance_id = "mongo-shard-xxx" + ssl_action = "Update" +} +``` +## Argument Reference +The following arguments are supported: +* `instance_id` - (Required) The ID of mongodb instance. +* `ssl_action` - (Optional) The action of ssl,valid value contains `Update`. + +## Attributes Reference +In addition to all arguments above, the following attributes are exported: +* `id` - ID of the resource. + + + +## Import +mongosdb ssl state can be imported using the ssl:instanceId, e.g. +set `ssl_action` to `Update` will update ssl always when terraform apply. +``` +$ terraform import volcengine_mongosdb_ssl_state.default ssl:mongo-shard-d050db19xxx +``` + diff --git a/website/volcengine.erb b/website/volcengine.erb index d56589f9..3c74fff3 100644 --- a/website/volcengine.erb +++ b/website/volcengine.erb @@ -332,7 +332,7 @@ escloud_instances