api

package
v0.0.0-...-1a28a91 Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2024 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Copyright 2024 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

View Source
const DEFAULT_DELETE_TIMEOUT_MINUTES = 20
View Source
const DEFAULT_INSERT_TIMEOUT_MINUTES = 20

Default timeout for all operation types is 20, the Terraform default (https://www.terraform.io/plugin/sdkv2/resources/retries-and-customizable-timeouts) minutes. This can be overridden for each resource.

View Source
const DEFAULT_UPDATE_TIMEOUT_MINUTES = 20
View Source
const MAX_NAME = 20

Variables

This section is empty.

Functions

func CompareByName

func CompareByName(a, b *Type) int

func Compile

func Compile(yamlPath string, obj interface{}, overrideDir string)

func DeepMerge

func DeepMerge(arr1, arr2 reflect.Value)

func ImportIdFormats

func ImportIdFormats(importFormat, identity []string, baseUrl string) []string

Returns a list of import id formats for a given resource. If an id contains provider-default values, this fn will return formats both including and omitting the value.

If a resource has an explicit import_format value set, that will be the base import url used. Next, the values of `identity` will be used to construct a URL. Finally, `{{name}}` will be used by default.

For instance, if the resource base url is:

projects/{{project}}/global/networks

It returns 3 formats: a) self_link: projects/{{project}}/global/networks/{{name}} b) short id: {{project}}/{{name}} c) short id w/o defaults: {{name}}

func Merge

func Merge(self, otherObj reflect.Value)

Types

type Async

type Async struct {
	// Describes an operation
	Operation *Operation

	// The list of methods where operations are used.
	Actions []string

	// Describes an operation, one of "OpAsync", "PollAsync"
	Type string

	OpAsync `yaml:",inline"`

	PollAsync `yaml:",inline"`
}

Base class from which other Async classes can inherit.

func NewAsync

func NewAsync() *Async

func (Async) Allow

func (a Async) Allow(method string) bool

func (Async) IsA

func (a Async) IsA(asyncType string) bool

func (*Async) UnmarshalYAML

func (a *Async) UnmarshalYAML(unmarshal func(any) error) error

func (*Async) Validate

func (a *Async) Validate()

type OpAsync

type OpAsync struct {
	Result OpAsyncResult

	Status OpAsyncStatus `yaml:"status,omitempty"`

	Error OpAsyncError

	// If true, include project as an argument to OperationWaitTime.
	// It is intended for resources that calculate project/region from a selflink field
	IncludeProject bool `yaml:"include_project"`
}

Represents an asynchronous operation definition

type OpAsyncError

type OpAsyncError struct {
	google.YamlValidator `yaml:"-"`

	Path string `yaml:"path,omitempty"`

	Message string `yaml:"message,omitempty"`
}

Provides information on how to retrieve errors of the executed operations

type OpAsyncOperation

type OpAsyncOperation struct {
	Kind string `yaml:"kind,omitempty"`

	Path string `yaml:"path,omitempty"`

	BaseUrl string `yaml:"base_url,omitempty"`

	WaitMs int `yaml:"wait_ms,omitempty"`

	// Use this if the resource includes the full operation url.
	FullUrl string `yaml:"full_url,omitempty"`
}

type OpAsyncResult

type OpAsyncResult struct {
	ResourceInsideResponse bool `yaml:"resource_inside_response,omitempty"`

	Path string `yaml:"path,omitempty"`
}

Represents the results of an Operation request

type OpAsyncStatus

type OpAsyncStatus struct {
	Path string `yaml:"path,omitempty"`

	Complete bool `yaml:"complete,omitempty"`

	Allowed []bool `yaml:"allowed,omitempty"`
}

Provides information to parse the result response to check operation status

type Operation

type Operation struct {
	Timeouts         *Timeouts
	OpAsyncOperation `yaml:",inline"`
}

The main implementation of Operation, corresponding to common GCP Operation resources.

func NewOperation

func NewOperation() *Operation

type PollAsync

type PollAsync struct {

	// Function to call for checking the Poll response for
	// creating and updating a resource
	CheckResponseFuncExistence string `yaml:"check_response_func_existence,omitempty"`

	// Function to call for checking the Poll response for
	// deleting a resource
	CheckResponseFuncAbsence string `yaml:"check_response_func_absence,omitempty"`

	// If true, will suppress errors from polling and default to the
	// result of the final Read()
	SuppressError bool `yaml:"suppress_error,omitempty"`

	// Number of times the desired state has to occur continuously
	// during polling before returning a success
	TargetOccurrences int `yaml:"target_occurrences,omitempty"`
}

Async implementation for polling in Terraform

type Product

type Product struct {
	// The name of the product's API capitalised in the appropriate places.
	// This isn't just the API name because it doesn't meaningfully separate
	// words in the api name - "accesscontextmanager" vs "AccessContextManager"
	// Example inputs: "Compute", "AccessContextManager"
	Name string

	// original value of :name before the provider override happens
	// same as :name if not overridden in provider
	ApiName string `yaml:"api_name,omitempty"`

	// Display Name: The full name of the GCP product; eg "Cloud Bigtable"
	DisplayName string `yaml:"display_name,omitempty"`

	Objects []*Resource `yaml:"objects,omitempty"`

	// The list of permission scopes available for the service
	// For example: `https://www.googleapis.com/auth/compute`
	Scopes []string

	// The API versions of this product
	Versions []*product.Version

	// The base URL for the service API endpoint
	// For example: `https://www.googleapis.com/compute/v1/`
	BaseUrl string `yaml:"base_url,omitempty"`

	// The validator "relative URI" of a resource, relative to the product
	// base URL. Specific to defining the resource as a CAI asset.
	CaiBaseUrl string

	// A function reference designed for the rare case where you
	// need to use retries in operation calls. Used for the service api
	// as it enables itself (self referential) and can result in occasional
	// failures on operation_get. see github.com/hashicorp/terraform-provider-google/issues/9489
	OperationRetry string `yaml:"operation_retry,omitempty"`

	Async *Async `yaml:"async,omitempty"`

	LegacyName string `yaml:"legacy_name,omitempty"`

	ClientName string `yaml:"client_name,omitempty"`
}

