tfstate

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 26 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package tfstate は Terraform の state (tfstate) を各種 backend から読み出し、 アドレス指定で値を取り出す機能を提供します。

構成:

  • Backend: tfstate の生バイト列を取得する抽象 (s3 / local)。新しい backend は BackendFactory を 1 つ実装して Factories に登録するだけで追加できます。
  • State: tfstate (format version 4) のパース結果と Lookup。
  • Resolver: tazuna.yaml の spec.tfstates[] を名前で引き、state の読み込みを ソースごとに 1 回へキャッシュします。

Index

Constants

View Source
const (
	TemplateFuncName     = "tfstate"
	TemplateFuncNameJSON = "tfstateJSON"
)

Template 関数名。pkg/tmpl の stub と同じ名前でなければなりません。

View Source
const SupportedStateVersion = 4

SupportedStateVersion は対応している tfstate の format version です。 Terraform 0.12 以降 (OpenTofu を含む) はすべて version 4 を出力します。

Variables

This section is empty.

Functions

func FormatValue

func FormatValue(v any) (string, error)

FormatValue は tfstate の値を文字列に変換します。GenesisSecret の値や template 関数 `tfstate` の出力に使います。

  • string はそのまま
  • number / bool は文字列化 (整数は指数表記にならない)
  • list / object は JSON
  • null はエラー

func S3ObjectKey

func S3ObjectKey(c *v1.TFStateS3Backend) string

S3ObjectKey は workspace を考慮した実際のオブジェクトキーを返します。 terraform の s3 backend と同じく、workspace が空または "default" なら key を そのまま使い、それ以外は `<workspaceKeyPrefix>/<workspace>/<key>` になります。

Types

type Address

type Address struct {
	// Output は output 参照のときの output 名です。resource 参照のときは空です。
	Output string
	// Module は resource が属する module のアドレスです (例: `module.vpc`,
	// `module.app["web"]`)。root module の resource のときは空です。tfstate の
	// resources[].module と同じ書式です。
	Module string
	// Mode は resource の mode (managed / data) です。
	Mode ResourceMode
	// Type は resource type (例: aws_vpc) です。
	Type string
	// Name は resource 名です。
	Name string
	// Index は resource instance の添字 (count なら int64、for_each なら string) です。
	// 添字なしのときは nil です。
	Index any
	// Path は output の値 / resource の attributes の内側を辿る要素列です。
	Path []Step
	// contains filtered or unexported fields
}

Address は tfstate 内の値を指すパース済みアドレスです。

対応している書式:

output.<name>[<path>]
[module.<name>[<index>].]...[data.]<type>.<name>[<index>].<attribute>[<path>]

<path> は `.key` / `[0]` / `["key"]` の繰り返しで、output の値や resource の attributes の内側を辿ります。

func ParseAddress

func ParseAddress(s string) (Address, error)

ParseAddress はアドレス文字列をパースします。

func (Address) IsOutput

func (a Address) IsOutput() bool

IsOutput は output 参照かどうかを返します。

func (Address) String

func (a Address) String() string

String はパース前のアドレス文字列を返します。

type Backend

type Backend interface {
	// Read は tfstate の JSON をそのまま返します。
	Read(ctx context.Context) ([]byte, error)
	// LogAttrs はログやエラーメッセージに出す「どこを読んでいるか」の情報を返します。
	// 認証情報や state の中身は含めてはいけません。
	LogAttrs() []slog.Attr
}

Backend は tfstate の生バイト列を読み出す抽象です。

新しい terraform backend (gcs / azurerm / http など) に対応するには、 この interface を実装した型と、それを生成する BackendFactory を用意して DefaultFactories (または NewResolver に渡す Factories) に登録します。

func NewLocalBackend

func NewLocalBackend(cfg v1.TFStateBackend, baseDir string) (Backend, error)

NewLocalBackend は BackendFactory です。local.path の相対パスは baseDir から解決します。

func NewS3Backend

func NewS3Backend(cfg v1.TFStateBackend, _ string) (Backend, error)

NewS3Backend は BackendFactory です。AWS の設定や認証情報のロードは Read まで遅延します。

type BackendFactory

type BackendFactory func(cfg v1.TFStateBackend, baseDir string) (Backend, error)

BackendFactory は TFStateBackend の設定から Backend を生成します。 baseDir は tazuna.yaml のディレクトリで、相対パスの解決に使います。

Factory の中ではネットワークアクセスや認証情報のロードを行わず、設定の検査と 保持だけを行ってください。実際の I/O は Backend.Read まで遅延させることで、 tfstate を参照しない実行 (tazuna check 等) で backend に触れずに済みます。

type Factories

type Factories map[v1.TFStateBackendType]BackendFactory

Factories は backend type から BackendFactory への対応表です。

func DefaultFactories

func DefaultFactories() Factories

DefaultFactories は組み込みの backend 一覧を返します。

func (Factories) New

func (f Factories) New(cfg v1.TFStateBackend, baseDir string) (Backend, error)

New は cfg.Type に対応する Factory で Backend を生成します。

func (Factories) Supports

func (f Factories) Supports(t v1.TFStateBackendType) bool

Supports は backend type が登録済みかを返します。

type Instance

type Instance struct {
	// IndexKey は count なら int64、for_each なら string、どちらでもなければ nil です。
	IndexKey   any
	Attributes map[string]any
}

Instance は resource の 1 インスタンスです。

type LocalBackend

type LocalBackend struct {
	// contains filtered or unexported fields
}

LocalBackend はローカルファイルの tfstate を読む Backend です。 terraform の `backend "local"` (および backend 未指定時の terraform.tfstate) に相当します。

