github.com/kubernetes-incubator/kube-aws@v0.16.4/pkg/api/custom_file.go (about)

     1  package api
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  	"text/template"
     7  
     8  	"github.com/kubernetes-incubator/kube-aws/filereader/texttemplate"
     9  	"github.com/kubernetes-incubator/kube-aws/gzipcompressor"
    10  	"github.com/kubernetes-incubator/kube-aws/logger"
    11  )
    12  
    13  type CustomFile struct {
    14  	Path        string `yaml:"path"`
    15  	Permissions uint   `yaml:"permissions"`
    16  	Content     string `yaml:"content,omitempty"`
    17  	Template    string `yaml:"template,omitempty"`
    18  	Type        string `yaml:"type,omitempty"`
    19  	UnknownKeys `yaml:",inline"`
    20  }
    21  
    22  func (c CustomFile) Encrypted() bool {
    23  	return c.Type == "credential"
    24  }
    25  
    26  func (c CustomFile) PermissionsString() string {
    27  	// We also need to write out octal notation for permissions.
    28  	return fmt.Sprintf("0%o", c.Permissions)
    29  }
    30  
    31  func (c CustomFile) GzippedBase64Content() string {
    32  	out, err := gzipcompressor.StringToGzippedBase64String(c.Content)
    33  	if err != nil {
    34  		return ""
    35  	}
    36  	return out
    37  }
    38  
    39  func (c CustomFile) RenderContent(ctx interface{}) (string, error) {
    40  	var err error
    41  	if c.customFileHasTemplate() {
    42  		c.Content, err = c.renderTemplate(ctx)
    43  		if err != nil {
    44  			return "", err
    45  		}
    46  	}
    47  	return c.Content, nil
    48  }
    49  
    50  func (c CustomFile) RenderGzippedBase64Content(ctx interface{}) (string, error) {
    51  	var content string
    52  	// Every credential is already encrypted by AWS KMS that its ciphertext is already a base64-encoded string.
    53  	if c.Type == "credential" {
    54  		content = c.Content
    55  	} else {
    56  		var err error
    57  		content, err = c.RenderContent(ctx)
    58  		if err != nil {
    59  			return "", err
    60  		}
    61  	}
    62  	return gzipcompressor.StringToGzippedBase64String(content)
    63  }
    64  
    65  func (c CustomFile) customFileHasTemplate() bool {
    66  	return c.Template != ""
    67  }
    68  
    69  func (c CustomFile) renderTemplate(ctx interface{}) (string, error) {
    70  	var buf strings.Builder
    71  
    72  	tmpl, err := texttemplate.Parse("template", c.Template, template.FuncMap{})
    73  	if err != nil {
    74  		return "", fmt.Errorf("failed to parse CustomFile template %s: %v", c.Path, err)
    75  	}
    76  	err = tmpl.Execute(&buf, ctx)
    77  	if err != nil {
    78  		return "", fmt.Errorf("error rendering CustomFile template %s: %v", c.Path, err)
    79  	}
    80  
    81  	logger.Debugf("successfully rendered CustomFile template %s", c.Path)
    82  	return buf.String(), nil
    83  }