Represents a product to be managed

func (*Product) ExistsAtVersion

func (p *Product) ExistsAtVersion(name string) bool

func (*Product) ExistsAtVersionOrLower

func (p *Product) ExistsAtVersionOrLower(name string) bool

func (Product) Lineage

func (p Product) Lineage() string

Prints a dot notation path to where the field is nested within the parent object when called on a property. eg: parent.meta.label.foo Redefined on Product to terminate the calls up the parent chain.

func (*Product) ServiceBaseUrl

func (p *Product) ServiceBaseUrl() string

func (*Product) ServiceName

func (p *Product) ServiceName() string

func (*Product) ServiceVersion

func (p *Product) ServiceVersion() string

func (*Product) SetApiName

func (p *Product) SetApiName()

func (*Product) SetDisplayName

func (p *Product) SetDisplayName()

The product full name is the "display name" in string form intended for users to read in documentation; "Google Compute Engine", "Cloud Bigtable"

func (*Product) SetPropertiesBasedOnVersion

func (p *Product) SetPropertiesBasedOnVersion(version *product.Version)

func (*Product) TerraformName

func (p *Product) TerraformName() string

func (*Product) UnmarshalYAML

func (p *Product) UnmarshalYAML(unmarshal func(any) error) error

func (*Product) Validate

func (p *Product) Validate()

func (Product) VersionObjOrClosest

func (p Product) VersionObjOrClosest(name string) *product.Version

Get the version of the object specified by the version given if present Or else fall back to the closest version in the chain defined by product.ORDER

type Resource

