Skip to content

Commit

Permalink
store the id of started instance
Browse files Browse the repository at this point in the history
  • Loading branch information
WangDe7 committed Apr 21, 2024
1 parent c0edfe9 commit 31c1e25
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
21 changes: 15 additions & 6 deletions cmd/start/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,23 @@ import (
"context"
"errors"
"fmt"

"log"
"machine-operator/pkg"
"os"
"time"

"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/spf13/cobra"

"machine-operator/pkg"
)

var (
region string
serverLabelKey string
serverLabelValue string
instanceIDPath string
StartCmd = &cobra.Command{
Use: "start",
Short: "start machine",
Expand All @@ -43,12 +46,18 @@ func init() {
StartCmd.PersistentFlags().StringVar(&serverLabelValue,
"serverLabelValue", os.Getenv("serverLabelValue"),
"the value of server label")
StartCmd.PersistentFlags().StringVar(&instanceIDPath,
"instanceIDPath", os.Getenv("instanceIDPath"),
"file path to write instanceID")
}

func preRun() {
if serverLabelKey == "" {
serverLabelKey = "server"
}
if instanceIDPath == "" {
instanceIDPath = "instanceID.txt"
}
}

func run() error {
Expand Down Expand Up @@ -82,7 +91,7 @@ func run() error {
}

startOneInstance := false
startInstanceID := ""
startedInstanceID := ""
for true {
for _, instanceID := range instancesIDs {
instanceState, err := ec2Util.GetInstanceStatusByID(instanceID)
Expand All @@ -97,7 +106,7 @@ func run() error {
return err
}
startOneInstance = true
startInstanceID = instanceID
startedInstanceID = instanceID
break
}
}
Expand All @@ -115,7 +124,7 @@ StateWatch:
for {
select {
case <-ticker.C:
instanceState, _ := ec2Util.GetInstanceStatusByID(startInstanceID)
instanceState, _ := ec2Util.GetInstanceStatusByID(startedInstanceID)
fmt.Println("the instance state: " + instanceState)
if instanceState == pkg.InstanceStatusRunning {
break StateWatch
Expand All @@ -129,7 +138,7 @@ StateWatch:
if isTimeout {
return errors.New("start instance timeout")
}
fmt.Println("The instance started is " + startInstanceID)
err = os.Setenv("INSTANCE_ID", startInstanceID)
fmt.Println("The instance started is " + startedInstanceID)
err = pkg.WriteToFile(instanceIDPath, startedInstanceID)
return err
}
21 changes: 21 additions & 0 deletions pkg/file.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package pkg

import (
"log"
"os"
)

func WriteToFile(path, content string) error {
file, err := os.OpenFile(path, os.O_TRUNC|os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
log.Fatal(err)
return err
}
defer file.Close()

_, err = file.WriteString(content)
if err != nil {
log.Fatal(err)
}
return err
}

0 comments on commit 31c1e25

Please sign in to comment.