|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "github.com/cloudtools/ssh-cert-authority/util" |
| 7 | + "github.com/codegangsta/cli" |
| 8 | + "io/ioutil" |
| 9 | + "net/http" |
| 10 | + "os" |
| 11 | + "strings" |
| 12 | +) |
| 13 | + |
| 14 | +func generateConfigFlags() []cli.Flag { |
| 15 | + home := os.Getenv("HOME") |
| 16 | + if home == "" { |
| 17 | + home = "/" |
| 18 | + } |
| 19 | + return []cli.Flag{ |
| 20 | + cli.StringFlag{ |
| 21 | + Name: "url, u", |
| 22 | + Value: "", |
| 23 | + Usage: "An ssh-cert-authority url (e.g. https://ssh-cert-authority.example.com).", |
| 24 | + }, |
| 25 | + cli.StringFlag{ |
| 26 | + Name: "key-file, k", |
| 27 | + Value: fmt.Sprintf("%s/.ssh/id_rsa.pub", home), |
| 28 | + Usage: "Path to your SSH public key. The filename will be inserted into the generated config file.", |
| 29 | + }, |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +func cmdGenerateConfig(c *cli.Context) error { |
| 34 | + |
| 35 | + url := c.String("url") |
| 36 | + if url == "" { |
| 37 | + return cli.NewExitError("url is a required option.", 1) |
| 38 | + } |
| 39 | + if !strings.HasSuffix(url, "/") { |
| 40 | + url = url + "/" |
| 41 | + } |
| 42 | + |
| 43 | + getResp, err := http.Get(url + "config/environments") |
| 44 | + if err != nil { |
| 45 | + return cli.NewExitError(fmt.Sprintf("Didn't get a valid response: %s", err), 1) |
| 46 | + } |
| 47 | + |
| 48 | + getRespBuf, err := ioutil.ReadAll(getResp.Body) |
| 49 | + if err != nil { |
| 50 | + return cli.NewExitError(fmt.Sprintf("Error reading response body: %s", err), 1) |
| 51 | + } |
| 52 | + getResp.Body.Close() |
| 53 | + if getResp.StatusCode != 200 { |
| 54 | + return cli.NewExitError(fmt.Sprintf("Error getting listing of environments: %s", string(getRespBuf)), 1) |
| 55 | + } |
| 56 | + |
| 57 | + environments := make([]string, 0) |
| 58 | + json.Unmarshal(getRespBuf, &environments) |
| 59 | + |
| 60 | + wholeConfig := make(map[string]ssh_ca_util.RequesterConfig, len(environments)) |
| 61 | + for _, envName := range environments { |
| 62 | + wholeConfig[envName] = ssh_ca_util.RequesterConfig{ |
| 63 | + PublicKeyPath: c.String("key-file"), |
| 64 | + SignerUrl: url, |
| 65 | + } |
| 66 | + } |
| 67 | + result, err := json.MarshalIndent(wholeConfig, "", " ") |
| 68 | + if err != nil { |
| 69 | + return cli.NewExitError(fmt.Sprintf("Failed to serialize config file: %v", err), 1) |
| 70 | + } |
| 71 | + fmt.Print(string(result)) |
| 72 | + return nil |
| 73 | +} |
0 commit comments