type Resource struct {
	Name string

	// original value of :name before the provider override happens
	// same as :name if not overridden in provider
	ApiName string `yaml:"api_name,omitempty"`

	// [Required] A description of the resource that's surfaced in provider
	// documentation.
	Description string

	// [Required] Reference links provided in
	// downstream documentation. Expected to follow the format as follows:
	//
	//	references:
	//  	guides:
	//			'Guide name': 'official_documentation_url'
	//		api: 'rest_api_reference_url/version'
	//
	References resource.ReferenceLinks `yaml:"references,omitempty"`

	// [Required] The GCP "relative URI" of a resource, relative to the product
	// base URL. It can often be inferred from the `create` path.
	BaseUrl string `yaml:"base_url,omitempty"`

	// ====================
	// Common Configuration
	// ====================
	//
	// [Optional] The minimum API version this resource is in. Defaults to ga.
	MinVersion string `yaml:"min_version,omitempty"`

	// [Optional] If set to true, don't generate the resource.
	Exclude bool `yaml:"exclude,omitempty"`

	// [Optional] If set to true, the resource is not able to be updated.
	Immutable bool `yaml:"immutable,omitempty"`

	// [Optional] If set to true, this resource uses an update mask to perform
	// updates. This is typical of newer GCP APIs.
	UpdateMask bool `yaml:"update_mask,omitempty"`

	// [Optional] If set to true, the object has a `self_link` field. This is
	// typical of older GCP APIs.
	HasSelfLink bool `yaml:"has_self_link,omitempty"`

	// [Optional] The validator "relative URI" of a resource, relative to the product
	// base URL. Specific to defining the resource as a CAI asset.
	CaiBaseUrl string `yaml:"cai_base_url,omitempty"`

	// ====================
	// URL / HTTP Configuration
	// ====================
	//
	// [Optional] The "identity" URL of the resource. Defaults to:
	// * base_url when the create_verb is POST
	// * self_link when the create_verb is PUT  or PATCH
	SelfLink string `yaml:"self_link,omitempty"`

	// [Optional] The URL used to creating the resource. Defaults to:
	// * collection url when the create_verb is POST
	// * self_link when the create_verb is PUT or PATCH
	CreateUrl string `yaml:"create_url,omitempty"`

	// [Optional] The URL used to delete the resource. Defaults to the self
	// link.
	DeleteUrl string `yaml:"delete_url,omitempty"`

	// [Optional] The URL used to update the resource. Defaults to the self
	// link.
	UpdateUrl string `yaml:"update_url,omitempty"`
	// [Optional] The HTTP verb used during create. Defaults to POST.
	CreateVerb string `yaml:"create_verb,omitempty"`

	// [Optional] The HTTP verb used during read. Defaults to GET.
	ReadVerb string `yaml:"read_verb,omitempty"`

	// [Optional] The HTTP verb used during update. Defaults to PUT.
	UpdateVerb string `yaml:"update_verb,omitempty"`

	// [Optional] The HTTP verb used during delete. Defaults to DELETE.
	DeleteVerb string `yaml:"delete_verb,omitempty"`

	// [Optional] Additional Query Parameters to append to GET. Defaults to ""
	ReadQueryParams string `yaml:"read_query_params,omitempty"`

	// ====================
	// Collection / Identity URL Configuration
	// ====================
	//
	// [Optional] This is the name of the list of items
	// within the collection (list) json. Will default to the
	// camelcase plural name of the resource.
	CollectionUrlKey string `yaml:"collection_url_key,omitempty"`

	// [Optional] An ordered list of names of parameters that uniquely identify
	// the resource.
	// Generally, it's safe to leave empty, in which case it defaults to `name`.
	// Other values are normally useful in cases where an object has a parent
	// and is identified by some non-name value, such as an ip+port pair.
	// If you're writing a fine-grained resource (eg with nested_query) a value
	// must be set.
	Identity []string `yaml:"identity,omitempty"`

	// [Optional] (Api::Resource::NestedQuery) This is useful in case you need
	// to change the query made for GET requests only. In particular, this is
	// often used to extract an object from a parent object or a collection.
	// Note that if both nested_query and custom_code.decoder are provided,
	// the decoder will be included within the code handling the nested query.
	NestedQuery *resource.NestedQuery `yaml:"nested_query,omitempty"`

	// ====================
	// IAM Configuration
	// ====================
	//
	// [Optional] (Api::Resource::IamPolicy) Configuration of a resource's
	// resource-specific IAM Policy.
	IamPolicy *resource.IamPolicy `yaml:"iam_policy,omitempty"`

	// [Optional] If set to true, don't generate the resource itself; only
	// generate the IAM policy.
	// TODO rewrite: rename?
	ExcludeResource bool `yaml:"exclude_resource,omitempty"`

	// [Optional] GCP kind, e.g. `compute//disk`
	Kind string `yaml:"kind,omitempty"`

	// [Optional] If set to true, indicates that a resource is not configurable
	// such as GCP regions.
	Readonly bool `yaml:"readonly,omitempty"`

	// ====================
	// Terraform Overrides
	// ====================
	// [Optional] If non-empty, overrides the full filename prefix
	// i.e. google/resource_product_{{resource_filename_override}}.go
	// i.e. google/resource_product_{{resource_filename_override}}_test.go
	FilenameOverride string `yaml:"filename_override,omitempty"`

	// If non-empty, overrides the full given resource name.
	// i.e. 'google_project' for resourcemanager.Project
	// Use Provider::Terraform::Config.legacy_name to override just
	// product name.
	// Note: This should not be used for vanity names for new products.
	// This was added to handle preexisting handwritten resources that
	// don't match the natural generated name exactly, and to support
	// services with a mix of handwritten and generated resources.
	LegacyName string `yaml:"legacy_name,omitempty"`

	// The Terraform resource id format used when calling //setId(...).
	// For instance, `{{name}}` means the id will be the resource name.
	IdFormat string `yaml:"id_format,omitempty"`

	// Override attribute used to handwrite the formats for generating regex strings
	// that match templated values to a self_link when importing, only necessary when
	// a resource is not adequately covered by the standard provider generated options.
	// Leading a token with `%`
	// i.e. {{%parent}}/resource/{{resource}}
	// will allow that token to hold multiple /'s.
	//
	// Expected to be formatted as follows:
	//
	//	import_format:
	//		- example_import_one
	//		- example_import_two
	//
	ImportFormat []string `yaml:"import_format,omitempty"`

	CustomCode resource.CustomCode `yaml:"custom_code,omitempty"`

	Docs resource.Docs `yaml:"docs,omitempty"`

	// This block inserts entries into the customdiff.All() block in the
	// resource schema -- the code for these custom diff functions must
	// be included in the resource constants or come from tpgresource
	CustomDiff []string `yaml:"custom_diff,omitempty"`

	// Lock name for a mutex to prevent concurrent API calls for a given
	// resource.
	Mutex string `yaml:"mutex,omitempty"`

	// Examples in documentation. Backed by generated tests, and have
	// corresponding OiCS walkthroughs.
	Examples []resource.Examples

	// If true, generates product operation handling logic.
	AutogenAsync bool `yaml:"autogen_async,omitempty"`

	// If true, resource is not importable
	ExcludeImport bool `yaml:"exclude_import,omitempty"`

	// If true, exclude resource from Terraform Validator
	// (i.e. terraform-provider-conversion)
	ExcludeTgc bool `yaml:"exclude_tgc,omitempty"`

	// If true, skip sweeper generation for this resource
	ExcludeSweeper bool `yaml:"exclude_sweeper,omitempty"`

	// Override sweeper settings
	Sweeper resource.Sweeper `yaml:"sweeper,omitempty"`

	Timeouts *Timeouts `yaml:"timeouts,omitempty"`

	// An array of function names that determine whether an error is retryable.
	ErrorRetryPredicates []string `yaml:"error_retry_predicates,omitempty"`

	// An array of function names that determine whether an error is not retryable.
	ErrorAbortPredicates []string `yaml:"error_abort_predicates,omitempty"`

	// Optional attributes for declaring a resource's current version and generating
	// state_upgrader code to the output .go file from files stored at
	// mmv1/templates/terraform/state_migrations/
	// used for maintaining state stability with resources first provisioned on older api versions.
	SchemaVersion int `yaml:"schema_version,omitempty"`

	// From this schema version on, state_upgrader code is generated for the resource.
	// When unset, state_upgrade_base_schema_version defauts to 0.
	// Normally, it is not needed to be set.
	StateUpgradeBaseSchemaVersion int `yaml:"state_upgrade_base_schema_version,omitempty"`

	StateUpgraders bool `yaml:"state_upgraders,omitempty"`

	// Do not apply the default attribution label
	ExcludeAttributionLabel bool `yaml:"exclude_attribution_label,omitempty"`

	// This block inserts the named function and its attribute into the
	// resource schema -- the code for the migrate_state function must
	// be included in the resource constants or come from tpgresource
	// included for backwards compatibility as an older state migration method
	// and should not be used for new resources.
	MigrateState string `yaml:"migrate_state,omitempty"`

	// Set to true for resources that are unable to be deleted, such as KMS keyrings or project
	// level resources such as firebase project
	ExcludeDelete bool `yaml:"exclude_delete,omitempty"`

	// Set to true for resources that are unable to be read from the API, such as
	// public ca external account keys
	ExcludeRead bool `yaml:"exclude_read,omitempty"`

	// Set to true for resources that wish to disable automatic generation of default provider
	// value customdiff functions
	// TODO rewrite: 1 instance used
	ExcludeDefaultCdiff bool `yaml:"exclude_default_cdiff,omitempty"`

	// This enables resources that get their project via a reference to a different resource
	// instead of a project field to use User Project Overrides
	SupportsIndirectUserProjectOverride bool `yaml:"supports_indirect_user_project_override,omitempty"`

	// If true, the resource's project field can be specified as either the short form project
	// id or the long form projects/project-id. The extra projects/ string will be removed from
	// urls and ids. This should only be used for resources that previously supported long form
	// project ids for backwards compatibility.
	LegacyLongFormProject bool `yaml:"legacy_long_form_project,omitempty"`

	// Function to transform a read error so that handleNotFound recognises
	// it as a 404. This should be added as a handwritten fn that takes in
	// an error and returns one.
	ReadErrorTransform string `yaml:"read_error_transform,omitempty"`

	// If true, resources that failed creation will be marked as tainted. As a consequence
	// these resources will be deleted and recreated on the next apply call. This pattern
	// is preferred over deleting the resource directly in post_create_failure hooks.
	TaintResourceOnFailedCreate bool `yaml:"taint_resource_on_failed_create,omitempty"`

	// Add a deprecation message for a resource that's been deprecated in the API.
	DeprecationMessage string `yaml:"deprecation_message,omitempty"`

	Async *Async

	// Tag autogen resources so that we can track them. In the future this will
	// control if a resource is continuously generated from public OpenAPI docs
	AutogenStatus string `yaml:"autogen_status"`

	// Virtual fields are Terraform-only fields that control Terraform's
	// behaviour. They don't map to underlying API fields (although they
	// may map to parameters), and will require custom code to be added to
	// control them.
	//
	// Virtual fields are similar to url_param_only fields in that they create
	// a schema entry which is not read from or submitted to the API. However
	// virtual fields are meant to provide toggles for Terraform-specific behavior in a resource
	// (eg: delete_contents_on_destroy) whereas url_param_only fields _should_
	// be used for url construction.
	//
	// Both are resource level fields and do not make sense, and are also not
	// supported, for nested fields. Nested fields that shouldn't be included
	// in API payloads are better handled with custom expand/encoder logic.
	VirtualFields []*Type `yaml:"virtual_fields,omitempty"`

	Parameters []*Type

	Properties []*Type

	ProductMetadata *Product `yaml:"-"`

	// The version name provided by the user through CI
	TargetVersionName string `yaml:"-"`

	// The compiler to generate the downstream files, for example "terraformgoogleconversion-codegen".
	Compiler string `yaml:"-"`

	ApiResourceTypeKind string `yaml:"api_resource_type_kind,omitempty"`

	ImportPath string `yaml:"-"`
}

func (*Resource) AddLabelsRelatedFields

func (r *Resource) AddLabelsRelatedFields(props []*Type, parent *Type) []*Type

func (Resource) AllNestedProperties

func (r Resource) AllNestedProperties(props []*Type) []*Type

func (Resource) AllProperties

func (r Resource) AllProperties() []*Type

Returns all properties and parameters including the ones that are excluded. This is used for PropertyOverride validation

func (Resource) AllPropertiesInVersion

func (r Resource) AllPropertiesInVersion() []*Type

func (Resource) AllUserProperties

func (r Resource) AllUserProperties() []*Type

Return the user-facing properties in client tools; this ends up meaning both properties and parameters but without any that are excluded due to version mismatches or manual exclusion

func (Resource) CaiApiVersion

func (r Resource) CaiApiVersion(productBackendName, caiProductBaseUrl string) string

Gets the Cai API version

func (Resource) CaiAssetNameTemplate

func (r Resource) CaiAssetNameTemplate(productBackendName string) string

Gets the Cai asset name template, which doesn't include version For example: //monitoring.googleapis.com/projects/{{project}}/services/{{service_id}}

func (Resource) CaiIamAssetNameTemplate

func (r Resource) CaiIamAssetNameTemplate(productBackendName string) string

Gets the Cai IAM asset name template For example: //monitoring.googleapis.com/v3/projects/{{project}}/services/{{service_id}}

func (Resource) CaiIamResourceParams

func (r Resource) CaiIamResourceParams() []string

For example: the uri "projects/{{project}}/schemas/{{name}}" The paramerter is "schema" as "project" is not returned.

func (Resource) CaiProductBackendName

func (r Resource) CaiProductBackendName(caiProductBaseUrl string) string

Returns the Cai product backend name from the version base url base_url: https://accessapproval.googleapis.com/v1/ -> accessapproval

func (Resource) CaiProductBaseUrl

func (r Resource) CaiProductBaseUrl() string

func (Resource) ClientNamePascal

func (r Resource) ClientNamePascal() string

Handwritten TF Operation objects will be shaped like accessContextManager while the Google Go Client will have a name like accesscontextmanager

func (Resource) CollectionUrl

func (r Resource) CollectionUrl() string

func (Resource) CreateUri

func (r Resource) CreateUri() string

func (Resource) CustomTemplate

func (r Resource) CustomTemplate(templatePath string, appendNewline bool) string

func (Resource) CustomUpdatePropertiesByKey

func (r Resource) CustomUpdatePropertiesByKey(properties []*Type, updateUrl string, updateId string, fingerprintName string, updateVerb string) []*Type

func (Resource) DeleteUri

func (r Resource) DeleteUri() string

func (Resource) DeleteUrlTemplate

func (r Resource) DeleteUrlTemplate() string

func (Resource) ExamplePrimaryResourceId

func (r Resource) ExamplePrimaryResourceId() string

func (*Resource) ExcludeIfNotInVersion

func (r *Resource) ExcludeIfNotInVersion(version *product.Version)

Recurses through all nested properties and parameters and changes their 'exclude' instance variable if the property is at a version below the one that is passed in.

func (Resource) ExtractIdentifiers

func (r Resource) ExtractIdentifiers(url string) []string

For example, for the url "projects/{{project}}/schemas/{{schema}}", the identifiers are "project", "schema".

func (Resource) FieldSpecificUpdateMethods

func (r Resource) FieldSpecificUpdateMethods() bool

func (Resource) FirstIamImportIdFormat

func (r Resource) FirstIamImportIdFormat() string

For example, projects/{{project}}/schemas/{{schema}}

func (Resource) FirstIdentityProp

func (r Resource) FirstIdentityProp() *Type

func (Resource) FirstTestExample

func (r Resource) FirstTestExample() resource.Examples

Since most resources define a "basic" config as their first example, we can reuse that config to create a resource to test IAM resources with.

func (Resource) FlattenedProperties

func (r Resource) FlattenedProperties() []*Type

func (Resource) FormatDocDescription

func (r Resource) FormatDocDescription(desc string, indent bool) string

Formats whitespace in the style of the old Ruby generator's descriptions in documentation

