Skip to content

Instantly share code, notes, and snippets.

@ggiamarchi
Last active August 29, 2015 14:14
Show Gist options
  • Save ggiamarchi/cc6f200842794c0b05eb to your computer and use it in GitHub Desktop.
Save ggiamarchi/cc6f200842794c0b05eb to your computer and use it in GitHub Desktop.
Terraform sample provider
package main
import (
"github.com/hashicorp/terraform/builtin/providers/test"
"github.com/hashicorp/terraform/plugin"
)
func main() {
plugin.Serve(&plugin.ServeOpts{
ProviderFunc: test.Provider,
})
}
package test
import (
"math/rand"
"log"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/terraform"
)
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func generateRandomId() string {
b := make([]rune, 30)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func Provider() terraform.ResourceProvider {
return &schema.Provider{
ResourcesMap: map[string]*schema.Resource{
"test_container": resourceContainer(),
"test_element": resourceElement(),
},
}
}
func resourceContainer() *schema.Resource {
return &schema.Resource{
Create: func (d *schema.ResourceData, meta interface{}) error {
id := generateRandomId()
log.Printf("[DEBUG] Create container with id %s and elements %#v", id, d.Get("elements").(*schema.Set))
d.SetId(id)
return nil
},
Schema: map[string]*schema.Schema{
"elements": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: func(v interface{}) int {
return hashcode.String(v.(string))
},
},
},
}
}
func resourceElement() *schema.Resource {
return &schema.Resource{
Create: func (d *schema.ResourceData, meta interface{}) error {
id := generateRandomId()
log.Printf("[DEBUG] Create element with id %s", id)
d.SetId(id)
return nil
},
}
}
provider "test" {
}
resource "test_container" "ctn001" {
elements = [
"${test_element.elt001.id}",
"${test_element.elt002.id}",
"${test_element.elt003.id}"
]
}
resource "test_element" "elt001" {
}
resource "test_element" "elt002" {
}
resource "test_element" "elt003" {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment