Skip to content

Commit

Permalink
add compute instance power action parameter (#1134)
Browse files Browse the repository at this point in the history
  • Loading branch information
Lance52259 authored May 19, 2021
1 parent fd9ff95 commit e362fd0
Show file tree
Hide file tree
Showing 6 changed files with 248 additions and 42 deletions.
9 changes: 7 additions & 2 deletions docs/resources/compute_instance.md
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,10 @@ The following arguments are supported:
* `agency_name` - (Optional, String, ForceNew) Specifies the IAM agency name which is created on IAM to provide
temporary credentials for ECS to access cloud services. Changing this creates a new instance.

* `power_action` - (Optional, String) Specifies the power action to be done for the instance.
The valid values are *ON*, *OFF*, *REBOOT*, *FORCE-OFF* and *FORCE-REBOOT*.

-> **NOTE:** The `power_action` is a one-time action.

The `network` block supports:

Expand Down Expand Up @@ -346,8 +350,9 @@ terraform import huaweicloud_compute_instance.my_instance b11b407c-e604-4e8d-8bc
Note that the imported state may not be identical to your resource definition, due to some attrubutes missing from the
API response, security or some other reason. The missing attributes include:
`admin_pass`, `user_data`, `data_disks`, `scheduler_hints`, `stop_before_destroy`, `delete_disks_on_termination`,
`network/access_network` and arguments for pre-paid. It is generally recommended running `terraform plan` after
importing an instance. You can then decide if changes should be applied to the instance, or the resource definition
`network/access_network`, `power_action` and arguments for pre-paid.
It is generally recommended running `terraform plan` after importing an instance.
You can then decide if changes should be applied to the instance, or the resource definition
should be updated to align with the instance. Also you can ignore changes as below.
```
resource "huaweicloud_compute_instance" "myinstance" {
Expand Down
144 changes: 104 additions & 40 deletions huaweicloud/resource_huaweicloud_compute_instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"encoding/hex"
"fmt"
"log"
"strings"
"time"

"github.com/hashicorp/terraform-plugin-sdk/helper/hashcode"
Expand All @@ -26,13 +27,21 @@ import (
"github.com/huaweicloud/golangsdk/openstack/compute/v2/servers"
"github.com/huaweicloud/golangsdk/openstack/ecs/v1/block_devices"
"github.com/huaweicloud/golangsdk/openstack/ecs/v1/cloudservers"
"github.com/huaweicloud/golangsdk/openstack/ecs/v1/powers"
"github.com/huaweicloud/golangsdk/openstack/networking/v1/subnets"
"github.com/huaweicloud/golangsdk/openstack/networking/v2/extensions/security/groups"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/config"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/utils"
)

var novaConflicts = []string{"block_device", "metadata"}
var (
novaConflicts = []string{"block_device", "metadata"}
powerActionMap = map[string]string{
"ON": "os-start",
"OFF": "os-stop",
"REBOOT": "reboot",
}
)

func ResourceComputeInstanceV2() *schema.Resource {
return &schema.Resource{
Expand Down Expand Up @@ -286,6 +295,14 @@ func ResourceComputeInstanceV2() *schema.Resource {
ValidateFunc: utils.ValidateECSTagValue,
Elem: &schema.Schema{Type: schema.TypeString},
},
"power_action": {
Type: schema.TypeString,
Optional: true,
// If you want to support more actions, please update powerActionMap simultaneously.
ValidateFunc: validation.StringInSlice([]string{
"ON", "OFF", "REBOOT", "FORCE-OFF", "FORCE-REBOOT",
}, false),
},
"volume_attached": {
Type: schema.TypeList,
Computed: true,
Expand Down Expand Up @@ -604,20 +621,11 @@ func resourceComputeInstanceV2Create(d *schema.ResourceData, meta interface{}) e
// Wait for the instance to become running so we can get some attributes
// that aren't available until later.
log.Printf("[DEBUG] Waiting for instance (%s) to become running", server.ID)
stateConf := &resource.StateChangeConf{
Pending: []string{"BUILD"},
Target: []string{"ACTIVE"},
Refresh: ServerV2StateRefreshFunc(computeClient, server.ID),
Timeout: d.Timeout(schema.TimeoutCreate),
Delay: 10 * time.Second,
MinTimeout: 3 * time.Second,
}

_, err = stateConf.WaitForState()
if err != nil {
return fmt.Errorf(
"Error waiting for instance (%s) to become ready: %s",
server.ID, err)
pending := []string{"BUILD"}
target := []string{"ACTIVE"}
timeout := d.Timeout(schema.TimeoutCreate)
if err := watiForServerTargetState(computeClient, d.Id(), pending, target, timeout); err != nil {
return fmt.Errorf("State waiting timeout: %s", err)
}
}

Expand All @@ -631,6 +639,18 @@ func resourceComputeInstanceV2Create(d *schema.ResourceData, meta interface{}) e
}
}

// Create an instance in the shutdown state.
if action, ok := d.GetOk("power_action"); ok {
action := action.(string)
if action == "OFF" || action == "FORCE-OFF" {
if err = doPowerAction(ecsClient, d, action); err != nil {
return fmt.Errorf("Doing power action (%s) for instance (%s) failed: %s", action, d.Id(), err)
}
} else {
log.Printf("[WARN] The power action (%s) is invalid after instance created", action)
}
}

return resourceComputeInstanceV2Read(d, meta)
}

Expand Down Expand Up @@ -963,6 +983,14 @@ func resourceComputeInstanceV2Update(d *schema.ResourceData, meta interface{}) e
}
}

// The instance power status update needs to be done at the end
if d.HasChange("power_action") {
action := d.Get("power_action").(string)
if err = doPowerAction(ecsClient, d, action); err != nil {
return fmt.Errorf("Doing power action (%s) for instance (%s) failed: %s", action, d.Id(), err)
}
}

return resourceComputeInstanceV2Read(d, meta)
}

Expand All @@ -979,18 +1007,12 @@ func resourceComputeInstanceV2Delete(d *schema.ResourceData, meta interface{}) e
if err != nil {
log.Printf("[WARN] Error stopping HuaweiCloud instance: %s", err)
} else {
stopStateConf := &resource.StateChangeConf{
Pending: []string{"ACTIVE"},
Target: []string{"SHUTOFF"},
Refresh: ServerV2StateRefreshFunc(computeClient, d.Id()),
Timeout: 3 * time.Minute,
Delay: 10 * time.Second,
MinTimeout: 3 * time.Second,
}
log.Printf("[DEBUG] Waiting for instance (%s) to stop", d.Id())
_, err = stopStateConf.WaitForState()
if err != nil {
log.Printf("[WARN] Error waiting for instance (%s) to stop: %s, proceeding to delete", d.Id(), err)
pending := []string{"ACTIVE"}
target := []string{"SHUTOFF"}
timeout := d.Timeout(schema.TimeoutCreate)
if err := watiForServerTargetState(computeClient, d.Id(), pending, target, timeout); err != nil {
return fmt.Errorf("State waiting timeout: %s", err)
}
}
}
Expand Down Expand Up @@ -1022,20 +1044,11 @@ func resourceComputeInstanceV2Delete(d *schema.ResourceData, meta interface{}) e
}

// Instance may still exist after Order/Job succeed.
stateConf := &resource.StateChangeConf{
Pending: []string{"ACTIVE", "SHUTOFF"},
Target: []string{"DELETED", "SOFT_DELETED"},
Refresh: ServerV2StateRefreshFunc(computeClient, d.Id()),
Timeout: d.Timeout(schema.TimeoutDelete),
Delay: 10 * time.Second,
MinTimeout: 3 * time.Second,
}

_, err = stateConf.WaitForState()
if err != nil {
return fmt.Errorf(
"Error waiting for instance (%s) to delete: %s",
d.Id(), err)
pending := []string{"ACTIVE", "SHUTOFF"}
target := []string{"DELETED", "SOFT_DELETED"}
deleteTimeout := d.Timeout(schema.TimeoutDelete)
if err := watiForServerTargetState(computeClient, d.Id(), pending, target, deleteTimeout); err != nil {
return fmt.Errorf("State waiting timeout: %s", err)
}

d.SetId("")
Expand Down Expand Up @@ -1370,3 +1383,54 @@ func checkBlockDeviceConfig(d *schema.ResourceData) error {

return nil
}

func watiForServerTargetState(client *golangsdk.ServiceClient, ID string, pending, target []string, timeout time.Duration) error {
stateConf := &resource.StateChangeConf{
Pending: pending,
Target: target,
Refresh: ServerV2StateRefreshFunc(client, ID),
Timeout: timeout,
Delay: 5 * time.Second,
PollInterval: 5 * time.Second,
}

_, err := stateConf.WaitForState()
if err != nil {
return fmt.Errorf("Error waiting for instance (%s) to become target state (%v): %s", ID, target, err)
}
return nil
}

// doPowerAction is a method for instance power doing shutdown, startup and reboot actions.
func doPowerAction(client *golangsdk.ServiceClient, d *schema.ResourceData, action string) error {
var jobResp *cloudservers.JobResponse
powerOpts := powers.PowerOpts{
Servers: []powers.ServerInfo{
{ID: d.Id()},
},
}
// In the reboot structure, Type is a required option.
// Since the type of power off and reboot is 'SOFT' by default, setting this value has solved the power structural
// compatibility problem between optional and required.
if action != "ON" {
powerOpts.Type = "SOFT"
}
if strings.HasPrefix(action, "FORCE-") {
powerOpts.Type = "HARD"
action = strings.TrimPrefix(action, "FORCE-")
}
op, ok := powerActionMap[action]
if !ok {
return fmt.Errorf("The powerMap does not contain option (%s)", action)
}
jobResp, err := powers.PowerAction(client, powerOpts, op).ExtractJobResponse()
if err != nil {
return fmt.Errorf("Doing power action (%s) for instance (%s) failed: %s", action, d.Id(), err)
}
// The time of the power on/off and reboot is usually between 15 and 35 seconds.
timeout := 3 * time.Minute
if err := cloudservers.WaitForJobSuccess(client, int(timeout/time.Second), jobResp.JobID); err != nil {
return err
}
return nil
}
88 changes: 88 additions & 0 deletions huaweicloud/resource_huaweicloud_compute_instance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,75 @@ func TestAccComputeV2Instance_tags(t *testing.T) {
})
}

func TestAccComputeV2Instance_powerAction(t *testing.T) {
var instance servers.Server

rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(5))
resourceName := "huaweicloud_compute_instance.test"

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckComputeV2InstanceDestroy,
Steps: []resource.TestStep{
{
Config: testAccComputeV2Instance_powerAction(rName, "OFF"),
Check: resource.ComposeTestCheckFunc(
testAccCheckComputeV2InstanceExists(resourceName, &instance),
resource.TestCheckResourceAttr(resourceName, "name", rName),
resource.TestCheckResourceAttr(resourceName, "power_action", "OFF"),
resource.TestCheckResourceAttr(resourceName, "status", "SHUTOFF"),
),
},
{
Config: testAccComputeV2Instance_powerAction(rName, "ON"),
Check: resource.ComposeTestCheckFunc(
testAccCheckComputeV2InstanceExists(resourceName, &instance),
resource.TestCheckResourceAttr(resourceName, "name", rName),
resource.TestCheckResourceAttr(resourceName, "power_action", "ON"),
resource.TestCheckResourceAttr(resourceName, "status", "ACTIVE"),
),
},
{
Config: testAccComputeV2Instance_powerAction(rName, "REBOOT"),
Check: resource.ComposeTestCheckFunc(
testAccCheckComputeV2InstanceExists(resourceName, &instance),
resource.TestCheckResourceAttr(resourceName, "name", rName),
resource.TestCheckResourceAttr(resourceName, "power_action", "REBOOT"),
resource.TestCheckResourceAttr(resourceName, "status", "ACTIVE"),
),
},
{
Config: testAccComputeV2Instance_powerAction(rName, "FORCE-REBOOT"),
Check: resource.ComposeTestCheckFunc(
testAccCheckComputeV2InstanceExists(resourceName, &instance),
resource.TestCheckResourceAttr(resourceName, "name", rName),
resource.TestCheckResourceAttr(resourceName, "power_action", "FORCE-REBOOT"),
resource.TestCheckResourceAttr(resourceName, "status", "ACTIVE"),
),
},
{
Config: testAccComputeV2Instance_powerAction(rName, "FORCE-OFF"),
Check: resource.ComposeTestCheckFunc(
testAccCheckComputeV2InstanceExists(resourceName, &instance),
resource.TestCheckResourceAttr(resourceName, "name", rName),
resource.TestCheckResourceAttr(resourceName, "power_action", "FORCE-OFF"),
resource.TestCheckResourceAttr(resourceName, "status", "SHUTOFF"),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{
"stop_before_destroy",
"power_action",
},
},
},
})
}

func testAccCheckComputeV2InstanceDestroy(s *terraform.State) error {
config := testAccProvider.Meta().(*config.Config)
computeClient, err := config.ComputeV2Client(HW_REGION_NAME)
Expand Down Expand Up @@ -391,3 +460,22 @@ resource "huaweicloud_compute_instance" "test" {
}
`, testAccCompute_data, rName)
}

