github.com/caos/orbos@v1.5.14-0.20221103111702-e6cd0cea7ad4/internal/operator/orbiter/kinds/providers/gce/gcloud.go (about)

     1  package gce
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"os"
     9  	"os/exec"
    10  	"strings"
    11  )
    12  
    13  func gcloudSession(jsonkey string, gcloud string, do func(binary string) error) error {
    14  
    15  	listBuf := new(bytes.Buffer)
    16  	defer resetBuffer(listBuf)
    17  	cmd := exec.Command(gcloud, "config", "configurations", "list")
    18  	cmd.Stdout = listBuf
    19  
    20  	if err := cmd.Run(); err != nil {
    21  		return err
    22  	}
    23  
    24  	scanner := bufio.NewScanner(listBuf)
    25  	reactivate := ""
    26  	for scanner.Scan() {
    27  		fields := strings.Fields(scanner.Text())
    28  		if fields[1] == "True" {
    29  			reactivate = fields[0]
    30  			break
    31  		}
    32  	}
    33  
    34  	if err := run(exec.Command(gcloud, "config", "configurations", "create", "orbiter-system"), func(out []byte) bool {
    35  		return strings.Contains(string(out), "it already exists")
    36  	}); err != nil {
    37  		return err
    38  	}
    39  
    40  	if err := run(exec.Command(gcloud, "config", "configurations", "activate", "orbiter-system"), nil); err != nil {
    41  		return err
    42  	}
    43  
    44  	file, err := ioutil.TempFile("", "orbiter-gce-key")
    45  	defer os.Remove(file.Name())
    46  	if err != nil {
    47  		return err
    48  	}
    49  
    50  	_, err = file.WriteString(jsonkey)
    51  	if err != nil {
    52  		return err
    53  	}
    54  	if err := file.Close(); err != nil {
    55  		return err
    56  	}
    57  
    58  	if err := run(exec.Command(gcloud, "auth", "activate-service-account", "--key-file", file.Name()), nil); err != nil {
    59  		return err
    60  	}
    61  	if err := do(gcloud); err != nil {
    62  		return err
    63  	}
    64  	if reactivate != "" {
    65  		if err := run(exec.Command(gcloud, "config", "configurations", "activate", reactivate), nil); err != nil {
    66  			return err
    67  		}
    68  	}
    69  	return nil
    70  }
    71  
    72  func run(cmd *exec.Cmd, ignoreErr func([]byte) bool) error {
    73  	out, err := cmd.CombinedOutput()
    74  	if err != nil && ignoreErr != nil && !ignoreErr(out) {
    75  		return fmt.Errorf("failed to run \"%s\": %s: %w", strings.Join(cmd.Args, "\" \""), string(out), err)
    76  	}
    77  	return nil
    78  }