Skip to content

Commit

Permalink
detach key前先关机,避免创建镜像过程中发生重启导致服务意外启动
Browse files Browse the repository at this point in the history
  • Loading branch information
shinny-taojiachun committed Apr 23, 2024
1 parent 01733d3 commit 52f9805
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions builder/tencentcloud/cvm/step_detach_temp_key_pair.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,31 @@ func (s *stepDetachTempKeyPair) Run(ctx context.Context, state multistep.StateBa
keyId := state.Get("temporary_key_pair_id").(string)
instance := state.Get("instance").(*cvm.Instance)

// 生成镜像前先关机,避免创建镜像过程中发生重启导致服务意外启动
Say(state, *instance.InstanceName, "Trying to stop instance")

stopReq := cvm.NewStopInstancesRequest()
stopReq.InstanceIds = []*string{instance.InstanceId}
err := Retry(ctx, func(ctx context.Context) error {
_, e := client.StopInstances(stopReq)
return e
})
if err != nil {
return Halt(state, err, "Failed to stop instance")
}
Message(state, "Waiting for instance stop", "")
err = WaitForInstance(ctx, client, *instance.InstanceId, "STOPPED", 1800)
if err != nil {
return Halt(state, err, "Failed to wait for instance to be stopped")
}

Say(state, keyId, "Trying to detach keypair")

req := cvm.NewDisassociateInstancesKeyPairsRequest()
req.KeyIds = []*string{&keyId}
req.InstanceIds = []*string{instance.InstanceId}
req.ForceStop = common.BoolPtr(true)
err := Retry(ctx, func(ctx context.Context) error {
req.ForceStop = common.BoolPtr(false)
err = Retry(ctx, func(ctx context.Context) error {
_, e := client.DisassociateInstancesKeyPairs(req)
return e
})
Expand All @@ -39,7 +57,7 @@ func (s *stepDetachTempKeyPair) Run(ctx context.Context, state multistep.StateBa
}

Message(state, "Waiting for keypair detached", "")
err = WaitForInstance(ctx, client, *instance.InstanceId, "RUNNING", 1800)
err = WaitForInstance(ctx, client, *instance.InstanceId, "STOPPED", 1800)
if err != nil {
return Halt(state, err, "Failed to wait for keypair detached")
}
Expand Down

0 comments on commit 52f9805

Please sign in to comment.