func testAccComputeV2Instance_powerAction(rName, powerAction string) string {
return fmt.Sprintf(`
%s
resource "huaweicloud_compute_instance" "test" {
name = "%s"
image_id = data.huaweicloud_images_image.test.id
flavor_id = data.huaweicloud_compute_flavors.test.ids[0]
security_groups = ["default"]
availability_zone = data.huaweicloud_availability_zones.test.names[0]
power_action = "%s"
network {
uuid = data.huaweicloud_vpc_subnet.test.id
}
}
`, testAccCompute_data, rName, powerAction)
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions vendor/modules.txt
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,7 @@ github.com/huaweicloud/golangsdk/openstack/ecs/v1/auto_recovery
github.com/huaweicloud/golangsdk/openstack/ecs/v1/block_devices
github.com/huaweicloud/golangsdk/openstack/ecs/v1/cloudservers
github.com/huaweicloud/golangsdk/openstack/ecs/v1/flavors
github.com/huaweicloud/golangsdk/openstack/ecs/v1/powers
github.com/huaweicloud/golangsdk/openstack/elb/v2/loadbalancers
github.com/huaweicloud/golangsdk/openstack/elb/v3/flavors
github.com/huaweicloud/golangsdk/openstack/elb/v3/listeners
Expand Down

0 comments on commit e362fd0

Please sign in to comment.