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

     1  package api
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  )
     7  
     8  type Identifier struct {
     9  	ID                string `yaml:"id,omitempty"`
    10  	IDFromStackOutput string `yaml:"idFromStackOutput,omitempty"`
    11  	IDFromFn          string `yaml:"idFromFn,omitempty"`
    12  }
    13  
    14  // HasIdentifier returns true when the id of a resource i.e. either `id` or `idFromStackOutput` is specified
    15  func (i Identifier) HasIdentifier() bool {
    16  	return i.ID != "" || i.IDFromStackOutput != ""
    17  }
    18  
    19  func (i Identifier) Validate() error {
    20  	if i.IDFromFn != "" {
    21  		var jsonHolder map[string]interface{}
    22  		if err := json.Unmarshal([]byte(i.IDFromFn), &jsonHolder); err != nil {
    23  			return fmt.Errorf("idFromFn must be a valid json expression but was not: %s", i.IDFromFn)
    24  		}
    25  	}
    26  	return nil
    27  }
    28  
    29  func (i Identifier) Ref(logicalNameProvider func() string) string {
    30  	if i.IDFromStackOutput != "" {
    31  		return fmt.Sprintf(`{ "Fn::ImportValue" : %q }`, i.IDFromStackOutput)
    32  	} else if i.ID != "" {
    33  		return fmt.Sprintf(`"%s"`, i.ID)
    34  	} else if i.IDFromFn != "" {
    35  		return i.IDFromFn
    36  	} else {
    37  		return fmt.Sprintf(`{ "Ref" : %q }`, logicalNameProvider())
    38  	}
    39  }
    40  
    41  // RefOrError should be used instead of Ref where possible so that kube-aws can print a more useful error message with
    42  // the line number for the stack-template.json when there's an error.
    43  func (i Identifier) RefOrError(logicalNameProvider func() (string, error)) (string, error) {
    44  	if i.IDFromStackOutput != "" {
    45  		return fmt.Sprintf(`{ "Fn::ImportValue" : %q }`, i.IDFromStackOutput), nil
    46  	} else if i.ID != "" {
    47  		return fmt.Sprintf(`"%s"`, i.ID), nil
    48  	} else if i.IDFromFn != "" {
    49  		return i.IDFromFn, nil
    50  	} else {
    51  		logicalName, err := logicalNameProvider()
    52  		if err != nil {
    53  			return "", fmt.Errorf("failed to get id or ref: %v", err)
    54  		}
    55  		return fmt.Sprintf(`{ "Ref" : %q }`, logicalName), nil
    56  	}
    57  }