func (Resource) GetAsync

func (r Resource) GetAsync() *Async

Return the product-level async object, or the resource-specific one if one exists.

func (Resource) GetIdFormat

func (r Resource) GetIdFormat() string

Returns the id format of an object, or self_link_uri if none is explicitly defined We prefer the long name of a resource as the id so that users can reference resources in a standard way, and most APIs accept short name, long name or self_link

func (Resource) GetIdentity

func (r Resource) GetIdentity() []*Type

Return the resource-specific identity properties, or a best guess of the `name` value for the resource.

func (Resource) GetPropertyUpdateMasksGroupKeys

func (r Resource) GetPropertyUpdateMasksGroupKeys(properties []*Type) []string

func (Resource) GetPropertyUpdateMasksGroups

func (r Resource) GetPropertyUpdateMasksGroups(properties []*Type, maskPrefix string) map[string][]string

func (Resource) GetTimeouts

func (r Resource) GetTimeouts() *Timeouts

In order of preference, use TF override, general defined timeouts, or default Timeouts

func (Resource) GettableProperties

func (r Resource) GettableProperties() []*Type

Properties that will be returned in the API body

func (*Resource) HasLabelsField

func (r *Resource) HasLabelsField() bool

func (Resource) HasProject

func (r Resource) HasProject() bool

func (Resource) HasRegion

func (r Resource) HasRegion() bool

func (Resource) HasZone

func (r Resource) HasZone() bool

func (Resource) IamAttributes

func (r Resource) IamAttributes() []string

Returns the attributes from the selflink url

func (Resource) IamImportFormat

func (r Resource) IamImportFormat() string

func (Resource) IamImportFormats

func (r Resource) IamImportFormats() []string

func (Resource) IamImportQualifiersForTest

func (r Resource) IamImportQualifiersForTest() string

func (Resource) IamParentResourceName

func (r Resource) IamParentResourceName() string

==================== Iam Methods ====================

func (Resource) IamParentSourceType

func (r Resource) IamParentSourceType() string

func (Resource) IamResourceParams

func (r Resource) IamResourceParams() []string

For example: the uri "projects/{{project}}/schemas/{{name}}" The paramerters are "project", "schema".

func (Resource) IamResourceUri

func (r Resource) IamResourceUri() string

For example: "projects/{{project}}/schemas/{{name}}"

func (Resource) IamResourceUriFormat

func (r Resource) IamResourceUriFormat() string

For example: "projects/%s/schemas/%s"

func (Resource) IamResourceUriStringQualifiers

func (r Resource) IamResourceUriStringQualifiers() string

For example: for the uri "projects/{{project}}/schemas/{{name}}", the string qualifiers are "u.project, u.schema"

func (Resource) IamSelfLinkIdentifiers

func (r Resource) IamSelfLinkIdentifiers() []string

func (Resource) IamSelfLinkProperties

func (r Resource) IamSelfLinkProperties() []*Type

Returns the resource properties that are idenfifires in the selflink url

func (Resource) IamTerraformName

func (r Resource) IamTerraformName() string

func (Resource) IgnoreReadLabelsFields

func (r Resource) IgnoreReadLabelsFields(props []*Type) []string

Return labels fields that should be added to ImportStateVerifyIgnore

func (Resource) IgnoreReadPropertiesToString

func (r Resource) IgnoreReadPropertiesToString(e resource.Examples) string

func (Resource) ImportIdFormatsFromIam

func (r Resource) ImportIdFormatsFromIam() []string

For example, "projects/{{project}}/schemas/{{name}}", "{{project}}/{{name}}", "{{name}}"

func (Resource) ImportIdFormatsFromResource

func (r Resource) ImportIdFormatsFromResource() []string

func (Resource) ImportIdRegexesFromIam

func (r Resource) ImportIdRegexesFromIam() string

For example, projects/(?P<project>[^/]+)/schemas/(?P<schema>[^/]+)", "(?P<project>[^/]+)/(?P<schema>[^/]+)", "(?P<schema>[^/]+)

func (Resource) IncludeProjectForOperation

func (r Resource) IncludeProjectForOperation() bool

func (Resource) IsExcluded

func (r Resource) IsExcluded() bool

func (Resource) IsInIamResourceParams

func (r Resource) IsInIamResourceParams(param string) bool

func (Resource) IsInIdentity

func (r Resource) IsInIdentity(t Type) bool

func (Resource) IsSettableProperty

func (r Resource) IsSettableProperty(t *Type) bool

func (Resource) LastNestedQueryKey

func (r Resource) LastNestedQueryKey() string

func (Resource) Lineage

func (r Resource) Lineage() string

Prints a dot notation path to where the field is nested within the parent object when called on a property. eg: parent.meta.label.foo Redefined on Resource to terminate the calls up the parent chain.

func (Resource) ListUrlTemplate

func (r Resource) ListUrlTemplate() string

func (Resource) MinVersionObj

func (r Resource) MinVersionObj() *product.Version

==================== Version-related methods ====================

func (Resource) NotInVersion

func (r Resource) NotInVersion(version *product.Version) bool

func (Resource) OrderProperties

func (r Resource) OrderProperties(props []*Type) []*Type

func (Resource) PackageName

func (r Resource) PackageName() string

func (Resource) PropertiesByCustomUpdate

func (r Resource) PropertiesByCustomUpdate(properties []*Type) map[UpdateGroup][]*Type

func (Resource) PropertiesByCustomUpdateGroups

func (r Resource) PropertiesByCustomUpdateGroups() []UpdateGroup

func (Resource) PropertiesWithExcluded

func (r Resource) PropertiesWithExcluded() []*Type

func (Resource) PropertyNamesToStrings

func (r Resource) PropertyNamesToStrings(properties []*Type) []string

func (Resource) RawImportIdFormatsFromIam

func (r Resource) RawImportIdFormatsFromIam() []string

For example, "projects/{{project}}/schemas/{{name}}", "{{project}}/{{name}}", "{{name}}"

func (Resource) ReadProperties

func (r Resource) ReadProperties() []*Type

