tfconfig

package
v0.10.1 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2020 License: MIT, MPL-2.0 Imports: 16 Imported by: 0

README

terraform-config-inspect

Note: This package is in-project (sligtly modified) fork of terraform-config-inspect.

This package contains a helper library for extracting high-level metadata about Terraform modules from their source code. It processes only a subset of the information Terraform itself would process, and in return it's able to be broadly compatible with modules written for many different versions of Terraform.

$ go get github.com/hashicorp/terraform-config-inspect
import "github.com/hashicorp/terraform-config-inspect/tfconfig"

/// ...

    module, diags := tfconfig.LoadModule(dir)
    /// ...

There are not yet any formal compatibility promises for the Terraform configuration file format, so this tool can't yet promise to be compatible with unknown future extensions to the format. However, it should be capable of parsing valid configurations targeting Terraform versions between 0.10 and 0.12.

Command Line Tool

The primary way to use this repository is as a Go library, but as a convenience it also contains a CLI tool called terraform-config-inspect, installed automatically by the go get command above, that allows viewing module information in either a Markdown-like format or in JSON format.

$ terraform-config-inspect path/to/module

# Module `path/to/module`

Provider Requirements:
* **null:** (any version)

## Input Variables
* `a` (default `"a default"`)
* `b` (required): The b variable

## Output Values
* `a`
* `b`: I am B

## Managed Resources
* `null_resource.a` from `null`
* `null_resource.b` from `null`
$ terraform-config-inspect --json path/to/module
{
  "path": "path/to/module",
  "variables": {
    "A": {
      "name": "A",
      "default": "A default",
      "pos": {
        "filename": "path/to/module/basics.tf",
        "line": 1
      }
    },
    "B": {
      "name": "B",
      "description": "The B variable",
      "pos": {
        "filename": "path/to/module/basics.tf",
        "line": 5
      }
    }
  },
  "outputs": {
    "A": {
      "name": "A",
      "pos": {
        "filename": "path/to/module/basics.tf",
        "line": 9
      }
    },
    "B": {
      "name": "B",
      "description": "I am B",
      "pos": {
        "filename": "path/to/module/basics.tf",
        "line": 13
      }
    }
  },
  "required_providers": {
    "null": []
  },
  "managed_resources": {
    "null_resource.A": {
      "mode": "managed",
      "type": "null_resource",
      "name": "A",
      "provider": {
        "name": "null"
      },
      "pos": {
        "filename": "path/to/module/basics.tf",
        "line": 18
      }
    },
    "null_resource.B": {
      "mode": "managed",
      "type": "null_resource",
      "name": "B",
      "provider": {
        "name": "null"
      },
      "pos": {
        "filename": "path/to/module/basics.tf",
        "line": 19
      }
    }
  },
  "data_resources": {},
  "module_calls": {}
}

Contributing

This library and tool are intentionally focused on only extracting simple top-level metadata about a single Terraform module. This is to reduce the maintenance burden of keeping this codebase synchronized with changes to Terraform itself: the features extracted by this package are unlikely to change significantly in future versions.

For that reason, we cannot accept external PRs for this codebase that add support for additional Terraform language features.

We would be happy to review PRs to fix bugs in existing functionality or to improve the usability of the Go package API, however. We will be hesitant about any breaking changes to the API, since this library is used by a number of existing tools and systems.

To work on this codebase you will need a recent version of Go installed. Please ensure all files match the formatting rules applied by go fmt and that all unit tests are passing.

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.

Important Note: This is in-project fork of https://github.com/hashicorp/terraform-config-inspect and by no means should be used outside of this project. The reason for bringing the project over internally was that terraform-config-inspect is considered feature-complete and new enhancement pull requests are not accepted and we've decided to bring the project over internally and apply one change that we really depended on in terraform-docs.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

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 LoadModule

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

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

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 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"`

	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.

type ModuleCall

type ModuleCall struct {
	Name    string `json:"name"`
	Source  string `json:"source"`
	Version string `json:"version,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"`

	Pos SourcePos `json:"pos"`
}

Output represents a single output from a Terraform module.

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"`
}

type Resource

type Resource struct {
	Mode ResourceMode `json:"mode"`
	Type string       `json:"type"`
	Name string       `json:"name"`

	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"`
	Required bool        `json:"required"`

	Pos SourcePos `json:"pos"`
}

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