tfconfig

package
v1.0.0-beta4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 26, 2023 License: MPL-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package tfconfig is a helper library that does careful, shallow parsing of Terraform modules to provide access to high-level metadata while remaining broadly compatible with configurations targeting various different Terraform versions.

This packge focuses on describing top-level objects only, and in particular does not attempt any sort of processing that would require access to plugins. Currently it allows callers to extract high-level information about variables, outputs, resource blocks, provider dependencies, and Terraform Core dependencies.

This package only works at the level of single modules. A full configuration is a tree of potentially several modules, some of which may be references to remote packages. There are some basic helpers for traversing calls to modules at relative local paths, however.

This package employs a "best effort" parsing strategy, producing as complete a result as possible even though the input may not be entirely valid. The intended use-case is high-level analysis and indexing of externally-facing module characteristics, as opposed to validating or even applying the module.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CheckForInitDirectoryAndLoadIBMModule

func CheckForInitDirectoryAndLoadIBMModule(dir string, metadataPath string) (*Module, Diagnostics)

LoadIBMModule takes template file directory and metadataPath as input and returns final module struct.

func ExtractOutputMetadata

func ExtractOutputMetadata(o *Output, m interface{}, moduleName, moduleAttribute string)

Name string `json:"name"`

Description    string        `json:"description,omitempty"`
Value          string        `json:"value,omitempty"`
Sensitive      bool          `json:"sensitive,omitempty"`
Pos            *SourcePos    `json:"pos,omitempty"`
Type           string        `json:"type,omitempty"`
Source         []string      `json:"source,omitempty"`
CloudDataType  string        `json:"cloud_data_type,omitempty" description:"Cloud data type of the variable. eg. resource_group_id, region, vpc_id."`
CloudDataRange []interface{} `json:"cloud_data_range,omitempty" description:""`

func ExtractVariableMetadata

func ExtractVariableMetadata(v *Variable, m interface{}, moduleName, moduleAttribute string)

func IsModuleDir

func IsModuleDir(dir string) bool

IsModuleDir checks if the given path contains terraform configuration files. This allows the caller to decide how to handle directories that do not have tf files.

func IsModuleDirOnFilesystem

func IsModuleDirOnFilesystem(fs FS, dir string) bool

IsModuleDirOnFilesystem checks if the given path in the given FS contains Terraform configuration files. This allows the caller to decide how to handle directories that do not have tf files.

func LoadIBMModule

func LoadIBMModule(dir string, metadataPath string, fileStruct map[string]interface{}) (*Module, Diagnostics)

LoadIBMModule takes template file directory and metadataPath as input and returns final module struct.

func LoadModule

func LoadModule(dir string) (*Module, Diagnostics)

LoadModule reads the directory at the given path and attempts to interpret it as a Terraform module.

func LoadModuleFromFile

func LoadModuleFromFile(file *hcl.File, mod *Module) hcl.Diagnostics

LoadModuleFromFile reads given file, interprets it and stores in given Module This is useful for any caller which does tokenization/parsing on its own e.g. because it will reuse these parsed files later for more detailed interpretation.

func LoadModuleFromFilesystem

func LoadModuleFromFilesystem(fs FS, dir string) (*Module, Diagnostics)

LoadModuleFromFilesystem reads the directory at the given path in the given FS and attempts to interpret it as a Terraform module

func RenderMarkdown

func RenderMarkdown(w io.Writer, module *Module, variable bool) error

func SortedKeysOfMap

func SortedKeysOfMap(mapper interface{}) []string

SortedKeysOfMap when there is a range on map, keys are always picked in random. This function sorts keys of map and returns sorted list of keys

Types

type DiagSeverity

type DiagSeverity rune

DiagSeverity describes the severity of a Diagnostic.

const DiagError DiagSeverity = 'E'

DiagError indicates a problem that prevented proper processing of the configuration. In the precense of DiagError diagnostics the result is likely to be incomplete.

const DiagWarning DiagSeverity = 'W'

DiagWarning indicates a problem that the user may wish to consider but that did not prevent proper processing of the configuration.

func (DiagSeverity) MarshalJSON

func (s DiagSeverity) MarshalJSON() ([]byte, error)

MarshalJSON is an implementation of encoding/json.Marshaler

type Diagnostic