==================== Template Methods ==================== Functions used to create slices of resource properties that could not otherwise be called from within generating templates.

func (Resource) RequiredProperties

func (r Resource) RequiredProperties() []*Type

func (Resource) ResourceListKey

func (r Resource) ResourceListKey() string

Returns the key of the list of resources in the List API response Used to get the list of resources to sweep

func (Resource) ResourceName

func (r Resource) ResourceName() string

func (Resource) RootLabels

func (r Resource) RootLabels() bool

Check if the resource has root "labels" field

func (Resource) RootProperties

func (r Resource) RootProperties() []*Type

Returns the list of top-level properties once any nested objects with flatten_object set to true have been collapsed

func (Resource) SelfLinkUri

func (r Resource) SelfLinkUri() string

Returns the partial uri / relative path of a resource. In newer resources, this is the name. This fn is named self_link_uri for consistency, but could otherwise be considered to be "path"

func (Resource) SelfLinkUrl

func (r Resource) SelfLinkUrl() string

Returns the "self_link_url" which is generally really the resource's GET URL. In older resources generally, this was the self_link value & was the product.base_url + resource.base_url + '/name' In newer resources there is much less standardisation in terms of value. Generally for them though, it's the product.base_url + resource.name

func (Resource) SensitiveProps

func (r Resource) SensitiveProps() []*Type

func (Resource) SensitivePropsToString

func (r Resource) SensitivePropsToString() string

func (Resource) ServiceVersion

func (r Resource) ServiceVersion() string

func (*Resource) SetCompiler

func (r *Resource) SetCompiler(t string)

func (*Resource) SetDefault

func (r *Resource) SetDefault(product *Product)

func (Resource) SettableProperties

func (r Resource) SettableProperties() []*Type

All settable properties in the resource. Fingerprints aren't *really" settable properties, but they behave like one. At Create, they have no value but they can just be read in anyways, and after a Read they will need to be set in every Update.

func (Resource) StateMigrationFile

func (r Resource) StateMigrationFile() string

func (Resource) StateUpgradersCount

func (r Resource) StateUpgradersCount() []int

func (Resource) TerraformName

func (r Resource) TerraformName() string

func (Resource) TestExamples

func (r Resource) TestExamples() []resource.Examples

func (*Resource) UnmarshalYAML

func (r *Resource) UnmarshalYAML(unmarshal func(any) error) error

func (Resource) UnorderedListProperties

func (r Resource) UnorderedListProperties() []*Type

func (Resource) Updatable

func (r Resource) Updatable() bool

resource functions needed for template that previously existed in terraform.go but due to how files are being inherited here it was easier to put in here taken wholesale from tpgtools

func (Resource) UpdateBodyProperties

func (r Resource) UpdateBodyProperties() []*Type

func (Resource) UpdateUri

func (r Resource) UpdateUri() string

func (Resource) UserParameters

func (r Resource) UserParameters() []*Type

func (Resource) UserProperites

func (r Resource) UserProperites() []*Type

func (*Resource) Validate

func (r *Resource) Validate()

func (Resource) VersionedProvider

func (r Resource) VersionedProvider(exampleVersion string) bool

type Timeouts

type Timeouts struct {
	InsertMinutes int `yaml:"insert_minutes"`
	UpdateMinutes int `yaml:"update_minutes"`
	DeleteMinutes int `yaml:"delete_minutes"`
}

Provides timeout information for the different operation types

func NewTimeouts

func NewTimeouts() *Timeouts

type Type

