github.com/zntrio/harp/v2@v2.0.9/pkg/tasks/from/template.go (about) 1 // Licensed to Elasticsearch B.V. under one or more contributor 2 // license agreements. See the NOTICE file distributed with 3 // this work for additional information regarding copyright 4 // ownership. Elasticsearch B.V. licenses this file to you under 5 // the Apache License, Version 2.0 (the "License"); you may 6 // not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, 12 // software distributed under the License is distributed on an 13 // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 // KIND, either express or implied. See the License for the 15 // specific language governing permissions and limitations 16 // under the License. 17 18 package from 19 20 import ( 21 "context" 22 "fmt" 23 "io" 24 25 bundlev1 "github.com/zntrio/harp/v2/api/gen/go/harp/bundle/v1" 26 "github.com/zntrio/harp/v2/pkg/bundle" 27 "github.com/zntrio/harp/v2/pkg/bundle/template" 28 "github.com/zntrio/harp/v2/pkg/bundle/template/visitor/secretbuilder" 29 "github.com/zntrio/harp/v2/pkg/tasks" 30 "github.com/zntrio/harp/v2/pkg/template/engine" 31 ) 32 33 // BundleTemplateTask implements secret-container generation from BundleTemplate 34 // manifest. 35 type BundleTemplateTask struct { 36 TemplateReader tasks.ReaderProvider 37 OutputWriter tasks.WriterProvider 38 TemplateContext engine.Context 39 } 40 41 // Run the task. 42 func (t *BundleTemplateTask) Run(ctx context.Context) error { 43 var ( 44 reader io.Reader 45 writer io.Writer 46 spec *bundlev1.Template 47 err error 48 ) 49 50 // Create input reader 51 reader, err = t.TemplateReader(ctx) 52 if err != nil { 53 return fmt.Errorf("unable to open input bundle template: %w", err) 54 } 55 56 // Parse the input specification 57 spec, err = template.YAML(reader) 58 if err != nil { 59 return fmt.Errorf("unable to parse template: %w", err) 60 } 61 62 // Initialize output 63 b := &bundlev1.Bundle{ 64 Template: spec, 65 } 66 67 // Initialize a bundle creator 68 v := secretbuilder.New(b, t.TemplateContext) 69 70 // Execute the template to generate an output bundle 71 if err = template.Execute(spec, v); err != nil { 72 return fmt.Errorf("unable to generate output bundle from template: %w", err) 73 } 74 75 // Create output writer 76 writer, err = t.OutputWriter(ctx) 77 if err != nil { 78 return fmt.Errorf("unable to open output bundle: %w", err) 79 } 80 81 // Dump all content 82 if err = bundle.ToContainerWriter(writer, b); err != nil { 83 return fmt.Errorf("unable to dump bundle content: %w", err) 84 } 85 86 // No error 87 return nil 88 }