func (*LocalBackend) LogAttrs

func (b *LocalBackend) LogAttrs() []slog.Attr

LogAttrs implements Backend.

func (*LocalBackend) Read

func (b *LocalBackend) Read(_ context.Context) ([]byte, error)

Read implements Backend.

type Lookuper

type Lookuper interface {
	Lookup(ctx context.Context, sourceName, address string) (any, error)
}

Lookuper は tfstate から値を引く操作だけを切り出した interface です。 manager / Secret provider はこの interface に依存することで、テストで fake を 差し込めます。*Resolver が実装します (nil の *Resolver でも未宣言エラーを返して安全に動作します)。

type Output

type Output struct {
	Value     any
	Sensitive bool
}

Output は tfstate の outputs の 1 エントリです。

type Resolver

type Resolver struct {
	// contains filtered or unexported fields
}

Resolver は spec.tfstates[] で宣言された名前付き tfstate ソースを解決します。

state は各ソースが初めて参照されたときに 1 回だけ backend から読み込まれ、 以降は同じ Resolver 内でキャッシュされます。読み込みはソース単位で排他される ため、dependsOn による並列 apply から同時に参照されても安全です。 読み込みに失敗した場合もその結果 (エラー) がキャッシュされ、同じ実行中に 何度も backend へアクセスし直すことはありません。

ログには「どのソースをどこから読んだか」だけを出し、state 内の値は一切出力しません。

func NewResolver

func NewResolver(logger *slog.Logger, sources []v1.TFStateSource, baseDir string, factories Factories) (*Resolver, error)

NewResolver は spec.tfstates[] から Resolver を構築します。backend の生成 (設定値の検査) のみを行い、state の読み込みは Lookup まで遅延します。 factories が nil の場合は DefaultFactories() を使います。logger が nil の場合はログを破棄します。

func (*Resolver) Has

func (r *Resolver) Has(name string) bool

Has は name のソースが宣言されているかを返します。nil の Resolver では常に false です。

func (*Resolver) Lookup

func (r *Resolver) Lookup(ctx context.Context, sourceName, address string) (any, error)

Lookup は source の tfstate から address の値を返します。 戻り値は string / bool / int64 / float64 / []any / map[string]any / nil のいずれかです。

func (*Resolver) LookupString

func (r *Resolver) LookupString(ctx context.Context, sourceName, address string) (string, error)

LookupString は Lookup した値を FormatValue で文字列化して返します。

func (*Resolver) State

func (r *Resolver) State(ctx context.Context, sourceName string) (*State, error)

State は source の tfstate を (必要なら backend から読み込んで) 返します。

func (*Resolver) TemplateFuncs

func (r *Resolver) TemplateFuncs(ctx context.Context) template.FuncMap

TemplateFuncs は tazuna.yaml / include ファイルの描画で使う template 関数を返します。

  • {{ tfstate "<source>" "<address>" }}: 値を FormatValue で文字列化したもの
  • {{ tfstateJSON "<source>" "<address>" }}: 値の JSON 表現 (YAML の flow 値として埋め込める)

type Resource

type Resource struct {
	Module    string
	Mode      ResourceMode
	Type      string
	Name      string
	Instances []Instance
}

Resource は tfstate の resources の 1 エントリです。

type ResourceMode

type ResourceMode string

ResourceMode は managed resource か data source かを表します。

const (
	// ResourceModeManaged は通常の resource ブロックです。
	ResourceModeManaged ResourceMode = "managed"
	// ResourceModeData は data ブロックです。
	ResourceModeData ResourceMode = "data"
)

type S3Backend

type S3Backend struct {
	// contains filtered or unexported fields
}

S3Backend は S3 (および S3 互換ストレージ) 上の tfstate を読む Backend です。 terraform の `backend "s3"` と同じ bucket / key / workspace の規則でオブジェクトを 特定します。認証情報は AWS SDK 標準の credential chain で解決します。

func (*S3Backend) LogAttrs

func (b *S3Backend) LogAttrs() []slog.Attr

LogAttrs implements Backend.

func (*S3Backend) Read

func (b *S3Backend) Read(ctx context.Context) ([]byte, error)

Read implements Backend.

type State

type State struct {
	Version          int
	TerraformVersion string
	Serial           int64
	Lineage          string
	Outputs          map[string]Output
	Resources        []Resource
}

State はパース済みの tfstate です。

func Parse

func Parse(data []byte) (*State, error)

Parse は tfstate の JSON をパースします。format version 4 以外はエラーです。

func (*State) Lookup

func (s *State) Lookup(addr Address) (any, error)

Lookup は addr が指す値を返します。見つからない場合は、候補 (output 名や resource アドレス) を含むエラーを返します。エラーメッセージには値そのものは 含めません。

func (*State) LookupString

func (s *State) LookupString(address string) (any, error)

LookupString は Address をパースして Lookup します。

type Step

type Step struct {
	// Name は `.foo` 形式の要素名です。Index 要素のときは空文字列です。
	Name string
	// Index は `[...]` 形式の添字です。Name 要素のときは nil です。
	// 整数添字なら int64、文字列添字なら string が入ります。
	Index any
}

Step はアドレスを構成する 1 要素です。`.name` 形式の Name か、`[0]` / `["key"]` 形式の Index のいずれかを表します。

func (Step) IsIndex

func (s Step) IsIndex() bool

IsIndex は Step が `[...]` 形式の添字かどうかを返します。

func (Step) String

func (s Step) String() string

Jump to

Keyboard shortcuts

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