type Type struct {
	Name string `yaml:"name,omitempty"`

	// original value of :name before the provider override happens
	// same as :name if not overridden in provider
	ApiName string `yaml:"api_name,omitempty"`

	// TODO rewrite: improve the parsing of properties based on type in resource yaml files.
	Type string

	DefaultValue interface{} `yaml:"default_value,omitempty"`

	// Expected to follow the format as follows:
	//
	//	description: |
	//		This is a description of a field.
	//		If it comprises multiple lines, it must continue to be indented.
	//
	Description string `yaml:"description,omitempty"`

	Exclude bool `yaml:"exclude,omitempty"`

	// Add a deprecation message for a field that's been deprecated in the API
	// use the YAML chomping folding indicator (>-) if this is a multiline
	// string, as providers expect a single-line one w/o a newline.
	DeprecationMessage string `yaml:"deprecation_message,omitempty"`

	// Add a removed message for fields no longer supported in the API. This should
	// be used for fields supported in one version but have been removed from
	// a different version.
	RemovedMessage string `yaml:"removed_message,omitempty"`

	// If set value will not be sent to server on sync.
	// For nested fields, this also needs to be set on each descendant (ie. self,
	// child, etc.).
	Output bool `yaml:"output,omitempty"`

	// If set to true, changes in the field's value require recreating the
	// resource.
	// For nested fields, this only applies at the current level. This means
	// it should be explicitly added to each field that needs the ForceNew
	// behavior.
	Immutable bool `yaml:"immutable,omitempty"`

	// Indicates that this field is client-side only (aka virtual.)
	ClientSide bool `yaml:"client_side,omitempty"`

	// url_param_only will not send the field in the resource body and will
	// not attempt to read the field from the API response.
	// NOTE - this doesn't work for nested fields
	UrlParamOnly bool `yaml:"url_param_only,omitempty"`

	// For nested fields, this only applies within the parent.
	// For example, an optional parent can contain a required child.
	Required bool `yaml:"required,omitempty"`

	// Additional query Parameters to append to GET calls.
	ReadQueryParams string `yaml:"read_query_params,omitempty"`

	UpdateVerb string `yaml:"update_verb,omitempty"`

	UpdateUrl string `yaml:"update_url,omitempty"`

	// Some updates only allow updating certain fields at once (generally each
	// top-level field can be updated one-at-a-time). If this is set, we group
	// fields to update by (verb, url, fingerprint, id) instead of just
	// (verb, url, fingerprint), to allow multiple fields to reuse the same
	// endpoints.
	UpdateId string `yaml:"update_id,omitempty"`

	// The fingerprint value required to update this field. Downstreams should
	// GET the resource and parse the fingerprint value while doing each update
	// call. This ensures we can supply the fingerprint to each distinct
	// request.
	FingerprintName string `yaml:"fingerprint_name,omitempty"`

	// If true, we will include the empty value in requests made including
	// this attribute (both creates and updates).  This rarely needs to be
	// set to true, and corresponds to both the "NullFields" and
	// "ForceSendFields" concepts in the autogenerated API clients.
	SendEmptyValue bool `yaml:"send_empty_value,omitempty"`

	// [Optional] If true, empty nested objects are sent to / read from the
	// API instead of flattened to null.
	// The difference between this and send_empty_value is that send_empty_value
	// applies when the key of an object is empty; this applies when the values
	// are all nil / default. eg: "expiration: null" vs "expiration: {}"
	// In the case of Terraform, this occurs when a block in config has optional
	// values, and none of them are used. Terraform returns a nil instead of an
	// empty map[string]interface{} like we'd expect.
	AllowEmptyObject bool `yaml:"allow_empty_object,omitempty"`

	MinVersion string `yaml:"min_version,omitempty"`

	ExactVersion string `yaml:"exact_version,omitempty"`

	// A list of properties that conflict with this property. Uses the "lineage"
	// field to identify the property eg: parent.meta.label.foo
	Conflicts []string `yaml:"conflicts,omitempty"`

	// A list of properties that at least one of must be set.
	AtLeastOneOf []string `yaml:"at_least_one_of,omitempty"`

	// A list of properties that exactly one of must be set.
	ExactlyOneOf []string `yaml:"exactly_one_of,omitempty"`

	// A list of properties that are required to be set together.
	RequiredWith []string `yaml:"required_with,omitempty"`

	// Can only be overridden - we should never set this ourselves.
	NewType string `yaml:"-"`

	Properties []*Type `yaml:"properties,omitempty"`

	EnumValues []string `yaml:"enum_values,omitempty"`

	ExcludeDocsValues bool `yaml:"exclude_docs_values,omitempty"`

	// ====================
	// Array Fields
	// ====================
	ItemType *Type  `yaml:"item_type,omitempty"`
	MinSize  string `yaml:"min_size,omitempty"`
	MaxSize  string `yaml:"max_size,omitempty"`
	// Adds a ValidateFunc to the item schema
	ItemValidation resource.Validation `yaml:"item_validation,omitempty"`

	ParentName string `yaml:"parent_name,omitempty"`

	// ====================
	// ResourceRef Fields
	// ====================
	Resource string `yaml:"resource,omitempty"`
	Imports  string `yaml:"imports,omitempty"`

	// Adds a DiffSuppressFunc to the schema
	DiffSuppressFunc string `yaml:"diff_suppress_func,omitempty"`

	StateFunc string `yaml:"state_func,omitempty"` // Adds a StateFunc to the schema

	Sensitive bool `yaml:"sensitive,omitempty"` // Adds `Sensitive: true` to the schema

	// Does not set this value to the returned API value.  Useful for fields
	// like secrets where the returned API value is not helpful.
	IgnoreRead bool `yaml:"ignore_read,omitempty"`

	// Adds a ValidateFunc to the schema
	Validation resource.Validation `yaml:"validation,omitempty"`

	// Indicates that this is an Array that should have Set diff semantics.
	UnorderedList bool `yaml:"unordered_list,omitempty"`

	IsSet bool `yaml:"is_set,omitempty"` // Uses a Set instead of an Array

	// Optional function to determine the unique ID of an item in the set
	// If not specified, schema.HashString (when elements are string) or
	// schema.HashSchema are used.
	SetHashFunc string `yaml:"set_hash_func,omitempty"`

	// if true, then we get the default value from the Google API if no value
	// is set in the terraform configuration for this field.
	// It translates to setting the field to Computed & Optional in the schema.
	// For nested fields, this only applies at the current level. This means
	// it should be explicitly added to each field that needs the defaulting
	// behavior.
	DefaultFromApi bool `yaml:"default_from_api,omitempty"`

	// https://github.com/hashicorp/terraform/pull/20837
	// Apply a ConfigMode of SchemaConfigModeAttr to the field.
	// This should be avoided for new fields, and only used with old ones.
	SchemaConfigModeAttr bool `yaml:"schema_config_mode_attr,omitempty"`

	// Names of fields that should be included in the updateMask.
	UpdateMaskFields []string `yaml:"update_mask_fields,omitempty"`

	// For a TypeMap, the expander function to call on the key.
	// Defaults to expandString.
	KeyExpander string `yaml:"key_expander,omitempty"`

	// For a TypeMap, the DSF to apply to the key.
	KeyDiffSuppressFunc string `yaml:"key_diff_suppress_func,omitempty"`

	// ====================
	// Map Fields
	// ====================
	// The type definition of the contents of the map.
	ValueType *Type `yaml:"value_type,omitempty"`

	// While the API doesn't give keys an explicit name, we specify one
	// because in Terraform the key has to be a property of the object.
	//
	// The name of the key. Used in the Terraform schema as a field name.
	KeyName string `yaml:"key_name,omitempty"`

	// A description of the key's format. Used in Terraform to describe
	// the field in documentation.
	KeyDescription string `yaml:"key_description,omitempty"`

	// ====================
	// KeyValuePairs Fields
	// ====================
	// Ignore writing the "effective_labels" and "effective_annotations" fields to API.
	IgnoreWrite bool `yaml:"ignore_write,omitempty"`

	// Flattens a NestedObject by removing that field from the Terraform
	// schema but will preserve it in the JSON sent/retrieved from the API
	//
	// EX: a API schema where fields are nested (eg: `one.two.three`) and we
	// desire the properties of the deepest nested object (eg: `three`) to
	// become top level properties in the Terraform schema. By overriding
	// the properties `one` and `one.two` and setting flatten_object then
	// all the properties in `three` will be at the root of the TF schema.
	//
	// We need this for cases where a field inside a nested object has a
	// default, if we can't spend a breaking change to fix a misshapen
	// field, or if the UX is _much_ better otherwise.
	//
	// WARN: only fully flattened properties are currently supported. In the
	// example above you could not flatten `one.two` without also flattening
	// all of it's parents such as `one`
	FlattenObject bool `yaml:"flatten_object,omitempty"`

	// A custom expander replaces the default expander for an attribute.
	// It is called as part of Create, and as part of Update if
	// object.input is false.  It can return an object of any type,
	// so the function header *is* part of the custom code template.
	// As with flatten, `property` and `prefix` are available.
	CustomExpand string `yaml:"custom_expand,omitempty"`

	// A custom flattener replaces the default flattener for an attribute.
	// It is called as part of Read.  It can return an object of any
	// type, and may sometimes need to return an object with non-interface{}
	// type so that the d.Set() call will succeed, so the function
	// header *is* a part of the custom code template.  To help with
	// creating the function header, `property` and `prefix` are available,
	// just as they are in the standard flattener template.
	CustomFlatten string `yaml:"custom_flatten,omitempty"`

	ResourceMetadata *Resource `yaml:"resource_metadata,omitempty"`

	ParentMetadata *Type `yaml:"parent_metadata,omitempty"` // is nil for top-level properties

	// The prefix used as part of the property expand/flatten function name
	// flatten{{$.GetPrefix}}{{$.TitlelizeProperty}}
	Prefix string `yaml:"prefix,omitempty"`
}

