kubeconfig.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. package connect
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "strings"
  10. "github.com/fatih/color"
  11. "github.com/porter-dev/porter/cli/cmd/utils"
  12. "github.com/porter-dev/porter/internal/kubernetes/local"
  13. gcpLocal "github.com/porter-dev/porter/internal/providers/gcp/local"
  14. "github.com/porter-dev/porter/cli/cmd/api"
  15. "github.com/porter-dev/porter/internal/models"
  16. )
  17. // Kubeconfig creates a service account for a project by parsing the local
  18. // kubeconfig and resolving actions that must be performed.
  19. func Kubeconfig(
  20. client *api.Client,
  21. kubeconfigPath string,
  22. contexts []string,
  23. projectID uint,
  24. ) error {
  25. // if project ID is 0, ask the user to set the project ID or create a project
  26. if projectID == 0 {
  27. return fmt.Errorf("no project set, please run porter project set [id]")
  28. }
  29. // get the kubeconfig
  30. rawBytes, err := local.GetKubeconfigFromHost(kubeconfigPath, contexts)
  31. if err != nil {
  32. return err
  33. }
  34. // send kubeconfig to client
  35. saCandidates, err := client.CreateProjectCandidates(
  36. context.Background(),
  37. projectID,
  38. &api.CreateProjectCandidatesRequest{
  39. Kubeconfig: string(rawBytes),
  40. },
  41. )
  42. if err != nil {
  43. return err
  44. }
  45. for _, saCandidate := range saCandidates {
  46. var clusters []models.ClusterExternal
  47. var saID uint
  48. if len(saCandidate.Actions) > 0 {
  49. resolvers := make(api.CreateProjectServiceAccountRequest, 0)
  50. for _, action := range saCandidate.Actions {
  51. switch action.Name {
  52. case models.ClusterCADataAction:
  53. resolveAction, err := resolveClusterCAAction(action.Filename)
  54. if err != nil {
  55. return err
  56. }
  57. resolvers = append(resolvers, resolveAction)
  58. case models.ClientCertDataAction:
  59. resolveAction, err := resolveClientCertAction(action.Filename)
  60. if err != nil {
  61. return err
  62. }
  63. resolvers = append(resolvers, resolveAction)
  64. case models.ClientKeyDataAction:
  65. resolveAction, err := resolveClientKeyAction(action.Filename)
  66. if err != nil {
  67. return err
  68. }
  69. resolvers = append(resolvers, resolveAction)
  70. case models.OIDCIssuerDataAction:
  71. resolveAction, err := resolveOIDCIssuerAction(action.Filename)
  72. if err != nil {
  73. return err
  74. }
  75. resolvers = append(resolvers, resolveAction)
  76. case models.TokenDataAction:
  77. resolveAction, err := resolveTokenDataAction(action.Filename)
  78. if err != nil {
  79. return err
  80. }
  81. resolvers = append(resolvers, resolveAction)
  82. case models.GCPKeyDataAction:
  83. resolveAction, err := resolveGCPKeyAction(
  84. saCandidate.ClusterEndpoint,
  85. saCandidate.ClusterName,
  86. )
  87. if err != nil {
  88. return err
  89. }
  90. resolvers = append(resolvers, resolveAction)
  91. case models.AWSDataAction:
  92. resolveAction, err := resolveAWSAction(
  93. saCandidate.ClusterEndpoint,
  94. saCandidate.ClusterName,
  95. saCandidate.AWSClusterIDGuess,
  96. )
  97. if err != nil {
  98. return err
  99. }
  100. resolvers = append(resolvers, resolveAction)
  101. }
  102. }
  103. sa, err := client.CreateProjectServiceAccount(
  104. context.Background(),
  105. projectID,
  106. saCandidate.ID,
  107. resolvers,
  108. )
  109. if err != nil {
  110. return err
  111. }
  112. clusters = sa.Clusters
  113. saID = sa.ID
  114. } else {
  115. sa, err := client.GetProjectServiceAccount(
  116. context.Background(),
  117. projectID,
  118. saCandidate.CreatedServiceAccountID,
  119. )
  120. if err != nil {
  121. return err
  122. }
  123. clusters = sa.Clusters
  124. saID = sa.ID
  125. }
  126. for _, cluster := range clusters {
  127. color.New(color.FgGreen).Printf("created service account for cluster %s with id %d\n", cluster.Name, saID)
  128. // sanity check to ensure it's working
  129. // namespaces, err := client.GetK8sNamespaces(
  130. // context.Background(),
  131. // projectID,
  132. // saID,
  133. // cluster.ID,
  134. // )
  135. // if err != nil {
  136. // return err
  137. // }
  138. // for _, ns := range namespaces.Items {
  139. // fmt.Println(ns.ObjectMeta.GetName())
  140. // }
  141. }
  142. }
  143. return nil
  144. }
  145. // resolves a cluster ca data action
  146. func resolveClusterCAAction(
  147. filename string,
  148. ) (*models.ServiceAccountAllActions, error) {
  149. fileBytes, err := ioutil.ReadFile(filename)
  150. if err != nil {
  151. return nil, err
  152. }
  153. return &models.ServiceAccountAllActions{
  154. Name: models.ClusterCADataAction,
  155. ClusterCAData: base64.StdEncoding.EncodeToString(fileBytes),
  156. }, nil
  157. }
  158. // resolves a client cert data action
  159. func resolveClientCertAction(
  160. filename string,
  161. ) (*models.ServiceAccountAllActions, error) {
  162. fileBytes, err := ioutil.ReadFile(filename)
  163. if err != nil {
  164. return nil, err
  165. }
  166. return &models.ServiceAccountAllActions{
  167. Name: models.ClientCertDataAction,
  168. ClientCertData: base64.StdEncoding.EncodeToString(fileBytes),
  169. }, nil
  170. }
  171. // resolves a client key data action
  172. func resolveClientKeyAction(
  173. filename string,
  174. ) (*models.ServiceAccountAllActions, error) {
  175. fileBytes, err := ioutil.ReadFile(filename)
  176. if err != nil {
  177. return nil, err
  178. }
  179. return &models.ServiceAccountAllActions{
  180. Name: models.ClientKeyDataAction,
  181. ClientKeyData: base64.StdEncoding.EncodeToString(fileBytes),
  182. }, nil
  183. }
  184. // resolves an oidc issuer data action
  185. func resolveOIDCIssuerAction(
  186. filename string,
  187. ) (*models.ServiceAccountAllActions, error) {
  188. fileBytes, err := ioutil.ReadFile(filename)
  189. if err != nil {
  190. return nil, err
  191. }
  192. return &models.ServiceAccountAllActions{
  193. Name: models.OIDCIssuerDataAction,
  194. OIDCIssuerCAData: base64.StdEncoding.EncodeToString(fileBytes),
  195. }, nil
  196. }
  197. // resolves a token data action
  198. func resolveTokenDataAction(
  199. filename string,
  200. ) (*models.ServiceAccountAllActions, error) {
  201. fileBytes, err := ioutil.ReadFile(filename)
  202. if err != nil {
  203. return nil, err
  204. }
  205. return &models.ServiceAccountAllActions{
  206. Name: models.TokenDataAction,
  207. TokenData: string(fileBytes),
  208. }, nil
  209. }
  210. // resolves a gcp key data action
  211. func resolveGCPKeyAction(endpoint string, clusterName string) (*models.ServiceAccountAllActions, error) {
  212. userResp, err := utils.PromptPlaintext(
  213. fmt.Sprintf(
  214. `Detected GKE cluster in kubeconfig for the endpoint %s (%s).
  215. Porter can set up a service account in your GCP project to connect to this cluster automatically.
  216. Would you like to proceed? %s `,
  217. color.New(color.FgCyan).Sprintf("%s", endpoint),
  218. clusterName,
  219. color.New(color.FgCyan).Sprintf("[y/n]"),
  220. ),
  221. )
  222. if err != nil {
  223. return nil, err
  224. }
  225. if userResp := strings.ToLower(userResp); userResp == "y" || userResp == "yes" {
  226. agent, _ := gcpLocal.NewDefaultAgent()
  227. projID, err := agent.GetProjectIDForGKECluster(endpoint)
  228. if err != nil {
  229. return nil, err
  230. }
  231. agent.ProjectID = projID
  232. name := "porter-dashboard-" + utils.StringWithCharset(6, "abcdefghijklmnopqrstuvwxyz1234567890")
  233. // create the service account and give it the correct iam permissions
  234. resp, err := agent.CreateServiceAccount(name)
  235. if err != nil {
  236. color.New(color.FgRed).Println("Automatic creation failed, manual input required.")
  237. return resolveGCPKeyActionManual(endpoint, clusterName)
  238. }
  239. err = agent.SetServiceAccountIAMPolicy(resp)
  240. if err != nil {
  241. return nil, err
  242. }
  243. // get the service account key data to send to the server
  244. bytes, err := agent.CreateServiceAccountKey(resp)
  245. if err != nil {
  246. return nil, err
  247. }
  248. return &models.ServiceAccountAllActions{
  249. Name: models.GCPKeyDataAction,
  250. GCPKeyData: string(bytes),
  251. }, nil
  252. }
  253. return resolveGCPKeyActionManual(endpoint, clusterName)
  254. }
  255. func resolveGCPKeyActionManual(endpoint string, clusterName string) (*models.ServiceAccountAllActions, error) {
  256. keyFileLocation, err := utils.PromptPlaintext(fmt.Sprintf(`Please provide the full path to a service account key file.
  257. Key file location: `))
  258. if err != nil {
  259. return nil, err
  260. }
  261. // attempt to read the key file location
  262. if info, err := os.Stat(keyFileLocation); !os.IsNotExist(err) && !info.IsDir() {
  263. // read the file
  264. bytes, err := ioutil.ReadFile(keyFileLocation)
  265. if err != nil {
  266. return nil, err
  267. }
  268. return &models.ServiceAccountAllActions{
  269. Name: models.GCPKeyDataAction,
  270. GCPKeyData: string(bytes),
  271. }, nil
  272. }
  273. return nil, errors.New("Key file not found")
  274. }
  275. // resolves an aws key data action
  276. func resolveAWSAction(
  277. endpoint string,
  278. clusterName string,
  279. awsClusterIDGuess string,
  280. ) (*models.ServiceAccountAllActions, error) {
  281. // just support manual for now
  282. return resolveAWSActionManual(endpoint, clusterName, awsClusterIDGuess)
  283. }
  284. func resolveAWSActionManual(
  285. endpoint string,
  286. clusterName string,
  287. awsClusterIDGuess string,
  288. ) (*models.ServiceAccountAllActions, error) {
  289. // query to see if the AWS cluster ID guess is correct
  290. var clusterID string
  291. userResp, err := utils.PromptPlaintext(
  292. fmt.Sprintf(
  293. `Detected AWS cluster ID as %s. Is this correct? %s `,
  294. color.New(color.FgCyan).Sprintf(awsClusterIDGuess),
  295. color.New(color.FgCyan).Sprintf("[y/n]"),
  296. ),
  297. )
  298. if err != nil {
  299. return nil, err
  300. }
  301. if userResp := strings.ToLower(userResp); userResp == "y" || userResp == "yes" {
  302. clusterID = awsClusterIDGuess
  303. } else {
  304. clusterID, err = utils.PromptPlaintext(fmt.Sprintf(`Cluster ID: `))
  305. if err != nil {
  306. return nil, err
  307. }
  308. }
  309. // query for the access key id
  310. accessKeyID, err := utils.PromptPlaintext(fmt.Sprintf(`AWS Access Key ID: `))
  311. if err != nil {
  312. return nil, err
  313. }
  314. // query for the secret access key
  315. secretKey, err := utils.PromptPlaintext(fmt.Sprintf(`AWS Secret Access Key: `))
  316. if err != nil {
  317. return nil, err
  318. }
  319. return &models.ServiceAccountAllActions{
  320. Name: models.AWSDataAction,
  321. AWSAccessKeyID: accessKeyID,
  322. AWSSecretAccessKey: secretKey,
  323. AWSClusterID: clusterID,
  324. }, nil
  325. }