schema

package module
v0.0.0-...-287c012 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2023 License: MIT Imports: 2 Imported by: 0

README

tf-schema

A libary to help trim down the verbosity of writing TF providers.

  • Generates a typed Resource and Provider for your plugin
  • Provides combinators for declarative and terse schema

If you want to use v2 Providers, you can use tf-schema/v2!

Usage: Codegen & Setup

You are generally writing a provider to interact with some client library. tf-schema works with go generate to build typed versions of resources and providers that are interchangeable with standard ones from terraform.

Example
imports
import (
	lib "some/url/package/lib"

	tfschema "github.com/hashicorp/terraform-plugin-sdk/helper/schema"
	terraform "github.com/hashicorp/terraform-plugin-sdk/terraform"
	schema "github.com/stanistan/tf-schema"
)
go generate

This is mandatory to generate the types to interact with the client.

//go:generate go run -mod readonly github.com/stanistan/tf-schema/v2/cmd/generate lib.Client some/url/package/lib
Provider
func Provider() *tfschema.Provider {
	// libProvider is a generated struct private to your code
	return (&libProvider{
		Schema: schema.Must(
		// provider settings
		),
		// NOTE: the below return interface objects, not just structs
		DataSourcesMap: map[string]schema.ResourceConvertible{
			"lib_foo": dataSourceLibFoo(),
		},
		// NOTE: the below is now _typed_! to the client/struct type you want to be
		// returning, and _not_ just returning an `interface{}`.
		ConfigureFunc: func(d *tfschema.ResourceData) (*lib.Client, error) {
			return lib.NewClient()
		},
	}).AsProvider()
}
A Datasource/Resource
func dataSourceLibFoo() schema.ResourceConvertible {
	// libResource is a generated struct private to your code
	return &libResource{
		Schema: schema.Must(
			schema.RequiredString("key"),
			schema.OptionalInt("query_page"),
			schema.ComputedString("value"),
		),
		// NOTE: Read is now _typed_ to the _kind_ of `meta` you would be returning
		// from the ConfigureFunc in the provider, and not an interface you have to cast
		// yourself. The validation has already been done.
		Read: func(d *tfschema.ResourceData, c *lib.Client) error {
			// snip...
			data, err := c.GetFoo(d.Get("key").(string))
			// snip...
			return nil
		},
	}
}

Usage: schema Combinators

Option, Named, and Type

An Option is anything that can mutate a schema.Schema (tf).

type Option func(*schema.Schema)

You can create your own types by using the defining Options, and common ones are defined in option.go and common types are defined in types.go using Type.

For example:

// import (
//	schema "github.com/stanistan/tf-schema/v2"
//)

// This is how schema.OptionalString is defined.
//
// It returns a schema.NamedSchemaFactory,
// to which you can provide a name, and other schema.Options.
var optionalString = schema.Type(schema.Optional, schema.String)

var optionalStringDefaultsToBanana = schema.Type(
	schema.Optional, schema.String, schema.Default("banana"))

// and later use this with schema.Schema
schema.Must(
	optionalStringDefaultsToBanana("fruit"),
)

// this is equivalent
schema.Must(
    schema.OptionalString("fruit", schema.Default("banana")),
)
MapMutator

You can create a schema with anything that conforms to MapMutator, and use them in composition.

type Once struct {
    named Named
}

func (s *Once) AddTo(m map[string]*schema.Schema) error {
    name := s.named.Name()
    _, exists := m[name]
    if exists {
        return fmt.Errorf("can't override name %s", name)
    }
    return s.named.AddTo(m)
}

or

type Fruit string

func (s *Fruit) AddTo(m map[string]*schema.Schema) error {
    m["fruit"] = &schema.Schema{ /** stuff */ }
    // this can set multiple keys
    m["not_fruit"] = &schema.Schema{ /** stuff */ }
    return nil
}

Documentation

Overview

tf-schema is a library to help trim down the verbosity of writing terraform providers.

It does this in a couple of ways.

1. By providing primitive combinators to make writing schemas/resources simpler, easier to read and write.

2. By providing a codegen tool so a provider can have its own typed resources, not relying on interface{}, but whatever userland type is desired.

These two features can be used separately or together.

See the README at https://github.com/stanistan/tf-schema for examples.

Index

Constants

This section is empty.

Variables

View Source
var (
	RequiredBool   NamedSchemaFactory = Type(Required, Bool)
	RequiredInt                       = Type(Required, Int)
	RequiredString                    = Type(Required, String)
	ComputedBool                      = Type(Computed, Bool)
	ComputedInt                       = Type(Computed, Int)
	ComputedString                    = Type(Computed, String)
	OptionalBool                      = Type(Optional, Bool)
	OptionalInt                       = Type(Optional, Int)
	OptionalString                    = Type(Optional, String)
)

These are pre-defined type constructors for Named.

Use them like so:

Resource(
	RequiredBool("bool_field_name")
)
View Source
var Resource = Must

Resource is an alias for Must.

This may become the actual thing we call the package.

Functions

func Bool

func Bool(s *schema.Schema)

Bool is an Option that marks the schema to be a Bool.

func Computed

func Computed(s *schema.Schema)

Computed is an Option that marks the schema Computed.

func ConvertResourceMap

func ConvertResourceMap(in map[string]ResourceConverible) map[string]*schema.Resource

ConvertResourceMap converts a map of ResourceConveribles into a map of schema.Resources.

func Int

func Int(s *schema.Schema)

Int is an Option that marks the schema to be an Int.

func List

func List(s *schema.Schema)

List is an Option that marks the schema to be a List.

func Map

func Map(s *schema.Schema)

Map is an Option that marks the schema to be a Map.

func Optional

func Optional(s *schema.Schema)

Optional is an Option that marks the scheam Optional.

func Required

func Required(s *schema.Schema)

Required is an Option that marks the schema Required.

func String

func String(s *schema.Schema)

String is an Option that marks the schema to be a String.

Types

type MapMutator

type MapMutator interface {
	AddTo(map[string]*schema.Schema) error
}

MapMutator is an interface that describes something that can mutate a schema.Schema.

type Named

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

Named holds a schema.Schema with it's name.

func NewNamed

func NewNamed(name string, opts ...Option) *Named

NewNamed creates a Named schema given any Options.

func (*Named) AddTo

func (s *Named) AddTo(m map[string]*schema.Schema) error

AddTo implements the MapMutator interface.

func (*Named) Apply

func (s *Named) Apply(opts ...Option) *Named

Apply applies any Options to the contained schema.Schema.

func (*Named) Name

func (s *Named) Name() string

Name gets us the name of the Named schema.

type NamedSchemaFactory

type NamedSchemaFactory func(string, ...Option) *Named

NamedSchemaFactory is a function that creates a Named.

func Type

func Type(defaultOpts ...Option) NamedSchemaFactory

Type is a constructor of NamedSchemaFactory given default Options.

type Option

type Option func(*schema.Schema)

Option can mutate the schema.

Use this for composition.

func Default

func Default(v interface{}) Option

Default creates an Option marks the schema's Default field.

func Elem

func Elem(r interface{}) Option

Elem creates an Option that sets the Elem field on the schema.

Accepts either schema.Schema, schema.Response, or an Option.

func ListOf

func ListOf(value interface{}) Option

ListOf is an Option that marks the schema to be a List of value.

func MapOf

func MapOf(value interface{}) Option

MapOf is an Option that marks the schema to be a map of value.

func Options

func Options(opts ...Option) Option

Options returns an Option that applies the given options.

type ProviderConvertible

type ProviderConvertible interface {
	AsProvider() *schema.Provider
}

ProviderConvertible is anything that can be converted into a schema.Provider.

type ResourceConverible

type ResourceConverible interface {
	AsResource() *schema.Resource
}

ResourceConverible is anything that can be converted to a schema.Resource.

type Schema

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

Schema is a wrapper for the terraform map[string]*schema.Schema.

This is similar to something you would use if you were creating a resource.

func Must

func Must(fs ...MapMutator) *Schema

Must creates a Schema and panics if there is an error.

func New

func New(fs ...MapMutator) (*Schema, error)

New creates a Schema given any MapMutators and applies them.

func (*Schema) AsResource

func (s *Schema) AsResource() *schema.Resource

AsResource turns this schema into a schema.Resource.

func (*Schema) ComputedList

func (s *Schema) ComputedList(name string) MapMutator

ComputedList wraps this Schema into a MapMutator.

func (*Schema) ComputedMap

func (s *Schema) ComputedMap(name string) MapMutator

ComputedMap wraps this Schema into a MapMutator.

func (*Schema) Get

func (s *Schema) Get() map[string]*schema.Schema

Get extracts the schema map from Schema.

func (*Schema) MustPush

func (s *Schema) MustPush(fs ...MapMutator) *Schema

MustPush adds any MapMutators to a Schema, panics on failure.

func (*Schema) Push

func (s *Schema) Push(fs ...MapMutator) (*Schema, error)

Push adds any MapMutators to a Schema.

Directories

Path Synopsis
cmd
generate
This generates structs and conversion functions so that you can use a "typed" terraform provider.
This generates structs and conversion functions so that you can use a "typed" terraform provider.
v2
tf-schema is a library to help trim down the verbosity of writing terraform providers.
tf-schema is a library to help trim down the verbosity of writing terraform providers.
cmd/generate
This generates structs and conversion functions so that you can use a "typed" terraform provider.
This generates structs and conversion functions so that you can use a "typed" terraform provider.

Jump to

Keyboard shortcuts

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