Skip to content

feat(cvm): [119840232] cvm support action_timer params #2874

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Nov 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .changelog/2874.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:new-resource
tencentcloud_cvm_action_timer
```
1 change: 1 addition & 0 deletions tencentcloud/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -2001,6 +2001,7 @@ func Provider() *schema.Provider {
"tencentcloud_cvm_renew_host": cvm.ResourceTencentCloudCvmRenewHost(),
"tencentcloud_cvm_program_fpga_image": cvm.ResourceTencentCloudCvmProgramFpgaImage(),
"tencentcloud_cvm_modify_instance_disk_type": cvm.ResourceTencentCloudCvmModifyInstanceDiskType(),
"tencentcloud_cvm_action_timer": cvm.ResourceTencentCloudCvmActionTimer(),
"tencentcloud_lighthouse_disk_backup": lighthouse.ResourceTencentCloudLighthouseDiskBackup(),
"tencentcloud_lighthouse_apply_disk_backup": lighthouse.ResourceTencentCloudLighthouseApplyDiskBackup(),
"tencentcloud_lighthouse_disk_attachment": lighthouse.ResourceTencentCloudLighthouseDiskAttachment(),
Expand Down
1 change: 1 addition & 0 deletions tencentcloud/provider.md
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,7 @@ Cloud Virtual Machine(CVM)
tencentcloud_cvm_sync_image
tencentcloud_cvm_export_images
tencentcloud_cvm_image_share_permission
tencentcloud_cvm_action_timer

TDSQL-C MySQL(CynosDB)
Data Source
Expand Down
170 changes: 170 additions & 0 deletions tencentcloud/services/cvm/resource_tc_cvm_action_timer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
package cvm

import (
"context"
"fmt"
"log"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
cvm "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cvm/v20170312"
tccommon "github.com/tencentcloudstack/terraform-provider-tencentcloud/tencentcloud/common"
"github.com/tencentcloudstack/terraform-provider-tencentcloud/tencentcloud/internal/helper"
)

func ResourceTencentCloudCvmActionTimer() *schema.Resource {
return &schema.Resource{
Create: resourceTencentCloudCvmActionTimerCreate,
Read: resourceTencentCloudCvmActionTimerRead,
//Update: resourceTencentCloudCvmActionTimerUpdate,
Delete: resourceTencentCloudCvmActionTimerDelete,
//Importer: &schema.ResourceImporter{
// State: schema.ImportStatePassthrough,
//},
Schema: map[string]*schema.Schema{
"instance_id": {
Required: true,
ForceNew: true,
Type: schema.TypeString,
Description: "Instance ID.",
},
"action_timer": {
Required: true,
ForceNew: true,
Type: schema.TypeList,
MaxItems: 1,
Description: "Scheduled tasks. This parameter can be used to specify scheduled tasks for instances, and currently only supports scheduled destruction.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"timer_action": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "Timer action, currently only supports destroying one value: TerminateInstances.",
},
"action_time": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "Execution time, expressed according to ISO8601 standard and using UTC time. The format is YYYY-MM-DDThh:mm:ssZ. For example, 2018-05-29T11:26:40Z, the execution time must be 5 minutes longer than the current time.",
},
},
},
},
},
}
}

func resourceTencentCloudCvmActionTimerCreate(d *schema.ResourceData, meta interface{}) error {
defer tccommon.LogElapsed("resource.tencentcloud_cvm_action_timer.create")()

var (
logId = tccommon.GetLogId(tccommon.ContextNil)
request = cvm.NewImportInstancesActionTimerRequest()
response = cvm.NewImportInstancesActionTimerResponse()
actionTimerId string
)

if v, ok := d.GetOk("instance_id"); ok {
request.InstanceIds = []*string{helper.String(v.(string))}
}

if dMap, ok := helper.InterfacesHeadMap(d, "action_timer"); ok {
actionTimer := cvm.ActionTimer{}
if v, ok := dMap["timer_action"]; ok {
actionTimer.TimerAction = helper.String(v.(string))
}

if v, ok := dMap["action_time"]; ok {
actionTimer.ActionTime = helper.String(v.(string))
}

request.ActionTimer = &actionTimer
}

err := resource.Retry(tccommon.WriteRetryTimeout, func() *resource.RetryError {
result, e := meta.(tccommon.ProviderMeta).GetAPIV3Conn().UseCvmClient().ImportInstancesActionTimer(request)
if e != nil {
return resource.RetryableError(e)
} else {
log.Printf("[DEBUG]%s api[%s] success, request body [%s], response body [%s]\n", logId, request.GetAction(), request.ToJsonString(), result.ToJsonString())
}

if result == nil || result.Response == nil || len(result.Response.ActionTimerIds) != 1 {
e = fmt.Errorf("create cvm InstanceActionTimer failed")
return resource.NonRetryableError(e)
}

response = result
return nil
})

if err != nil {
log.Printf("[CRITAL]%s create cvm InstanceActionTimer failed, reason:%+v", logId, err)
return err
}

actionTimerId = *response.Response.ActionTimerIds[0]
d.SetId(actionTimerId)

return resourceTencentCloudCvmActionTimerRead(d, meta)
}

func resourceTencentCloudCvmActionTimerRead(d *schema.ResourceData, meta interface{}) error {
defer tccommon.LogElapsed("resource.tencentcloud_cvm_action_timer.read")()

var (
logId = tccommon.GetLogId(tccommon.ContextNil)
ctx = context.WithValue(context.TODO(), tccommon.LogIdKey, logId)
service = CvmService{client: meta.(tccommon.ProviderMeta).GetAPIV3Conn()}
actionTimerId = d.Id()
)

InstanceActionTimer, err := service.DescribeCvmInstanceActionTimerById(ctx, actionTimerId)
if err != nil {
return err
}

if InstanceActionTimer == nil {
d.SetId("")
log.Printf("[WARN]%s resource `CvmInstanceActionTimer` [%s] not found, please check if it has been deleted.\n", logId, d.Id())
return nil
}

actionTimerMap := map[string]interface{}{}
if InstanceActionTimer.TimerAction != nil {
actionTimerMap["timer_action"] = InstanceActionTimer.TimerAction
}

if InstanceActionTimer.ActionTime != nil {
actionTimerMap["action_time"] = InstanceActionTimer.ActionTime
}

_ = d.Set("action_timer", []interface{}{actionTimerMap})

return nil
}

// func resourceTencentCloudCvmActionTimerUpdate(d *schema.ResourceData, meta interface{}) error {
// defer tccommon.LogElapsed("resource.tencentcloud_cvm_action_timer.update")()
// defer tccommon.InconsistentCheck(d, meta)()

// return resourceTencentCloudCvmActionTimerRead(d, meta)
// }

func resourceTencentCloudCvmActionTimerDelete(d *schema.ResourceData, meta interface{}) error {
defer tccommon.LogElapsed("resource.tencentcloud_cvm_action_timer.delete")()

var (
logId = tccommon.GetLogId(tccommon.ContextNil)
ctx = context.WithValue(context.TODO(), tccommon.LogIdKey, logId)
service = CvmService{client: meta.(tccommon.ProviderMeta).GetAPIV3Conn()}
actionTimerId = d.Id()
)

if err := service.DeleteCvmInstanceActionTimerById(ctx, actionTimerId); err != nil {
return err
}

return nil
}
63 changes: 63 additions & 0 deletions tencentcloud/services/cvm/resource_tc_cvm_action_timer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
Provides a resource to create a CVM instance action timer

Example Usage

```hcl
variable "availability_zone" {
default = "ap-guangzhou-6"
}
data "tencentcloud_images" "images" {
image_type = ["PUBLIC_IMAGE"]
image_name_regex = "TencentOS Server"
}
# create vpc
resource "tencentcloud_vpc" "vpc" {
name = "vpc"
cidr_block = "10.0.0.0/16"
}
# create vpc subnet
resource "tencentcloud_subnet" "subnet" {
name = "subnet"
vpc_id = tencentcloud_vpc.vpc.id
availability_zone = var.availability_zone
cidr_block = "10.0.20.0/28"
is_multicast = false
}
# create cvm
resource "tencentcloud_instance" "example" {
instance_name = "tf_example"
availability_zone = var.availability_zone
image_id = data.tencentcloud_images.images.images.0.image_id
instance_type = "SA3.MEDIUM4"
system_disk_type = "CLOUD_HSSD"
system_disk_size = 100
hostname = "example"
project_id = 0
vpc_id = tencentcloud_vpc.vpc.id
subnet_id = tencentcloud_subnet.subnet.id
data_disks {
data_disk_type = "CLOUD_HSSD"
data_disk_size = 50
encrypt = false
}
tags = {
createBy = "terraform"
}
}
# create cvm action timer
resource "tencentcloud_cvm_action_timer" "example" {
instance_id = tencentcloud_instance.example.id
action_timer {
timer_action = "TerminateInstances"
action_time = "2024-11-11T11:26:40Z"
}
}
```
90 changes: 90 additions & 0 deletions tencentcloud/services/cvm/resource_tc_cvm_action_timer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package cvm_test

import (
"testing"

tcacctest "github.com/tencentcloudstack/terraform-provider-tencentcloud/tencentcloud/acctest"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

// go test -i; go test -test.run TestAccTencentCloudNeedFixCvmActionTimerResource_basic -v
func TestAccTencentCloudNeedFixCvmActionTimerResource_basic(t *testing.T) {
t.Parallel()
resource.Test(t, resource.TestCase{
PreCheck: func() {
tcacctest.AccPreCheck(t)
},
Providers: tcacctest.AccProviders,
Steps: []resource.TestStep{
{
Config: testAccCvmActionTimer,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttrSet("tencentcloud_cvm_action_timer.example", "id"),
resource.TestCheckResourceAttrSet("tencentcloud_cvm_action_timer.example", "instance_id"),
resource.TestCheckResourceAttr("tencentcloud_cvm_action_timer.example", "action_timer.#", "1"),
),
},
},
})
}

const testAccCvmActionTimer = `
variable "availability_zone" {
default = "ap-guangzhou-6"
}

data "tencentcloud_images" "images" {
image_type = ["PUBLIC_IMAGE"]
image_name_regex = "TencentOS Server"
}

# create vpc
resource "tencentcloud_vpc" "vpc" {
name = "vpc"
cidr_block = "10.0.0.0/16"
}

# create vpc subnet
resource "tencentcloud_subnet" "subnet" {
name = "subnet"
vpc_id = tencentcloud_vpc.vpc.id
availability_zone = var.availability_zone
cidr_block = "10.0.20.0/28"
is_multicast = false
}

# create cvm
resource "tencentcloud_instance" "example" {
instance_name = "tf_example"
availability_zone = var.availability_zone
image_id = data.tencentcloud_images.images.images.0.image_id
instance_type = "SA3.MEDIUM4"
system_disk_type = "CLOUD_HSSD"
system_disk_size = 100
hostname = "example"
project_id = 0
vpc_id = tencentcloud_vpc.vpc.id
subnet_id = tencentcloud_subnet.subnet.id

data_disks {
data_disk_type = "CLOUD_HSSD"
data_disk_size = 50
encrypt = false
}

tags = {
createBy = "terraform"
}
}

# create cvm action timer
resource "tencentcloud_cvm_action_timer" "example" {
instance_id = tencentcloud_instance.example.id

action_timer {
timer_action = "TerminateInstances"
action_time = "2024-11-11T11:26:40Z"
}
}
`
Loading
Loading