commit
8f5232313c
|
@ -0,0 +1,151 @@
|
|||
package aws
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/hashicorp/terraform/flatmap"
|
||||
"github.com/hashicorp/terraform/helper/diff"
|
||||
"github.com/hashicorp/terraform/terraform"
|
||||
"github.com/mitchellh/goamz/elb"
|
||||
)
|
||||
|
||||
func resource_aws_elb_create(
|
||||
s *terraform.ResourceState,
|
||||
d *terraform.ResourceDiff,
|
||||
meta interface{}) (*terraform.ResourceState, error) {
|
||||
p := meta.(*ResourceProvider)
|
||||
elbconn := p.elbconn
|
||||
|
||||
// Merge the diff into the state so that we have all the attributes
|
||||
// properly.
|
||||
rs := s.MergeDiff(d)
|
||||
|
||||
// The name specified for the ELB. This is also our unique ID
|
||||
// we save to state if the creation is succesful (amazon verifies
|
||||
// it is unique)
|
||||
elbName := rs.Attributes["name"]
|
||||
|
||||
// Expand the "listener" array to goamz compat []elb.Listener
|
||||
v := flatmap.Expand(rs.Attributes, "listener").([]interface{})
|
||||
listeners := expandListeners(v)
|
||||
|
||||
v = flatmap.Expand(rs.Attributes, "availability_zones").([]interface{})
|
||||
zones := expandStringList(v)
|
||||
|
||||
// Provision the elb
|
||||
elbOpts := &elb.CreateLoadBalancer{
|
||||
LoadBalancerName: elbName,
|
||||
Listeners: listeners,
|
||||
AvailZone: zones,
|
||||
}
|
||||
|
||||
log.Printf("[DEBUG] ELB create configuration: %#v", elbOpts)
|
||||
|
||||
_, err := elbconn.CreateLoadBalancer(elbOpts)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Error creating ELB: %s", err)
|
||||
}
|
||||
|
||||
// Assign the elb's unique identifer for use later
|
||||
rs.ID = elbName
|
||||
log.Printf("[INFO] ELB ID: %s", elbName)
|
||||
|
||||
// If we have any instances, we need to register them
|
||||
v = flatmap.Expand(rs.Attributes, "instances").([]interface{})
|
||||
instances := expandStringList(v)
|
||||
|
||||
if len(instances) > 0 {
|
||||
registerInstancesOpts := elb.RegisterInstancesWithLoadBalancer{
|
||||
LoadBalancerName: elbName,
|
||||
Instances: instances,
|
||||
}
|
||||
|
||||
_, err := elbconn.RegisterInstancesWithLoadBalancer(®isterInstancesOpts)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Failure registering instances: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
describeElbOpts := &elb.DescribeLoadBalancer{
|
||||
Names: []string{elbName},
|
||||
}
|
||||
|
||||
// Retrieve the ELB properties for updating the state
|
||||
describeResp, err := elbconn.DescribeLoadBalancers(describeElbOpts)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Error retrieving ELB: %s", err)
|
||||
}
|
||||
|
||||
loadBalancer := describeResp.LoadBalancers[0]
|
||||
|
||||
// Verify AWS returned our ELB
|
||||
if len(describeResp.LoadBalancers) != 1 ||
|
||||
describeResp.LoadBalancers[0].LoadBalancerName != elbName {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Unable to find ELB: %#v", describeResp.LoadBalancers)
|
||||
}
|
||||
}
|
||||
|
||||
return resource_aws_elb_update_state(rs, &loadBalancer)
|
||||
}
|
||||
|
||||
func resource_aws_elb_update(
|
||||
s *terraform.ResourceState,
|
||||
d *terraform.ResourceDiff,
|
||||
meta interface{}) (*terraform.ResourceState, error) {
|
||||
// p := meta.(*ResourceProvider)
|
||||
// elbconn := p.elbconn
|
||||
|
||||
// Merge the diff into the state so that we have all the attributes
|
||||
// properly.
|
||||
// rs := s.MergeDiff(d)
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func resource_aws_elb_destroy(
|
||||
s *terraform.ResourceState,
|
||||
meta interface{}) error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func resource_aws_elb_refresh(
|
||||
s *terraform.ResourceState,
|
||||
meta interface{}) (*terraform.ResourceState, error) {
|
||||
|
||||
loadBalancer := &elb.LoadBalancer{}
|
||||
|
||||
return resource_aws_elb_update_state(s, loadBalancer)
|
||||
}
|
||||
|
||||
func resource_aws_elb_diff(
|
||||
s *terraform.ResourceState,
|
||||
c *terraform.ResourceConfig,
|
||||
meta interface{}) (*terraform.ResourceDiff, error) {
|
||||
|
||||
b := &diff.ResourceBuilder{
|
||||
Attrs: map[string]diff.AttrType{
|
||||
"name": diff.AttrTypeCreate,
|
||||
"availability_zone": diff.AttrTypeCreate,
|
||||
"listener": diff.AttrTypeCreate,
|
||||
"instances": diff.AttrTypeUpdate,
|
||||
},
|
||||
|
||||
ComputedAttrs: []string{
|
||||
"dns_name",
|
||||
},
|
||||
}
|
||||
|
||||
return b.Diff(s, c)
|
||||
}
|
||||
|
||||
func resource_aws_elb_update_state(
|
||||
s *terraform.ResourceState,
|
||||
balancer *elb.LoadBalancer) (*terraform.ResourceState, error) {
|
||||
s.Attributes["name"] = balancer.LoadBalancerName
|
||||
s.Attributes["dns_name"] = balancer.DNSName
|
||||
return s, nil
|
||||
}
|
|
@ -0,0 +1,193 @@
|
|||
package aws
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/terraform/helper/diff"
|
||||
"github.com/hashicorp/terraform/helper/resource"
|
||||
"github.com/hashicorp/terraform/terraform"
|
||||
"github.com/mitchellh/goamz/ec2"
|
||||
)
|
||||
|
||||
func resource_aws_instance_create(
|
||||
s *terraform.ResourceState,
|
||||
d *terraform.ResourceDiff,
|
||||
meta interface{}) (*terraform.ResourceState, error) {
|
||||
p := meta.(*ResourceProvider)
|
||||
ec2conn := p.ec2conn
|
||||
|
||||
// Merge the diff into the state so that we have all the attributes
|
||||
// properly.
|
||||
rs := s.MergeDiff(d)
|
||||
|
||||
// Create the instance
|
||||
runOpts := &ec2.RunInstances{
|
||||
ImageId: rs.Attributes["ami"],
|
||||
InstanceType: rs.Attributes["instance_type"],
|
||||
}
|
||||
log.Printf("[DEBUG] Run configuration: %#v", runOpts)
|
||||
runResp, err := ec2conn.RunInstances(runOpts)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Error launching source instance: %s", err)
|
||||
}
|
||||
|
||||
instance := &runResp.Instances[0]
|
||||
log.Printf("[INFO] Instance ID: %s", instance.InstanceId)
|
||||
|
||||
// Store the resulting ID so we can look this up later
|
||||
rs.ID = instance.InstanceId
|
||||
|
||||
// Wait for the instance to become running so we can get some attributes
|
||||
// that aren't available until later.
|
||||
log.Printf(
|
||||
"[DEBUG] Waiting for instance (%s) to become running",
|
||||
instance.InstanceId)
|
||||
|
||||
stateConf := &resource.StateChangeConf{
|
||||
Pending: []string{"pending"},
|
||||
Target: "running",
|
||||
Refresh: InstanceStateRefreshFunc(ec2conn, instance.InstanceId),
|
||||
Timeout: 10 * time.Minute,
|
||||
}
|
||||
|
||||
instanceRaw, err := stateConf.WaitForState()
|
||||
|
||||
if err != nil {
|
||||
return rs, fmt.Errorf(
|
||||
"Error waiting for instance (%s) to become ready: %s",
|
||||
instance.InstanceId, err)
|
||||
}
|
||||
|
||||
instance = instanceRaw.(*ec2.Instance)
|
||||
|
||||
// Set our attributes
|
||||
return resource_aws_instance_update_state(rs, instance)
|
||||
}
|
||||
|
||||
func resource_aws_instance_destroy(
|
||||
s *terraform.ResourceState,
|
||||
meta interface{}) error {
|
||||
p := meta.(*ResourceProvider)
|
||||
ec2conn := p.ec2conn
|
||||
|
||||
log.Printf("[INFO] Terminating instance: %s", s.ID)
|
||||
if _, err := ec2conn.TerminateInstances([]string{s.ID}); err != nil {
|
||||
return fmt.Errorf("Error terminating instance: %s", err)
|
||||
}
|
||||
|
||||
log.Printf(
|
||||
"[DEBUG] Waiting for instance (%s) to become terminated",
|
||||
s.ID)
|
||||
|
||||
stateConf := &resource.StateChangeConf{
|
||||
Pending: []string{"pending", "running", "shutting-down", "stopped", "stopping"},
|
||||
Target: "terminated",
|
||||
Refresh: InstanceStateRefreshFunc(ec2conn, s.ID),
|
||||
Timeout: 10 * time.Minute,
|
||||
}
|
||||
|
||||
_, err := stateConf.WaitForState()
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf(
|
||||
"Error waiting for instance (%s) to terminate: %s",
|
||||
s.ID, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func resource_aws_instance_diff(
|
||||
s *terraform.ResourceState,
|
||||
c *terraform.ResourceConfig,
|
||||
meta interface{}) (*terraform.ResourceDiff, error) {
|
||||
b := &diff.ResourceBuilder{
|
||||
Attrs: map[string]diff.AttrType{
|
||||
"ami": diff.AttrTypeCreate,
|
||||
"availability_zone": diff.AttrTypeCreate,
|
||||
"instance_type": diff.AttrTypeCreate,
|
||||
},
|
||||
|
||||
ComputedAttrs: []string{
|
||||
"public_dns",
|
||||
"public_ip",
|
||||
"private_dns",
|
||||
"private_ip",
|
||||
"instance_id",
|
||||
},
|
||||
}
|
||||
|
||||
return b.Diff(s, c)
|
||||
}
|
||||
|
||||
func resource_aws_instance_refresh(
|
||||
s *terraform.ResourceState,
|
||||
meta interface{}) (*terraform.ResourceState, error) {
|
||||
p := meta.(*ResourceProvider)
|
||||
ec2conn := p.ec2conn
|
||||
|
||||
resp, err := ec2conn.Instances([]string{s.ID}, ec2.NewFilter())
|
||||
if err != nil {
|
||||
// If the instance was not found, return nil so that we can show
|
||||
// that the instance is gone.
|
||||
if ec2err, ok := err.(*ec2.Error); ok && ec2err.Code == "InvalidInstanceID.NotFound" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Some other error, report it
|
||||
return s, err
|
||||
}
|
||||
|
||||
// If nothing was found, then return no state
|
||||
if len(resp.Reservations) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
instance := &resp.Reservations[0].Instances[0]
|
||||
|
||||
// If the instance is terminated, then it is gone
|
||||
if instance.State.Name == "terminated" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return resource_aws_instance_update_state(s, instance)
|
||||
}
|
||||
|
||||
func resource_aws_instance_update_state(
|
||||
s *terraform.ResourceState,
|
||||
instance *ec2.Instance) (*terraform.ResourceState, error) {
|
||||
s.Attributes["public_dns"] = instance.DNSName
|
||||
s.Attributes["public_ip"] = instance.PublicIpAddress
|
||||
s.Attributes["private_dns"] = instance.PrivateDNSName
|
||||
s.Attributes["private_ip"] = instance.PrivateIpAddress
|
||||
s.Attributes["instance_id"] = instance.InstanceId
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// InstanceStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch
|
||||
// an EC2 instance.
|
||||
func InstanceStateRefreshFunc(conn *ec2.EC2, instanceID string) resource.StateRefreshFunc {
|
||||
return func() (interface{}, string, error) {
|
||||
resp, err := conn.Instances([]string{instanceID}, ec2.NewFilter())
|
||||
if err != nil {
|
||||
if ec2err, ok := err.(*ec2.Error); ok && ec2err.Code == "InvalidInstanceID.NotFound" {
|
||||
// Set this to nil as if we didn't find anything.
|
||||
resp = nil
|
||||
} else {
|
||||
log.Printf("Error on InstanceStateRefresh: %s", err)
|
||||
return nil, "", err
|
||||
}
|
||||
}
|
||||
|
||||
if resp == nil || len(resp.Reservations) == 0 || len(resp.Reservations[0].Instances) == 0 {
|
||||
// Sometimes AWS just has consistency issues and doesn't see
|
||||
// our instance yet. Return an empty state.
|
||||
return nil, "", nil
|
||||
}
|
||||
|
||||
i := &resp.Reservations[0].Instances[0]
|
||||
return i, i.State.Name, nil
|
||||
}
|
||||
}
|
|
@ -7,12 +7,14 @@ import (
|
|||
"github.com/hashicorp/terraform/helper/multierror"
|
||||
"github.com/hashicorp/terraform/terraform"
|
||||
"github.com/mitchellh/goamz/ec2"
|
||||
"github.com/mitchellh/goamz/elb"
|
||||
)
|
||||
|
||||
type ResourceProvider struct {
|
||||
Config Config
|
||||
|
||||
ec2conn *ec2.EC2
|
||||
elbconn *elb.ELB
|
||||
}
|
||||
|
||||
func (p *ResourceProvider) Validate(c *terraform.ResourceConfig) ([]string, []error) {
|
||||
|
@ -47,6 +49,8 @@ func (p *ResourceProvider) Configure(c *terraform.ResourceConfig) error {
|
|||
if len(errs) == 0 {
|
||||
log.Println("Initializing EC2 connection")
|
||||
p.ec2conn = ec2.New(auth, region)
|
||||
log.Println("Initializing ELB connection")
|
||||
p.elbconn = elb.New(auth, region)
|
||||
}
|
||||
|
||||
if len(errs) > 0 {
|
||||
|
|
|
@ -1,13 +1,7 @@
|
|||
package aws
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/hashicorp/terraform/helper/diff"
|
||||
"github.com/hashicorp/terraform/helper/resource"
|
||||
"github.com/hashicorp/terraform/terraform"
|
||||
"github.com/mitchellh/goamz/ec2"
|
||||
)
|
||||
|
||||
// resourceMap is the mapping of resources we support to their basic
|
||||
|
@ -23,148 +17,13 @@ func init() {
|
|||
Diff: resource_aws_instance_diff,
|
||||
Refresh: resource_aws_instance_refresh,
|
||||
},
|
||||
"aws_elb": resource.Resource{
|
||||
Create: resource_aws_elb_create,
|
||||
Update: resource_aws_elb_update,
|
||||
Destroy: resource_aws_elb_destroy,
|
||||
Diff: resource_aws_elb_diff,
|
||||
Refresh: resource_aws_elb_refresh,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func resource_aws_instance_create(
|
||||
s *terraform.ResourceState,
|
||||
d *terraform.ResourceDiff,
|
||||
meta interface{}) (*terraform.ResourceState, error) {
|
||||
p := meta.(*ResourceProvider)
|
||||
ec2conn := p.ec2conn
|
||||
|
||||
// Merge the diff into the state so that we have all the attributes
|
||||
// properly.
|
||||
rs := s.MergeDiff(d)
|
||||
|
||||
// Create the instance
|
||||
runOpts := &ec2.RunInstances{
|
||||
ImageId: rs.Attributes["ami"],
|
||||
InstanceType: rs.Attributes["instance_type"],
|
||||
}
|
||||
log.Printf("[DEBUG] Run configuration: %#v", runOpts)
|
||||
runResp, err := ec2conn.RunInstances(runOpts)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Error launching source instance: %s", err)
|
||||
}
|
||||
|
||||
instance := &runResp.Instances[0]
|
||||
log.Printf("[INFO] Instance ID: %s", instance.InstanceId)
|
||||
|
||||
// Store the resulting ID so we can look this up later
|
||||
rs.ID = instance.InstanceId
|
||||
|
||||
// Wait for the instance to become running so we can get some attributes
|
||||
// that aren't available until later.
|
||||
log.Printf(
|
||||
"[DEBUG] Waiting for instance (%s) to become running",
|
||||
instance.InstanceId)
|
||||
instanceRaw, err := WaitForState(&StateChangeConf{
|
||||
Pending: []string{"pending"},
|
||||
Target: "running",
|
||||
Refresh: InstanceStateRefreshFunc(ec2conn, instance.InstanceId),
|
||||
})
|
||||
if err != nil {
|
||||
return rs, fmt.Errorf(
|
||||
"Error waiting for instance (%s) to become ready: %s",
|
||||
instance.InstanceId, err)
|
||||
}
|
||||
instance = instanceRaw.(*ec2.Instance)
|
||||
|
||||
// Set our attributes
|
||||
return resource_aws_instance_update_state(rs, instance)
|
||||
}
|
||||
|
||||
func resource_aws_instance_destroy(
|
||||
s *terraform.ResourceState,
|
||||
meta interface{}) error {
|
||||
p := meta.(*ResourceProvider)
|
||||
ec2conn := p.ec2conn
|
||||
|
||||
log.Printf("[INFO] Terminating instance: %s", s.ID)
|
||||
if _, err := ec2conn.TerminateInstances([]string{s.ID}); err != nil {
|
||||
return fmt.Errorf("Error terminating instance: %s", err)
|
||||
}
|
||||
|
||||
log.Printf(
|
||||
"[DEBUG] Waiting for instance (%s) to become terminated",
|
||||
s.ID)
|
||||
_, err := WaitForState(&StateChangeConf{
|
||||
Pending: []string{"pending", "running", "shutting-down", "stopped", "stopping"},
|
||||
Target: "terminated",
|
||||
Refresh: InstanceStateRefreshFunc(ec2conn, s.ID),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf(
|
||||
"Error waiting for instance (%s) to terminate: %s",
|
||||
s.ID, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func resource_aws_instance_diff(
|
||||
s *terraform.ResourceState,
|
||||
c *terraform.ResourceConfig,
|
||||
meta interface{}) (*terraform.ResourceDiff, error) {
|
||||
b := &diff.ResourceBuilder{
|
||||
Attrs: map[string]diff.AttrType{
|
||||
"ami": diff.AttrTypeCreate,
|
||||
"availability_zone": diff.AttrTypeCreate,
|
||||
"instance_type": diff.AttrTypeCreate,
|
||||
},
|
||||
|
||||
ComputedAttrs: []string{
|
||||
"public_dns",
|
||||
"public_ip",
|
||||
"private_dns",
|
||||
"private_ip",
|
||||
},
|
||||
}
|
||||
|
||||
return b.Diff(s, c)
|
||||
}
|
||||
|
||||
func resource_aws_instance_refresh(
|
||||
s *terraform.ResourceState,
|
||||
meta interface{}) (*terraform.ResourceState, error) {
|
||||
p := meta.(*ResourceProvider)
|
||||
ec2conn := p.ec2conn
|
||||
|
||||
resp, err := ec2conn.Instances([]string{s.ID}, ec2.NewFilter())
|
||||
if err != nil {
|
||||
// If the instance was not found, return nil so that we can show
|
||||
// that the instance is gone.
|
||||
if ec2err, ok := err.(*ec2.Error); ok && ec2err.Code == "InvalidInstanceID.NotFound" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Some other error, report it
|
||||
return s, err
|
||||
}
|
||||
|
||||
// If nothing was found, then return no state
|
||||
if len(resp.Reservations) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
instance := &resp.Reservations[0].Instances[0]
|
||||
|
||||
// If the instance is terminated, then it is gone
|
||||
if instance.State.Name == "terminated" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return resource_aws_instance_update_state(s, instance)
|
||||
}
|
||||
|
||||
func resource_aws_instance_update_state(
|
||||
s *terraform.ResourceState,
|
||||
instance *ec2.Instance) (*terraform.ResourceState, error) {
|
||||
s.Attributes["public_dns"] = instance.DNSName
|
||||
s.Attributes["public_ip"] = instance.PublicIpAddress
|
||||
s.Attributes["private_dns"] = instance.PrivateDNSName
|
||||
s.Attributes["private_ip"] = instance.PrivateIpAddress
|
||||
return s, nil
|
||||
}
|
||||
|
|
|
@ -1,104 +0,0 @@
|
|||
package aws
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/mitchellh/goamz/ec2"
|
||||
)
|
||||
|
||||
// StateRefreshFunc is a function type used for StateChangeConf that is
|
||||
// responsible for refreshing the item being watched for a state change.
|
||||
//
|
||||
// It returns three results. `result` is any object that will be returned
|
||||
// as the final object after waiting for state change. This allows you to
|
||||
// return the final updated object, for example an EC2 instance after refreshing
|
||||
// it.
|
||||
//
|
||||
// `state` is the latest state of that object. And `err` is any error that
|
||||
// may have happened while refreshing the state.
|
||||
type StateRefreshFunc func() (result interface{}, state string, err error)
|
||||
|
||||
// StateChangeConf is the configuration struct used for `WaitForState`.
|
||||
type StateChangeConf struct {
|
||||
Pending []string
|
||||
Refresh StateRefreshFunc
|
||||
Target string
|
||||
}
|
||||
|
||||
// InstanceStateRefreshFunc returns a StateRefreshFunc that is used to watch
|
||||
// an EC2 instance.
|
||||
func InstanceStateRefreshFunc(conn *ec2.EC2, instanceID string) StateRefreshFunc {
|
||||
return func() (interface{}, string, error) {
|
||||
resp, err := conn.Instances([]string{instanceID}, ec2.NewFilter())
|
||||
if err != nil {
|
||||
if ec2err, ok := err.(*ec2.Error); ok && ec2err.Code == "InvalidInstanceID.NotFound" {
|
||||
// Set this to nil as if we didn't find anything.
|
||||
resp = nil
|
||||
} else {
|
||||
log.Printf("Error on InstanceStateRefresh: %s", err)
|
||||
return nil, "", err
|
||||
}
|
||||
}
|
||||
|
||||
if resp == nil || len(resp.Reservations) == 0 || len(resp.Reservations[0].Instances) == 0 {
|
||||
// Sometimes AWS just has consistency issues and doesn't see
|
||||
// our instance yet. Return an empty state.
|
||||
return nil, "", nil
|
||||
}
|
||||
|
||||
i := &resp.Reservations[0].Instances[0]
|
||||
return i, i.State.Name, nil
|
||||
}
|
||||
}
|
||||
|
||||
// WaitForState watches an object and waits for it to achieve a certain
|
||||
// state.
|
||||
func WaitForState(conf *StateChangeConf) (i interface{}, err error) {
|
||||
log.Printf("Waiting for state to become: %s", conf.Target)
|
||||
|
||||
notfoundTick := 0
|
||||
|
||||
for {
|
||||
var currentState string
|
||||
i, currentState, err = conf.Refresh()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if i == nil {
|
||||
// If we didn't find the resource, check if we have been
|
||||
// not finding it for awhile, and if so, report an error.
|
||||
notfoundTick += 1
|
||||
if notfoundTick > 20 {
|
||||
return nil, errors.New("couldn't find resource")
|
||||
}
|
||||
} else {
|
||||
// Reset the counter for when a resource isn't found
|
||||
notfoundTick = 0
|
||||
|
||||
if currentState == conf.Target {
|
||||
return
|
||||
}
|
||||
|
||||
found := false
|
||||
for _, allowed := range conf.Pending {
|
||||
if currentState == allowed {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !found {
|
||||
fmt.Errorf("unexpected state '%s', wanted target '%s'", currentState, conf.Target)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
package aws
|
||||
|
||||
import (
|
||||
"github.com/mitchellh/goamz/elb"
|
||||
)
|
||||
|
||||
// Takes the result of flatmap.Expand for an array of listeners and
|
||||
// returns ELB API compatible objects
|
||||
func expandListeners(configured []interface{}) []elb.Listener {
|
||||
listeners := make([]elb.Listener, 0, len(configured))
|
||||
|
||||
// Loop over our configured listeners and create
|
||||
// an array of goamz compatabile objects
|
||||
for _, listener := range configured {
|
||||
newL := listener.(map[string]interface{})
|
||||
|
||||
l := elb.Listener{
|
||||
InstancePort: int64(newL["instance_port"].(int)),
|
||||
InstanceProtocol: newL["instance_protocol"].(string),
|
||||
LoadBalancerPort: int64(newL["lb_port"].(int)),
|
||||
Protocol: newL["lb_protocol"].(string),
|
||||
}
|
||||
|
||||
listeners = append(listeners, l)
|
||||
}
|
||||
|
||||
return listeners
|
||||
}
|
||||
|
||||
// Takes the result of flatmap.Expand for an array of strings
|
||||
// and returns a []string
|
||||
func expandStringList(configured []interface{}) []string {
|
||||
vs := make([]string, 0, len(configured))
|
||||
for _, v := range configured {
|
||||
vs = append(vs, v.(string))
|
||||
}
|
||||
return vs
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
package aws
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/terraform/flatmap"
|
||||
"github.com/mitchellh/goamz/elb"
|
||||
)
|
||||
|
||||
// Returns test configuration
|
||||
func testConf() map[string]string {
|
||||
return map[string]string{
|
||||
"listener.#": "1",
|
||||
"listener.0.lb_port": "80",
|
||||
"listener.0.lb_protocol": "http",
|
||||
"listener.0.instance_port": "8000",
|
||||
"listener.0.instance_protocol": "http",
|
||||
"availability_zones.#": "2",
|
||||
"availability_zones.0": "us-east-1a",
|
||||
"availability_zones.1": "us-east-1b",
|
||||
}
|
||||
}
|
||||
|
||||
func Test_expandListeners(t *testing.T) {
|
||||
expanded := flatmap.Expand(testConf(), "listener").([]interface{})
|
||||
listeners := expandListeners(expanded)
|
||||
expected := elb.Listener{
|
||||
InstancePort: 8000,
|
||||
LoadBalancerPort: 80,
|
||||
InstanceProtocol: "http",
|
||||
Protocol: "http",
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(listeners[0], expected) {
|
||||
t.Fatalf(
|
||||
"Got:\n\n%#v\n\nExpected:\n\n%#v\n",
|
||||
listeners[0],
|
||||
expected)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func Test_expandStringList(t *testing.T) {
|
||||
expanded := flatmap.Expand(testConf(), "availability_zones").([]interface{})
|
||||
stringList := expandStringList(expanded)
|
||||
expected := []string{
|
||||
"us-east-1a",
|
||||
"us-east-1b",
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(stringList, expected) {
|
||||
t.Fatalf(
|
||||
"Got:\n\n%#v\n\nExpected:\n\n%#v\n",
|
||||
stringList,
|
||||
expected)
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,100 @@
|
|||
package resource
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
// StateRefreshFunc is a function type used for StateChangeConf that is
|
||||
// responsible for refreshing the item being watched for a state change.
|
||||
//
|
||||
// It returns three results. `result` is any object that will be returned
|
||||
// as the final object after waiting for state change. This allows you to
|
||||
// return the final updated object, for example an EC2 instance after refreshing
|
||||
// it.
|
||||
//
|
||||
// `state` is the latest state of that object. And `err` is any error that
|
||||
// may have happened while refreshing the state.
|
||||
type StateRefreshFunc func() (result interface{}, state string, err error)
|
||||
|
||||
// StateChangeConf is the configuration struct used for `WaitForState`.
|
||||
type StateChangeConf struct {
|
||||
Pending []string // States that are "allowed" and will continue trying
|
||||
Refresh StateRefreshFunc // Refreshes the current state
|
||||
Target string // Target state
|
||||
Timeout time.Duration // The amount of time to wait before timeout
|
||||
}
|
||||
|
||||
type waitResult struct {
|
||||
obj interface{}
|
||||
err error
|
||||
}
|
||||
|
||||
// WaitForState watches an object and waits for it to achieve the state
|
||||
// specified in the configuration using the specified Refresh() func,
|
||||
// waiting the number of seconds specified in the timeout configuration.
|
||||
func (conf *StateChangeConf) WaitForState() (i interface{}, err error) {
|
||||
log.Printf("Waiting for state to become: %s", conf.Target)
|
||||
|
||||
notfoundTick := 0
|
||||
|
||||
result := make(chan waitResult, 1)
|
||||
|
||||
go func() {
|
||||
for {
|
||||
var currentState string
|
||||
i, currentState, err = conf.Refresh()
|
||||
if err != nil {
|
||||
result <- waitResult{nil, err}
|
||||
return
|
||||
}
|
||||
|
||||
if i == nil {
|
||||
// If we didn't find the resource, check if we have been
|
||||
// not finding it for awhile, and if so, report an error.
|
||||
notfoundTick += 1
|
||||
if notfoundTick > 20 {
|
||||
result <- waitResult{nil, errors.New("couldn't find resource")}
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// Reset the counter for when a resource isn't found
|
||||
notfoundTick = 0
|
||||
|
||||
if currentState == conf.Target {
|
||||
result <- waitResult{i, nil}
|
||||
return
|
||||
}
|
||||
|
||||
found := false
|
||||
for _, allowed := range conf.Pending {
|
||||
if currentState == allowed {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !found {
|
||||
result <- waitResult{nil, fmt.Errorf("unexpected state '%s', wanted target '%s'", currentState, conf.Target)}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Wait between refreshes
|
||||
time.Sleep(2 * time.Second)
|
||||
}()
|
||||
|
||||
select {
|
||||
case waitResult := <-result:
|
||||
err := waitResult.err
|
||||
i = waitResult.obj
|
||||
return i, err
|
||||
case <-time.After(conf.Timeout):
|
||||
err := fmt.Errorf("timeout while waiting for state to become '%s'", conf.Target)
|
||||
i = nil
|
||||
return i, err
|
||||
}
|
||||
}
|
|
@ -0,0 +1,87 @@
|
|||
package resource
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type nullObject struct{}
|
||||
|
||||
func FailedStateRefreshFunc() StateRefreshFunc {
|
||||
return func() (interface{}, string, error) {
|
||||
return nil, "", errors.New("failed")
|
||||
}
|
||||
}
|
||||
|
||||
func TimeoutStateRefreshFunc() StateRefreshFunc {
|
||||
return func() (interface{}, string, error) {
|
||||
time.Sleep(100 * time.Second)
|
||||
return nil, "", errors.New("failed")
|
||||
}
|
||||
}
|
||||
|
||||
func SuccessfulStateRefreshFunc() StateRefreshFunc {
|
||||
return func() (interface{}, string, error) {
|
||||
return &nullObject{}, "running", nil
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitForState_timeout(t *testing.T) {
|
||||
conf := &StateChangeConf{
|
||||
Pending: []string{"pending", "incomplete"},
|
||||
Target: "running",
|
||||
Refresh: TimeoutStateRefreshFunc(),
|
||||
Timeout: 1 * time.Millisecond,
|
||||
}
|
||||
|
||||
obj, err := conf.WaitForState()
|
||||
|
||||
if err == nil && err.Error() != "timeout while waiting for state to become 'running'" {
|
||||
t.Fatalf("err: %s", err)
|
||||
}
|
||||
|
||||
if obj != nil {
|
||||
t.Fatalf("should not return obj")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestWaitForState_success(t *testing.T) {
|
||||
conf := &StateChangeConf{
|
||||
Pending: []string{"pending", "incomplete"},
|
||||
Target: "running",
|
||||
Refresh: SuccessfulStateRefreshFunc(),
|
||||
Timeout: 200 * time.Second,
|
||||
}
|
||||
|
||||
obj, err := conf.WaitForState()
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("err: %s", err)
|
||||
}
|
||||
|
||||
if obj == nil {
|
||||
t.Fatalf("should return obj")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestWaitForState_failure(t *testing.T) {
|
||||
conf := &StateChangeConf{
|
||||
Pending: []string{"pending", "incomplete"},
|
||||
Target: "running",
|
||||
Refresh: FailedStateRefreshFunc(),
|
||||
Timeout: 200 * time.Second,
|
||||
}
|
||||
|
||||
obj, err := conf.WaitForState()
|
||||
|
||||
if err == nil && err.Error() != "failed" {
|
||||
t.Fatalf("err: %s", err)
|
||||
}
|
||||
|
||||
if obj != nil {
|
||||
t.Fatalf("should not return obj")
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue