@@ -2,6 +2,7 @@ package deploy
22
33import (
44 "archive/tar"
5+ "bufio"
56 "compress/gzip"
67 "context"
78 "encoding/json"
@@ -224,4 +225,74 @@ func manageResource(owner metav1.Object, ctx context.Context, cli client.Client,
224225 return cli .Patch (ctx , found , client .RawPatch (types .ApplyPatchType , data ), client .ForceOwnership , client .FieldOwner (owner .GetName ()))
225226}
226227
228+ func ApplyImageParams (componentPath string , imageParamsMap map [string ]string ) error {
229+ envFilePath := componentPath + "/params.env"
230+ // Require params.env at the root folder
231+ file , err := os .Open (envFilePath )
232+ if err != nil {
233+ if os .IsNotExist (err ) {
234+ // params.env doesn't exist, do not apply any changes
235+ return nil
236+ }
237+ return err
238+ }
239+ backupPath := envFilePath + ".bak"
240+ defer file .Close ()
241+
242+ envMap := make (map [string ]string )
243+ scanner := bufio .NewScanner (file )
244+ for scanner .Scan () {
245+ line := scanner .Text ()
246+ parts := strings .SplitN (line , "=" , 2 )
247+ if len (parts ) == 2 {
248+ envMap [parts [0 ]] = parts [1 ]
249+ }
250+ }
251+
252+ if err := scanner .Err (); err != nil {
253+ return err
254+ }
255+
256+ // Update images with env variables
257+ for key , _ := range envMap {
258+ relatedImageValue := os .Getenv (imageParamsMap [key ])
259+ if relatedImageValue != "" {
260+ envMap [key ] = relatedImageValue
261+ }
262+ }
263+
264+ // Move the existing file to a backup file
265+ os .Rename (envFilePath , backupPath )
266+
267+ // Now, write the map back to the file
268+ file , err = os .Create (envFilePath )
269+ if err != nil {
270+ // If create fails, restore the backup file
271+ os .Rename (backupPath , envFilePath )
272+ return err
273+ }
274+ defer file .Close ()
275+
276+ writer := bufio .NewWriter (file )
277+ for key , value := range envMap {
278+ fmt .Fprintf (writer , "%s=%s\n " , key , value )
279+ }
280+ if err := writer .Flush (); err != nil {
281+ if removeErr := os .Remove (envFilePath ); removeErr != nil {
282+ fmt .Printf ("Failed to remove file: %v" , removeErr )
283+ }
284+ if renameErr := os .Rename (backupPath , envFilePath ); renameErr != nil {
285+ fmt .Printf ("Failed to restore file from backup: %v" , renameErr )
286+ }
287+ fmt .Printf ("Failed to write to file: %v" , err )
288+ return err
289+ }
290+
291+ if err := os .Remove (backupPath ); err != nil {
292+ fmt .Printf ("Failed to remove backup file: %v" , err )
293+ return err
294+ }
295+ return nil
296+ }
297+
227298// TODO : Add function to cleanup code created as part of pre install and post intall task of a component
0 commit comments