Represents a property type

func NewProperty

func NewProperty(name, apiName string, options []func(*Type)) *Type

An array of string -> string key -> value pairs, such as labels. While this is technically a map, it's split out because it's a much simpler property to generate and means we can avoid conditional logic in Map.

func (Type) AllProperties

func (t Type) AllProperties() []*Type

Returns all properties including the ones that are excluded This is used for PropertyOverride validation

func (Type) AtLeastOneOfList

func (t Type) AtLeastOneOfList() []string

Returns list of properties that needs at least one of their fields set. func (t *Type) at_least_one_of_list() {

func (Type) Conflicting

func (t Type) Conflicting() []string

Returns list of properties that are in conflict with this property. func (t *Type) conflicting() {

func (Type) CustomTemplate

func (t Type) CustomTemplate(templatePath string, appendNewline bool) string

func (Type) Deprecated

func (t Type) Deprecated() bool

func (Type) EnumValuesToString

func (t Type) EnumValuesToString(quoteSeperator string, addEmpty bool) string

func (Type) ExactlyOneOfList

func (t Type) ExactlyOneOfList() []string

Returns list of properties that needs exactly one of their fields set. func (t *Type) exactly_one_of_list() {

func (*Type) ExcludeIfNotInVersion

func (t *Type) ExcludeIfNotInVersion(version *product.Version)

func (*Type) GetDescription

func (t *Type) GetDescription() string

func (*Type) GetIdFormat

func (t *Type) GetIdFormat() string

func (*Type) GetPrefix

func (t *Type) GetPrefix() string

If the Prefix field is already set, returns the value. Otherwise, set the Prefix field and returns the value.

func (*Type) GetPropertySchemaPath

func (t *Type) GetPropertySchemaPath(schemaPath string) string

Returns an updated path for a given Terraform field path (e.g. 'a_field', 'parent_field.0.child_name'). Returns nil if the property is not included in the resource's properties and removes keys that have been flattened FYI: Fields that have been renamed should use the new name, however, flattened fields still need to be included, ie: flattenedField > newParent > renameMe should be passed to this function as flattened_field.0.new_parent.0.im_renamed TODO(emilymye): Change format of input for exactly_one_of/at_least_one_of/etc to use camelcase, MM properities and convert to snake in this method

func (Type) GetPropertySchemaPathList

func (t Type) GetPropertySchemaPathList(propertyList []string) []string

func (*Type) GoLiteral

func (t *Type) GoLiteral(value interface{}) string

func (Type) IsA

func (t Type) IsA(clazz string) bool

func (*Type) IsForceNew

func (t *Type) IsForceNew() bool

func (Type) ItemTypeClass

func (t Type) ItemTypeClass() string

This function is for array field

func (Type) Lineage

func (t Type) Lineage() string

Prints a dot notation path to where the field is nested within the parent object. eg: parent.meta.label.foo The only intended purpose is to allow better error messages. Some objects and at some points in the build this doesn't output a valid output.

func (Type) MinVersionObj

func (t Type) MinVersionObj() *product.Version

func (Type) NamespaceProperty

func (t Type) NamespaceProperty() string

"Namespace" - prefix with product and resource - a property with information from the "object" variable

func (Type) NestedProperties

func (t Type) NestedProperties() []*Type

Returns nested properties for this property.

func (Type) Parent

func (t Type) Parent() *Type

func (Type) PropertyNsPrefix

func (t Type) PropertyNsPrefix() []string

func (Type) Removed

func (t Type) Removed() bool

func (Type) RequiredWithList

func (t Type) RequiredWithList() []string

Returns list of properties that needs required with their fields set.

func (Type) ResourceRef

func (t Type) ResourceRef() *Resource

func (Type) ResourceType

func (t Type) ResourceType() string

func (*Type) RootProperties

func (t *Type) RootProperties() []*Type

Returns the list of top-level properties once any nested objects with flatten_object set to true have been collapsed

func (*Type) SetDefault

func (t *Type) SetDefault(r *Resource)

func (Type) TFType

func (t Type) TFType(s string) string

func (Type) TerraformLineage

func (t Type) TerraformLineage() string

Prints the access path of the field in the configration eg: metadata.0.labels The only intended purpose is to get the value of the labes field by calling d.Get().

func (Type) TitlelizeProperty

func (t Type) TitlelizeProperty() string

func (Type) UserProperties

func (t Type) UserProperties() []*Type

func (*Type) Validate

func (t *Type) Validate(rName string)

type UpdateGroup

type UpdateGroup struct {
	UpdateUrl       string
	UpdateVerb      string
	UpdateId        string
	FingerprintName string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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