type Diagnostic struct {
	Severity DiagSeverity `json:"severity"`
	Summary  string       `json:"summary"`
	Detail   string       `json:"detail,omitempty"`

	// Pos is not populated for all diagnostics, but when populated should
	// indicate a particular line that the described problem relates to.
	Pos *SourcePos `json:"pos,omitempty"`
}

Diagnostic describes a problem (error or warning) encountered during configuration loading.

type Diagnostics

type Diagnostics []Diagnostic

Diagnostics represents a sequence of diagnostics. This is the type that should be returned from a function that might generate diagnostics.

func (Diagnostics) Err

func (diags Diagnostics) Err() error

Err returns an error representing the receiver if the receiver HasErrors, or nil otherwise.

The returned error can be type-asserted back to a Diagnostics if needed.

func (Diagnostics) Error

func (diags Diagnostics) Error() string

func (Diagnostics) HasErrors

func (diags Diagnostics) HasErrors() bool

HasErrors returns true if there is at least one Diagnostic of severity DiagError in the receiever.

If a function returns a Diagnostics without errors then the result can be assumed to be complete within the "best effort" constraints of this library. If errors are present then the caller may wish to employ more caution in relying on the result.

type FS

type FS interface {
	Open(name string) (File, error)
	ReadFile(name string) ([]byte, error)
	ReadDir(dirname string) ([]os.FileInfo, error)
}

FS represents a minimal filesystem implementation See io/fs.FS in http://golang.org/s/draft-iofs-design

func NewOsFs

func NewOsFs() FS

NewOsFs provides a basic implementation of FS for an OS filesystem

type File

type File interface {
	Stat() (os.FileInfo, error)
	Read([]byte) (int, error)
	Close() error
}

File represents an open file in FS See io/fs.File in http://golang.org/s/draft-iofs-design

type Metadata

type Metadata struct {
	Variables map[string]*Variable `json:"variables"`
	Outputs   map[string]*Output   `json:"outputs,omitempty"`
}

type Module

type Module struct {
	// Path is the local filesystem directory where the module was loaded from.
	Path string `json:"path"`

	Variables map[string]*Variable `json:"variables"`
	Outputs   map[string]*Output   `json:"outputs"`

	RequiredCore      []string                        `json:"required_core,omitempty"`
	RequiredProviders map[string]*ProviderRequirement `json:"required_providers"`

	ProviderConfigs  map[string]*ProviderConfig `json:"provider_configs,omitempty"`
	ManagedResources map[string]*Resource       `json:"managed_resources"`
	DataResources    map[string]*Resource       `json:"data_resources"`
	ModuleCalls      map[string]*ModuleCall     `json:"module_calls"`

	// Diagnostics records any errors and warnings that were detected during
	// loading, primarily for inclusion in serialized forms of the module
	// since this slice is also returned as a second argument from LoadModule.
	Diagnostics Diagnostics `json:"diagnostics,omitempty"`
}

Module is the top-level type representing a parsed and processed Terraform module.

func NewModule

func NewModule(path string) *Module

NewModule creates new Module representing Terraform module at the given path

type ModuleCall

type ModuleCall struct {
	Name             string                 `json:"name"`
	Source           string                 `json:"source"`
	Version          string                 `json:"version,omitempty"`
	Attributes       map[string]interface{} `json:"attributes,omitempty"`
	ManagedResources map[string]*Resource   `json:"managed_resources"`
	DataResources    map[string]*Resource   `json:"data_resources"`
	Outputs          map[string]*Output     `json:"outputs,omitempty"`

	Pos SourcePos `json:"pos"`
}

ModuleCall represents a "module" block within a module. That is, a declaration of a child module from inside its parent.

type Output

type Output struct {
	Name           string        `json:"name"`
	Description    string        `json:"description,omitempty"`
	Value          string        `json:"value,omitempty"`
	Sensitive      bool          `json:"sensitive,omitempty"`
	Pos            *SourcePos    `json:"pos,omitempty"`
	Type           string        `json:"type,omitempty"`
	Source         []string      `json:"source,omitempty"`
	CloudDataType  string        `json:"cloud_data_type,omitempty" description:"Cloud data type of the variable. eg. resource_group_id, region, vpc_id."`
	CloudDataRange []interface{} `json:"cloud_data_range,omitempty" description:""`
}

Output represents a single output from a Terraform module.

type ProviderConfig

type ProviderConfig struct {
	Name  string `json:"name"`
	Alias string `json:"alias,omitempty"`
}

ProviderConfig represents a provider block in the configuration

type ProviderRef

type ProviderRef struct {
	Name  string `json:"name"`
	Alias string `json:"alias,omitempty"` // Empty if the default provider configuration is referenced
}

ProviderRef is a reference to a provider configuration within a module. It represents the contents of a "provider" argument in a resource, or a value in the "providers" map for a module call.

type ProviderRequirement

type ProviderRequirement struct {
	Source               string        `json:"source,omitempty"`
	VersionConstraints   []string      `json:"version_constraints,omitempty"`
	ConfigurationAliases []ProviderRef `json:"aliases,omitempty"`
}

type Resource

type Resource struct {
	Mode       ResourceMode           `json:"mode"`
	Type       string                 `json:"type"`
	Name       string                 `json:"name"`
	Attributes map[string]interface{} `json:"attributes,omitempty"`

	Provider ProviderRef `json:"provider"`

	Pos SourcePos `json:"pos"`
}

Resource represents a single "resource" or "data" block within a module.

func (*Resource) MapKey

func (r *Resource) MapKey() string

MapKey returns a string that can be used to uniquely identify the receiver in a map[string]*Resource.

type ResourceMode

type ResourceMode rune

ResourceMode represents the "mode" of a resource, which is used to distinguish between managed resources ("resource" blocks in config) and data resources ("data" blocks in config).

const DataResourceMode ResourceMode = 'D'
const InvalidResourceMode ResourceMode = 0
const ManagedResourceMode ResourceMode = 'M'

func (ResourceMode) MarshalJSON

func (m ResourceMode) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json.Marshaler.

func (ResourceMode) String

func (m ResourceMode) String() string

type SourcePos

type SourcePos struct {
	Filename string `json:"filename"`
	Line     int    `json:"line"`
}

SourcePos is a pointer to a particular location in a source file.

This type is embedded into other structs to allow callers to locate the definition of each described module element. The SourcePos of an element is usually the first line of its definition, although the definition can be a little "fuzzy" with JSON-based config files.

type Variable

type Variable struct {
	Name        string `json:"name"`
	Type        string `json:"type,omitempty"`
	Description string `json:"description,omitempty"`

	// Default is an approximate representation of the default value in
	// the native Go type system. The conversion from the value given in
	// configuration may be slightly lossy. Only values that can be
	// serialized by json.Marshal will be included here.
	Default        interface{} `json:"default,omitempty"`
	Required       *bool       `json:"required,omitempty"`
	Sensitive      *bool       `json:"sensitive,omitempty"`
	Source         []string    `json:"source,omitempty"`
	Pos            *SourcePos  `json:"pos,omitempty"`
	Aliases        []string    `json:"aliases,omitempty" description:"The list of aliases for the variable name"`
	CloudDataType  string      `json:"cloud_data_type,omitempty" description:"Cloud data type of the variable. eg. resource_group_id, region, vpc_id."`
	LinkStatus     string      `json:"link_status,omitempty" description:"The status of the link"`
	Immutable      *bool       `json:"immutable,omitempty" description:"Is the variable readonly"`
	Hidden         *bool       `json:"hidden,omitempty" description:"If **true**, the variable is not displayed on UI or Command line."`
	AllowedValues  string      `` /* 223-byte string literal not displayed */
	MinValue       string      `json:"min_value,omitempty" description:"The minimum value of the variable"`
	MaxValue       string      `json:"max_value,omitempty" description:"The maximum value of the variable"`
	MinValueLength interface{} `json:"min_length,omitempty" description:"The minimum length of the variable value. Applicable for the string type."`
	MaxValueLength interface{} `json:"max_length,omitempty" description:"The maximum length of the variable value. Applicable for the string type."`
	Matches        string      `json:"matches,omitempty" description:"The regex for the variable value."`

	//Values that are not present in schematics Variable Metadata
	Optional       *bool         `json:"optional,omitempty" description:""`
	Computed       *bool         `json:"computed,omitempty" description:""`
	Elem           interface{}   `json:"elem,omitempty" description:""`
	MaxItems       *int          `json:"max_items,omitempty" description:""`
	MinItems       *int          `json:"min_items,omitempty" description:""`
	Deprecated     string        `json:"deprecated,omitempty" description:""`
	CloudDataRange []interface{} `json:"cloud_data_range,omitempty" description:""`
}

Variable represents a single variable from a Terraform module.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL