deploy.go 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "time"
  9. "github.com/briandowns/spinner"
  10. "github.com/fatih/color"
  11. api "github.com/porter-dev/porter/api/client"
  12. "github.com/porter-dev/porter/api/types"
  13. "github.com/porter-dev/porter/cli/cmd/config"
  14. "github.com/porter-dev/porter/cli/cmd/deploy"
  15. "github.com/porter-dev/porter/cli/cmd/docker"
  16. "github.com/porter-dev/porter/cli/cmd/utils"
  17. templaterUtils "github.com/porter-dev/porter/internal/templater/utils"
  18. "github.com/spf13/cobra"
  19. "k8s.io/client-go/util/homedir"
  20. )
  21. // updateCmd represents the "porter update" base command when called
  22. // without any subcommands
  23. var updateCmd = &cobra.Command{
  24. Use: "update",
  25. Short: "Builds and updates a specified application given by the --app flag.",
  26. Long: fmt.Sprintf(`
  27. %s
  28. Builds and updates a specified application given by the --app flag. For example:
  29. %s
  30. This command will automatically build from a local path. The path can be configured via the
  31. --path flag. You can also overwrite the tag using the --tag flag. For example, to build from the
  32. local directory ~/path-to-dir with the tag "testing":
  33. %s
  34. If the application has a remote Git repository source configured, you can specify that the remote
  35. Git repository should be used to build the new image by specifying "--source github". Porter will use
  36. the latest commit from the remote repo and branch to update an application, and will use the latest
  37. commit as the image tag.
  38. %s
  39. To add new configuration or update existing configuration, you can pass a values.yaml file in via the
  40. --values flag. For example;
  41. %s
  42. If your application is set up to use a Dockerfile by default, you can use a buildpack via the flag
  43. "--method pack". Conversely, if your application is set up to use a buildpack by default, you can
  44. use a Dockerfile by passing the flag "--method docker". You can specify the relative path to a Dockerfile
  45. in your remote Git repository. For example, if a Dockerfile is found at ./docker/prod.Dockerfile, you can
  46. specify it as follows:
  47. %s
  48. `,
  49. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter update\":"),
  50. color.New(color.FgGreen, color.Bold).Sprintf("porter update --app example-app"),
  51. color.New(color.FgGreen, color.Bold).Sprintf("porter update --app example-app --path ~/path-to-dir --tag testing"),
  52. color.New(color.FgGreen, color.Bold).Sprintf("porter update --app remote-git-app --source github"),
  53. color.New(color.FgGreen, color.Bold).Sprintf("porter update --app example-app --values my-values.yaml"),
  54. color.New(color.FgGreen, color.Bold).Sprintf("porter update --app example-app --method docker --dockerfile ./docker/prod.Dockerfile"),
  55. ),
  56. Run: func(cmd *cobra.Command, args []string) {
  57. err := checkLoginAndRun(args, updateFull)
  58. if err != nil {
  59. os.Exit(1)
  60. }
  61. },
  62. }
  63. var updateGetEnvCmd = &cobra.Command{
  64. Use: "get-env",
  65. Short: "Gets environment variables for a deployment for a specified application given by the --app flag.",
  66. Long: fmt.Sprintf(`
  67. %s
  68. Gets environment variables for a deployment for a specified application given by the --app
  69. flag. By default, env variables are printed via stdout for use in downstream commands:
  70. %s
  71. Output can also be written to a file via the --file flag, which should specify the
  72. destination path for a .env file. For example:
  73. %s
  74. `,
  75. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter update get-env\":"),
  76. color.New(color.FgGreen, color.Bold).Sprintf("porter update get-env --app example-app | xargs"),
  77. color.New(color.FgGreen, color.Bold).Sprintf("porter update get-env --app example-app --file .env"),
  78. ),
  79. Run: func(cmd *cobra.Command, args []string) {
  80. err := checkLoginAndRun(args, updateGetEnv)
  81. if err != nil {
  82. os.Exit(1)
  83. }
  84. },
  85. }
  86. var updateBuildCmd = &cobra.Command{
  87. Use: "build",
  88. Short: "Builds a new version of the application specified by the --app flag.",
  89. Long: fmt.Sprintf(`
  90. %s
  91. Builds a new version of the application specified by the --app flag. Depending on the
  92. configured settings, this command may work automatically or will require a specified
  93. --method flag.
  94. If you have configured the Dockerfile path and/or a build context for this application,
  95. this command will by default use those settings, so you just need to specify the --app
  96. flag:
  97. %s
  98. If you have not linked the build-time requirements for this application, the command will
  99. use a local build. By default, the cloud-native buildpacks builder will automatically be run
  100. from the current directory. If you would like to change the build method, you can do so by
  101. using the --method flag, for example:
  102. %s
  103. When using "--method docker", you can specify the path to the Dockerfile using the
  104. --dockerfile flag. This will also override the Dockerfile path that you may have linked
  105. for the application:
  106. %s
  107. `,
  108. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter update build\":"),
  109. color.New(color.FgGreen, color.Bold).Sprintf("porter update build --app example-app"),
  110. color.New(color.FgGreen, color.Bold).Sprintf("porter update build --app example-app --method docker"),
  111. color.New(color.FgGreen, color.Bold).Sprintf("porter update build --app example-app --method docker --dockerfile ./prod.Dockerfile"),
  112. ),
  113. Run: func(cmd *cobra.Command, args []string) {
  114. err := checkLoginAndRun(args, updateBuild)
  115. if err != nil {
  116. os.Exit(1)
  117. }
  118. },
  119. }
  120. var updatePushCmd = &cobra.Command{
  121. Use: "push",
  122. Short: "Pushes an image to a Docker registry linked to your Porter project.",
  123. Args: cobra.MaximumNArgs(1),
  124. Long: fmt.Sprintf(`
  125. %s
  126. Pushes a local Docker image to a registry linked to your Porter project. This command
  127. requires the project ID to be set either by using the %s command
  128. or the --project flag. For example, to push a local nginx image:
  129. %s
  130. %s
  131. Pushes a new image for an application specified by the --app flag. This command uses
  132. the image repository saved in the application config by default. For example, if an
  133. application "nginx" was created from the image repo "gcr.io/snowflake-123456/nginx",
  134. the following command would push the image "gcr.io/snowflake-123456/nginx:new-tag":
  135. %s
  136. This command will not use your pre-saved authentication set up via "docker login," so if you
  137. are using an image registry that was created outside of Porter, make sure that you have
  138. linked it via "porter connect".
  139. `,
  140. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter update push\":"),
  141. color.New(color.FgBlue).Sprintf("porter config set-project"),
  142. color.New(color.FgGreen, color.Bold).Sprintf("porter update push gcr.io/snowflake-123456/nginx:1234567"),
  143. color.New(color.Bold).Sprintf("LEGACY USAGE:"),
  144. color.New(color.FgGreen, color.Bold).Sprintf("porter update push --app nginx --tag new-tag"),
  145. ),
  146. Run: func(cmd *cobra.Command, args []string) {
  147. err := checkLoginAndRun(args, updatePush)
  148. if err != nil {
  149. os.Exit(1)
  150. }
  151. },
  152. }
  153. var updateConfigCmd = &cobra.Command{
  154. Use: "config",
  155. Short: "Updates the configuration for an application specified by the --app flag.",
  156. Long: fmt.Sprintf(`
  157. %s
  158. Updates the configuration for an application specified by the --app flag, using the configuration
  159. given by the --values flag. This will trigger a new deployment for the application with
  160. new configuration set. Note that this will merge your existing configuration with configuration
  161. specified in the --values file. For example:
  162. %s
  163. You can update the configuration with only a new tag with the --tag flag, which will only update
  164. the image that the application uses if no --values file is specified:
  165. %s
  166. `,
  167. color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter update config\":"),
  168. color.New(color.FgGreen, color.Bold).Sprintf("porter update config --app example-app --values my-values.yaml"),
  169. color.New(color.FgGreen, color.Bold).Sprintf("porter update config --app example-app --tag custom-tag"),
  170. ),
  171. Run: func(cmd *cobra.Command, args []string) {
  172. err := checkLoginAndRun(args, updateUpgrade)
  173. if err != nil {
  174. os.Exit(1)
  175. }
  176. },
  177. }
  178. var updateEnvGroupCmd = &cobra.Command{
  179. Use: "env-group",
  180. Aliases: []string{"eg", "envgroup", "env-groups", "envgroups"},
  181. Short: "Updates an environment group's variables, specified by the --name flag.",
  182. Run: func(cmd *cobra.Command, args []string) {
  183. color.New(color.FgRed).Println("need to specify an operation to continue")
  184. },
  185. }
  186. var updateSetEnvGroupCmd = &cobra.Command{
  187. Use: "set",
  188. Short: "Sets the desired value of an environment variable in an env group in the form VAR=VALUE.",
  189. Args: cobra.MaximumNArgs(1),
  190. Run: func(cmd *cobra.Command, args []string) {
  191. err := checkLoginAndRun(args, updateSetEnvGroup)
  192. if err != nil {
  193. os.Exit(1)
  194. }
  195. },
  196. }
  197. var updateUnsetEnvGroupCmd = &cobra.Command{
  198. Use: "unset",
  199. Short: "Removes an environment variable from an env group.",
  200. Args: cobra.MinimumNArgs(1),
  201. Run: func(cmd *cobra.Command, args []string) {
  202. err := checkLoginAndRun(args, updateUnsetEnvGroup)
  203. if err != nil {
  204. os.Exit(1)
  205. }
  206. },
  207. }
  208. var app string
  209. var getEnvFileDest string
  210. var localPath string
  211. var tag string
  212. var dockerfile string
  213. var method string
  214. var stream bool
  215. var buildFlagsEnv []string
  216. var forcePush bool
  217. var useCache bool
  218. var version uint
  219. var varType string
  220. var normalEnvGroupVars []string
  221. var secretEnvGroupVars []string
  222. func init() {
  223. buildFlagsEnv = []string{}
  224. rootCmd.AddCommand(updateCmd)
  225. updateCmd.PersistentFlags().StringVar(
  226. &app,
  227. "app",
  228. "",
  229. "Application in the Porter dashboard",
  230. )
  231. updateCmd.PersistentFlags().BoolVar(
  232. &useCache,
  233. "use-cache",
  234. false,
  235. "Whether to use cache (currently in beta)",
  236. )
  237. updateCmd.PersistentFlags().StringVar(
  238. &namespace,
  239. "namespace",
  240. "default",
  241. "Namespace of the application",
  242. )
  243. updateCmd.PersistentFlags().StringVar(
  244. &source,
  245. "source",
  246. "local",
  247. "the type of source (\"local\" or \"github\")",
  248. )
  249. updateCmd.PersistentFlags().StringVarP(
  250. &localPath,
  251. "path",
  252. "p",
  253. "",
  254. "If local build, the path to the build directory. If remote build, the relative path from the repository root to the build directory.",
  255. )
  256. updateCmd.PersistentFlags().StringVarP(
  257. &tag,
  258. "tag",
  259. "t",
  260. "",
  261. "the specified tag to use, if not \"latest\"",
  262. )
  263. updateCmd.PersistentFlags().StringVarP(
  264. &values,
  265. "values",
  266. "v",
  267. "",
  268. "Filepath to a values.yaml file",
  269. )
  270. updateCmd.PersistentFlags().StringVar(
  271. &dockerfile,
  272. "dockerfile",
  273. "",
  274. "the path to the dockerfile",
  275. )
  276. updateCmd.PersistentFlags().StringArrayVarP(
  277. &buildFlagsEnv,
  278. "env",
  279. "e",
  280. []string{},
  281. "Build-time environment variable, in the form 'VAR=VALUE'. These are not available at image runtime.",
  282. )
  283. updateCmd.PersistentFlags().StringVar(
  284. &method,
  285. "method",
  286. "",
  287. "the build method to use (\"docker\" or \"pack\")",
  288. )
  289. updateCmd.PersistentFlags().BoolVar(
  290. &stream,
  291. "stream",
  292. false,
  293. "stream update logs to porter dashboard",
  294. )
  295. updateCmd.PersistentFlags().BoolVar(
  296. &forceBuild,
  297. "force-build",
  298. false,
  299. "set this to force build an image (images tagged with \"latest\" have this set by default)",
  300. )
  301. updateCmd.PersistentFlags().BoolVar(
  302. &forcePush,
  303. "force-push",
  304. false,
  305. "set this to force push an image (images tagged with \"latest\" have this set by default)",
  306. )
  307. updateCmd.PersistentFlags().MarkDeprecated("force-build", "--force-build is now deprecated")
  308. updateCmd.PersistentFlags().MarkDeprecated("force-push", "--force-push is now deprecated")
  309. updateCmd.AddCommand(updateGetEnvCmd)
  310. updateGetEnvCmd.PersistentFlags().StringVar(
  311. &getEnvFileDest,
  312. "file",
  313. "",
  314. "file destination for .env files",
  315. )
  316. updateGetEnvCmd.MarkPersistentFlagRequired("app")
  317. updateBuildCmd.MarkPersistentFlagRequired("app")
  318. updateConfigCmd.MarkPersistentFlagRequired("app")
  319. updateEnvGroupCmd.PersistentFlags().StringVar(
  320. &name,
  321. "name",
  322. "",
  323. "the name of the environment group",
  324. )
  325. updateEnvGroupCmd.PersistentFlags().UintVar(
  326. &version,
  327. "version",
  328. 0,
  329. "the version of the environment group",
  330. )
  331. updateEnvGroupCmd.MarkPersistentFlagRequired("name")
  332. updateSetEnvGroupCmd.PersistentFlags().StringVar(
  333. &varType,
  334. "type",
  335. "normal",
  336. "the type of environment variable (either \"normal\" or \"secret\")",
  337. )
  338. updateSetEnvGroupCmd.PersistentFlags().StringArrayVarP(
  339. &normalEnvGroupVars,
  340. "normal",
  341. "n",
  342. []string{},
  343. "list of variables to set, in the form VAR=VALUE",
  344. )
  345. updateSetEnvGroupCmd.PersistentFlags().StringArrayVarP(
  346. &secretEnvGroupVars,
  347. "secret",
  348. "s",
  349. []string{},
  350. "list of secret variables to set, in the form VAR=VALUE",
  351. )
  352. updateEnvGroupCmd.AddCommand(updateSetEnvGroupCmd)
  353. updateEnvGroupCmd.AddCommand(updateUnsetEnvGroupCmd)
  354. updateCmd.AddCommand(updateBuildCmd)
  355. updateCmd.AddCommand(updatePushCmd)
  356. updateCmd.AddCommand(updateConfigCmd)
  357. updateCmd.AddCommand(updateEnvGroupCmd)
  358. }
  359. func updateFull(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  360. fullPath, err := filepath.Abs(localPath)
  361. if err != nil {
  362. return err
  363. }
  364. if os.Getenv("GITHUB_ACTIONS") == "" && source == "local" && fullPath == homedir.HomeDir() {
  365. proceed, err := utils.PromptConfirm("You are deploying your home directory. Do you want to continue?", false)
  366. if err != nil {
  367. return err
  368. }
  369. if !proceed {
  370. return nil
  371. }
  372. }
  373. color.New(color.FgGreen).Println("Deploying app:", app)
  374. updateAgent, err := updateGetAgent(client)
  375. if err != nil {
  376. return err
  377. }
  378. err = updateBuildWithAgent(updateAgent)
  379. if err != nil {
  380. return err
  381. }
  382. err = updatePushWithAgent(updateAgent)
  383. if err != nil {
  384. return err
  385. }
  386. err = updateUpgradeWithAgent(updateAgent)
  387. if err != nil {
  388. return err
  389. }
  390. return nil
  391. }
  392. func updateGetEnv(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  393. updateAgent, err := updateGetAgent(client)
  394. if err != nil {
  395. return err
  396. }
  397. buildEnv, err := updateAgent.GetBuildEnv(&deploy.GetBuildEnvOpts{
  398. UseNewConfig: false,
  399. })
  400. if err != nil {
  401. return err
  402. }
  403. // set the environment variables in the process
  404. err = updateAgent.SetBuildEnv(buildEnv)
  405. if err != nil {
  406. return err
  407. }
  408. // write the environment variables to either a file or stdout (stdout by default)
  409. return updateAgent.WriteBuildEnv(getEnvFileDest)
  410. }
  411. func updateBuild(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  412. updateAgent, err := updateGetAgent(client)
  413. if err != nil {
  414. return err
  415. }
  416. return updateBuildWithAgent(updateAgent)
  417. }
  418. func updatePush(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  419. if app == "" {
  420. if len(args) == 0 {
  421. return fmt.Errorf("please provide the docker image name")
  422. }
  423. image := args[0]
  424. registries, err := client.ListRegistries(context.Background(), cliConf.Project)
  425. if err != nil {
  426. return err
  427. }
  428. regs := *registries
  429. regID := uint(0)
  430. for _, reg := range regs {
  431. if strings.Contains(image, reg.URL) {
  432. regID = reg.ID
  433. break
  434. }
  435. }
  436. if regID == 0 {
  437. return fmt.Errorf("could not find registry for image: %s", image)
  438. }
  439. err = client.CreateRepository(context.Background(), cliConf.Project, regID,
  440. &types.CreateRegistryRepositoryRequest{
  441. ImageRepoURI: strings.Split(image, ":")[0],
  442. },
  443. )
  444. if err != nil {
  445. return err
  446. }
  447. agent, err := docker.NewAgentWithAuthGetter(client, cliConf.Project)
  448. if err != nil {
  449. return err
  450. }
  451. err = agent.PushImage(image)
  452. if err != nil {
  453. return err
  454. }
  455. return nil
  456. }
  457. updateAgent, err := updateGetAgent(client)
  458. if err != nil {
  459. return err
  460. }
  461. return updatePushWithAgent(updateAgent)
  462. }
  463. func updateUpgrade(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  464. updateAgent, err := updateGetAgent(client)
  465. if err != nil {
  466. return err
  467. }
  468. return updateUpgradeWithAgent(updateAgent)
  469. }
  470. func updateSetEnvGroup(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  471. if len(normalEnvGroupVars) == 0 && len(secretEnvGroupVars) == 0 && len(args) == 0 {
  472. return fmt.Errorf("please provide one or more variables to update")
  473. }
  474. s := spinner.New(spinner.CharSets[9], 100*time.Millisecond)
  475. s.Color("cyan")
  476. s.Suffix = fmt.Sprintf(" Fetching env group '%s' in namespace '%s'", name, namespace)
  477. s.Start()
  478. envGroupResp, err := client.GetEnvGroup(context.Background(), cliConf.Project, cliConf.Cluster, namespace,
  479. &types.GetEnvGroupRequest{
  480. Name: name, Version: version,
  481. },
  482. )
  483. s.Stop()
  484. if err != nil {
  485. return err
  486. }
  487. newEnvGroup := &types.CreateEnvGroupRequest{
  488. Name: envGroupResp.Name,
  489. Variables: envGroupResp.Variables,
  490. }
  491. // first check for multiple variables being set using the -e or -s flags
  492. if len(normalEnvGroupVars) > 0 || len(secretEnvGroupVars) > 0 {
  493. for _, v := range normalEnvGroupVars {
  494. delete(newEnvGroup.Variables, v)
  495. key, value, err := validateVarValue(v)
  496. if err != nil {
  497. return err
  498. }
  499. newEnvGroup.Variables[key] = value
  500. }
  501. if len(secretEnvGroupVars) > 0 {
  502. newEnvGroup.SecretVariables = make(map[string]string)
  503. }
  504. for _, v := range secretEnvGroupVars {
  505. delete(newEnvGroup.Variables, v)
  506. key, value, err := validateVarValue(v)
  507. if err != nil {
  508. return err
  509. }
  510. newEnvGroup.SecretVariables[key] = value
  511. }
  512. s.Suffix = fmt.Sprintf(" Updating env group '%s' in namespace '%s'", name, namespace)
  513. } else { // legacy usage
  514. key, value, err := validateVarValue(args[0])
  515. if err != nil {
  516. return err
  517. }
  518. delete(newEnvGroup.Variables, key)
  519. if varType == "secret" {
  520. newEnvGroup.SecretVariables = make(map[string]string)
  521. newEnvGroup.SecretVariables[key] = value
  522. s.Suffix = fmt.Sprintf(" Adding new secret variable '%s' to env group '%s' in namespace '%s'", key, name, namespace)
  523. } else {
  524. newEnvGroup.Variables[key] = value
  525. s.Suffix = fmt.Sprintf(" Adding new variable '%s' to env group '%s' in namespace '%s'", key, name, namespace)
  526. }
  527. }
  528. s.Start()
  529. _, err = client.CreateEnvGroup(
  530. context.Background(), cliConf.Project, cliConf.Cluster, namespace, newEnvGroup,
  531. )
  532. s.Stop()
  533. if err != nil {
  534. return err
  535. }
  536. color.New(color.FgGreen).Println("env group successfully updated")
  537. return nil
  538. }
  539. func validateVarValue(in string) (string, string, error) {
  540. key, value, found := strings.Cut(in, "=")
  541. if !found {
  542. return "", "", fmt.Errorf("%s is not in the form of VAR=VALUE", in)
  543. }
  544. return key, value, nil
  545. }
  546. func updateUnsetEnvGroup(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []string) error {
  547. if len(args) == 0 {
  548. return fmt.Errorf("required variable name")
  549. }
  550. s := spinner.New(spinner.CharSets[9], 100*time.Millisecond)
  551. s.Color("cyan")
  552. s.Suffix = fmt.Sprintf(" Fetching env group '%s' in namespace '%s'", name, namespace)
  553. s.Start()
  554. envGroupResp, err := client.GetEnvGroup(context.Background(), cliConf.Project, cliConf.Cluster, namespace,
  555. &types.GetEnvGroupRequest{
  556. Name: name, Version: version,
  557. },
  558. )
  559. s.Stop()
  560. if err != nil {
  561. return err
  562. }
  563. newEnvGroup := &types.CreateEnvGroupRequest{
  564. Name: envGroupResp.Name,
  565. Variables: envGroupResp.Variables,
  566. }
  567. for _, v := range args {
  568. delete(newEnvGroup.Variables, v)
  569. }
  570. s.Suffix = fmt.Sprintf(" Removing variables from env group '%s' in namespace '%s'", name, namespace)
  571. s.Start()
  572. _, err = client.CreateEnvGroup(
  573. context.Background(), cliConf.Project, cliConf.Cluster, namespace, newEnvGroup,
  574. )
  575. s.Stop()
  576. if err != nil {
  577. return err
  578. }
  579. color.New(color.FgGreen).Println("env group successfully updated")
  580. return nil
  581. }
  582. // HELPER METHODS
  583. func updateGetAgent(client *api.Client) (*deploy.DeployAgent, error) {
  584. var buildMethod deploy.DeployBuildType
  585. if method != "" {
  586. buildMethod = deploy.DeployBuildType(method)
  587. }
  588. // add additional env, if they exist
  589. additionalEnv := make(map[string]string)
  590. for _, buildEnv := range buildFlagsEnv {
  591. if strSplArr := strings.SplitN(buildEnv, "=", 2); len(strSplArr) >= 2 {
  592. additionalEnv[strSplArr[0]] = strSplArr[1]
  593. }
  594. }
  595. // initialize the update agent
  596. return deploy.NewDeployAgent(client, app, &deploy.DeployOpts{
  597. SharedOpts: &deploy.SharedOpts{
  598. ProjectID: cliConf.Project,
  599. ClusterID: cliConf.Cluster,
  600. Namespace: namespace,
  601. LocalPath: localPath,
  602. LocalDockerfile: dockerfile,
  603. OverrideTag: tag,
  604. Method: buildMethod,
  605. AdditionalEnv: additionalEnv,
  606. UseCache: useCache,
  607. },
  608. Local: source != "github",
  609. })
  610. }
  611. func updateBuildWithAgent(updateAgent *deploy.DeployAgent) error {
  612. // build the deployment
  613. color.New(color.FgGreen).Println("Building docker image for", app)
  614. if stream {
  615. updateAgent.StreamEvent(types.SubEvent{
  616. EventID: "build",
  617. Name: "Build",
  618. Index: 100,
  619. Status: types.EventStatusInProgress,
  620. Info: "",
  621. })
  622. }
  623. if useCache {
  624. err := config.SetDockerConfig(updateAgent.Client)
  625. if err != nil {
  626. return err
  627. }
  628. }
  629. // read the values if necessary
  630. valuesObj, err := readValuesFile()
  631. if err != nil {
  632. return err
  633. }
  634. buildEnv, err := updateAgent.GetBuildEnv(&deploy.GetBuildEnvOpts{
  635. UseNewConfig: true,
  636. NewConfig: valuesObj,
  637. })
  638. if err != nil {
  639. if stream {
  640. // another concern: is it safe to ignore the error here?
  641. updateAgent.StreamEvent(types.SubEvent{
  642. EventID: "build",
  643. Name: "Build",
  644. Index: 110,
  645. Status: types.EventStatusFailed,
  646. Info: err.Error(),
  647. })
  648. }
  649. return err
  650. }
  651. // set the environment variables in the process
  652. err = updateAgent.SetBuildEnv(buildEnv)
  653. if err != nil {
  654. if stream {
  655. updateAgent.StreamEvent(types.SubEvent{
  656. EventID: "build",
  657. Name: "Build",
  658. Index: 120,
  659. Status: types.EventStatusFailed,
  660. Info: err.Error(),
  661. })
  662. }
  663. return err
  664. }
  665. if err := updateAgent.Build(nil); err != nil {
  666. if stream {
  667. updateAgent.StreamEvent(types.SubEvent{
  668. EventID: "build",
  669. Name: "Build",
  670. Index: 130,
  671. Status: types.EventStatusFailed,
  672. Info: err.Error(),
  673. })
  674. }
  675. return err
  676. }
  677. if stream {
  678. updateAgent.StreamEvent(types.SubEvent{
  679. EventID: "build",
  680. Name: "Build",
  681. Index: 140,
  682. Status: types.EventStatusSuccess,
  683. Info: "",
  684. })
  685. }
  686. return nil
  687. }
  688. func updatePushWithAgent(updateAgent *deploy.DeployAgent) error {
  689. if useCache {
  690. color.New(color.FgGreen).Println("Skipping image push for", app, "as use-cache is set")
  691. return nil
  692. }
  693. // push the deployment
  694. color.New(color.FgGreen).Println("Pushing new image for", app)
  695. if stream {
  696. updateAgent.StreamEvent(types.SubEvent{
  697. EventID: "push",
  698. Name: "Push",
  699. Index: 200,
  700. Status: types.EventStatusInProgress,
  701. Info: "",
  702. })
  703. }
  704. if err := updateAgent.Push(); err != nil {
  705. if stream {
  706. updateAgent.StreamEvent(types.SubEvent{
  707. EventID: "push",
  708. Name: "Push",
  709. Index: 210,
  710. Status: types.EventStatusFailed,
  711. Info: err.Error(),
  712. })
  713. }
  714. return err
  715. }
  716. if stream {
  717. updateAgent.StreamEvent(types.SubEvent{
  718. EventID: "push",
  719. Name: "Push",
  720. Index: 220,
  721. Status: types.EventStatusSuccess,
  722. Info: "",
  723. })
  724. }
  725. return nil
  726. }
  727. func updateUpgradeWithAgent(updateAgent *deploy.DeployAgent) error {
  728. // push the deployment
  729. color.New(color.FgGreen).Println("Upgrading configuration for", app)
  730. if stream {
  731. updateAgent.StreamEvent(types.SubEvent{
  732. EventID: "upgrade",
  733. Name: "Upgrade",
  734. Index: 300,
  735. Status: types.EventStatusInProgress,
  736. Info: "",
  737. })
  738. }
  739. var err error
  740. // read the values if necessary
  741. valuesObj, err := readValuesFile()
  742. if err != nil {
  743. return err
  744. }
  745. if err != nil {
  746. if stream {
  747. updateAgent.StreamEvent(types.SubEvent{
  748. EventID: "upgrade",
  749. Name: "Upgrade",
  750. Index: 310,
  751. Status: types.EventStatusFailed,
  752. Info: err.Error(),
  753. })
  754. }
  755. return err
  756. }
  757. if len(updateAgent.Opts.AdditionalEnv) > 0 {
  758. syncedEnv, err := deploy.GetSyncedEnv(
  759. updateAgent.Client,
  760. updateAgent.Release.Config,
  761. updateAgent.Opts.ProjectID,
  762. updateAgent.Opts.ClusterID,
  763. updateAgent.Opts.Namespace,
  764. false,
  765. )
  766. if err != nil {
  767. return err
  768. }
  769. for k := range updateAgent.Opts.AdditionalEnv {
  770. if _, ok := syncedEnv[k]; ok {
  771. return fmt.Errorf("environment variable %s already exists as part of a synced environment group", k)
  772. }
  773. }
  774. normalEnv, err := deploy.GetNormalEnv(
  775. updateAgent.Client,
  776. updateAgent.Release.Config,
  777. updateAgent.Opts.ProjectID,
  778. updateAgent.Opts.ClusterID,
  779. updateAgent.Opts.Namespace,
  780. false,
  781. )
  782. if err != nil {
  783. return err
  784. }
  785. // add the additional environment variables to container.env.normal
  786. for k, v := range updateAgent.Opts.AdditionalEnv {
  787. normalEnv[k] = v
  788. }
  789. valuesObj = templaterUtils.CoalesceValues(valuesObj, map[string]interface{}{
  790. "container": map[string]interface{}{
  791. "env": map[string]interface{}{
  792. "normal": normalEnv,
  793. },
  794. },
  795. })
  796. }
  797. err = updateAgent.UpdateImageAndValues(valuesObj)
  798. if err != nil {
  799. if stream {
  800. updateAgent.StreamEvent(types.SubEvent{
  801. EventID: "upgrade",
  802. Name: "Upgrade",
  803. Index: 320,
  804. Status: types.EventStatusFailed,
  805. Info: err.Error(),
  806. })
  807. }
  808. return err
  809. }
  810. if stream {
  811. updateAgent.StreamEvent(types.SubEvent{
  812. EventID: "upgrade",
  813. Name: "Upgrade",
  814. Index: 330,
  815. Status: types.EventStatusSuccess,
  816. Info: "",
  817. })
  818. }
  819. color.New(color.FgGreen).Println("Successfully updated", app)
  820. return nil
  821. }