Index
Overview
builtin package represents the predefined, Terraform domain-specific,
functions and types in the scope of any thread of AsCode. This means
that is not required to use the load
statement, and any of the function
can be called without any prefix.
Functions
def backend
backend(type) Backend
Instantiates a new Backend
Arguments
name | type | description |
---|---|---|
type | string | Backend type. |
def evaluate
evaluate(filename, predeclared=None) dict
Evaluates a Starlark file and returns its global context. Kwargs may be used to set predeclared.
Arguments
name | type | description |
---|---|---|
filename | string | Name of the file to execute. |
predeclared | dict | Defines the predeclared context for the execution. Execution doesnot modify this dictionary |
Examples
# evaluable.star file
print("Print from evaluable.star: '%s'" % foo)
bar="bar"
# Evaluate execute the given file, with the given context, in this case `foo`
values = evaluate("evaluable.star", foo="foo")
# The context it's a module, in this case contains the key `bar`
print("Print from main: '%s'" % values.bar)
# Output:
# Print from evaluable.star: 'foo'
# Print from main: 'bar'
def fn
fn(name, target) Attribute
Fn wraps an Attribute in a HCL function. Since the Attributes value
are only available in the apply
phase of Terraform, the only method
to manipulate this values is using the Terraform
HCL functions.
Arguments
name | type | description |
---|---|---|
name | string | Name of the HCL function to be applied. Eg.: base64encode |
target | Attribute | Target Attribute of the HCL function. |
def hcl
hcl(resource) string
Returns the HCL encoding of the given resource.
Arguments
name | type | description |
---|---|---|
resource | <resource> | resource to be encoded. |
def provisioner
provisioner(type) Provisioner
Instantiates a new Provisioner
Arguments
name | type | description |
---|---|---|
type | string | Provisioner type. |
def ref
ref(resource, argument) string
Returns a reference to a resource argument.
Arguments
name | type | description |
---|---|---|
resource | <resource> | resource to be referenced. |
field | string | field to be referenced. |
Examples
# Non-computed arguments are passed by value to one argument to another
# in some cases may be required to make a referece to and relay in the HCL
# interpolation.
aws = tf.provider("aws")
instance = aws.resource.instance("foo")
instance.ami = "foo"
print(ref(instance, "ami"))
# Output:
# ${aws_instance.foo.ami}
def validate
validate(resource) list
Returns a list with validating errors if any. A validating error is
a struct with two fields: msg
and pos
Arguments
name | type | description |
---|---|---|
resource | <resource> | resource to be validated. |
Types
type Attribute
Attribute is a reference to an argument of a Resource. Used mainly for Computed arguments of Resources.
Attribute behaves as the type of the argument represented, this means that them can be assigned to other resource arguments of the same type. And, if the type is a list are indexable.
Properties
name | type | description |
---|---|---|
__resource__ | Resource | Resource of the attribute. |
__type__ | string | Type of the attribute. Eg.: string |
Examples
# When a Resource has an Attribute means that the value it's only available
# during the `apply` phase of Terraform. So in, AsCode an attribute behaves
# like a poor-man pointer.
aws = tf.provider("aws")
ami = aws.resource.ami("ubuntu")
instance = aws.resource.instance("foo")
instance.ami = ami.id
print(instance.ami)
# Output:
# ${aws_ami.ubuntu.id}
type Backend
The part of Terraform’s core that determines how Terraform stores state and performs operations (like plan, apply, import, etc.). Terraform has multiple backends to choose from, which can be configured in a variety of ways.
Properties
name | type | description |
---|---|---|
__kind__ | string | Kind of the backend. Fixed value backend . |
__type__ | string | Type of the backend. Eg.: local . |
__dict__ | Dict | A dictionary containing all the config values of the backend. |
<argument> | <scalar> | Arguments defined by the backend schema, thus can be of anyscalar type. |
Methods
def Backend.state
Backend.state(module="", workspace="default") State
Loads the latest state for a given module or workspace.
Arguments
name | type | description |
---|---|---|
module | string | name of the module, empty equals to root. |
workspace | string | backend workspace |
type Provider
A plugin for Terraform that makes a collection of related resources available. A provider plugin is responsible for understanding API interactions with some kind of service and exposing resources based on that API.
Properties
name | type | description |
---|---|---|
__version__ | string | Provider version |
__kind__ | string | Kind of the provider. Fixed value provider |
__type__ | string | Type of the resource. Eg.: aws_instance |
__name__ | string | Local name of the provider, if none was provided to the constructor,the name is auto-generated following the pattern id_%s . AtTerraform is called alias |
__dict__ | Dict | A dictionary containing all set arguments and blocks of the provider. |
data | MapSchema | Data sources defined by the provider. |
resource | MapSchema | Resources defined by the provider. |
<argument> | <scalar> | Arguments defined by the provider schema, thus can be of anyscalar type. |
<block> | Resource | Blocks defined by the provider schema, thus are nested resources,containing other arguments and/or blocks. |
Examples
def print_provider_info(p):
print("Provider %s[%s] (%s)" % (p.__type__, p.__name__, p.__version__))
print(" Defines Data Sources: %d" % len(dir(p.data)))
print(" Defines Resources: %d" % len(dir(p.resource)))
print(" Configuration: %s" % p.__dict__)
provider = tf.provider("google", "3.13.0")
provider.project = "acme-app"
provider.region = "us-central1"
print_provider_info(provider)
# Output:
# Provider google[id_1] (3.13.0)
# Defines Data Sources: 60
# Defines Resources: 263
# Configuration: {"project": "acme-app", "region": "us-central1"}
Resource instantiation from a Provider.
helm = tf.provider("helm", "1.0.0")
podinfo = helm.resource.release("podinfo")
podinfo.chart = "podinfo"
podinfo.version = "3.1.8"
print(hcl(podinfo))
# Output:
# resource "helm_release" "podinfo" {
# provider = helm.id_1
# chart = "podinfo"
# version = "3.1.8"
# }
Methods
def Provider.set_prefix
Provider.set_prefix(enable, prefix="")
If enabled, all the resource names belonging to this provider are prefixed, with the given prefix or by default the alias name.
Arguments
name | type | description |
---|---|---|
enable | bool | if True enables the the prefix of resources. |
prefix | string | string to be used as prefix of the resources, if None, theprovider name it’s used as prefix. |
type ProviderCollection
ProviderCollection holds the providers in a nested dictionary,
indexed by provider type and provider name. The values can be
accessed by indexing or using the built-in method of dict
.
Examples
tf.provider("aws", "2.13.0", "qux")
tf.provider("aws", "2.13.0", "bar")
tf.provider("google")
# providers can be access by indexing
aws_names = tf.provider["aws"].keys()
print("aws providers:", sorted(aws_names))
# or by the get method
google_names = tf.provider.get("google").keys()
print("google providers:", google_names)
# Output:
# aws providers: ["bar", "qux"]
# google providers: ["id_1"]
Methods
def ProviderCollection.__call__
ProviderCollection.__call__(type, version="", name="") Provider
Returns a new provider instance of the given type.
Arguments
name | type | description |
---|---|---|
type | string | Provider type. Eg.: aws |
version | string | Version value, if None latest version available it’s used. |
name | string | Local name of the resource, if None is provided it’sautogenerated. |
Examples
Defining multiple providers and traversing tf.providers
aws = tf.provider("aws", "2.13.0", "aliased")
helm = tf.provider("helm", "1.0.0")
ignition = tf.provider("ignition")
print("terraform =", tf.version)
for type in sorted(list(tf.provider)):
for name in tf.provider[type]:
p = tf.provider[type][name]
print(" %s (%s) = %s" % (type, name, p.__version__))
# Output:
# terraform = 0.12.23
# aws (aliased) = 2.13.0
# helm (id_1) = 1.0.0
# ignition (id_2) = 1.2.1
type Provisioner
Provisioner represents a Terraform provider of a specif type. As written in the terraform documentation: “Provisioners are a Last Resort”
Properties
name | type | description |
---|---|---|
__kind__ | string | Kind of the provisioner. Fixed value provisioner |
__type__ | string | Type of the resource. Eg.: `aws_instance | |
<argument> | <scalar> | Arguments defined by the provisioner schema, thus can be of anyscalar type. |
<block> | Resource | Blocks defined by the provisioner schema, thus are nested resources,containing other arguments and/or blocks. |
type Resource
Resources are the most important element in the Terraform language. Each resource block describes one or more infrastructure objects, such as virtual networks, compute instances, or higher-level components such as DNS records.
Each resource is associated with a single resource type, which determines the kind of infrastructure object it manages and what arguments and other attributes the resource supports.
Each resource type in turn belongs to a provider, which is a plugin for Terraform that offers a collection of resource types. A provider usually provides resources to manage a single cloud or on-premises infrastructure platform.
Following the schema of HCL Terraform resources each type of arguments and blocks are transformed in native AsCode elements:
Blocks defined as a list of Resources are transformed into:
ResourceCollection<nested>
, if theBlock
is a list capped to one item, its represented asResource<nested>
.Arguments are transformed as basic scalar types.
Attributes aka computed arguments are transformed in
Attributes
Properties
name | type | description |
---|---|---|
__provider__ | Provider | Provider of this resource if any. |
__kind__ | string | Kind of the resource. Eg.: data |
__type__ | string | Type of the resource. Eg.: aws_instance |
__name__ | string | Local name of the resource, if none was provided to the constructorthe name is auto-generated following the partern id_%s . Nested kindresources are unamed. |
__dict__ | Dict | A dictionary containing all set arguments and blocks of the resource. |
<argument> | <scalar>/Computed | Arguments defined by the resource schema, thus can be of anyscalar type or Computed values. |
<block> | Resource/ResourceCollection | Blocks defined by the resource schema, thus are nested resources,containing other arguments and/or blocks. |
Examples
# Create a new instance of the latest Ubuntu 14.04 on an
# t2.micro node with an AWS Tag naming it "HelloWorld"
aws = tf.provider("aws", "2.54.0")
aws.region = "us-west-2"
ubuntu_filter = "ubuntu/images/*/ubuntu-xenial-16.04-amd64-server-*"
canonical = "099720109477"
ami = aws.data.ami("ubuntu")
ami.most_recent = True
ami.filter(name="name", values=[ubuntu_filter])
ami.filter(name="virtualization-type", values=["hvm"])
ami.owners = [canonical]
instance = aws.resource.instance("web")
instance.instance_type = "t2.micro"
instance.ami = ami.id
instance.tags = {
"name": "HelloWorld"
}
print(hcl(tf))
# Output:
# provider "aws" {
# alias = "id_1"
# version = "2.54.0"
# region = "us-west-2"
# }
#
# data "aws_ami" "ubuntu" {
# provider = aws.id_1
# most_recent = true
# owners = ["099720109477"]
#
# filter {
# name = "name"
# values = ["ubuntu/images/*/ubuntu-xenial-16.04-amd64-server-*"]
# }
#
# filter {
# name = "virtualization-type"
# values = ["hvm"]
# }
# }
#
# resource "aws_instance" "web" {
# provider = aws.id_1
# ami = "${data.aws_ami.ubuntu.id}"
# instance_type = "t2.micro"
# tags = { name = "HelloWorld" }
# }
Methods
def Resource.depends_on
Resource.depends_on(resource)
Explicitly declares a dependency on another resource. Use the depends_on meta-argument to handle hidden resource dependencies that Terraform can’t automatically infer. (Only in resources of kind “resource”)
Arguments
name | type | description |
---|---|---|
resource | Resource | depended data or resource kind. |
def Resource.add_provisioner
Resource.add_provisioner(provisioner)
Create-time actions like these can be described using resource provisioners. A provisioner is another type of plugin supported by Terraform, and each provisioner takes a different kind of action in the context of a resource being created. Provisioning steps should be used sparingly, since they represent non-declarative actions taken during the creation of a resource and so Terraform is not able to model changes to them as it can for the declarative portions of the Terraform language. (Only in resources of kind “resource”)
Arguments
name | type | description |
---|---|---|
provisioner | Provisioner | provisioner resource to be executed. |
type ResourceCollection
ResourceCollection stores and instantiates resources for a specific
pair of provider and resource. The resources can be accessed by
indexing or using the built-in method of dict
.
Properties
name | type | description |
---|---|---|
__provider__ | Provider | Provider of this resource collection. |
__kind__ | string | Kind of the resource collection. Eg.: data |
__type__ | string | Type of the resource collection. Eg.: aws_instance |
Methods
def ResourceCollection.__call__
ResourceCollection.__call__(name="", values={}) Resource
Returns a new resourced with the given name and values.
Arguments
name | type | description |
---|---|---|
name | string | Local name of the resource, if None is provided it’sautogenerated. |
values | dict | List of arguments and nested blocks to be set in the newresource, these values can also be defined using kwargs . |
Examples
Resource instantiation using values, dicts or kwargs.
aws = tf.provider("aws")
# Resources can be defined in different ways...
# you can set the resource attributes...
v = aws.resource.instance()
v.instance_type = "t2.micro"
v.tags = {"name": "HelloWorld"}
# or using a dict in the constructor...
d = aws.resource.instance({
"instance_type": "t2.micro",
"tags": {"name": "HelloWorld"},
})
# or even using kwargs
k = aws.resource.instance(instance_type="t2.micro", tags={"name": "HelloWorld"})
# and all the resources are equivalent:
print(v.__dict__)
print(d.__dict__)
print(k.__dict__)
# Output:
# {"instance_type": "t2.micro", "tags": {"name": "HelloWorld"}}
# {"instance_type": "t2.micro", "tags": {"name": "HelloWorld"}}
# {"instance_type": "t2.micro", "tags": {"name": "HelloWorld"}}
def ResourceCollection.search
ResourceCollection.search(key="id", value) list
Return all the Resources with the given value in the given key.
Arguments
name | type | description |
---|---|---|
name | string | Key to search. The default value is id . |
value | <any> | Value to match in the given key. |
Examples
aws = tf.provider("aws")
aws.resource.instance("foo", instance_type="t2.micro")
aws.resource.instance("bar", instance_type="a1.medium")
aws.resource.instance("qux", instance_type="t2.micro")
r = aws.resource.instance.search("bar")
print("Instance type of `bar`: %s" % r[0].instance_type)
r = aws.resource.instance.search("instance_type", "t2.micro")
print("Instances with 't2.micro`: %d" % len(r))
# Output:
# Instance type of `bar`: a1.medium
# Instances with 't2.micro`: 2
type ResourceCollectionGroup
ResourceCollectionGroup represents a group by kind (resource or data resource) of ResourceCollections for a given provider.
Properties
name | type | description |
---|---|---|
__provider__ | Provider | Provider of this group. |
__kind__ | string | Kind of the resources (data or resource ). |
<resource-name> | ResourceCollection | Returns a ResourceCollection if the resource name is valid forthe schema of the provider. The resource name should be providedwithout the provider prefix, aws_instance becomesjust an instance . |
type State
Terraform’s cached information about your managed infrastructure and configuration. This state is used to persistently map the same real world resources to your configuration from run-to-run, keep track of metadata, and improve performance for large infrastructures.
State implements a Dict, where the first level are the providers
containing the keys data
with the data sources and resources
with
the resources.
Properties
name | type | description |
---|---|---|
<provider> | AttrDict | provider and all the resources state. |
Examples
An example of how to print a resume of providers and resources count from the state.
# new instance of a local backend
# https://www.terraform.io/docs/backends/types/local.html
b = backend("local")
b.path = "terraform.tfstate"
# it reads the state
s = b.state()
for provider in sorted(list(s)):
print("%s:" % provider)
for resource in sorted(list(s[provider]["resource"])):
count = len(s[provider]["resource"][resource])
print(" %s (%d)" % (resource, count))
# Output:
# google:
# container_cluster (1)
# container_node_pool (1)
# helm:
# release (5)
# kubernetes:
# cluster_role_binding (1)
# namespace (1)
# secret (1)
type Terraform
Terraform holds all the configuration defined by a script. A global
variable called tf
contains a unique instance of Terraform.
Properties
name | type | description |
---|---|---|
version | string | Terraform version. |
backend | Backend | Backend used to store the state, if None a local backend it’sused. |
provider | ProviderCollection | Dict with all the providers defined by provider type. |
Examples
tf.backend = backend("gcs", bucket="tf-state")
aws = tf.provider("aws", "2.54.0", region="us-west-2")
aws.resource.instance("foo", instance_type="t2.micro")
print(hcl(tf))
# Output:
# terraform {
# backend "gcs" {
# bucket = "tf-state"
# }
# }
#
# provider "aws" {
# alias = "id_1"
# version = "2.54.0"
# region = "us-west-2"
# }
#
# resource "aws_instance" "foo" {
# provider = aws.id_1
# instance_type = "t2.micro"
# }