env.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package commands
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "github.com/fatih/color"
  7. api "github.com/porter-dev/porter/api/client"
  8. "github.com/porter-dev/porter/api/types"
  9. "github.com/porter-dev/porter/cli/cmd/config"
  10. "github.com/spf13/cobra"
  11. )
  12. var (
  13. appName string
  14. envGroupName string
  15. envFilePath string
  16. )
  17. type envVariables struct {
  18. Variables map[string]string `json:"variables"`
  19. Secrets map[string]string `json:"secrets"`
  20. }
  21. func registerCommand_Env(cliConf config.CLIConfig) *cobra.Command {
  22. envCmd := &cobra.Command{
  23. Use: "env",
  24. Args: cobra.MinimumNArgs(0),
  25. Short: "Manage environment variables for a project",
  26. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  27. if len(cmd.Commands()) == 1 {
  28. return nil
  29. }
  30. if appName == "" && envGroupName == "" {
  31. return fmt.Errorf("must specify either --app or --group")
  32. }
  33. if appName != "" && envGroupName != "" {
  34. return fmt.Errorf("only one of --app or --group can be specified")
  35. }
  36. return nil
  37. },
  38. RunE: func(cmd *cobra.Command, args []string) error {
  39. return cmd.Help()
  40. },
  41. }
  42. envCmd.PersistentFlags().StringVarP(&appName, "app", "a", "", "app name")
  43. envCmd.PersistentFlags().StringVarP(&envGroupName, "group", "g", "", "environment group name")
  44. envCmd.PersistentFlags().StringVarP(&deploymentTargetName, "target", "x", "", "the name of the deployment target for the app")
  45. pullCommand := &cobra.Command{
  46. Use: "pull",
  47. Short: "Pull environment variables for an app or environment group",
  48. Long: `Pull environment variables for an app or environment group.
  49. Optionally, specify a file to write the environment variables to. Otherwise the environment variables will be written to stdout.`,
  50. Args: cobra.NoArgs,
  51. RunE: func(cmd *cobra.Command, args []string) error {
  52. return checkLoginAndRunWithConfig(cmd, cliConf, args, pullEnv)
  53. },
  54. }
  55. pullCommand.Flags().StringVarP(&envFilePath, "file", "f", "", "file to write environment variables to")
  56. setCommand := &cobra.Command{
  57. Use: "set",
  58. Short: "Set environment variables for an app or environment group",
  59. Long: `Set environment variables for an app or environment group.
  60. Both variables and secrets can be specified as key-value pairs.`,
  61. Args: cobra.NoArgs,
  62. RunE: func(cmd *cobra.Command, args []string) error {
  63. return checkLoginAndRunWithConfig(cmd, cliConf, args, setEnv)
  64. },
  65. }
  66. setCommand.Flags().StringToStringP("variables", "v", nil, "variables to set")
  67. setCommand.Flags().StringToStringP("secrets", "s", nil, "secrets to set")
  68. unsetCommand := &cobra.Command{
  69. Use: "unset",
  70. Short: "Unset environment variables for an app or environment group",
  71. Long: `Unset environment variables for an app or environment group.
  72. Both variables and secrets can be specified as keys.`,
  73. Args: cobra.NoArgs,
  74. RunE: func(cmd *cobra.Command, args []string) error {
  75. return checkLoginAndRunWithConfig(cmd, cliConf, args, unsetEnv)
  76. },
  77. }
  78. unsetCommand.Flags().StringSliceP("variables", "v", nil, "variables to unset")
  79. unsetCommand.Flags().StringSliceP("secrets", "s", nil, "secrets to unset")
  80. envCmd.AddCommand(pullCommand)
  81. envCmd.AddCommand(setCommand)
  82. envCmd.AddCommand(unsetCommand)
  83. return envCmd
  84. }
  85. func pullEnv(ctx context.Context, user *types.GetAuthenticatedUserResponse, client api.Client, cliConf config.CLIConfig, featureFlags config.FeatureFlags, cmd *cobra.Command, args []string) error {
  86. var envVars envVariables
  87. if appName != "" {
  88. color.New(color.FgGreen).Printf("Pulling environment variables for app %s...\n", appName) // nolint:errcheck,gosec
  89. envVarsResp, err := client.GetAppEnvVariables(ctx, cliConf.Project, cliConf.Cluster, appName, deploymentTargetName)
  90. if err != nil {
  91. return fmt.Errorf("could not get app env variables: %w", err)
  92. }
  93. if envVarsResp == nil {
  94. return fmt.Errorf("could not get app env variables: response was nil")
  95. }
  96. envVars = envVariables{
  97. Variables: envVarsResp.EnvVariables.Variables,
  98. Secrets: envVarsResp.EnvVariables.Secrets,
  99. }
  100. }
  101. if envGroupName != "" {
  102. color.New(color.FgGreen).Printf("Pulling environment variables for environment group %s...\n", envGroupName) // nolint:errcheck,gosec
  103. envVarsResp, err := client.GetLatestEnvGroupVariables(ctx, cliConf.Project, cliConf.Cluster, envGroupName)
  104. if err != nil {
  105. return fmt.Errorf("could not get env group env variables: %w", err)
  106. }
  107. if envVarsResp == nil {
  108. return fmt.Errorf("could not get env group variables: response was nil")
  109. }
  110. envVars = envVariables{
  111. Variables: envVarsResp.Variables,
  112. Secrets: envVarsResp.Secrets,
  113. }
  114. }
  115. if envFilePath != "" {
  116. err := writeEnvFile(envFilePath, envVars)
  117. if err != nil {
  118. return fmt.Errorf("could not write env file: %w", err)
  119. }
  120. color.New(color.FgGreen).Printf("Wrote environment variables to %s\n", envFilePath) // nolint:errcheck,gosec
  121. }
  122. if envFilePath == "" {
  123. err := exportEnvVars(envVars)
  124. if err != nil {
  125. return fmt.Errorf("could not export env vars: %w", err)
  126. }
  127. }
  128. return nil
  129. }
  130. func setEnv(ctx context.Context, user *types.GetAuthenticatedUserResponse, client api.Client, cliConf config.CLIConfig, featureFlags config.FeatureFlags, cmd *cobra.Command, args []string) error {
  131. var envVars envVariables
  132. variables, err := cmd.Flags().GetStringToString("variables")
  133. if err != nil {
  134. return fmt.Errorf("could not get variables: %w", err)
  135. }
  136. secrets, err := cmd.Flags().GetStringToString("secrets")
  137. if err != nil {
  138. return fmt.Errorf("could not get secrets: %w", err)
  139. }
  140. envVars = envVariables{
  141. Variables: variables,
  142. Secrets: secrets,
  143. }
  144. if appName != "" {
  145. color.New(color.FgGreen).Printf("Setting environment variables for app %s...\n", appName) // nolint:errcheck,gosec
  146. _, err := client.UpdateApp(ctx, api.UpdateAppInput{
  147. ProjectID: cliConf.Project,
  148. ClusterID: cliConf.Cluster,
  149. Name: appName,
  150. DeploymentTargetName: deploymentTargetName,
  151. Variables: envVars.Variables,
  152. Secrets: envVars.Secrets,
  153. })
  154. if err != nil {
  155. return fmt.Errorf("could not set app env variables: %w", err)
  156. }
  157. }
  158. if envGroupName != "" {
  159. color.New(color.FgGreen).Printf("Setting environment variables for environment group %s...\n", envGroupName) // nolint:errcheck,gosec
  160. err := client.UpdateEnvGroup(ctx, api.UpdateEnvGroupInput{
  161. ProjectID: cliConf.Project,
  162. ClusterID: cliConf.Cluster,
  163. EnvGroupName: envGroupName,
  164. Variables: envVars.Variables,
  165. Secrets: envVars.Secrets,
  166. })
  167. if err != nil {
  168. return fmt.Errorf("could not set env group env variables: %w", err)
  169. }
  170. }
  171. return nil
  172. }
  173. func unsetEnv(ctx context.Context, user *types.GetAuthenticatedUserResponse, client api.Client, cliConf config.CLIConfig, featureFlags config.FeatureFlags, cmd *cobra.Command, args []string) error {
  174. fmt.Println("This command is not supported for your project. Contact support@porter.run for more information.")
  175. return nil
  176. }
  177. func writeEnvFile(envFilePath string, envVars envVariables) error {
  178. // open existing file or create new file: https://pkg.go.dev/os#example-OpenFile-Append
  179. envFile, err := os.OpenFile(envFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) // nolint:gosec
  180. if err != nil {
  181. return err
  182. }
  183. defer envFile.Close() // nolint:errcheck
  184. _, err = envFile.WriteString("# Generated by Porter CLI\n")
  185. if err != nil {
  186. return err
  187. }
  188. for k, v := range envVars.Variables {
  189. _, err := envFile.WriteString(fmt.Sprintf("%s=%s\n", k, v))
  190. if err != nil {
  191. return err
  192. }
  193. }
  194. for k, v := range envVars.Secrets {
  195. _, err := envFile.WriteString(fmt.Sprintf("%s=%s\n", k, v))
  196. if err != nil {
  197. return err
  198. }
  199. }
  200. return nil
  201. }
  202. func exportEnvVars(envVars envVariables) error {
  203. for k, v := range envVars.Variables {
  204. _, err := os.Stdout.WriteString(fmt.Sprintf("%s=%s\n", k, v))
  205. if err != nil {
  206. return err
  207. }
  208. }
  209. for k, v := range envVars.Secrets {
  210. _, err := os.Stdout.WriteString(fmt.Sprintf("%s=%s\n", k, v))
  211. if err != nil {
  212. return err
  213. }
  214. }
  215. return nil
  216. }