<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_config_configuration_recorder.go<|end_filename|>
package aws

import (
	"fmt"
	"log"

	"github.com/hashicorp/terraform/helper/schema"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/configservice"
)

func resourceAwsConfigConfigurationRecorder() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsConfigConfigurationRecorderPut,
		Read:   resourceAwsConfigConfigurationRecorderRead,
		Update: resourceAwsConfigConfigurationRecorderPut,
		Delete: resourceAwsConfigConfigurationRecorderDelete,

		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"name": {
				Type:         schema.TypeString,
				Optional:     true,
				ForceNew:     true,
				Default:      "default",
				ValidateFunc: validateMaxLength(256),
			},
			"role_arn": {
				Type:         schema.TypeString,
				Required:     true,
				ValidateFunc: validateArn,
			},
			"recording_group": {
				Type:     schema.TypeList,
				Optional: true,
				Computed: true,
				MaxItems: 1,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"all_supported": {
							Type:     schema.TypeBool,
							Optional: true,
							Default:  true,
						},
						"include_global_resource_types": {
							Type:     schema.TypeBool,
							Optional: true,
						},
						"resource_types": {
							Type:     schema.TypeSet,
							Set:      schema.HashString,
							Optional: true,
							Elem:     &schema.Schema{Type: schema.TypeString},
						},
					},
				},
			},
		},
	}
}

func resourceAwsConfigConfigurationRecorderPut(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).configconn

	name := d.Get("name").(string)
	recorder := configservice.ConfigurationRecorder{
		Name:    aws.String(name),
		RoleARN: aws.String(d.Get("role_arn").(string)),
	}

	if g, ok := d.GetOk("recording_group"); ok {
		recorder.RecordingGroup = expandConfigRecordingGroup(g.([]interface{}))
	}

	input := configservice.PutConfigurationRecorderInput{
		ConfigurationRecorder: &recorder,
	}
	_, err := conn.PutConfigurationRecorder(&input)
	if err != nil {
		return fmt.Errorf("Creating Configuration Recorder failed: %s", err)
	}

	d.SetId(name)

	return resourceAwsConfigConfigurationRecorderRead(d, meta)
}

func resourceAwsConfigConfigurationRecorderRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).configconn

	input := configservice.DescribeConfigurationRecordersInput{
		ConfigurationRecorderNames: []*string{aws.String(d.Id())},
	}
	out, err := conn.DescribeConfigurationRecorders(&input)
	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoSuchConfigurationRecorderException" {
			log.Printf("[WARN] Configuration Recorder %q is gone (NoSuchConfigurationRecorderException)", d.Id())
			d.SetId("")
			return nil
		}
		return fmt.Errorf("Getting Configuration Recorder failed: %s", err)
	}

	numberOfRecorders := len(out.ConfigurationRecorders)
	if numberOfRecorders < 1 {
		log.Printf("[WARN] Configuration Recorder %q is gone (no recorders found)", d.Id())
		d.SetId("")
		return nil
	}

	if numberOfRecorders > 1 {
		return fmt.Errorf("Expected exactly 1 Configuration Recorder, received %d: %#v",
			numberOfRecorders, out.ConfigurationRecorders)
	}

	recorder := out.ConfigurationRecorders[0]

	d.Set("name", recorder.Name)
	d.Set("role_arn", recorder.RoleARN)

	if recorder.RecordingGroup != nil {
		flattened := flattenConfigRecordingGroup(recorder.RecordingGroup)
		err = d.Set("recording_group", flattened)
		if err != nil {
			return fmt.Errorf("Failed to set recording_group: %s", err)
		}
	}

	return nil
}

func resourceAwsConfigConfigurationRecorderDelete(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).configconn
	input := configservice.DeleteConfigurationRecorderInput{
		ConfigurationRecorderName: aws.String(d.Id()),
	}
	_, err := conn.DeleteConfigurationRecorder(&input)
	if err != nil {
		return fmt.Errorf("Deleting Configuration Recorder failed: %s", err)
	}

	d.SetId("")
	return nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/command/refresh.go<|end_filename|>
package command

import (
	"context"
	"fmt"
	"strings"

	"github.com/hashicorp/terraform/backend"
	"github.com/hashicorp/terraform/config"
	"github.com/hashicorp/terraform/terraform"
	"github.com/hashicorp/terraform/tfdiags"
)

// RefreshCommand is a cli.Command implementation that refreshes the state
// file.
type RefreshCommand struct {
	Meta
}

func (c *RefreshCommand) Run(args []string) int {
	args, err := c.Meta.process(args, true)
	if err != nil {
		return 1
	}

	cmdFlags := c.Meta.flagSet("refresh")
	cmdFlags.StringVar(&c.Meta.statePath, "state", DefaultStateFilename, "path")
	cmdFlags.IntVar(&c.Meta.parallelism, "parallelism", 0, "parallelism")
	cmdFlags.StringVar(&c.Meta.stateOutPath, "state-out", "", "path")
	cmdFlags.StringVar(&c.Meta.backupPath, "backup", "", "path")
	cmdFlags.BoolVar(&c.Meta.stateLock, "lock", true, "lock state")
	cmdFlags.DurationVar(&c.Meta.stateLockTimeout, "lock-timeout", 0, "lock timeout")
	cmdFlags.Usage = func() { c.Ui.Error(c.Help()) }
	if err := cmdFlags.Parse(args); err != nil {
		return 1
	}

	configPath, err := ModulePath(cmdFlags.Args())
	if err != nil {
		c.Ui.Error(err.Error())
		return 1
	}

	var diags tfdiags.Diagnostics

	// Load the module
	mod, diags := c.Module(configPath)
	if diags.HasErrors() {
		c.showDiagnostics(diags)
		return 1
	}

	// Check for user-supplied plugin path
	if c.pluginPath, err = c.loadPluginPath(); err != nil {
		c.Ui.Error(fmt.Sprintf("Error loading plugin path: %s", err))
		return 1
	}

	var conf *config.Config
	if mod != nil {
		conf = mod.Config()
	}

	// Load the backend
	b, err := c.Backend(&BackendOpts{
		Config: conf,
	})
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Failed to load backend: %s", err))
		return 1
	}

	// Build the operation
	opReq := c.Operation()
	opReq.Type = backend.OperationTypeRefresh
	opReq.Module = mod

	// Perform the operation
	op, err := b.Operation(context.Background(), opReq)
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Error starting operation: %s", err))
		return 1
	}

	// Wait for the operation to complete
	<-op.Done()
	if err := op.Err; err != nil {
		diags = diags.Append(err)
	}

	c.showDiagnostics(diags)
	if diags.HasErrors() {
		return 1
	}

	// Output the outputs
	if outputs := outputsAsString(op.State, terraform.RootModulePath, nil, true); outputs != "" {
		c.Ui.Output(c.Colorize().Color(outputs))
	}

	return 0
}

func (c *RefreshCommand) Help() string {
	helpText := `
Usage: terraform refresh [options] [dir]

  Update the state file of your infrastructure with metadata that matches
  the physical resources they are tracking.

  This will not modify your infrastructure, but it can modify your
  state file to update metadata. This metadata might cause new changes
  to occur when you generate a plan or call apply next.

Options:

  -backup=path        Path to backup the existing state file before
                      modifying. Defaults to the "-state-out" path with
                      ".backup" extension. Set to "-" to disable backup.

  -input=true         Ask for input for variables if not directly set.

  -lock=true          Lock the state file when locking is supported.

  -lock-timeout=0s    Duration to retry a state lock.

  -no-color           If specified, output won't contain any color.

  -state=path         Path to read and save state (unless state-out
                      is specified). Defaults to "terraform.tfstate".

  -state-out=path     Path to write updated state file. By default, the
                      "-state" path will be used.

  -target=resource    Resource to target. Operation will be limited to this
                      resource and its dependencies. This flag can be used
                      multiple times.

  -var 'foo=bar'      Set a variable in the Terraform configuration. This
                      flag can be set multiple times.

  -var-file=foo       Set variables in the Terraform configuration from
                      a file. If "terraform.tfvars" or any ".auto.tfvars"
                      files are present, they will be automatically loaded.

`
	return strings.TrimSpace(helpText)
}

func (c *RefreshCommand) Synopsis() string {
	return "Update local state file against real resources"
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/aws/aws-sdk-go/service/servicediscovery/api.go<|end_filename|>
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.

package servicediscovery

import (
	"fmt"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awsutil"
	"github.com/aws/aws-sdk-go/aws/request"
)

const opCreatePrivateDnsNamespace = "CreatePrivateDnsNamespace"

// CreatePrivateDnsNamespaceRequest generates a "aws/request.Request" representing the
// client's request for the CreatePrivateDnsNamespace operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See CreatePrivateDnsNamespace for more information on using the CreatePrivateDnsNamespace
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the CreatePrivateDnsNamespaceRequest method.
//    req, resp := client.CreatePrivateDnsNamespaceRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/CreatePrivateDnsNamespace
func (c *ServiceDiscovery) CreatePrivateDnsNamespaceRequest(input *CreatePrivateDnsNamespaceInput) (req *request.Request, output *CreatePrivateDnsNamespaceOutput) {
	op := &request.Operation{
		Name:       opCreatePrivateDnsNamespace,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &CreatePrivateDnsNamespaceInput{}
	}

	output = &CreatePrivateDnsNamespaceOutput{}
	req = c.newRequest(op, input, output)
	return
}

// CreatePrivateDnsNamespace API operation for Amazon Route 53 Auto Naming.
//
// Creates a private namespace based on DNS, which will be visible only inside
// a specified Amazon VPC. The namespace defines your service naming scheme.
// For example, if you name your namespace example.com and name your service
// backend, the resulting DNS name for the service will be backend.example.com.
// You can associate more than one service with the same namespace.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Route 53 Auto Naming's
// API operation CreatePrivateDnsNamespace for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeInvalidInput "InvalidInput"
//   One or more specified values aren't valid. For example, when you're creating
//   a namespace, the value of Name might not be a valid DNS name.
//
//   * ErrCodeNamespaceAlreadyExists "NamespaceAlreadyExists"
//   The namespace that you're trying to create already exists.
//
//   * ErrCodeResourceLimitExceeded "ResourceLimitExceeded"
//   The resource can't be created because you've reached the limit on the number
//   of resources.
//
//   * ErrCodeDuplicateRequest "DuplicateRequest"
//   This request tried to create an object that already exists.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/CreatePrivateDnsNamespace
func (c *ServiceDiscovery) CreatePrivateDnsNamespace(input *CreatePrivateDnsNamespaceInput) (*CreatePrivateDnsNamespaceOutput, error) {
	req, out := c.CreatePrivateDnsNamespaceRequest(input)
	return out, req.Send()
}

// CreatePrivateDnsNamespaceWithContext is the same as CreatePrivateDnsNamespace with the addition of
// the ability to pass a context and additional request options.
//
// See CreatePrivateDnsNamespace for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) CreatePrivateDnsNamespaceWithContext(ctx aws.Context, input *CreatePrivateDnsNamespaceInput, opts ...request.Option) (*CreatePrivateDnsNamespaceOutput, error) {
	req, out := c.CreatePrivateDnsNamespaceRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opCreatePublicDnsNamespace = "CreatePublicDnsNamespace"

// CreatePublicDnsNamespaceRequest generates a "aws/request.Request" representing the
// client's request for the CreatePublicDnsNamespace operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See CreatePublicDnsNamespace for more information on using the CreatePublicDnsNamespace
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the CreatePublicDnsNamespaceRequest method.
//    req, resp := client.CreatePublicDnsNamespaceRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/CreatePublicDnsNamespace
func (c *ServiceDiscovery) CreatePublicDnsNamespaceRequest(input *CreatePublicDnsNamespaceInput) (req *request.Request, output *CreatePublicDnsNamespaceOutput) {
	op := &request.Operation{
		Name:       opCreatePublicDnsNamespace,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &CreatePublicDnsNamespaceInput{}
	}

	output = &CreatePublicDnsNamespaceOutput{}
	req = c.newRequest(op, input, output)
	return
}

// CreatePublicDnsNamespace API operation for Amazon Route 53 Auto Naming.
//
// Creates a public namespace based on DNS, which will be visible on the internet.
// The namespace defines your service naming scheme. For example, if you name
// your namespace example.com and name your service backend, the resulting DNS
// name for the service will be backend.example.com. You can associate more
// than one service with the same namespace.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Route 53 Auto Naming's
// API operation CreatePublicDnsNamespace for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeInvalidInput "InvalidInput"
//   One or more specified values aren't valid. For example, when you're creating
//   a namespace, the value of Name might not be a valid DNS name.
//
//   * ErrCodeNamespaceAlreadyExists "NamespaceAlreadyExists"
//   The namespace that you're trying to create already exists.
//
//   * ErrCodeResourceLimitExceeded "ResourceLimitExceeded"
//   The resource can't be created because you've reached the limit on the number
//   of resources.
//
//   * ErrCodeDuplicateRequest "DuplicateRequest"
//   This request tried to create an object that already exists.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/CreatePublicDnsNamespace
func (c *ServiceDiscovery) CreatePublicDnsNamespace(input *CreatePublicDnsNamespaceInput) (*CreatePublicDnsNamespaceOutput, error) {
	req, out := c.CreatePublicDnsNamespaceRequest(input)
	return out, req.Send()
}

// CreatePublicDnsNamespaceWithContext is the same as CreatePublicDnsNamespace with the addition of
// the ability to pass a context and additional request options.
//
// See CreatePublicDnsNamespace for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) CreatePublicDnsNamespaceWithContext(ctx aws.Context, input *CreatePublicDnsNamespaceInput, opts ...request.Option) (*CreatePublicDnsNamespaceOutput, error) {
	req, out := c.CreatePublicDnsNamespaceRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opCreateService = "CreateService"

// CreateServiceRequest generates a "aws/request.Request" representing the
// client's request for the CreateService operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See CreateService for more information on using the CreateService
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the CreateServiceRequest method.
//    req, resp := client.CreateServiceRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/CreateService
func (c *ServiceDiscovery) CreateServiceRequest(input *CreateServiceInput) (req *request.Request, output *CreateServiceOutput) {
	op := &request.Operation{
		Name:       opCreateService,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &CreateServiceInput{}
	}

	output = &CreateServiceOutput{}
	req = c.newRequest(op, input, output)
	return
}

// CreateService API operation for Amazon Route 53 Auto Naming.
//
// Creates a service, which defines a template for the following entities:
//
//    * One to five resource record sets
//
//    * Optionally, a health check
//
// After you create the service, you can submit a RegisterInstance request,
// and Amazon Route 53 uses the values in the template to create the specified
// entities.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Route 53 Auto Naming's
// API operation CreateService for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeInvalidInput "InvalidInput"
//   One or more specified values aren't valid. For example, when you're creating
//   a namespace, the value of Name might not be a valid DNS name.
//
//   * ErrCodeResourceLimitExceeded "ResourceLimitExceeded"
//   The resource can't be created because you've reached the limit on the number
//   of resources.
//
//   * ErrCodeNamespaceNotFound "NamespaceNotFound"
//   No namespace exists with the specified ID.
//
//   * ErrCodeServiceAlreadyExists "ServiceAlreadyExists"
//   The service can't be created because a service with the same name already
//   exists.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/CreateService
func (c *ServiceDiscovery) CreateService(input *CreateServiceInput) (*CreateServiceOutput, error) {
	req, out := c.CreateServiceRequest(input)
	return out, req.Send()
}

// CreateServiceWithContext is the same as CreateService with the addition of
// the ability to pass a context and additional request options.
//
// See CreateService for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) CreateServiceWithContext(ctx aws.Context, input *CreateServiceInput, opts ...request.Option) (*CreateServiceOutput, error) {
	req, out := c.CreateServiceRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opDeleteNamespace = "DeleteNamespace"

// DeleteNamespaceRequest generates a "aws/request.Request" representing the
// client's request for the DeleteNamespace operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeleteNamespace for more information on using the DeleteNamespace
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the DeleteNamespaceRequest method.
//    req, resp := client.DeleteNamespaceRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/DeleteNamespace
func (c *ServiceDiscovery) DeleteNamespaceRequest(input *DeleteNamespaceInput) (req *request.Request, output *DeleteNamespaceOutput) {
	op := &request.Operation{
		Name:       opDeleteNamespace,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &DeleteNamespaceInput{}
	}

	output = &DeleteNamespaceOutput{}
	req = c.newRequest(op, input, output)
	return
}

// DeleteNamespace API operation for Amazon Route 53 Auto Naming.
//
// Deletes a namespace from the current account. If the namespace still contains
// one or more services, the request fails.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Route 53 Auto Naming's
// API operation DeleteNamespace for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeInvalidInput "InvalidInput"
//   One or more specified values aren't valid. For example, when you're creating
//   a namespace, the value of Name might not be a valid DNS name.
//
//   * ErrCodeNamespaceNotFound "NamespaceNotFound"
//   No namespace exists with the specified ID.
//
//   * ErrCodeResourceInUse "ResourceInUse"
//   The specified resource can't be deleted because it contains other resources.
//   For example, you can't delete a service that contains any instances.
//
//   * ErrCodeDuplicateRequest "DuplicateRequest"
//   This request tried to create an object that already exists.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/DeleteNamespace
func (c *ServiceDiscovery) DeleteNamespace(input *DeleteNamespaceInput) (*DeleteNamespaceOutput, error) {
	req, out := c.DeleteNamespaceRequest(input)
	return out, req.Send()
}

// DeleteNamespaceWithContext is the same as DeleteNamespace with the addition of
// the ability to pass a context and additional request options.
//
// See DeleteNamespace for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) DeleteNamespaceWithContext(ctx aws.Context, input *DeleteNamespaceInput, opts ...request.Option) (*DeleteNamespaceOutput, error) {
	req, out := c.DeleteNamespaceRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opDeleteService = "DeleteService"

// DeleteServiceRequest generates a "aws/request.Request" representing the
// client's request for the DeleteService operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeleteService for more information on using the DeleteService
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the DeleteServiceRequest method.
//    req, resp := client.DeleteServiceRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/DeleteService
func (c *ServiceDiscovery) DeleteServiceRequest(input *DeleteServiceInput) (req *request.Request, output *DeleteServiceOutput) {
	op := &request.Operation{
		Name:       opDeleteService,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &DeleteServiceInput{}
	}

	output = &DeleteServiceOutput{}
	req = c.newRequest(op, input, output)
	return
}

// DeleteService API operation for Amazon Route 53 Auto Naming.
//
// Deletes a specified service. If the service still contains one or more registered
// instances, the request fails.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Route 53 Auto Naming's
// API operation DeleteService for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeInvalidInput "InvalidInput"
//   One or more specified values aren't valid. For example, when you're creating
//   a namespace, the value of Name might not be a valid DNS name.
//
//   * ErrCodeServiceNotFound "ServiceNotFound"
//   No service exists with the specified ID.
//
//   * ErrCodeResourceInUse "ResourceInUse"
//   The specified resource can't be deleted because it contains other resources.
//   For example, you can't delete a service that contains any instances.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/DeleteService
func (c *ServiceDiscovery) DeleteService(input *DeleteServiceInput) (*DeleteServiceOutput, error) {
	req, out := c.DeleteServiceRequest(input)
	return out, req.Send()
}

// DeleteServiceWithContext is the same as DeleteService with the addition of
// the ability to pass a context and additional request options.
//
// See DeleteService for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) DeleteServiceWithContext(ctx aws.Context, input *DeleteServiceInput, opts ...request.Option) (*DeleteServiceOutput, error) {
	req, out := c.DeleteServiceRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opDeregisterInstance = "DeregisterInstance"

// DeregisterInstanceRequest generates a "aws/request.Request" representing the
// client's request for the DeregisterInstance operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeregisterInstance for more information on using the DeregisterInstance
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the DeregisterInstanceRequest method.
//    req, resp := client.DeregisterInstanceRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/DeregisterInstance
func (c *ServiceDiscovery) DeregisterInstanceRequest(input *DeregisterInstanceInput) (req *request.Request, output *DeregisterInstanceOutput) {
	op := &request.Operation{
		Name:       opDeregisterInstance,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &DeregisterInstanceInput{}
	}

	output = &DeregisterInstanceOutput{}
	req = c.newRequest(op, input, output)
	return
}

// DeregisterInstance API operation for Amazon Route 53 Auto Naming.
//
// Deletes the resource record sets and the health check, if any, that Amazon
// Route 53 created for the specified instance.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Route 53 Auto Naming's
// API operation DeregisterInstance for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeDuplicateRequest "DuplicateRequest"
//   This request tried to create an object that already exists.
//
//   * ErrCodeInvalidInput "InvalidInput"
//   One or more specified values aren't valid. For example, when you're creating
//   a namespace, the value of Name might not be a valid DNS name.
//
//   * ErrCodeInstanceNotFound "InstanceNotFound"
//   No instance exists with the specified ID.
//
//   * ErrCodeResourceInUse "ResourceInUse"
//   The specified resource can't be deleted because it contains other resources.
//   For example, you can't delete a service that contains any instances.
//
//   * ErrCodeServiceNotFound "ServiceNotFound"
//   No service exists with the specified ID.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/DeregisterInstance
func (c *ServiceDiscovery) DeregisterInstance(input *DeregisterInstanceInput) (*DeregisterInstanceOutput, error) {
	req, out := c.DeregisterInstanceRequest(input)
	return out, req.Send()
}

// DeregisterInstanceWithContext is the same as DeregisterInstance with the addition of
// the ability to pass a context and additional request options.
//
// See DeregisterInstance for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) DeregisterInstanceWithContext(ctx aws.Context, input *DeregisterInstanceInput, opts ...request.Option) (*DeregisterInstanceOutput, error) {
	req, out := c.DeregisterInstanceRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opGetInstance = "GetInstance"

// GetInstanceRequest generates a "aws/request.Request" representing the
// client's request for the GetInstance operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See GetInstance for more information on using the GetInstance
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the GetInstanceRequest method.
//    req, resp := client.GetInstanceRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetInstance
func (c *ServiceDiscovery) GetInstanceRequest(input *GetInstanceInput) (req *request.Request, output *GetInstanceOutput) {
	op := &request.Operation{
		Name:       opGetInstance,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &GetInstanceInput{}
	}

	output = &GetInstanceOutput{}
	req = c.newRequest(op, input, output)
	return
}

// GetInstance API operation for Amazon Route 53 Auto Naming.
//
// Gets information about a specified instance.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Route 53 Auto Naming's
// API operation GetInstance for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeInstanceNotFound "InstanceNotFound"
//   No instance exists with the specified ID.
//
//   * ErrCodeInvalidInput "InvalidInput"
//   One or more specified values aren't valid. For example, when you're creating
//   a namespace, the value of Name might not be a valid DNS name.
//
//   * ErrCodeServiceNotFound "ServiceNotFound"
//   No service exists with the specified ID.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetInstance
func (c *ServiceDiscovery) GetInstance(input *GetInstanceInput) (*GetInstanceOutput, error) {
	req, out := c.GetInstanceRequest(input)
	return out, req.Send()
}

// GetInstanceWithContext is the same as GetInstance with the addition of
// the ability to pass a context and additional request options.
//
// See GetInstance for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) GetInstanceWithContext(ctx aws.Context, input *GetInstanceInput, opts ...request.Option) (*GetInstanceOutput, error) {
	req, out := c.GetInstanceRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opGetInstancesHealthStatus = "GetInstancesHealthStatus"

// GetInstancesHealthStatusRequest generates a "aws/request.Request" representing the
// client's request for the GetInstancesHealthStatus operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See GetInstancesHealthStatus for more information on using the GetInstancesHealthStatus
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the GetInstancesHealthStatusRequest method.
//    req, resp := client.GetInstancesHealthStatusRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetInstancesHealthStatus
func (c *ServiceDiscovery) GetInstancesHealthStatusRequest(input *GetInstancesHealthStatusInput) (req *request.Request, output *GetInstancesHealthStatusOutput) {
	op := &request.Operation{
		Name:       opGetInstancesHealthStatus,
		HTTPMethod: "POST",
		HTTPPath:   "/",
		Paginator: &request.Paginator{
			InputTokens:     []string{"NextToken"},
			OutputTokens:    []string{"NextToken"},
			LimitToken:      "MaxResults",
			TruncationToken: "",
		},
	}

	if input == nil {
		input = &GetInstancesHealthStatusInput{}
	}

	output = &GetInstancesHealthStatusOutput{}
	req = c.newRequest(op, input, output)
	return
}

// GetInstancesHealthStatus API operation for Amazon Route 53 Auto Naming.
//
// Gets the current health status (Healthy, Unhealthy, or Unknown) of one or
// more instances that are associated with a specified service.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Route 53 Auto Naming's
// API operation GetInstancesHealthStatus for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeInstanceNotFound "InstanceNotFound"
//   No instance exists with the specified ID.
//
//   * ErrCodeInvalidInput "InvalidInput"
//   One or more specified values aren't valid. For example, when you're creating
//   a namespace, the value of Name might not be a valid DNS name.
//
//   * ErrCodeServiceNotFound "ServiceNotFound"
//   No service exists with the specified ID.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetInstancesHealthStatus
func (c *ServiceDiscovery) GetInstancesHealthStatus(input *GetInstancesHealthStatusInput) (*GetInstancesHealthStatusOutput, error) {
	req, out := c.GetInstancesHealthStatusRequest(input)
	return out, req.Send()
}

// GetInstancesHealthStatusWithContext is the same as GetInstancesHealthStatus with the addition of
// the ability to pass a context and additional request options.
//
// See GetInstancesHealthStatus for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) GetInstancesHealthStatusWithContext(ctx aws.Context, input *GetInstancesHealthStatusInput, opts ...request.Option) (*GetInstancesHealthStatusOutput, error) {
	req, out := c.GetInstancesHealthStatusRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

// GetInstancesHealthStatusPages iterates over the pages of a GetInstancesHealthStatus operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See GetInstancesHealthStatus method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
//    // Example iterating over at most 3 pages of a GetInstancesHealthStatus operation.
//    pageNum := 0
//    err := client.GetInstancesHealthStatusPages(params,
//        func(page *GetInstancesHealthStatusOutput, lastPage bool) bool {
//            pageNum++
//            fmt.Println(page)
//            return pageNum <= 3
//        })
//
func (c *ServiceDiscovery) GetInstancesHealthStatusPages(input *GetInstancesHealthStatusInput, fn func(*GetInstancesHealthStatusOutput, bool) bool) error {
	return c.GetInstancesHealthStatusPagesWithContext(aws.BackgroundContext(), input, fn)
}

// GetInstancesHealthStatusPagesWithContext same as GetInstancesHealthStatusPages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) GetInstancesHealthStatusPagesWithContext(ctx aws.Context, input *GetInstancesHealthStatusInput, fn func(*GetInstancesHealthStatusOutput, bool) bool, opts ...request.Option) error {
	p := request.Pagination{
		NewRequest: func() (*request.Request, error) {
			var inCpy *GetInstancesHealthStatusInput
			if input != nil {
				tmp := *input
				inCpy = &tmp
			}
			req, _ := c.GetInstancesHealthStatusRequest(inCpy)
			req.SetContext(ctx)
			req.ApplyOptions(opts...)
			return req, nil
		},
	}

	cont := true
	for p.Next() && cont {
		cont = fn(p.Page().(*GetInstancesHealthStatusOutput), !p.HasNextPage())
	}
	return p.Err()
}

const opGetNamespace = "GetNamespace"

// GetNamespaceRequest generates a "aws/request.Request" representing the
// client's request for the GetNamespace operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See GetNamespace for more information on using the GetNamespace
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the GetNamespaceRequest method.
//    req, resp := client.GetNamespaceRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetNamespace
func (c *ServiceDiscovery) GetNamespaceRequest(input *GetNamespaceInput) (req *request.Request, output *GetNamespaceOutput) {
	op := &request.Operation{
		Name:       opGetNamespace,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &GetNamespaceInput{}
	}

	output = &GetNamespaceOutput{}
	req = c.newRequest(op, input, output)
	return
}

// GetNamespace API operation for Amazon Route 53 Auto Naming.
//
// Gets information about a namespace.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Route 53 Auto Naming's
// API operation GetNamespace for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeInvalidInput "InvalidInput"
//   One or more specified values aren't valid. For example, when you're creating
//   a namespace, the value of Name might not be a valid DNS name.
//
//   * ErrCodeNamespaceNotFound "NamespaceNotFound"
//   No namespace exists with the specified ID.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetNamespace
func (c *ServiceDiscovery) GetNamespace(input *GetNamespaceInput) (*GetNamespaceOutput, error) {
	req, out := c.GetNamespaceRequest(input)
	return out, req.Send()
}

// GetNamespaceWithContext is the same as GetNamespace with the addition of
// the ability to pass a context and additional request options.
//
// See GetNamespace for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) GetNamespaceWithContext(ctx aws.Context, input *GetNamespaceInput, opts ...request.Option) (*GetNamespaceOutput, error) {
	req, out := c.GetNamespaceRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opGetOperation = "GetOperation"

// GetOperationRequest generates a "aws/request.Request" representing the
// client's request for the GetOperation operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See GetOperation for more information on using the GetOperation
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the GetOperationRequest method.
//    req, resp := client.GetOperationRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetOperation
func (c *ServiceDiscovery) GetOperationRequest(input *GetOperationInput) (req *request.Request, output *GetOperationOutput) {
	op := &request.Operation{
		Name:       opGetOperation,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &GetOperationInput{}
	}

	output = &GetOperationOutput{}
	req = c.newRequest(op, input, output)
	return
}

// GetOperation API operation for Amazon Route 53 Auto Naming.
//
// Gets information about any operation that returns an operation ID in the
// response, such as a CreateService request. To get a list of operations that
// match specified criteria, see ListOperations.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Route 53 Auto Naming's
// API operation GetOperation for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeOperationNotFound "OperationNotFound"
//   No operation exists with the specified ID.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetOperation
func (c *ServiceDiscovery) GetOperation(input *GetOperationInput) (*GetOperationOutput, error) {
	req, out := c.GetOperationRequest(input)
	return out, req.Send()
}

// GetOperationWithContext is the same as GetOperation with the addition of
// the ability to pass a context and additional request options.
//
// See GetOperation for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) GetOperationWithContext(ctx aws.Context, input *GetOperationInput, opts ...request.Option) (*GetOperationOutput, error) {
	req, out := c.GetOperationRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opGetService = "GetService"

// GetServiceRequest generates a "aws/request.Request" representing the
// client's request for the GetService operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See GetService for more information on using the GetService
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the GetServiceRequest method.
//    req, resp := client.GetServiceRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetService
func (c *ServiceDiscovery) GetServiceRequest(input *GetServiceInput) (req *request.Request, output *GetServiceOutput) {
	op := &request.Operation{
		Name:       opGetService,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &GetServiceInput{}
	}

	output = &GetServiceOutput{}
	req = c.newRequest(op, input, output)
	return
}

// GetService API operation for Amazon Route 53 Auto Naming.
//
// Gets the settings for a specified service.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Route 53 Auto Naming's
// API operation GetService for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeInvalidInput "InvalidInput"
//   One or more specified values aren't valid. For example, when you're creating
//   a namespace, the value of Name might not be a valid DNS name.
//
//   * ErrCodeServiceNotFound "ServiceNotFound"
//   No service exists with the specified ID.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetService
func (c *ServiceDiscovery) GetService(input *GetServiceInput) (*GetServiceOutput, error) {
	req, out := c.GetServiceRequest(input)
	return out, req.Send()
}

// GetServiceWithContext is the same as GetService with the addition of
// the ability to pass a context and additional request options.
//
// See GetService for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) GetServiceWithContext(ctx aws.Context, input *GetServiceInput, opts ...request.Option) (*GetServiceOutput, error) {
	req, out := c.GetServiceRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opListInstances = "ListInstances"

// ListInstancesRequest generates a "aws/request.Request" representing the
// client's request for the ListInstances operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListInstances for more information on using the ListInstances
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the ListInstancesRequest method.
//    req, resp := client.ListInstancesRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListInstances
func (c *ServiceDiscovery) ListInstancesRequest(input *ListInstancesInput) (req *request.Request, output *ListInstancesOutput) {
	op := &request.Operation{
		Name:       opListInstances,
		HTTPMethod: "POST",
		HTTPPath:   "/",
		Paginator: &request.Paginator{
			InputTokens:     []string{"NextToken"},
			OutputTokens:    []string{"NextToken"},
			LimitToken:      "MaxResults",
			TruncationToken: "",
		},
	}

	if input == nil {
		input = &ListInstancesInput{}
	}

	output = &ListInstancesOutput{}
	req = c.newRequest(op, input, output)
	return
}

// ListInstances API operation for Amazon Route 53 Auto Naming.
//
// Gets summary information about the instances that you created by using a
// specified service.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Route 53 Auto Naming's
// API operation ListInstances for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeServiceNotFound "ServiceNotFound"
//   No service exists with the specified ID.
//
//   * ErrCodeInvalidInput "InvalidInput"
//   One or more specified values aren't valid. For example, when you're creating
//   a namespace, the value of Name might not be a valid DNS name.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListInstances
func (c *ServiceDiscovery) ListInstances(input *ListInstancesInput) (*ListInstancesOutput, error) {
	req, out := c.ListInstancesRequest(input)
	return out, req.Send()
}

// ListInstancesWithContext is the same as ListInstances with the addition of
// the ability to pass a context and additional request options.
//
// See ListInstances for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) ListInstancesWithContext(ctx aws.Context, input *ListInstancesInput, opts ...request.Option) (*ListInstancesOutput, error) {
	req, out := c.ListInstancesRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

// ListInstancesPages iterates over the pages of a ListInstances operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See ListInstances method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
//    // Example iterating over at most 3 pages of a ListInstances operation.
//    pageNum := 0
//    err := client.ListInstancesPages(params,
//        func(page *ListInstancesOutput, lastPage bool) bool {
//            pageNum++
//            fmt.Println(page)
//            return pageNum <= 3
//        })
//
func (c *ServiceDiscovery) ListInstancesPages(input *ListInstancesInput, fn func(*ListInstancesOutput, bool) bool) error {
	return c.ListInstancesPagesWithContext(aws.BackgroundContext(), input, fn)
}

// ListInstancesPagesWithContext same as ListInstancesPages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) ListInstancesPagesWithContext(ctx aws.Context, input *ListInstancesInput, fn func(*ListInstancesOutput, bool) bool, opts ...request.Option) error {
	p := request.Pagination{
		NewRequest: func() (*request.Request, error) {
			var inCpy *ListInstancesInput
			if input != nil {
				tmp := *input
				inCpy = &tmp
			}
			req, _ := c.ListInstancesRequest(inCpy)
			req.SetContext(ctx)
			req.ApplyOptions(opts...)
			return req, nil
		},
	}

	cont := true
	for p.Next() && cont {
		cont = fn(p.Page().(*ListInstancesOutput), !p.HasNextPage())
	}
	return p.Err()
}

const opListNamespaces = "ListNamespaces"

// ListNamespacesRequest generates a "aws/request.Request" representing the
// client's request for the ListNamespaces operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListNamespaces for more information on using the ListNamespaces
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the ListNamespacesRequest method.
//    req, resp := client.ListNamespacesRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListNamespaces
func (c *ServiceDiscovery) ListNamespacesRequest(input *ListNamespacesInput) (req *request.Request, output *ListNamespacesOutput) {
	op := &request.Operation{
		Name:       opListNamespaces,
		HTTPMethod: "POST",
		HTTPPath:   "/",
		Paginator: &request.Paginator{
			InputTokens:     []string{"NextToken"},
			OutputTokens:    []string{"NextToken"},
			LimitToken:      "MaxResults",
			TruncationToken: "",
		},
	}

	if input == nil {
		input = &ListNamespacesInput{}
	}

	output = &ListNamespacesOutput{}
	req = c.newRequest(op, input, output)
	return
}

// ListNamespaces API operation for Amazon Route 53 Auto Naming.
//
// Gets information about the namespaces that were created by the current AWS
// account.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Route 53 Auto Naming's
// API operation ListNamespaces for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeInvalidInput "InvalidInput"
//   One or more specified values aren't valid. For example, when you're creating
//   a namespace, the value of Name might not be a valid DNS name.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListNamespaces
func (c *ServiceDiscovery) ListNamespaces(input *ListNamespacesInput) (*ListNamespacesOutput, error) {
	req, out := c.ListNamespacesRequest(input)
	return out, req.Send()
}

// ListNamespacesWithContext is the same as ListNamespaces with the addition of
// the ability to pass a context and additional request options.
//
// See ListNamespaces for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) ListNamespacesWithContext(ctx aws.Context, input *ListNamespacesInput, opts ...request.Option) (*ListNamespacesOutput, error) {
	req, out := c.ListNamespacesRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

// ListNamespacesPages iterates over the pages of a ListNamespaces operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See ListNamespaces method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
//    // Example iterating over at most 3 pages of a ListNamespaces operation.
//    pageNum := 0
//    err := client.ListNamespacesPages(params,
//        func(page *ListNamespacesOutput, lastPage bool) bool {
//            pageNum++
//            fmt.Println(page)
//            return pageNum <= 3
//        })
//
func (c *ServiceDiscovery) ListNamespacesPages(input *ListNamespacesInput, fn func(*ListNamespacesOutput, bool) bool) error {
	return c.ListNamespacesPagesWithContext(aws.BackgroundContext(), input, fn)
}

// ListNamespacesPagesWithContext same as ListNamespacesPages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) ListNamespacesPagesWithContext(ctx aws.Context, input *ListNamespacesInput, fn func(*ListNamespacesOutput, bool) bool, opts ...request.Option) error {
	p := request.Pagination{
		NewRequest: func() (*request.Request, error) {
			var inCpy *ListNamespacesInput
			if input != nil {
				tmp := *input
				inCpy = &tmp
			}
			req, _ := c.ListNamespacesRequest(inCpy)
			req.SetContext(ctx)
			req.ApplyOptions(opts...)
			return req, nil
		},
	}

	cont := true
	for p.Next() && cont {
		cont = fn(p.Page().(*ListNamespacesOutput), !p.HasNextPage())
	}
	return p.Err()
}

const opListOperations = "ListOperations"

// ListOperationsRequest generates a "aws/request.Request" representing the
// client's request for the ListOperations operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListOperations for more information on using the ListOperations
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the ListOperationsRequest method.
//    req, resp := client.ListOperationsRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListOperations
func (c *ServiceDiscovery) ListOperationsRequest(input *ListOperationsInput) (req *request.Request, output *ListOperationsOutput) {
	op := &request.Operation{
		Name:       opListOperations,
		HTTPMethod: "POST",
		HTTPPath:   "/",
		Paginator: &request.Paginator{
			InputTokens:     []string{"NextToken"},
			OutputTokens:    []string{"NextToken"},
			LimitToken:      "<PASSWORD>",
			TruncationToken: "",
		},
	}

	if input == nil {
		input = &ListOperationsInput{}
	}

	output = &ListOperationsOutput{}
	req = c.newRequest(op, input, output)
	return
}

// ListOperations API operation for Amazon Route 53 Auto Naming.
//
// Lists operations that match the criteria that you specify.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Route 53 Auto Naming's
// API operation ListOperations for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeInvalidInput "InvalidInput"
//   One or more specified values aren't valid. For example, when you're creating
//   a namespace, the value of Name might not be a valid DNS name.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListOperations
func (c *ServiceDiscovery) ListOperations(input *ListOperationsInput) (*ListOperationsOutput, error) {
	req, out := c.ListOperationsRequest(input)
	return out, req.Send()
}

// ListOperationsWithContext is the same as ListOperations with the addition of
// the ability to pass a context and additional request options.
//
// See ListOperations for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) ListOperationsWithContext(ctx aws.Context, input *ListOperationsInput, opts ...request.Option) (*ListOperationsOutput, error) {
	req, out := c.ListOperationsRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

// ListOperationsPages iterates over the pages of a ListOperations operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See ListOperations method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
//    // Example iterating over at most 3 pages of a ListOperations operation.
//    pageNum := 0
//    err := client.ListOperationsPages(params,
//        func(page *ListOperationsOutput, lastPage bool) bool {
//            pageNum++
//            fmt.Println(page)
//            return pageNum <= 3
//        })
//
func (c *ServiceDiscovery) ListOperationsPages(input *ListOperationsInput, fn func(*ListOperationsOutput, bool) bool) error {
	return c.ListOperationsPagesWithContext(aws.BackgroundContext(), input, fn)
}

// ListOperationsPagesWithContext same as ListOperationsPages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) ListOperationsPagesWithContext(ctx aws.Context, input *ListOperationsInput, fn func(*ListOperationsOutput, bool) bool, opts ...request.Option) error {
	p := request.Pagination{
		NewRequest: func() (*request.Request, error) {
			var inCpy *ListOperationsInput
			if input != nil {
				tmp := *input
				inCpy = &tmp
			}
			req, _ := c.ListOperationsRequest(inCpy)
			req.SetContext(ctx)
			req.ApplyOptions(opts...)
			return req, nil
		},
	}

	cont := true
	for p.Next() && cont {
		cont = fn(p.Page().(*ListOperationsOutput), !p.HasNextPage())
	}
	return p.Err()
}

const opListServices = "ListServices"

// ListServicesRequest generates a "aws/request.Request" representing the
// client's request for the ListServices operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ListServices for more information on using the ListServices
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the ListServicesRequest method.
//    req, resp := client.ListServicesRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListServices
func (c *ServiceDiscovery) ListServicesRequest(input *ListServicesInput) (req *request.Request, output *ListServicesOutput) {
	op := &request.Operation{
		Name:       opListServices,
		HTTPMethod: "POST",
		HTTPPath:   "/",
		Paginator: &request.Paginator{
			InputTokens:     []string{"NextToken"},
			OutputTokens:    []string{"NextToken"},
			LimitToken:      "MaxResults",
			TruncationToken: "",
		},
	}

	if input == nil {
		input = &ListServicesInput{}
	}

	output = &ListServicesOutput{}
	req = c.newRequest(op, input, output)
	return
}

// ListServices API operation for Amazon Route 53 Auto Naming.
//
// Gets settings for all the services that are associated with one or more specified
// namespaces.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Route 53 Auto Naming's
// API operation ListServices for usage and error information.
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListServices
func (c *ServiceDiscovery) ListServices(input *ListServicesInput) (*ListServicesOutput, error) {
	req, out := c.ListServicesRequest(input)
	return out, req.Send()
}

// ListServicesWithContext is the same as ListServices with the addition of
// the ability to pass a context and additional request options.
//
// See ListServices for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) ListServicesWithContext(ctx aws.Context, input *ListServicesInput, opts ...request.Option) (*ListServicesOutput, error) {
	req, out := c.ListServicesRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

// ListServicesPages iterates over the pages of a ListServices operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See ListServices method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
//    // Example iterating over at most 3 pages of a ListServices operation.
//    pageNum := 0
//    err := client.ListServicesPages(params,
//        func(page *ListServicesOutput, lastPage bool) bool {
//            pageNum++
//            fmt.Println(page)
//            return pageNum <= 3
//        })
//
func (c *ServiceDiscovery) ListServicesPages(input *ListServicesInput, fn func(*ListServicesOutput, bool) bool) error {
	return c.ListServicesPagesWithContext(aws.BackgroundContext(), input, fn)
}

// ListServicesPagesWithContext same as ListServicesPages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) ListServicesPagesWithContext(ctx aws.Context, input *ListServicesInput, fn func(*ListServicesOutput, bool) bool, opts ...request.Option) error {
	p := request.Pagination{
		NewRequest: func() (*request.Request, error) {
			var inCpy *ListServicesInput
			if input != nil {
				tmp := *input
				inCpy = &tmp
			}
			req, _ := c.ListServicesRequest(inCpy)
			req.SetContext(ctx)
			req.ApplyOptions(opts...)
			return req, nil
		},
	}

	cont := true
	for p.Next() && cont {
		cont = fn(p.Page().(*ListServicesOutput), !p.HasNextPage())
	}
	return p.Err()
}

const opRegisterInstance = "RegisterInstance"

// RegisterInstanceRequest generates a "aws/request.Request" representing the
// client's request for the RegisterInstance operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See RegisterInstance for more information on using the RegisterInstance
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the RegisterInstanceRequest method.
//    req, resp := client.RegisterInstanceRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/RegisterInstance
func (c *ServiceDiscovery) RegisterInstanceRequest(input *RegisterInstanceInput) (req *request.Request, output *RegisterInstanceOutput) {
	op := &request.Operation{
		Name:       opRegisterInstance,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &RegisterInstanceInput{}
	}

	output = &RegisterInstanceOutput{}
	req = c.newRequest(op, input, output)
	return
}

// RegisterInstance API operation for Amazon Route 53 Auto Naming.
//
// Creates one or more resource record sets and optionally a health check based
// on the settings in a specified service. When you submit a RegisterInstance
// request, Amazon Route 53 does the following:
//
//    * Creates a resource record set for each resource record set template
//    in the service
//
//    * Creates a health check based on the settings in the health check template
//    in the service, if any
//
//    * Associates the health check, if any, with each of the resource record
//    sets
//
// One RegisterInstance request must complete before you can submit another
// request and specify the same service and instance ID.
//
// For more information, see CreateService.
//
// When Amazon Route 53 receives a DNS query for the specified DNS name, it
// returns the applicable value:
//
//    * If the health check is healthy: returns all the resource record sets
//
//    * If the health check is unhealthy: returns the IP address of the last
//    healthy instance
//
//    * If you didn't specify a health check template: returns all the resource
//    record sets
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Route 53 Auto Naming's
// API operation RegisterInstance for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeDuplicateRequest "DuplicateRequest"
//   This request tried to create an object that already exists.
//
//   * ErrCodeInvalidInput "InvalidInput"
//   One or more specified values aren't valid. For example, when you're creating
//   a namespace, the value of Name might not be a valid DNS name.
//
//   * ErrCodeResourceInUse "ResourceInUse"
//   The specified resource can't be deleted because it contains other resources.
//   For example, you can't delete a service that contains any instances.
//
//   * ErrCodeResourceLimitExceeded "ResourceLimitExceeded"
//   The resource can't be created because you've reached the limit on the number
//   of resources.
//
//   * ErrCodeServiceNotFound "ServiceNotFound"
//   No service exists with the specified ID.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/RegisterInstance
func (c *ServiceDiscovery) RegisterInstance(input *RegisterInstanceInput) (*RegisterInstanceOutput, error) {
	req, out := c.RegisterInstanceRequest(input)
	return out, req.Send()
}

// RegisterInstanceWithContext is the same as RegisterInstance with the addition of
// the ability to pass a context and additional request options.
//
// See RegisterInstance for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) RegisterInstanceWithContext(ctx aws.Context, input *RegisterInstanceInput, opts ...request.Option) (*RegisterInstanceOutput, error) {
	req, out := c.RegisterInstanceRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opUpdateService = "UpdateService"

// UpdateServiceRequest generates a "aws/request.Request" representing the
// client's request for the UpdateService operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See UpdateService for more information on using the UpdateService
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the UpdateServiceRequest method.
//    req, resp := client.UpdateServiceRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/UpdateService
func (c *ServiceDiscovery) UpdateServiceRequest(input *UpdateServiceInput) (req *request.Request, output *UpdateServiceOutput) {
	op := &request.Operation{
		Name:       opUpdateService,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &UpdateServiceInput{}
	}

	output = &UpdateServiceOutput{}
	req = c.newRequest(op, input, output)
	return
}

// UpdateService API operation for Amazon Route 53 Auto Naming.
//
// Updates the TTL setting for a specified service. You must specify all the
// resource record set templates (and, optionally, a health check template)
// that you want to appear in the updated service. Any current resource record
// set templates (or health check template) that don't appear in an UpdateService
// request are deleted.
//
// When you update the TTL setting for a service, Amazon Route 53 also updates
// the corresponding settings in all the resource record sets and health checks
// that were created by using the specified service.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Amazon Route 53 Auto Naming's
// API operation UpdateService for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeDuplicateRequest "DuplicateRequest"
//   This request tried to create an object that already exists.
//
//   * ErrCodeInvalidInput "InvalidInput"
//   One or more specified values aren't valid. For example, when you're creating
//   a namespace, the value of Name might not be a valid DNS name.
//
//   * ErrCodeServiceNotFound "ServiceNotFound"
//   No service exists with the specified ID.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/UpdateService
func (c *ServiceDiscovery) UpdateService(input *UpdateServiceInput) (*UpdateServiceOutput, error) {
	req, out := c.UpdateServiceRequest(input)
	return out, req.Send()
}

// UpdateServiceWithContext is the same as UpdateService with the addition of
// the ability to pass a context and additional request options.
//
// See UpdateService for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ServiceDiscovery) UpdateServiceWithContext(ctx aws.Context, input *UpdateServiceInput, opts ...request.Option) (*UpdateServiceOutput, error) {
	req, out := c.UpdateServiceRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/CreatePrivateDnsNamespaceRequest
type CreatePrivateDnsNamespaceInput struct {
	_ struct{} `type:"structure"`

	// An optional parameter that you can use to resolve concurrent creation requests.
	// CreatorRequestId helps to determine if a specific client owns the namespace.
	CreatorRequestId *string `type:"string" idempotencyToken:"true"`

	// A description for the namespace.
	Description *string `type:"string"`

	// The name that you want to assign to this namespace. When you create a namespace,
	// Amazon Route 53 automatically creates a hosted zone that has the same name
	// as the namespace.
	//
	// Name is a required field
	Name *string `type:"string" required:"true"`

	// The ID of the Amazon VPC that you want to associate the namespace with.
	//
	// Vpc is a required field
	Vpc *string `type:"string" required:"true"`
}

// String returns the string representation
func (s CreatePrivateDnsNamespaceInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s CreatePrivateDnsNamespaceInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *CreatePrivateDnsNamespaceInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "CreatePrivateDnsNamespaceInput"}
	if s.Name == nil {
		invalidParams.Add(request.NewErrParamRequired("Name"))
	}
	if s.Vpc == nil {
		invalidParams.Add(request.NewErrParamRequired("Vpc"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetCreatorRequestId sets the CreatorRequestId field's value.
func (s *CreatePrivateDnsNamespaceInput) SetCreatorRequestId(v string) *CreatePrivateDnsNamespaceInput {
	s.CreatorRequestId = &v
	return s
}

// SetDescription sets the Description field's value.
func (s *CreatePrivateDnsNamespaceInput) SetDescription(v string) *CreatePrivateDnsNamespaceInput {
	s.Description = &v
	return s
}

// SetName sets the Name field's value.
func (s *CreatePrivateDnsNamespaceInput) SetName(v string) *CreatePrivateDnsNamespaceInput {
	s.Name = &v
	return s
}

// SetVpc sets the Vpc field's value.
func (s *CreatePrivateDnsNamespaceInput) SetVpc(v string) *CreatePrivateDnsNamespaceInput {
	s.Vpc = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/CreatePrivateDnsNamespaceResponse
type CreatePrivateDnsNamespaceOutput struct {
	_ struct{} `type:"structure"`

	// A value that you can use to determine whether the request completed successfully.
	// To get the status of the operation, see GetOperation.
	OperationId *string `type:"string"`
}

// String returns the string representation
func (s CreatePrivateDnsNamespaceOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s CreatePrivateDnsNamespaceOutput) GoString() string {
	return s.String()
}

// SetOperationId sets the OperationId field's value.
func (s *CreatePrivateDnsNamespaceOutput) SetOperationId(v string) *CreatePrivateDnsNamespaceOutput {
	s.OperationId = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/CreatePublicDnsNamespaceRequest
type CreatePublicDnsNamespaceInput struct {
	_ struct{} `type:"structure"`

	// An optional parameter that you can use to resolve concurrent creation requests.
	// CreatorRequestId helps to determine if a specific client owns the namespace.
	CreatorRequestId *string `type:"string" idempotencyToken:"true"`

	// A description for the namespace.
	Description *string `type:"string"`

	// The name that you want to assign to this namespace.
	//
	// Name is a required field
	Name *string `type:"string" required:"true"`
}

// String returns the string representation
func (s CreatePublicDnsNamespaceInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s CreatePublicDnsNamespaceInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *CreatePublicDnsNamespaceInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "CreatePublicDnsNamespaceInput"}
	if s.Name == nil {
		invalidParams.Add(request.NewErrParamRequired("Name"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetCreatorRequestId sets the CreatorRequestId field's value.
func (s *CreatePublicDnsNamespaceInput) SetCreatorRequestId(v string) *CreatePublicDnsNamespaceInput {
	s.CreatorRequestId = &v
	return s
}

// SetDescription sets the Description field's value.
func (s *CreatePublicDnsNamespaceInput) SetDescription(v string) *CreatePublicDnsNamespaceInput {
	s.Description = &v
	return s
}

// SetName sets the Name field's value.
func (s *CreatePublicDnsNamespaceInput) SetName(v string) *CreatePublicDnsNamespaceInput {
	s.Name = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/CreatePublicDnsNamespaceResponse
type CreatePublicDnsNamespaceOutput struct {
	_ struct{} `type:"structure"`

	// A value that you can use to determine whether the request completed successfully.
	// To get the status of the operation, see GetOperation.
	OperationId *string `type:"string"`
}

// String returns the string representation
func (s CreatePublicDnsNamespaceOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s CreatePublicDnsNamespaceOutput) GoString() string {
	return s.String()
}

// SetOperationId sets the OperationId field's value.
func (s *CreatePublicDnsNamespaceOutput) SetOperationId(v string) *CreatePublicDnsNamespaceOutput {
	s.OperationId = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/CreateServiceRequest
type CreateServiceInput struct {
	_ struct{} `type:"structure"`

	// An optional parameter that you can use to resolve concurrent creation requests.
	// CreatorRequestId helps to determine if a specific client owns the namespace.
	CreatorRequestId *string `type:"string" idempotencyToken:"true"`

	// A description for the service.
	Description *string `type:"string"`

	// A complex type that contains information about the resource record sets that
	// you want Amazon Route 53 to create when you register an instance.
	//
	// DnsConfig is a required field
	DnsConfig *DnsConfig `type:"structure" required:"true"`

	// Public DNS namespaces only. A complex type that contains settings for an
	// optional health check. If you specify settings for a health check, Amazon
	// Route 53 associates the health check with all the resource record sets that
	// you specify in DnsConfig.
	//
	// The health check uses 30 seconds as the request interval. This is the number
	// of seconds between the time that each Amazon Route 53 health checker gets
	// a response from your endpoint and the time that it sends the next health
	// check request. A health checker in each data center around the world sends
	// your endpoint a health check request every 30 seconds. On average, your endpoint
	// receives a health check request about every two seconds. Health checkers
	// in different data centers don't coordinate with one another, so you'll sometimes
	// see several requests per second followed by a few seconds with no health
	// checks at all.
	//
	// For information about the charges for health checks, see Amazon Route 53
	// Pricing (http://aws.amazon.com/route53/pricing).
	HealthCheckConfig *HealthCheckConfig `type:"structure"`

	// The name that you want to assign to the service.
	//
	// Name is a required field
	Name *string `type:"string" required:"true"`
}

// String returns the string representation
func (s CreateServiceInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s CreateServiceInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *CreateServiceInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "CreateServiceInput"}
	if s.DnsConfig == nil {
		invalidParams.Add(request.NewErrParamRequired("DnsConfig"))
	}
	if s.Name == nil {
		invalidParams.Add(request.NewErrParamRequired("Name"))
	}
	if s.DnsConfig != nil {
		if err := s.DnsConfig.Validate(); err != nil {
			invalidParams.AddNested("DnsConfig", err.(request.ErrInvalidParams))
		}
	}
	if s.HealthCheckConfig != nil {
		if err := s.HealthCheckConfig.Validate(); err != nil {
			invalidParams.AddNested("HealthCheckConfig", err.(request.ErrInvalidParams))
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetCreatorRequestId sets the CreatorRequestId field's value.
func (s *CreateServiceInput) SetCreatorRequestId(v string) *CreateServiceInput {
	s.CreatorRequestId = &v
	return s
}

// SetDescription sets the Description field's value.
func (s *CreateServiceInput) SetDescription(v string) *CreateServiceInput {
	s.Description = &v
	return s
}

// SetDnsConfig sets the DnsConfig field's value.
func (s *CreateServiceInput) SetDnsConfig(v *DnsConfig) *CreateServiceInput {
	s.DnsConfig = v
	return s
}

// SetHealthCheckConfig sets the HealthCheckConfig field's value.
func (s *CreateServiceInput) SetHealthCheckConfig(v *HealthCheckConfig) *CreateServiceInput {
	s.HealthCheckConfig = v
	return s
}

// SetName sets the Name field's value.
func (s *CreateServiceInput) SetName(v string) *CreateServiceInput {
	s.Name = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/CreateServiceResponse
type CreateServiceOutput struct {
	_ struct{} `type:"structure"`

	// A complex type that contains information about the new service.
	Service *Service `type:"structure"`
}

// String returns the string representation
func (s CreateServiceOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s CreateServiceOutput) GoString() string {
	return s.String()
}

// SetService sets the Service field's value.
func (s *CreateServiceOutput) SetService(v *Service) *CreateServiceOutput {
	s.Service = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/DeleteNamespaceRequest
type DeleteNamespaceInput struct {
	_ struct{} `type:"structure"`

	// The ID of the namespace that you want to delete.
	//
	// Id is a required field
	Id *string `type:"string" required:"true"`
}

// String returns the string representation
func (s DeleteNamespaceInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DeleteNamespaceInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DeleteNamespaceInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DeleteNamespaceInput"}
	if s.Id == nil {
		invalidParams.Add(request.NewErrParamRequired("Id"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetId sets the Id field's value.
func (s *DeleteNamespaceInput) SetId(v string) *DeleteNamespaceInput {
	s.Id = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/DeleteNamespaceResponse
type DeleteNamespaceOutput struct {
	_ struct{} `type:"structure"`

	// A value that you can use to determine whether the request completed successfully.
	// To get the status of the operation, see GetOperation.
	OperationId *string `type:"string"`
}

// String returns the string representation
func (s DeleteNamespaceOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DeleteNamespaceOutput) GoString() string {
	return s.String()
}

// SetOperationId sets the OperationId field's value.
func (s *DeleteNamespaceOutput) SetOperationId(v string) *DeleteNamespaceOutput {
	s.OperationId = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/DeleteServiceRequest
type DeleteServiceInput struct {
	_ struct{} `type:"structure"`

	// The ID of the service that you want to delete.
	//
	// Id is a required field
	Id *string `type:"string" required:"true"`
}

// String returns the string representation
func (s DeleteServiceInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DeleteServiceInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DeleteServiceInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DeleteServiceInput"}
	if s.Id == nil {
		invalidParams.Add(request.NewErrParamRequired("Id"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetId sets the Id field's value.
func (s *DeleteServiceInput) SetId(v string) *DeleteServiceInput {
	s.Id = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/DeleteServiceResponse
type DeleteServiceOutput struct {
	_ struct{} `type:"structure"`
}

// String returns the string representation
func (s DeleteServiceOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DeleteServiceOutput) GoString() string {
	return s.String()
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/DeregisterInstanceRequest
type DeregisterInstanceInput struct {
	_ struct{} `type:"structure"`

	// The value that you specified for Id in the RegisterInstance request.
	//
	// InstanceId is a required field
	InstanceId *string `type:"string" required:"true"`

	// The ID of the service that the instance is associated with.
	//
	// ServiceId is a required field
	ServiceId *string `type:"string" required:"true"`
}

// String returns the string representation
func (s DeregisterInstanceInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DeregisterInstanceInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DeregisterInstanceInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DeregisterInstanceInput"}
	if s.InstanceId == nil {
		invalidParams.Add(request.NewErrParamRequired("InstanceId"))
	}
	if s.ServiceId == nil {
		invalidParams.Add(request.NewErrParamRequired("ServiceId"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetInstanceId sets the InstanceId field's value.
func (s *DeregisterInstanceInput) SetInstanceId(v string) *DeregisterInstanceInput {
	s.InstanceId = &v
	return s
}

// SetServiceId sets the ServiceId field's value.
func (s *DeregisterInstanceInput) SetServiceId(v string) *DeregisterInstanceInput {
	s.ServiceId = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/DeregisterInstanceResponse
type DeregisterInstanceOutput struct {
	_ struct{} `type:"structure"`

	// A value that you can use to determine whether the request completed successfully.
	// For more information, see GetOperation.
	OperationId *string `type:"string"`
}

// String returns the string representation
func (s DeregisterInstanceOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DeregisterInstanceOutput) GoString() string {
	return s.String()
}

// SetOperationId sets the OperationId field's value.
func (s *DeregisterInstanceOutput) SetOperationId(v string) *DeregisterInstanceOutput {
	s.OperationId = &v
	return s
}

// A complex type that contains information about the resource record sets that
// you want Amazon Route 53 to create when you register an instance.
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/DnsConfig
type DnsConfig struct {
	_ struct{} `type:"structure"`

	// An array that contains one DnsRecord object for each resource record set
	// that you want Amazon Route 53 to create when you register an instance.
	//
	// DnsRecords is a required field
	DnsRecords []*DnsRecord `type:"list" required:"true"`

	// The ID of the namespace to use for DNS configuration.
	//
	// NamespaceId is a required field
	NamespaceId *string `type:"string" required:"true"`
}

// String returns the string representation
func (s DnsConfig) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DnsConfig) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DnsConfig) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DnsConfig"}
	if s.DnsRecords == nil {
		invalidParams.Add(request.NewErrParamRequired("DnsRecords"))
	}
	if s.NamespaceId == nil {
		invalidParams.Add(request.NewErrParamRequired("NamespaceId"))
	}
	if s.DnsRecords != nil {
		for i, v := range s.DnsRecords {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "DnsRecords", i), err.(request.ErrInvalidParams))
			}
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetDnsRecords sets the DnsRecords field's value.
func (s *DnsConfig) SetDnsRecords(v []*DnsRecord) *DnsConfig {
	s.DnsRecords = v
	return s
}

// SetNamespaceId sets the NamespaceId field's value.
func (s *DnsConfig) SetNamespaceId(v string) *DnsConfig {
	s.NamespaceId = &v
	return s
}

// A complex type that contains information about changes to the resource record
// sets that Amazon Route 53 creates when you register an instance.
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/DnsConfigChange
type DnsConfigChange struct {
	_ struct{} `type:"structure"`

	// An array that contains one DnsRecord object for each resource record set
	// that you want Amazon Route 53 to create when you register an instance.
	//
	// DnsRecords is a required field
	DnsRecords []*DnsRecord `type:"list" required:"true"`
}

// String returns the string representation
func (s DnsConfigChange) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DnsConfigChange) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DnsConfigChange) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DnsConfigChange"}
	if s.DnsRecords == nil {
		invalidParams.Add(request.NewErrParamRequired("DnsRecords"))
	}
	if s.DnsRecords != nil {
		for i, v := range s.DnsRecords {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "DnsRecords", i), err.(request.ErrInvalidParams))
			}
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetDnsRecords sets the DnsRecords field's value.
func (s *DnsConfigChange) SetDnsRecords(v []*DnsRecord) *DnsConfigChange {
	s.DnsRecords = v
	return s
}

// A complex type that contains the ID for the hosted zone that Amazon Route
// 53 creates when you create a namespace.
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/DnsProperties
type DnsProperties struct {
	_ struct{} `type:"structure"`

	// The ID for the hosted zone that Amazon Route 53 creates when you create a
	// namespace.
	HostedZoneId *string `type:"string"`
}

// String returns the string representation
func (s DnsProperties) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DnsProperties) GoString() string {
	return s.String()
}

// SetHostedZoneId sets the HostedZoneId field's value.
func (s *DnsProperties) SetHostedZoneId(v string) *DnsProperties {
	s.HostedZoneId = &v
	return s
}

// A complex type that contains information about the resource record sets that
// you want Amazon Route 53 to create when you register an instance.
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/DnsRecord
type DnsRecord struct {
	_ struct{} `type:"structure"`

	// The amount of time, in seconds, that you want DNS resolvers to cache the
	// settings for this resource record set.
	//
	// TTL is a required field
	TTL *int64 `type:"long" required:"true"`

	// The type of the resource, which indicates the value that Amazon Route 53
	// returns in response to DNS queries. The following values are supported:
	//
	//    * A: Amazon Route 53 returns the IP address of the resource in IPv4 format,
	//    such as 192.0.2.44.
	//
	//    * AAAA: Amazon Route 53 returns the IP address of the resource in IPv6
	//    format, such as 2001:0db8:85a3:0000:0000:abcd:0001:2345.
	//
	//    * SRV: Amazon Route 53 returns the value for an SRV record. The value
	//    for an SRV record uses the following template, which can't be changed:
	//
	// priority weight port resource-record-set-name
	//
	// The values of priority and weight are both set to 1. The value of port comes
	//    from the value that you specify for Port when you submit a RegisterInstance
	//    request.
	//
	// Type is a required field
	Type *string `type:"string" required:"true" enum:"RecordType"`
}

// String returns the string representation
func (s DnsRecord) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DnsRecord) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DnsRecord) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DnsRecord"}
	if s.TTL == nil {
		invalidParams.Add(request.NewErrParamRequired("TTL"))
	}
	if s.Type == nil {
		invalidParams.Add(request.NewErrParamRequired("Type"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetTTL sets the TTL field's value.
func (s *DnsRecord) SetTTL(v int64) *DnsRecord {
	s.TTL = &v
	return s
}

// SetType sets the Type field's value.
func (s *DnsRecord) SetType(v string) *DnsRecord {
	s.Type = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetInstanceRequest
type GetInstanceInput struct {
	_ struct{} `type:"structure"`

	// The ID of the instance that you want to get information about.
	//
	// InstanceId is a required field
	InstanceId *string `type:"string" required:"true"`

	// The ID of the service that the instance is associated with.
	//
	// ServiceId is a required field
	ServiceId *string `type:"string" required:"true"`
}

// String returns the string representation
func (s GetInstanceInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s GetInstanceInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *GetInstanceInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "GetInstanceInput"}
	if s.InstanceId == nil {
		invalidParams.Add(request.NewErrParamRequired("InstanceId"))
	}
	if s.ServiceId == nil {
		invalidParams.Add(request.NewErrParamRequired("ServiceId"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetInstanceId sets the InstanceId field's value.
func (s *GetInstanceInput) SetInstanceId(v string) *GetInstanceInput {
	s.InstanceId = &v
	return s
}

// SetServiceId sets the ServiceId field's value.
func (s *GetInstanceInput) SetServiceId(v string) *GetInstanceInput {
	s.ServiceId = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetInstanceResponse
type GetInstanceOutput struct {
	_ struct{} `type:"structure"`

	// A complex type that contains information about a specified instance.
	Instance *Instance `type:"structure"`
}

// String returns the string representation
func (s GetInstanceOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s GetInstanceOutput) GoString() string {
	return s.String()
}

// SetInstance sets the Instance field's value.
func (s *GetInstanceOutput) SetInstance(v *Instance) *GetInstanceOutput {
	s.Instance = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetInstancesHealthStatusRequest
type GetInstancesHealthStatusInput struct {
	_ struct{} `type:"structure"`

	// An array that contains the IDs of all the instances that you want to get
	// the health status for. To get the IDs for the instances that you've created
	// by using a specified service, submit a ListInstances request.
	//
	// If you omit Instances, Amazon Route 53 returns the health status for all
	// the instances that are associated with the specified service.
	Instances []*string `min:"1" type:"list"`

	// The maximum number of instances that you want Amazon Route 53 to return in
	// the response to a GetInstancesHealthStatus request. If you don't specify
	// a value for MaxResults, Amazon Route 53 returns up to 100 instances.
	MaxResults *int64 `min:"1" type:"integer"`

	// For the first GetInstancesHealthStatus request, omit this value.
	//
	// If more than MaxResults instances match the specified criteria, you can submit
	// another GetInstancesHealthStatus request to get the next group of results.
	// Specify the value of NextToken from the previous response in the next request.
	NextToken *string `type:"string"`

	// The ID of the service that the instance is associated with.
	//
	// ServiceId is a required field
	ServiceId *string `type:"string" required:"true"`
}

// String returns the string representation
func (s GetInstancesHealthStatusInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s GetInstancesHealthStatusInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *GetInstancesHealthStatusInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "GetInstancesHealthStatusInput"}
	if s.Instances != nil && len(s.Instances) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("Instances", 1))
	}
	if s.MaxResults != nil && *s.MaxResults < 1 {
		invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1))
	}
	if s.ServiceId == nil {
		invalidParams.Add(request.NewErrParamRequired("ServiceId"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetInstances sets the Instances field's value.
func (s *GetInstancesHealthStatusInput) SetInstances(v []*string) *GetInstancesHealthStatusInput {
	s.Instances = v
	return s
}

// SetMaxResults sets the MaxResults field's value.
func (s *GetInstancesHealthStatusInput) SetMaxResults(v int64) *GetInstancesHealthStatusInput {
	s.MaxResults = &v
	return s
}

// SetNextToken sets the NextToken field's value.
func (s *GetInstancesHealthStatusInput) SetNextToken(v string) *GetInstancesHealthStatusInput {
	s.NextToken = &v
	return s
}

// SetServiceId sets the ServiceId field's value.
func (s *GetInstancesHealthStatusInput) SetServiceId(v string) *GetInstancesHealthStatusInput {
	s.ServiceId = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetInstancesHealthStatusResponse
type GetInstancesHealthStatusOutput struct {
	_ struct{} `type:"structure"`

	// If more than MaxResults instances match the specified criteria, you can submit
	// another GetInstancesHealthStatus request to get the next group of results.
	// Specify the value of NextToken from the previous response in the next request.
	NextToken *string `type:"string"`

	// A complex type that contains the IDs and the health status of the instances
	// that you specified in the GetInstancesHealthStatus request.
	Status map[string]*string `type:"map"`
}

// String returns the string representation
func (s GetInstancesHealthStatusOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s GetInstancesHealthStatusOutput) GoString() string {
	return s.String()
}

// SetNextToken sets the NextToken field's value.
func (s *GetInstancesHealthStatusOutput) SetNextToken(v string) *GetInstancesHealthStatusOutput {
	s.NextToken = &v
	return s
}

// SetStatus sets the Status field's value.
func (s *GetInstancesHealthStatusOutput) SetStatus(v map[string]*string) *GetInstancesHealthStatusOutput {
	s.Status = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetNamespaceRequest
type GetNamespaceInput struct {
	_ struct{} `type:"structure"`

	// The ID of the namespace that you want to get information about.
	//
	// Id is a required field
	Id *string `type:"string" required:"true"`
}

// String returns the string representation
func (s GetNamespaceInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s GetNamespaceInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *GetNamespaceInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "GetNamespaceInput"}
	if s.Id == nil {
		invalidParams.Add(request.NewErrParamRequired("Id"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetId sets the Id field's value.
func (s *GetNamespaceInput) SetId(v string) *GetNamespaceInput {
	s.Id = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetNamespaceResponse
type GetNamespaceOutput struct {
	_ struct{} `type:"structure"`

	// A complex type that contains information about the specified namespace.
	Namespace *Namespace `type:"structure"`
}

// String returns the string representation
func (s GetNamespaceOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s GetNamespaceOutput) GoString() string {
	return s.String()
}

// SetNamespace sets the Namespace field's value.
func (s *GetNamespaceOutput) SetNamespace(v *Namespace) *GetNamespaceOutput {
	s.Namespace = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetOperationRequest
type GetOperationInput struct {
	_ struct{} `type:"structure"`

	// The ID of the operation that you want to get more information about.
	//
	// OperationId is a required field
	OperationId *string `type:"string" required:"true"`
}

// String returns the string representation
func (s GetOperationInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s GetOperationInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *GetOperationInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "GetOperationInput"}
	if s.OperationId == nil {
		invalidParams.Add(request.NewErrParamRequired("OperationId"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetOperationId sets the OperationId field's value.
func (s *GetOperationInput) SetOperationId(v string) *GetOperationInput {
	s.OperationId = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetOperationResponse
type GetOperationOutput struct {
	_ struct{} `type:"structure"`

	// A complex type that contains information about the operation.
	Operation *Operation `type:"structure"`
}

// String returns the string representation
func (s GetOperationOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s GetOperationOutput) GoString() string {
	return s.String()
}

// SetOperation sets the Operation field's value.
func (s *GetOperationOutput) SetOperation(v *Operation) *GetOperationOutput {
	s.Operation = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetServiceRequest
type GetServiceInput struct {
	_ struct{} `type:"structure"`

	// The ID of the service that you want to get settings for.
	//
	// Id is a required field
	Id *string `type:"string" required:"true"`
}

// String returns the string representation
func (s GetServiceInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s GetServiceInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *GetServiceInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "GetServiceInput"}
	if s.Id == nil {
		invalidParams.Add(request.NewErrParamRequired("Id"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetId sets the Id field's value.
func (s *GetServiceInput) SetId(v string) *GetServiceInput {
	s.Id = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/GetServiceResponse
type GetServiceOutput struct {
	_ struct{} `type:"structure"`

	// A complex type that contains information about the service.
	Service *Service `type:"structure"`
}

// String returns the string representation
func (s GetServiceOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s GetServiceOutput) GoString() string {
	return s.String()
}

// SetService sets the Service field's value.
func (s *GetServiceOutput) SetService(v *Service) *GetServiceOutput {
	s.Service = v
	return s
}

// Public DNS namespaces only. A complex type that contains settings for an
// optional health check. If you specify settings for a health check, Amazon
// Route 53 associates the health check with all the resource record sets that
// you specify in DnsConfig.
//
// The health check uses 30 seconds as the request interval. This is the number
// of seconds between the time that each Amazon Route 53 health checker gets
// a response from your endpoint and the time that it sends the next health
// check request. A health checker in each data center around the world sends
// your endpoint a health check request every 30 seconds. On average, your endpoint
// receives a health check request about every two seconds. Health checkers
// in different data centers don't coordinate with one another, so you'll sometimes
// see several requests per second followed by a few seconds with no health
// checks at all.
//
// For information about the charges for health checks, see Amazon Route 53
// Pricing (http://aws.amazon.com/route53/pricing).
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/HealthCheckConfig
type HealthCheckConfig struct {
	_ struct{} `type:"structure"`

	// The number of consecutive health checks that an endpoint must pass or fail
	// for Amazon Route 53 to change the current status of the endpoint from unhealthy
	// to healthy or vice versa. For more information, see How Amazon Route 53 Determines
	// Whether an Endpoint Is Healthy (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html)
	// in the Amazon Route 53 Developer Guide.
	FailureThreshold *int64 `min:"1" type:"integer"`

	// The path that you want Amazon Route 53 to request when performing health
	// checks. The path can be any value for which your endpoint will return an
	// HTTP status code of 2xx or 3xx when the endpoint is healthy, such as the
	// file /docs/route53-health-check.html. Amazon Route 53 automatically adds
	// the DNS name for the service and a leading forward slash (/) character.
	ResourcePath *string `type:"string"`

	// The type of health check that you want to create, which indicates how Amazon
	// Route 53 determines whether an endpoint is healthy.
	//
	// You can't change the value of Type after you create a health check.
	//
	// You can create the following types of health checks:
	//
	//    * HTTP: Amazon Route 53 tries to establish a TCP connection. If successful,
	//    Amazon Route 53 submits an HTTP request and waits for an HTTP status code
	//    of 200 or greater and less than 400.
	//
	//    * HTTPS: Amazon Route 53 tries to establish a TCP connection. If successful,
	//    Amazon Route 53 submits an HTTPS request and waits for an HTTP status
	//    code of 200 or greater and less than 400.
	//
	// If you specify HTTPS for the value of Type, the endpoint must support TLS
	//    v1.0 or later.
	//
	//    * TCP: Amazon Route 53 tries to establish a TCP connection.
	//
	// For more information, see How Amazon Route 53 Determines Whether an Endpoint
	// Is Healthy (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html)
	// in the Amazon Route 53 Developer Guide.
	Type *string `type:"string" enum:"HealthCheckType"`
}

// String returns the string representation
func (s HealthCheckConfig) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s HealthCheckConfig) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *HealthCheckConfig) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "HealthCheckConfig"}
	if s.FailureThreshold != nil && *s.FailureThreshold < 1 {
		invalidParams.Add(request.NewErrParamMinValue("FailureThreshold", 1))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetFailureThreshold sets the FailureThreshold field's value.
func (s *HealthCheckConfig) SetFailureThreshold(v int64) *HealthCheckConfig {
	s.FailureThreshold = &v
	return s
}

// SetResourcePath sets the ResourcePath field's value.
func (s *HealthCheckConfig) SetResourcePath(v string) *HealthCheckConfig {
	s.ResourcePath = &v
	return s
}

// SetType sets the Type field's value.
func (s *HealthCheckConfig) SetType(v string) *HealthCheckConfig {
	s.Type = &v
	return s
}

// A complex type that contains information about an instance that Amazon Route
// 53 creates when you submit a RegisterInstance request.
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/Instance
type Instance struct {
	_ struct{} `type:"structure"`

	// A string map that contains attribute keys and values. Supported attribute
	// keys include the following:
	//
	//    * AWS_INSTANCE_PORT: The port on the endpoint that you want Amazon Route
	//    53 to perform health checks on. This value is also used for the port value
	//    in an SRV record if the service that you specify includes an SRV record.
	//    For more information, see CreateService.
	//
	//    * AWS_INSTANCE_IP: If the service that you specify contains a resource
	//    record set template for an A or AAAA record, the IP address that you want
	//    Amazon Route 53 to use for the value of the A record.
	//
	//    * AWS_INSTANCE_WEIGHT: The weight value in an SRV record if the service
	//    that you specify includes an SRV record. You can also specify a default
	//    weight that is applied to all instances in the Service configuration.
	//    For more information, see CreateService.
	//
	//    * AWS_INSTANCE_PRIORITY: The priority value in an SRV record if the service
	//    that you specify includes an SRV record.
	Attributes map[string]*string `type:"map"`

	// An optional parameter that you can use to resolve concurrent creation requests.
	// CreatorRequestId helps to determine if a specific client owns the namespace.
	CreatorRequestId *string `type:"string"`

	// An identifier that you want to associate with the instance. Note the following:
	//
	//    * You can use this value to update an existing instance.
	//
	//    * To associate a new instance, you must specify a value that is unique
	//    among instances that you associate by using the same service.
	//
	// Id is a required field
	Id *string `type:"string" required:"true"`
}

// String returns the string representation
func (s Instance) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s Instance) GoString() string {
	return s.String()
}

// SetAttributes sets the Attributes field's value.
func (s *Instance) SetAttributes(v map[string]*string) *Instance {
	s.Attributes = v
	return s
}

// SetCreatorRequestId sets the CreatorRequestId field's value.
func (s *Instance) SetCreatorRequestId(v string) *Instance {
	s.CreatorRequestId = &v
	return s
}

// SetId sets the Id field's value.
func (s *Instance) SetId(v string) *Instance {
	s.Id = &v
	return s
}

// A complex type that contains information about the instances that you created
// by using a specified service.
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/InstanceSummary
type InstanceSummary struct {
	_ struct{} `type:"structure"`

	// A string map that contain attribute keys and values for an instance. Supported
	// attribute keys include the following:
	//
	//    * AWS_INSTANCE_PORT: The port on the endpoint that you want Amazon Route
	//    53 to perform health checks on. This value is also used for the port value
	//    in an SRV record if the service that you specify includes an SRV record.
	//    For more information, see CreateService.
	//
	//    * AWS_INSTANCE_IP: If the service that you specify contains a resource
	//    record set template for an A or AAAA record, the IP address that you want
	//    Amazon Route 53 to use for the value of the A record.
	Attributes map[string]*string `type:"map"`

	// The ID for an instance that you created by using a specified service.
	Id *string `type:"string"`
}

// String returns the string representation
func (s InstanceSummary) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s InstanceSummary) GoString() string {
	return s.String()
}

// SetAttributes sets the Attributes field's value.
func (s *InstanceSummary) SetAttributes(v map[string]*string) *InstanceSummary {
	s.Attributes = v
	return s
}

// SetId sets the Id field's value.
func (s *InstanceSummary) SetId(v string) *InstanceSummary {
	s.Id = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListInstancesRequest
type ListInstancesInput struct {
	_ struct{} `type:"structure"`

	// The maximum number of instances that you want Amazon Route 53 to return in
	// the response to a ListInstances request. If you don't specify a value for
	// MaxResults, Amazon Route 53 returns up to 100 instances.
	MaxResults *int64 `min:"1" type:"integer"`

	// For the first ListInstances request, omit this value.
	//
	// If more than MaxResults instances match the specified criteria, you can submit
	// another ListInstances request to get the next group of results. Specify the
	// value of NextToken from the previous response in the next request.
	NextToken *string `type:"string"`

	// The ID of the service that you want to list instances for.
	//
	// ServiceId is a required field
	ServiceId *string `type:"string" required:"true"`
}

// String returns the string representation
func (s ListInstancesInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s ListInstancesInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *ListInstancesInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "ListInstancesInput"}
	if s.MaxResults != nil && *s.MaxResults < 1 {
		invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1))
	}
	if s.ServiceId == nil {
		invalidParams.Add(request.NewErrParamRequired("ServiceId"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetMaxResults sets the MaxResults field's value.
func (s *ListInstancesInput) SetMaxResults(v int64) *ListInstancesInput {
	s.MaxResults = &v
	return s
}

// SetNextToken sets the NextToken field's value.
func (s *ListInstancesInput) SetNextToken(v string) *ListInstancesInput {
	s.NextToken = &v
	return s
}

// SetServiceId sets the ServiceId field's value.
func (s *ListInstancesInput) SetServiceId(v string) *ListInstancesInput {
	s.ServiceId = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListInstancesResponse
type ListInstancesOutput struct {
	_ struct{} `type:"structure"`

	// Summary information about the instances that are associated with the specified
	// service.
	Instances []*InstanceSummary `type:"list"`

	// If more than MaxResults instances match the specified criteria, you can submit
	// another ListInstances request to get the next group of results. Specify the
	// value of NextToken from the previous response in the next request.
	NextToken *string `type:"string"`
}

// String returns the string representation
func (s ListInstancesOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s ListInstancesOutput) GoString() string {
	return s.String()
}

// SetInstances sets the Instances field's value.
func (s *ListInstancesOutput) SetInstances(v []*InstanceSummary) *ListInstancesOutput {
	s.Instances = v
	return s
}

// SetNextToken sets the NextToken field's value.
func (s *ListInstancesOutput) SetNextToken(v string) *ListInstancesOutput {
	s.NextToken = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListNamespacesRequest
type ListNamespacesInput struct {
	_ struct{} `type:"structure"`

	// A complex type that contains specifications for the namespaces that you want
	// to list.
	//
	// If you specify more than one filter, an operation must match all filters
	// to be returned by ListNamespaces.
	Filters []*NamespaceFilter `type:"list"`

	// The maximum number of namespaces that you want Amazon Route 53 to return
	// in the response to a ListNamespaces request. If you don't specify a value
	// for MaxResults, Amazon Route 53 returns up to 100 namespaces.
	MaxResults *int64 `min:"1" type:"integer"`

	// For the first ListNamespaces request, omit this value.
	//
	// If more than MaxResults namespaces match the specified criteria, you can
	// submit another ListNamespaces request to get the next group of results. Specify
	// the value of NextToken from the previous response in the next request.
	NextToken *string `type:"string"`
}

// String returns the string representation
func (s ListNamespacesInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s ListNamespacesInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *ListNamespacesInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "ListNamespacesInput"}
	if s.MaxResults != nil && *s.MaxResults < 1 {
		invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1))
	}
	if s.Filters != nil {
		for i, v := range s.Filters {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Filters", i), err.(request.ErrInvalidParams))
			}
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetFilters sets the Filters field's value.
func (s *ListNamespacesInput) SetFilters(v []*NamespaceFilter) *ListNamespacesInput {
	s.Filters = v
	return s
}

// SetMaxResults sets the MaxResults field's value.
func (s *ListNamespacesInput) SetMaxResults(v int64) *ListNamespacesInput {
	s.MaxResults = &v
	return s
}

// SetNextToken sets the NextToken field's value.
func (s *ListNamespacesInput) SetNextToken(v string) *ListNamespacesInput {
	s.NextToken = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListNamespacesResponse
type ListNamespacesOutput struct {
	_ struct{} `type:"structure"`

	// An array that contains one NamespaceSummary object for each namespace that
	// matches the specified filter criteria.
	Namespaces []*NamespaceSummary `type:"list"`

	// If more than MaxResults namespaces match the specified criteria, you can
	// submit another ListNamespaces request to get the next group of results. Specify
	// the value of NextToken from the previous response in the next request.
	NextToken *string `type:"string"`
}

// String returns the string representation
func (s ListNamespacesOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s ListNamespacesOutput) GoString() string {
	return s.String()
}

// SetNamespaces sets the Namespaces field's value.
func (s *ListNamespacesOutput) SetNamespaces(v []*NamespaceSummary) *ListNamespacesOutput {
	s.Namespaces = v
	return s
}

// SetNextToken sets the NextToken field's value.
func (s *ListNamespacesOutput) SetNextToken(v string) *ListNamespacesOutput {
	s.NextToken = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListOperationsRequest
type ListOperationsInput struct {
	_ struct{} `type:"structure"`

	// A complex type that contains specifications for the operations that you want
	// to list, for example, operations that you started between a specified start
	// date and end date.
	//
	// If you specify more than one filter, an operation must match all filters
	// to be returned by ListOperations.
	Filters []*OperationFilter `type:"list"`

	// The maximum number of items that you want Amazon Route 53 to return in the
	// response to a ListOperations request. If you don't specify a value for MaxResults,
	// Amazon Route 53 returns up to 100 operations.
	MaxResults *int64 `min:"1" type:"integer"`

	// For the first ListOperations request, omit this value.
	//
	// If more than MaxResults operations match the specified criteria, you can
	// submit another ListOperations request to get the next group of results. Specify
	// the value of NextToken from the previous response in the next request.
	NextToken *string `type:"string"`
}

// String returns the string representation
func (s ListOperationsInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s ListOperationsInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *ListOperationsInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "ListOperationsInput"}
	if s.MaxResults != nil && *s.MaxResults < 1 {
		invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1))
	}
	if s.Filters != nil {
		for i, v := range s.Filters {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Filters", i), err.(request.ErrInvalidParams))
			}
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetFilters sets the Filters field's value.
func (s *ListOperationsInput) SetFilters(v []*OperationFilter) *ListOperationsInput {
	s.Filters = v
	return s
}

// SetMaxResults sets the MaxResults field's value.
func (s *ListOperationsInput) SetMaxResults(v int64) *ListOperationsInput {
	s.MaxResults = &v
	return s
}

// SetNextToken sets the NextToken field's value.
func (s *ListOperationsInput) SetNextToken(v string) *ListOperationsInput {
	s.NextToken = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListOperationsResponse
type ListOperationsOutput struct {
	_ struct{} `type:"structure"`

	// If more than MaxResults operations match the specified criteria, you can
	// submit another ListOperations request to get the next group of results. Specify
	// the value of NextToken from the previous response in the next request.
	NextToken *string `type:"string"`

	// Summary information about the operations that match the specified criteria.
	Operations []*OperationSummary `type:"list"`
}

// String returns the string representation
func (s ListOperationsOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s ListOperationsOutput) GoString() string {
	return s.String()
}

// SetNextToken sets the NextToken field's value.
func (s *ListOperationsOutput) SetNextToken(v string) *ListOperationsOutput {
	s.NextToken = &v
	return s
}

// SetOperations sets the Operations field's value.
func (s *ListOperationsOutput) SetOperations(v []*OperationSummary) *ListOperationsOutput {
	s.Operations = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListServicesRequest
type ListServicesInput struct {
	_ struct{} `type:"structure"`

	// A complex type that contains specifications for the namespaces that you want
	// to list services for.
	//
	// If you specify more than one filter, an operation must match all filters
	// to be returned by ListServices.
	Filters []*ServiceFilter `type:"list"`

	// The maximum number of services that you want Amazon Route 53 to return in
	// the response to a ListServices request. If you don't specify a value for
	// MaxResults, Amazon Route 53 returns up to 100 services.
	MaxResults *int64 `min:"1" type:"integer"`

	// For the first ListServices request, omit this value.
	//
	// If more than MaxResults services match the specified criteria, you can submit
	// another ListServices request to get the next group of results. Specify the
	// value of NextToken from the previous response in the next request.
	NextToken *string `type:"string"`
}

// String returns the string representation
func (s ListServicesInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s ListServicesInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *ListServicesInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "ListServicesInput"}
	if s.MaxResults != nil && *s.MaxResults < 1 {
		invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1))
	}
	if s.Filters != nil {
		for i, v := range s.Filters {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Filters", i), err.(request.ErrInvalidParams))
			}
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetFilters sets the Filters field's value.
func (s *ListServicesInput) SetFilters(v []*ServiceFilter) *ListServicesInput {
	s.Filters = v
	return s
}

// SetMaxResults sets the MaxResults field's value.
func (s *ListServicesInput) SetMaxResults(v int64) *ListServicesInput {
	s.MaxResults = &v
	return s
}

// SetNextToken sets the NextToken field's value.
func (s *ListServicesInput) SetNextToken(v string) *ListServicesInput {
	s.NextToken = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListServicesResponse
type ListServicesOutput struct {
	_ struct{} `type:"structure"`

	// If more than MaxResults operations match the specified criteria, the value
	// of NextToken is the first service in the next group of services that were
	// created by the current AWS account. To get the next group, specify the value
	// of NextToken from the previous response in the next request.
	NextToken *string `type:"string"`

	// An array that contains one ServiceSummary object for each service that matches
	// the specified filter criteria.
	Services []*ServiceSummary `type:"list"`
}

// String returns the string representation
func (s ListServicesOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s ListServicesOutput) GoString() string {
	return s.String()
}

// SetNextToken sets the NextToken field's value.
func (s *ListServicesOutput) SetNextToken(v string) *ListServicesOutput {
	s.NextToken = &v
	return s
}

// SetServices sets the Services field's value.
func (s *ListServicesOutput) SetServices(v []*ServiceSummary) *ListServicesOutput {
	s.Services = v
	return s
}

// A complex type that contains information about a specified namespace.
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/Namespace
type Namespace struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) that Amazon Route 53 assigns to the namespace
	// when you create it.
	Arn *string `type:"string"`

	// The date that the namespace was created, in Unix date/time format and Coordinated
	// Universal Time (UTC).
	CreateDate *time.Time `type:"timestamp" timestampFormat:"unix"`

	// An optional parameter that you can use to resolve concurrent creation requests.
	// CreatorRequestId helps to determine if a specific client owns the namespace.
	CreatorRequestId *string `type:"string"`

	// The description that you specify for the namespace when you create it.
	Description *string `type:"string"`

	// The ID of a namespace.
	Id *string `type:"string"`

	// The name of the namespace, such as example.com.
	Name *string `type:"string"`

	// A complex type that contains information that's specific to the type of the
	// namespace.
	Properties *NamespaceProperties `type:"structure"`

	// The number of services that are associated with the namespace.
	ServiceCount *int64 `type:"integer"`

	// The type of the namespace. Valid values are DNS_PUBLIC and DNS_PRIVATE.
	Type *string `type:"string" enum:"NamespaceType"`
}

// String returns the string representation
func (s Namespace) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s Namespace) GoString() string {
	return s.String()
}

// SetArn sets the Arn field's value.
func (s *Namespace) SetArn(v string) *Namespace {
	s.Arn = &v
	return s
}

// SetCreateDate sets the CreateDate field's value.
func (s *Namespace) SetCreateDate(v time.Time) *Namespace {
	s.CreateDate = &v
	return s
}

// SetCreatorRequestId sets the CreatorRequestId field's value.
func (s *Namespace) SetCreatorRequestId(v string) *Namespace {
	s.CreatorRequestId = &v
	return s
}

// SetDescription sets the Description field's value.
func (s *Namespace) SetDescription(v string) *Namespace {
	s.Description = &v
	return s
}

// SetId sets the Id field's value.
func (s *Namespace) SetId(v string) *Namespace {
	s.Id = &v
	return s
}

// SetName sets the Name field's value.
func (s *Namespace) SetName(v string) *Namespace {
	s.Name = &v
	return s
}

// SetProperties sets the Properties field's value.
func (s *Namespace) SetProperties(v *NamespaceProperties) *Namespace {
	s.Properties = v
	return s
}

// SetServiceCount sets the ServiceCount field's value.
func (s *Namespace) SetServiceCount(v int64) *Namespace {
	s.ServiceCount = &v
	return s
}

// SetType sets the Type field's value.
func (s *Namespace) SetType(v string) *Namespace {
	s.Type = &v
	return s
}

// A complex type that identifies the namespaces that you want to list. You
// can choose to list public or private namespaces.
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/NamespaceFilter
type NamespaceFilter struct {
	_ struct{} `type:"structure"`

	// The operator that you want to use to determine whether ListNamespaces returns
	// a namespace. Valid values for condition include:
	//
	//    * EQ: When you specify EQ for the condition, you can choose to list only
	//    public namespaces or private namespaces, but not both. EQ is the default
	//    condition and can be omitted.
	//
	//    * IN: When you specify IN for the condition, you can choose to list public
	//    namespaces, private namespaces, or both.
	Condition *string `type:"string" enum:"FilterCondition"`

	// Specify TYPE.
	//
	// Name is a required field
	Name *string `type:"string" required:"true" enum:"NamespaceFilterName"`

	// If you specify EQ for Condition, specify either DNS_PUBLIC or DNS_PRIVATE.
	//
	// If you specify IN for Condition, you can specify DNS_PUBLIC, DNS_PRIVATE,
	// or both.
	//
	// Values is a required field
	Values []*string `type:"list" required:"true"`
}

// String returns the string representation
func (s NamespaceFilter) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s NamespaceFilter) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *NamespaceFilter) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "NamespaceFilter"}
	if s.Name == nil {
		invalidParams.Add(request.NewErrParamRequired("Name"))
	}
	if s.Values == nil {
		invalidParams.Add(request.NewErrParamRequired("Values"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetCondition sets the Condition field's value.
func (s *NamespaceFilter) SetCondition(v string) *NamespaceFilter {
	s.Condition = &v
	return s
}

// SetName sets the Name field's value.
func (s *NamespaceFilter) SetName(v string) *NamespaceFilter {
	s.Name = &v
	return s
}

// SetValues sets the Values field's value.
func (s *NamespaceFilter) SetValues(v []*string) *NamespaceFilter {
	s.Values = v
	return s
}

// A complex type that contains information that is specific to the namespace
// type.
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/NamespaceProperties
type NamespaceProperties struct {
	_ struct{} `type:"structure"`

	// A complex type that contains the ID for the hosted zone that Amazon Route
	// 53 creates when you create a namespace.
	DnsProperties *DnsProperties `type:"structure"`
}

// String returns the string representation
func (s NamespaceProperties) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s NamespaceProperties) GoString() string {
	return s.String()
}

// SetDnsProperties sets the DnsProperties field's value.
func (s *NamespaceProperties) SetDnsProperties(v *DnsProperties) *NamespaceProperties {
	s.DnsProperties = v
	return s
}

// A complex type that contains information about a namespace.
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/NamespaceSummary
type NamespaceSummary struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) that Amazon Route 53 assigns to the namespace
	// when you create it.
	Arn *string `type:"string"`

	// The ID of the namespace.
	Id *string `type:"string"`

	// The name of the namespace. When you create a namespace, Amazon Route 53 automatically
	// creates a hosted zone that has the same name as the namespace.
	Name *string `type:"string"`

	// The type of the namespace, either public or private.
	Type *string `type:"string" enum:"NamespaceType"`
}

// String returns the string representation
func (s NamespaceSummary) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s NamespaceSummary) GoString() string {
	return s.String()
}

// SetArn sets the Arn field's value.
func (s *NamespaceSummary) SetArn(v string) *NamespaceSummary {
	s.Arn = &v
	return s
}

// SetId sets the Id field's value.
func (s *NamespaceSummary) SetId(v string) *NamespaceSummary {
	s.Id = &v
	return s
}

// SetName sets the Name field's value.
func (s *NamespaceSummary) SetName(v string) *NamespaceSummary {
	s.Name = &v
	return s
}

// SetType sets the Type field's value.
func (s *NamespaceSummary) SetType(v string) *NamespaceSummary {
	s.Type = &v
	return s
}

// A complex type that contains information about a specified operation.
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/Operation
type Operation struct {
	_ struct{} `type:"structure"`

	// The date and time that the request was submitted, in Unix date/time format
	// and Coordinated Universal Time (UTC).
	CreateDate *time.Time `type:"timestamp" timestampFormat:"unix"`

	// The code associated with ErrorMessage.
	ErrorCode *string `type:"string"`

	// If the value of Status is FAIL, the reason that the operation failed.
	ErrorMessage *string `type:"string"`

	// The ID of the operation that you want to get information about.
	Id *string `type:"string"`

	// The status of the operation. Values include the following:
	//
	//    * SUBMITTED: This is the initial state immediately after you submit a
	//    request.
	//
	//    * PENDING: Amazon Route 53 is performing the operation.
	//
	//    * SUCCESS: The operation succeeded.
	//
	//    * FAIL: The operation failed. For the failure reason, see ErrorMessage.
	Status *string `type:"string" enum:"OperationStatus"`

	// The name of the target entity that is associated with the operation:
	//
	//    * NAMESPACE: The namespace ID is returned in the ResourceId property.
	//
	//    * SERVICE: The service ID is returned in the ResourceId property.
	//
	//    * INSTANCE: The instance ID is returned in the ResourceId property.
	Targets map[string]*string `type:"map"`

	// The name of the operation that is associated with the specified ID.
	Type *string `type:"string" enum:"OperationType"`

	// The date and time that the value of Status changed to the current value,
	// in Unix date/time format and Coordinated Universal Time (UTC).
	UpdateDate *time.Time `type:"timestamp" timestampFormat:"unix"`
}

// String returns the string representation
func (s Operation) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s Operation) GoString() string {
	return s.String()
}

// SetCreateDate sets the CreateDate field's value.
func (s *Operation) SetCreateDate(v time.Time) *Operation {
	s.CreateDate = &v
	return s
}

// SetErrorCode sets the ErrorCode field's value.
func (s *Operation) SetErrorCode(v string) *Operation {
	s.ErrorCode = &v
	return s
}

// SetErrorMessage sets the ErrorMessage field's value.
func (s *Operation) SetErrorMessage(v string) *Operation {
	s.ErrorMessage = &v
	return s
}

// SetId sets the Id field's value.
func (s *Operation) SetId(v string) *Operation {
	s.Id = &v
	return s
}

// SetStatus sets the Status field's value.
func (s *Operation) SetStatus(v string) *Operation {
	s.Status = &v
	return s
}

// SetTargets sets the Targets field's value.
func (s *Operation) SetTargets(v map[string]*string) *Operation {
	s.Targets = v
	return s
}

// SetType sets the Type field's value.
func (s *Operation) SetType(v string) *Operation {
	s.Type = &v
	return s
}

// SetUpdateDate sets the UpdateDate field's value.
func (s *Operation) SetUpdateDate(v time.Time) *Operation {
	s.UpdateDate = &v
	return s
}

// A complex type that lets you select the operations that you want to list.
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/OperationFilter
type OperationFilter struct {
	_ struct{} `type:"structure"`

	// The operator that you want to use to determine whether an operation matches
	// the specified value. Valid values for condition include:
	//
	//    * EQ: When you specify EQ for the condition, you can specify only one
	//    value. EQ is supported for NAMESPACE_ID, SERVICE_ID, STATUS, and TYPE.
	//    EQ is the default condition and can be omitted.
	//
	//    * IN: When you specify IN for the condition, you can specify a list of
	//    one or more values. IN is supported for STATUS and TYPE. An operation
	//    must match one of the specified values to be returned in the response.
	//
	//    * BETWEEN: Specify two values, a start date and an end date. The start
	//    date must be the first value. BETWEEN is supported for U.
	Condition *string `type:"string" enum:"FilterCondition"`

	// Specify the operations that you want to get:
	//
	//    * NAMESPACE_ID: Gets operations related to specified namespaces.
	//
	//    * SERVICE_ID: Gets operations related to specified services.
	//
	//    * STATUS: Gets operations based on the status of the operations: SUBMITTED,
	//    PENDING, SUCCEED, or FAIL.
	//
	//    * TYPE: Gets specified types of operation.
	//
	//    * UPDATE_DATE: Gets operations that changed status during a specified
	//    date/time range.
	//
	// Name is a required field
	Name *string `type:"string" required:"true" enum:"OperationFilterName"`

	// Specify values that are applicable to the value that you specify for Name:
	//
	//    * NAMESPACE_ID: Specify one namespace ID.
	//
	//    * SERVICE_ID: Specify one service ID.
	//
	//    * STATUS: Specify one or more statuses: SUBMITTED, PENDING, SUCCEED, or
	//    FAIL.
	//
	//    * TYPE: Specify one or more of the following types: CREATE_NAMESPACE,
	//    DELETE_NAMESPACE, UPDATE_SERVICE, REGISTER_INSTANCE, or DEREGISTER_INSTANCE.
	//
	//    * UPDATE_DATE: Specify a start date and an end date in Unix date/time
	//    format and Coordinated Universal Time (UTC). The start date must be the
	//    first value.
	//
	// Values is a required field
	Values []*string `type:"list" required:"true"`
}

// String returns the string representation
func (s OperationFilter) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s OperationFilter) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *OperationFilter) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "OperationFilter"}
	if s.Name == nil {
		invalidParams.Add(request.NewErrParamRequired("Name"))
	}
	if s.Values == nil {
		invalidParams.Add(request.NewErrParamRequired("Values"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetCondition sets the Condition field's value.
func (s *OperationFilter) SetCondition(v string) *OperationFilter {
	s.Condition = &v
	return s
}

// SetName sets the Name field's value.
func (s *OperationFilter) SetName(v string) *OperationFilter {
	s.Name = &v
	return s
}

// SetValues sets the Values field's value.
func (s *OperationFilter) SetValues(v []*string) *OperationFilter {
	s.Values = v
	return s
}

// A complex type that contains information about an operation that matches
// the criteria that you specified in a ListOperations request.
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/OperationSummary
type OperationSummary struct {
	_ struct{} `type:"structure"`

	// The ID for an operation.
	Id *string `type:"string"`

	// The status of the operation. Values include the following:
	//
	//    * SUBMITTED: This is the initial state immediately after you submit a
	//    request.
	//
	//    * PENDING: Amazon Route 53 is performing the operation.
	//
	//    * SUCCESS: The operation succeeded.
	//
	//    * FAIL: The operation failed. For the failure reason, see ErrorMessage.
	Status *string `type:"string" enum:"OperationStatus"`
}

// String returns the string representation
func (s OperationSummary) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s OperationSummary) GoString() string {
	return s.String()
}

// SetId sets the Id field's value.
func (s *OperationSummary) SetId(v string) *OperationSummary {
	s.Id = &v
	return s
}

// SetStatus sets the Status field's value.
func (s *OperationSummary) SetStatus(v string) *OperationSummary {
	s.Status = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/RegisterInstanceRequest
type RegisterInstanceInput struct {
	_ struct{} `type:"structure"`

	// A string map that contain attribute keys and values. Supported attribute
	// keys include the following:
	//
	//    * AWS_INSTANCE_PORT: The port on the endpoint that you want Amazon Route
	//    53 to perform health checks on. This value is also used for the port value
	//    in an SRV record if the service that you specify includes an SRV record.
	//    For more information, see CreateService.
	//
	//    * AWS_INSTANCE_IPV4: If the service that you specify contains a resource
	//    record set template for an A record, the IPv4 address that you want Amazon
	//    Route 53 to use for the value of the A record.
	//
	//    * AWS_INSTANCE_IPV6: If the service that you specify contains a resource
	//    record set template for an AAAA record, the IPv6 address that you want
	//    Amazon Route 53 to use for the value of the AAAA record.
	//
	// Attributes is a required field
	Attributes map[string]*string `type:"map" required:"true"`

	// An optional parameter that you can use to resolve concurrent creation requests.
	// CreatorRequestId helps to determine if a specific client owns the namespace.
	CreatorRequestId *string `type:"string" idempotencyToken:"true"`

	// An identifier that you want to associate with the instance. Note the following:
	//
	//    * You can use this value to update an existing instance.
	//
	//    * To register a new instance, you must specify a value that is unique
	//    among instances that you register by using the same service.
	//
	// InstanceId is a required field
	InstanceId *string `type:"string" required:"true"`

	// The ID of the service that you want to use for settings for the resource
	// record sets and health check that Amazon Route 53 will create.
	//
	// ServiceId is a required field
	ServiceId *string `type:"string" required:"true"`
}

// String returns the string representation
func (s RegisterInstanceInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s RegisterInstanceInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *RegisterInstanceInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "RegisterInstanceInput"}
	if s.Attributes == nil {
		invalidParams.Add(request.NewErrParamRequired("Attributes"))
	}
	if s.InstanceId == nil {
		invalidParams.Add(request.NewErrParamRequired("InstanceId"))
	}
	if s.ServiceId == nil {
		invalidParams.Add(request.NewErrParamRequired("ServiceId"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetAttributes sets the Attributes field's value.
func (s *RegisterInstanceInput) SetAttributes(v map[string]*string) *RegisterInstanceInput {
	s.Attributes = v
	return s
}

// SetCreatorRequestId sets the CreatorRequestId field's value.
func (s *RegisterInstanceInput) SetCreatorRequestId(v string) *RegisterInstanceInput {
	s.CreatorRequestId = &v
	return s
}

// SetInstanceId sets the InstanceId field's value.
func (s *RegisterInstanceInput) SetInstanceId(v string) *RegisterInstanceInput {
	s.InstanceId = &v
	return s
}

// SetServiceId sets the ServiceId field's value.
func (s *RegisterInstanceInput) SetServiceId(v string) *RegisterInstanceInput {
	s.ServiceId = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/RegisterInstanceResponse
type RegisterInstanceOutput struct {
	_ struct{} `type:"structure"`

	// A value that you can use to determine whether the request completed successfully.
	// To get the status of the operation, see GetOperation.
	OperationId *string `type:"string"`
}

// String returns the string representation
func (s RegisterInstanceOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s RegisterInstanceOutput) GoString() string {
	return s.String()
}

// SetOperationId sets the OperationId field's value.
func (s *RegisterInstanceOutput) SetOperationId(v string) *RegisterInstanceOutput {
	s.OperationId = &v
	return s
}

// A complex type that contains information about the specified service.
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/Service
type Service struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) that Amazon Route 53 assigns to the service
	// when you create it.
	Arn *string `type:"string"`

	// The date and time that the service was created, in Unix format and Coordinated
	// Universal Time (UTC).
	CreateDate *time.Time `type:"timestamp" timestampFormat:"unix"`

	// An optional parameter that you can use to resolve concurrent creation requests.
	// CreatorRequestId helps to determine if a specific client owns the namespace.
	CreatorRequestId *string `type:"string"`

	// The description of the service.
	Description *string `type:"string"`

	// A complex type that contains information about the resource record sets that
	// you want Amazon Route 53 to create when you register an instance.
	DnsConfig *DnsConfig `type:"structure"`

	// Public DNS namespaces only. A complex type that contains settings for an
	// optional health check. If you specify settings for a health check, Amazon
	// Route 53 associates the health check with all the resource record sets that
	// you specify in DnsConfig.
	//
	// The health check uses 30 seconds as the request interval. This is the number
	// of seconds between the time that each Amazon Route 53 health checker gets
	// a response from your endpoint and the time that it sends the next health
	// check request. A health checker in each data center around the world sends
	// your endpoint a health check request every 30 seconds. On average, your endpoint
	// receives a health check request about every two seconds. Health checkers
	// in different data centers don't coordinate with one another, so you'll sometimes
	// see several requests per second followed by a few seconds with no health
	// checks at all.
	//
	// For information about the charges for health checks, see Amazon Route 53
	// Pricing (http://aws.amazon.com/route53/pricing).
	HealthCheckConfig *HealthCheckConfig `type:"structure"`

	// The ID that Amazon Route 53 assigned to the service when you created it.
	Id *string `type:"string"`

	// The number of instances that are currently associated with the service. Instances
	// that were previously associated with the service but that have been deleted
	// are not included in the count.
	InstanceCount *int64 `type:"integer"`

	// The name of the service.
	Name *string `type:"string"`
}

// String returns the string representation
func (s Service) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s Service) GoString() string {
	return s.String()
}

// SetArn sets the Arn field's value.
func (s *Service) SetArn(v string) *Service {
	s.Arn = &v
	return s
}

// SetCreateDate sets the CreateDate field's value.
func (s *Service) SetCreateDate(v time.Time) *Service {
	s.CreateDate = &v
	return s
}

// SetCreatorRequestId sets the CreatorRequestId field's value.
func (s *Service) SetCreatorRequestId(v string) *Service {
	s.CreatorRequestId = &v
	return s
}

// SetDescription sets the Description field's value.
func (s *Service) SetDescription(v string) *Service {
	s.Description = &v
	return s
}

// SetDnsConfig sets the DnsConfig field's value.
func (s *Service) SetDnsConfig(v *DnsConfig) *Service {
	s.DnsConfig = v
	return s
}

// SetHealthCheckConfig sets the HealthCheckConfig field's value.
func (s *Service) SetHealthCheckConfig(v *HealthCheckConfig) *Service {
	s.HealthCheckConfig = v
	return s
}

// SetId sets the Id field's value.
func (s *Service) SetId(v string) *Service {
	s.Id = &v
	return s
}

// SetInstanceCount sets the InstanceCount field's value.
func (s *Service) SetInstanceCount(v int64) *Service {
	s.InstanceCount = &v
	return s
}

// SetName sets the Name field's value.
func (s *Service) SetName(v string) *Service {
	s.Name = &v
	return s
}

// A complex type that contains changes to an existing service.
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ServiceChange
type ServiceChange struct {
	_ struct{} `type:"structure"`

	// A description for the service.
	Description *string `type:"string"`

	// A complex type that contains information about the resource record sets that
	// you want Amazon Route 53 to create when you register an instance.
	//
	// DnsConfig is a required field
	DnsConfig *DnsConfigChange `type:"structure" required:"true"`

	// Public DNS namespaces only. A complex type that contains settings for an
	// optional health check. If you specify settings for a health check, Amazon
	// Route 53 associates the health check with all the resource record sets that
	// you specify in DnsConfig.
	//
	// The health check uses 30 seconds as the request interval. This is the number
	// of seconds between the time that each Amazon Route 53 health checker gets
	// a response from your endpoint and the time that it sends the next health
	// check request. A health checker in each data center around the world sends
	// your endpoint a health check request every 30 seconds. On average, your endpoint
	// receives a health check request about every two seconds. Health checkers
	// in different data centers don't coordinate with one another, so you'll sometimes
	// see several requests per second followed by a few seconds with no health
	// checks at all.
	//
	// For information about the charges for health checks, see Amazon Route 53
	// Pricing (http://aws.amazon.com/route53/pricing).
	HealthCheckConfig *HealthCheckConfig `type:"structure"`
}

// String returns the string representation
func (s ServiceChange) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s ServiceChange) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *ServiceChange) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "ServiceChange"}
	if s.DnsConfig == nil {
		invalidParams.Add(request.NewErrParamRequired("DnsConfig"))
	}
	if s.DnsConfig != nil {
		if err := s.DnsConfig.Validate(); err != nil {
			invalidParams.AddNested("DnsConfig", err.(request.ErrInvalidParams))
		}
	}
	if s.HealthCheckConfig != nil {
		if err := s.HealthCheckConfig.Validate(); err != nil {
			invalidParams.AddNested("HealthCheckConfig", err.(request.ErrInvalidParams))
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetDescription sets the Description field's value.
func (s *ServiceChange) SetDescription(v string) *ServiceChange {
	s.Description = &v
	return s
}

// SetDnsConfig sets the DnsConfig field's value.
func (s *ServiceChange) SetDnsConfig(v *DnsConfigChange) *ServiceChange {
	s.DnsConfig = v
	return s
}

// SetHealthCheckConfig sets the HealthCheckConfig field's value.
func (s *ServiceChange) SetHealthCheckConfig(v *HealthCheckConfig) *ServiceChange {
	s.HealthCheckConfig = v
	return s
}

// A complex type that lets you specify the namespaces that you want to list
// services for.
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ServiceFilter
type ServiceFilter struct {
	_ struct{} `type:"structure"`

	// The operator that you want to use to determine whether a service is returned
	// by ListServices. Valid values for Condition include the following:
	//
	//    * EQ: When you specify EQ, specify one namespace ID for Values. EQ is
	//    the default condition and can be omitted.
	//
	//    * IN: When you specify IN, specify a list of the IDs for the namespaces
	//    that you want ListServices to return a list of services for.
	Condition *string `type:"string" enum:"FilterCondition"`

	// Specify NAMESPACE_ID.
	//
	// Name is a required field
	Name *string `type:"string" required:"true" enum:"ServiceFilterName"`

	// The values that are applicable to the value that you specify for Condition
	// to filter the list of services.
	//
	// Values is a required field
	Values []*string `type:"list" required:"true"`
}

// String returns the string representation
func (s ServiceFilter) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s ServiceFilter) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *ServiceFilter) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "ServiceFilter"}
	if s.Name == nil {
		invalidParams.Add(request.NewErrParamRequired("Name"))
	}
	if s.Values == nil {
		invalidParams.Add(request.NewErrParamRequired("Values"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetCondition sets the Condition field's value.
func (s *ServiceFilter) SetCondition(v string) *ServiceFilter {
	s.Condition = &v
	return s
}

// SetName sets the Name field's value.
func (s *ServiceFilter) SetName(v string) *ServiceFilter {
	s.Name = &v
	return s
}

// SetValues sets the Values field's value.
func (s *ServiceFilter) SetValues(v []*string) *ServiceFilter {
	s.Values = v
	return s
}

// A complex type that contains information about a specified service.
// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ServiceSummary
type ServiceSummary struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) that Amazon Route 53 assigns to the service
	// when you create it.
	Arn *string `type:"string"`

	// The description that you specify when you create the service.
	Description *string `type:"string"`

	// The ID that Amazon Route 53 assigned to the service when you created it.
	Id *string `type:"string"`

	// The number of instances that are currently associated with the service. Instances
	// that were previously associated with the service but that have been deleted
	// are not included in the count.
	InstanceCount *int64 `type:"integer"`

	// The name of the service.
	Name *string `type:"string"`
}

// String returns the string representation
func (s ServiceSummary) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s ServiceSummary) GoString() string {
	return s.String()
}

// SetArn sets the Arn field's value.
func (s *ServiceSummary) SetArn(v string) *ServiceSummary {
	s.Arn = &v
	return s
}

// SetDescription sets the Description field's value.
func (s *ServiceSummary) SetDescription(v string) *ServiceSummary {
	s.Description = &v
	return s
}

// SetId sets the Id field's value.
func (s *ServiceSummary) SetId(v string) *ServiceSummary {
	s.Id = &v
	return s
}

// SetInstanceCount sets the InstanceCount field's value.
func (s *ServiceSummary) SetInstanceCount(v int64) *ServiceSummary {
	s.InstanceCount = &v
	return s
}

// SetName sets the Name field's value.
func (s *ServiceSummary) SetName(v string) *ServiceSummary {
	s.Name = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/UpdateServiceRequest
type UpdateServiceInput struct {
	_ struct{} `type:"structure"`

	// The ID of the service that you want to update.
	//
	// Id is a required field
	Id *string `type:"string" required:"true"`

	// A complex type that contains the new settings for the service.
	//
	// Service is a required field
	Service *ServiceChange `type:"structure" required:"true"`
}

// String returns the string representation
func (s UpdateServiceInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s UpdateServiceInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *UpdateServiceInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "UpdateServiceInput"}
	if s.Id == nil {
		invalidParams.Add(request.NewErrParamRequired("Id"))
	}
	if s.Service == nil {
		invalidParams.Add(request.NewErrParamRequired("Service"))
	}
	if s.Service != nil {
		if err := s.Service.Validate(); err != nil {
			invalidParams.AddNested("Service", err.(request.ErrInvalidParams))
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetId sets the Id field's value.
func (s *UpdateServiceInput) SetId(v string) *UpdateServiceInput {
	s.Id = &v
	return s
}

// SetService sets the Service field's value.
func (s *UpdateServiceInput) SetService(v *ServiceChange) *UpdateServiceInput {
	s.Service = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/UpdateServiceResponse
type UpdateServiceOutput struct {
	_ struct{} `type:"structure"`

	// A value that you can use to determine whether the request completed successfully.
	// To get the status of the operation, see GetOperation.
	OperationId *string `type:"string"`
}

// String returns the string representation
func (s UpdateServiceOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s UpdateServiceOutput) GoString() string {
	return s.String()
}

// SetOperationId sets the OperationId field's value.
func (s *UpdateServiceOutput) SetOperationId(v string) *UpdateServiceOutput {
	s.OperationId = &v
	return s
}

const (
	// FilterConditionEq is a FilterCondition enum value
	FilterConditionEq = "EQ"

	// FilterConditionIn is a FilterCondition enum value
	FilterConditionIn = "IN"

	// FilterConditionBetween is a FilterCondition enum value
	FilterConditionBetween = "BETWEEN"
)

const (
	// HealthCheckTypeHttp is a HealthCheckType enum value
	HealthCheckTypeHttp = "HTTP"

	// HealthCheckTypeHttps is a HealthCheckType enum value
	HealthCheckTypeHttps = "HTTPS"

	// HealthCheckTypeTcp is a HealthCheckType enum value
	HealthCheckTypeTcp = "TCP"
)

const (
	// HealthStatusHealthy is a HealthStatus enum value
	HealthStatusHealthy = "HEALTHY"

	// HealthStatusUnhealthy is a HealthStatus enum value
	HealthStatusUnhealthy = "UNHEALTHY"

	// HealthStatusUnknown is a HealthStatus enum value
	HealthStatusUnknown = "UNKNOWN"
)

const (
	// NamespaceFilterNameType is a NamespaceFilterName enum value
	NamespaceFilterNameType = "TYPE"
)

const (
	// NamespaceTypeDnsPublic is a NamespaceType enum value
	NamespaceTypeDnsPublic = "DNS_PUBLIC"

	// NamespaceTypeDnsPrivate is a NamespaceType enum value
	NamespaceTypeDnsPrivate = "DNS_PRIVATE"
)

const (
	// OperationFilterNameNamespaceId is a OperationFilterName enum value
	OperationFilterNameNamespaceId = "NAMESPACE_ID"

	// OperationFilterNameServiceId is a OperationFilterName enum value
	OperationFilterNameServiceId = "SERVICE_ID"

	// OperationFilterNameStatus is a OperationFilterName enum value
	OperationFilterNameStatus = "STATUS"

	// OperationFilterNameType is a OperationFilterName enum value
	OperationFilterNameType = "TYPE"

	// OperationFilterNameUpdateDate is a OperationFilterName enum value
	OperationFilterNameUpdateDate = "UPDATE_DATE"
)

const (
	// OperationStatusSubmitted is a OperationStatus enum value
	OperationStatusSubmitted = "SUBMITTED"

	// OperationStatusPending is a OperationStatus enum value
	OperationStatusPending = "PENDING"

	// OperationStatusSuccess is a OperationStatus enum value
	OperationStatusSuccess = "SUCCESS"

	// OperationStatusFail is a OperationStatus enum value
	OperationStatusFail = "FAIL"
)

const (
	// OperationTargetTypeNamespace is a OperationTargetType enum value
	OperationTargetTypeNamespace = "NAMESPACE"

	// OperationTargetTypeService is a OperationTargetType enum value
	OperationTargetTypeService = "SERVICE"

	// OperationTargetTypeInstance is a OperationTargetType enum value
	OperationTargetTypeInstance = "INSTANCE"
)

const (
	// OperationTypeCreateNamespace is a OperationType enum value
	OperationTypeCreateNamespace = "CREATE_NAMESPACE"

	// OperationTypeDeleteNamespace is a OperationType enum value
	OperationTypeDeleteNamespace = "DELETE_NAMESPACE"

	// OperationTypeUpdateService is a OperationType enum value
	OperationTypeUpdateService = "UPDATE_SERVICE"

	// OperationTypeRegisterInstance is a OperationType enum value
	OperationTypeRegisterInstance = "REGISTER_INSTANCE"

	// OperationTypeDeregisterInstance is a OperationType enum value
	OperationTypeDeregisterInstance = "DEREGISTER_INSTANCE"
)

const (
	// RecordTypeSrv is a RecordType enum value
	RecordTypeSrv = "SRV"

	// RecordTypeA is a RecordType enum value
	RecordTypeA = "A"

	// RecordTypeAaaa is a RecordType enum value
	RecordTypeAaaa = "AAAA"
)

const (
	// ServiceFilterNameNamespaceId is a ServiceFilterName enum value
	ServiceFilterNameNamespaceId = "NAMESPACE_ID"
)


<|start_filename|>vendor/github.com/zclconf/go-cty/cty/set/ops.go<|end_filename|>
package set

import (
	"sort"
)

// Add inserts the given value into the receiving Set.
//
// This mutates the set in-place. This operation is not thread-safe.
func (s Set) Add(val interface{}) {
	hv := s.rules.Hash(val)
	if _, ok := s.vals[hv]; !ok {
		s.vals[hv] = make([]interface{}, 0, 1)
	}
	bucket := s.vals[hv]

	// See if an equivalent value is already present
	for _, ev := range bucket {
		if s.rules.Equivalent(val, ev) {
			return
		}
	}

	s.vals[hv] = append(bucket, val)
}

// Remove deletes the given value from the receiving set, if indeed it was
// there in the first place. If the value is not present, this is a no-op.
func (s Set) Remove(val interface{}) {
	hv := s.rules.Hash(val)
	bucket, ok := s.vals[hv]
	if !ok {
		return
	}

	for i, ev := range bucket {
		if s.rules.Equivalent(val, ev) {
			newBucket := make([]interface{}, 0, len(bucket)-1)
			newBucket = append(newBucket, bucket[:i]...)
			newBucket = append(newBucket, bucket[i+1:]...)
			if len(newBucket) > 0 {
				s.vals[hv] = newBucket
			} else {
				delete(s.vals, hv)
			}
			return
		}
	}
}

// Has returns true if the given value is in the receiving set, or false if
// it is not.
func (s Set) Has(val interface{}) bool {
	hv := s.rules.Hash(val)
	bucket, ok := s.vals[hv]
	if !ok {
		return false
	}

	for _, ev := range bucket {
		if s.rules.Equivalent(val, ev) {
			return true
		}
	}
	return false
}

// Iterator returns an iterator over values in the set, in an undefined order
// that callers should not depend on.
//
// The pattern for using the returned iterator is:
//
//     it := set.Iterator()
//     for it.Next() {
//         val := it.Value()
//         // ...
//     }
//
// Once an iterator has been created for a set, the set *must not* be mutated
// until the iterator is no longer in use.
func (s Set) Iterator() *Iterator {
	// Sort the bucketIds to ensure that we always traverse in a
	// consistent order.
	bucketIds := make([]int, 0, len(s.vals))
	for id := range s.vals {
		bucketIds = append(bucketIds, id)
	}
	sort.Ints(bucketIds)

	return &Iterator{
		bucketIds: bucketIds,
		vals:      s.vals,
		bucketIdx: -1,
	}
}

// EachValue calls the given callback once for each value in the set, in an
// undefined order that callers should not depend on.
func (s Set) EachValue(cb func(interface{})) {
	it := s.Iterator()
	for it.Next() {
		cb(it.Value())
	}
}

// Values returns a slice of all of the values in the set in no particular
// order. This is just a wrapper around EachValue that accumulates the results
// in a slice for caller convenience.
//
// The returned slice will be nil if there are no values in the set.
func (s Set) Values() []interface{} {
	var ret []interface{}
	s.EachValue(func(v interface{}) {
		ret = append(ret, v)
	})
	return ret
}

// Length returns the number of values in the set.
func (s Set) Length() int {
	var count int
	for _, bucket := range s.vals {
		count = count + len(bucket)
	}
	return count
}

// Union returns a new set that contains all of the members of both the
// receiving set and the given set. Both sets must have the same rules, or
// else this function will panic.
func (s1 Set) Union(s2 Set) Set {
	mustHaveSameRules(s1, s2)
	rs := NewSet(s1.rules)
	s1.EachValue(func(v interface{}) {
		rs.Add(v)
	})
	s2.EachValue(func(v interface{}) {
		rs.Add(v)
	})
	return rs
}

// Intersection returns a new set that contains the values that both the
// receiver and given sets have in common. Both sets must have the same rules,
// or else this function will panic.
func (s1 Set) Intersection(s2 Set) Set {
	mustHaveSameRules(s1, s2)
	rs := NewSet(s1.rules)
	s1.EachValue(func(v interface{}) {
		if s2.Has(v) {
			rs.Add(v)
		}
	})
	return rs
}

// Subtract returns a new set that contains all of the values from the receiver
// that are not also in the given set. Both sets must have the same rules,
// or else this function will panic.
func (s1 Set) Subtract(s2 Set) Set {
	mustHaveSameRules(s1, s2)
	rs := NewSet(s1.rules)
	s1.EachValue(func(v interface{}) {
		if !s2.Has(v) {
			rs.Add(v)
		}
	})
	return rs
}

// SymmetricDifference returns a new set that contains all of the values from
// both the receiver and given sets, except those that both sets have in
// common. Both sets must have the same rules, or else this function will
// panic.
func (s1 Set) SymmetricDifference(s2 Set) Set {
	mustHaveSameRules(s1, s2)
	rs := NewSet(s1.rules)
	s1.EachValue(func(v interface{}) {
		if !s2.Has(v) {
			rs.Add(v)
		}
	})
	s2.EachValue(func(v interface{}) {
		if !s1.Has(v) {
			rs.Add(v)
		}
	})
	return rs
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_dx_lag.go<|end_filename|>
package aws

import (
	"fmt"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/directconnect"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsDxLag() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsDxLagCreate,
		Read:   resourceAwsDxLagRead,
		Update: resourceAwsDxLagUpdate,
		Delete: resourceAwsDxLagDelete,

		Schema: map[string]*schema.Schema{
			"name": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
			},
			"connections_bandwidth": &schema.Schema{
				Type:         schema.TypeString,
				Required:     true,
				ForceNew:     true,
				ValidateFunc: validateDxConnectionBandWidth,
			},
			"location": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"number_of_connections": &schema.Schema{
				Type:     schema.TypeInt,
				Required: true,
				ForceNew: true,
			},
			"force_destroy": &schema.Schema{
				Type:     schema.TypeBool,
				Optional: true,
				Default:  false,
			},
		},
	}
}

func resourceAwsDxLagCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).dxconn

	input := &directconnect.CreateLagInput{
		ConnectionsBandwidth: aws.String(d.Get("connections_bandwidth").(string)),
		LagName:              aws.String(d.Get("name").(string)),
		Location:             aws.String(d.Get("location").(string)),
		NumberOfConnections:  aws.Int64(int64(d.Get("number_of_connections").(int))),
	}
	resp, err := conn.CreateLag(input)
	if err != nil {
		return err
	}
	d.SetId(*resp.LagId)
	return resourceAwsDxLagRead(d, meta)
}

func resourceAwsDxLagRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).dxconn

	lagId := d.Id()
	input := &directconnect.DescribeLagsInput{
		LagId: aws.String(lagId),
	}
	resp, err := conn.DescribeLags(input)
	if err != nil {
		return err
	}
	if len(resp.Lags) < 1 {
		d.SetId("")
		return nil
	}
	if len(resp.Lags) != 1 {
		return fmt.Errorf("[ERROR] Number of DX Lag (%s) isn't one, got %d", lagId, len(resp.Lags))
	}
	if d.Id() != *resp.Lags[0].LagId {
		return fmt.Errorf("[ERROR] DX Lag (%s) not found", lagId)
	}
	return nil
}

func resourceAwsDxLagUpdate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).dxconn

	input := &directconnect.UpdateLagInput{
		LagId: aws.String(d.Id()),
	}
	if d.HasChange("name") {
		input.LagName = aws.String(d.Get("name").(string))
	}
	_, err := conn.UpdateLag(input)
	if err != nil {
		return err
	}
	return nil
}

func resourceAwsDxLagDelete(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).dxconn

	if d.Get("force_destroy").(bool) {
		input := &directconnect.DescribeLagsInput{
			LagId: aws.String(d.Id()),
		}
		resp, err := conn.DescribeLags(input)
		if err != nil {
			return err
		}
		lag := resp.Lags[0]
		for _, v := range lag.Connections {
			dcinput := &directconnect.DeleteConnectionInput{
				ConnectionId: v.ConnectionId,
			}
			if _, err := conn.DeleteConnection(dcinput); err != nil {
				return err
			}
		}
	}

	input := &directconnect.DeleteLagInput{
		LagId: aws.String(d.Id()),
	}
	_, err := conn.DeleteLag(input)
	if err != nil {
		return err
	}
	deleteStateConf := &resource.StateChangeConf{
		Pending:    []string{directconnect.LagStateAvailable, directconnect.LagStateRequested, directconnect.LagStatePending, directconnect.LagStateDeleting},
		Target:     []string{directconnect.LagStateDeleted},
		Refresh:    dxLagRefreshStateFunc(conn, d.Id()),
		Timeout:    10 * time.Minute,
		Delay:      10 * time.Second,
		MinTimeout: 3 * time.Second,
	}
	_, err = deleteStateConf.WaitForState()
	if err != nil {
		return fmt.Errorf("Error waiting for Dx Lag (%s) to be deleted: %s", d.Id(), err)
	}
	d.SetId("")
	return nil
}

func dxLagRefreshStateFunc(conn *directconnect.DirectConnect, lagId string) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		input := &directconnect.DescribeLagsInput{
			LagId: aws.String(lagId),
		}
		resp, err := conn.DescribeLags(input)
		if err != nil {
			return nil, "failed", err
		}
		return resp, *resp.Lags[0].LagState, nil
	}
}


<|start_filename|>vendor/github.com/zclconf/go-cty/cty/function/stdlib/json.go<|end_filename|>
package stdlib

import (
	"github.com/zclconf/go-cty/cty"
	"github.com/zclconf/go-cty/cty/function"
	"github.com/zclconf/go-cty/cty/json"
)

var JSONEncodeFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name:             "val",
			Type:             cty.DynamicPseudoType,
			AllowDynamicType: true,
		},
	},
	Type: function.StaticReturnType(cty.String),
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		val := args[0]
		buf, err := json.Marshal(val, val.Type())
		if err != nil {
			return cty.NilVal, err
		}

		return cty.StringVal(string(buf)), nil
	},
})

var JSONDecodeFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name: "str",
			Type: cty.String,
		},
	},
	Type: func(args []cty.Value) (cty.Type, error) {
		str := args[0]
		if !str.IsKnown() {
			return cty.DynamicPseudoType, nil
		}

		buf := []byte(str.AsString())
		return json.ImpliedType(buf)
	},
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		buf := []byte(args[0].AsString())
		return json.Unmarshal(buf, retType)
	},
})

// JSONEncode returns a JSON serialization of the given value.
func JSONEncode(val cty.Value) (cty.Value, error) {
	return JSONEncodeFunc.Call([]cty.Value{val})
}

// JSONDecode parses the given JSON string and, if it is valid, returns the
// value it represents.
//
// Note that applying JSONDecode to the result of JSONEncode may not produce
// an identically-typed result, since JSON encoding is lossy for cty Types.
// The resulting value will consist only of primitive types, object types, and
// tuple types.
func JSONDecode(str cty.Value) (cty.Value, error) {
	return JSONDecodeFunc.Call([]cty.Value{str})
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_iam_user_login_profile.go<|end_filename|>
package aws

import (
	"errors"
	"fmt"
	"log"
	"math/rand"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/iam"
	"github.com/hashicorp/errwrap"
	"github.com/hashicorp/terraform/helper/encryption"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsIamUserLoginProfile() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsIamUserLoginProfileCreate,
		Read:   schema.Noop,
		Update: schema.Noop,
		Delete: schema.RemoveFromState,

		Schema: map[string]*schema.Schema{
			"user": {
				Type:     schema.TypeString,
				Required: true,
			},
			"pgp_key": {
				Type:     schema.TypeString,
				Required: true,
			},
			"password_reset_required": {
				Type:     schema.TypeBool,
				Optional: true,
				Default:  true,
			},
			"password_length": {
				Type:         schema.TypeInt,
				Optional:     true,
				Default:      20,
				ValidateFunc: validateAwsIamLoginProfilePasswordLength,
			},

			"key_fingerprint": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"encrypted_password": {
				Type:     schema.TypeString,
				Computed: true,
			},
		},
	}
}

func validateAwsIamLoginProfilePasswordLength(v interface{}, _ string) (_ []string, es []error) {
	length := v.(int)
	if length < 4 {
		es = append(es, errors.New("minimum password_length is 4 characters"))
	}
	if length > 128 {
		es = append(es, errors.New("maximum password_length is 128 characters"))
	}
	return
}

// generatePassword generates a random password of a given length using
// characters that are likely to satisfy any possible AWS password policy
// (given sufficient length).
func generatePassword(length int) string {
	charsets := []string{
		"abcdefghijklmnopqrstuvwxyz",
		"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
		"012346789",
		"!@#$%^&*()_+-=[]{}|'",
	}

	// Use all character sets
	random := rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
	components := make(map[int]byte, length)
	for i := 0; i < length; i++ {
		charset := charsets[i%len(charsets)]
		components[i] = charset[random.Intn(len(charset))]
	}

	// Randomise the ordering so we don't end up with a predictable
	// lower case, upper case, numeric, symbol pattern
	result := make([]byte, length)
	i := 0
	for _, b := range components {
		result[i] = b
		i = i + 1
	}

	return string(result)
}

func resourceAwsIamUserLoginProfileCreate(d *schema.ResourceData, meta interface{}) error {
	iamconn := meta.(*AWSClient).iamconn

	encryptionKey, err := encryption.RetrieveGPGKey(d.Get("pgp_key").(string))
	if err != nil {
		return err
	}

	username := d.Get("user").(string)
	passwordResetRequired := d.Get("password_reset_required").(bool)
	passwordLength := d.Get("password_length").(int)

	_, err = iamconn.GetLoginProfile(&iam.GetLoginProfileInput{
		UserName: aws.String(username),
	})
	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() != "NoSuchEntity" {
			// If there is already a login profile, bring it under management (to prevent
			// resource creation diffs) - we will never modify it, but obviously cannot
			// set the password.
			d.SetId(username)
			d.Set("key_fingerprint", "")
			d.Set("encrypted_password", "")
			return nil
		}
	}

	initialPassword := generatePassword(passwordLength)
	fingerprint, encrypted, err := encryption.EncryptValue(encryptionKey, initialPassword, "Password")
	if err != nil {
		return err
	}

	request := &iam.CreateLoginProfileInput{
		UserName:              aws.String(username),
		Password:              aws.String(initialPassword),
		PasswordResetRequired: aws.Bool(passwordResetRequired),
	}

	log.Println("[DEBUG] Create IAM User Login Profile request:", request)
	createResp, err := iamconn.CreateLoginProfile(request)
	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "EntityAlreadyExists" {
			// If there is already a login profile, bring it under management (to prevent
			// resource creation diffs) - we will never modify it, but obviously cannot
			// set the password.
			d.SetId(username)
			d.Set("key_fingerprint", "")
			d.Set("encrypted_password", "")
			return nil
		}
		return errwrap.Wrapf(fmt.Sprintf("Error creating IAM User Login Profile for %q: {{err}}", username), err)
	}

	d.SetId(*createResp.LoginProfile.UserName)
	d.Set("key_fingerprint", fingerprint)
	d.Set("encrypted_password", encrypted)
	return nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_ecr_lifecycle_policy.go<|end_filename|>
package aws

import (
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/ecr"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsEcrLifecyclePolicy() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsEcrLifecyclePolicyCreate,
		Read:   resourceAwsEcrLifecyclePolicyRead,
		Delete: resourceAwsEcrLifecyclePolicyDelete,

		Schema: map[string]*schema.Schema{
			"repository": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"policy": &schema.Schema{
				Type:         schema.TypeString,
				Required:     true,
				ForceNew:     true,
				ValidateFunc: validateJsonString,
			},
			"registry_id": &schema.Schema{
				Type:     schema.TypeString,
				Computed: true,
			},
		},
	}
}

func resourceAwsEcrLifecyclePolicyCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ecrconn

	input := &ecr.PutLifecyclePolicyInput{
		RepositoryName:      aws.String(d.Get("repository").(string)),
		LifecyclePolicyText: aws.String(d.Get("policy").(string)),
	}

	resp, err := conn.PutLifecyclePolicy(input)
	if err != nil {
		return err
	}
	d.SetId(*resp.RepositoryName)
	d.Set("registry_id", resp.RegistryId)
	return resourceAwsEcrLifecyclePolicyRead(d, meta)
}

func resourceAwsEcrLifecyclePolicyRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ecrconn

	input := &ecr.GetLifecyclePolicyInput{
		RegistryId:     aws.String(d.Get("registry_id").(string)),
		RepositoryName: aws.String(d.Get("repository").(string)),
	}

	_, err := conn.GetLifecyclePolicy(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case ecr.ErrCodeRepositoryNotFoundException, ecr.ErrCodeLifecyclePolicyNotFoundException:
				d.SetId("")
				return nil
			default:
				return err
			}
		}
		return err
	}

	return nil
}

func resourceAwsEcrLifecyclePolicyDelete(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ecrconn

	input := &ecr.DeleteLifecyclePolicyInput{
		RegistryId:     aws.String(d.Get("registry_id").(string)),
		RepositoryName: aws.String(d.Get("repository").(string)),
	}

	_, err := conn.DeleteLifecyclePolicy(input)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case ecr.ErrCodeRepositoryNotFoundException, ecr.ErrCodeLifecyclePolicyNotFoundException:
				d.SetId("")
				return nil
			default:
				return err
			}
		}
		return err
	}

	return nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/data_source_aws_rds_cluster.go<|end_filename|>
package aws

import (
	"log"
	"strings"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/rds"
	"github.com/hashicorp/errwrap"
	"github.com/hashicorp/terraform/helper/schema"
)

func dataSourceAwsRdsCluster() *schema.Resource {
	return &schema.Resource{
		Read: dataSourceAwsRdsClusterRead,
		Schema: map[string]*schema.Schema{
			"cluster_identifier": {
				Type:     schema.TypeString,
				Required: true,
			},

			"availability_zones": {
				Type:     schema.TypeSet,
				Elem:     &schema.Schema{Type: schema.TypeString},
				Computed: true,
				Set:      schema.HashString,
			},

			"backup_retention_period": {
				Type:     schema.TypeInt,
				Computed: true,
			},

			"cluster_members": {
				Type:     schema.TypeSet,
				Elem:     &schema.Schema{Type: schema.TypeString},
				Computed: true,
				Set:      schema.HashString,
			},

			"cluster_resource_id": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"database_name": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"db_subnet_group_name": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"db_cluster_parameter_group_name": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"endpoint": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"engine": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"engine_version": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"final_snapshot_identifier": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"iam_database_authentication_enabled": {
				Type:     schema.TypeBool,
				Computed: true,
			},

			"iam_roles": {
				Type:     schema.TypeSet,
				Computed: true,
				Elem:     &schema.Schema{Type: schema.TypeString},
				Set:      schema.HashString,
			},

			"kms_key_id": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"master_username": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"preferred_backup_window": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"preferred_maintenance_window": {
				Type:     schema.TypeString,
				Computed: true,
				StateFunc: func(val interface{}) string {
					if val == nil {
						return ""
					}
					return strings.ToLower(val.(string))
				},
			},

			"port": {
				Type:     schema.TypeInt,
				Computed: true,
			},

			"reader_endpoint": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"replication_source_identifier": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"storage_encrypted": {
				Type:     schema.TypeBool,
				Computed: true,
			},

			"tags": tagsSchemaComputed(),

			"vpc_security_group_ids": {
				Type:     schema.TypeSet,
				Computed: true,
				Elem:     &schema.Schema{Type: schema.TypeString},
				Set:      schema.HashString,
			},
		},
	}
}

func dataSourceAwsRdsClusterRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).rdsconn

	params := &rds.DescribeDBClustersInput{
		DBClusterIdentifier: aws.String(d.Get("cluster_identifier").(string)),
	}
	log.Printf("[DEBUG] Reading RDS Cluster: %s", params)
	resp, err := conn.DescribeDBClusters(params)

	if err != nil {
		return errwrap.Wrapf("Error retrieving RDS cluster: {{err}}", err)
	}

	d.SetId(*resp.DBClusters[0].DBClusterIdentifier)

	return flattenAwsRdsClusterResource(d, meta, resp.DBClusters[0])
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_dms_replication_task.go<|end_filename|>
package aws

import (
	"fmt"
	"log"
	"strconv"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	dms "github.com/aws/aws-sdk-go/service/databasemigrationservice"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"
	"github.com/hashicorp/terraform/helper/validation"
)

func resourceAwsDmsReplicationTask() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsDmsReplicationTaskCreate,
		Read:   resourceAwsDmsReplicationTaskRead,
		Update: resourceAwsDmsReplicationTaskUpdate,
		Delete: resourceAwsDmsReplicationTaskDelete,

		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"cdc_start_time": {
				Type:     schema.TypeString,
				Optional: true,
				// Requires a Unix timestamp in seconds. Example 1484346880
			},
			"migration_type": {
				Type:     schema.TypeString,
				Required: true,
				ValidateFunc: validation.StringInSlice([]string{
					"full-load",
					"cdc",
					"full-load-and-cdc",
				}, false),
			},
			"replication_instance_arn": {
				Type:         schema.TypeString,
				Required:     true,
				ForceNew:     true,
				ValidateFunc: validateArn,
			},
			"replication_task_arn": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"replication_task_id": {
				Type:         schema.TypeString,
				Required:     true,
				ForceNew:     true,
				ValidateFunc: validateDmsReplicationTaskId,
			},
			"replication_task_settings": {
				Type:             schema.TypeString,
				Optional:         true,
				ValidateFunc:     validateJsonString,
				DiffSuppressFunc: suppressEquivalentJsonDiffs,
			},
			"source_endpoint_arn": {
				Type:         schema.TypeString,
				Required:     true,
				ForceNew:     true,
				ValidateFunc: validateArn,
			},
			"table_mappings": {
				Type:             schema.TypeString,
				Required:         true,
				ValidateFunc:     validateJsonString,
				DiffSuppressFunc: suppressEquivalentJsonDiffs,
			},
			"tags": {
				Type:     schema.TypeMap,
				Optional: true,
			},
			"target_endpoint_arn": {
				Type:         schema.TypeString,
				Required:     true,
				ForceNew:     true,
				ValidateFunc: validateArn,
			},
		},
	}
}

func resourceAwsDmsReplicationTaskCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).dmsconn

	request := &dms.CreateReplicationTaskInput{
		MigrationType:             aws.String(d.Get("migration_type").(string)),
		ReplicationInstanceArn:    aws.String(d.Get("replication_instance_arn").(string)),
		ReplicationTaskIdentifier: aws.String(d.Get("replication_task_id").(string)),
		SourceEndpointArn:         aws.String(d.Get("source_endpoint_arn").(string)),
		TableMappings:             aws.String(d.Get("table_mappings").(string)),
		Tags:                      dmsTagsFromMap(d.Get("tags").(map[string]interface{})),
		TargetEndpointArn:         aws.String(d.Get("target_endpoint_arn").(string)),
	}

	if v, ok := d.GetOk("cdc_start_time"); ok {
		seconds, err := strconv.ParseInt(v.(string), 10, 64)
		if err != nil {
			return fmt.Errorf("[ERROR] DMS create replication task. Invalid CDC Unix timestamp: %s", err)
		}
		request.CdcStartTime = aws.Time(time.Unix(seconds, 0))
	}

	if v, ok := d.GetOk("replication_task_settings"); ok {
		request.ReplicationTaskSettings = aws.String(v.(string))
	}

	log.Println("[DEBUG] DMS create replication task:", request)

	_, err := conn.CreateReplicationTask(request)
	if err != nil {
		return err
	}

	taskId := d.Get("replication_task_id").(string)
	d.SetId(taskId)

	stateConf := &resource.StateChangeConf{
		Pending:    []string{"creating"},
		Target:     []string{"ready"},
		Refresh:    resourceAwsDmsReplicationTaskStateRefreshFunc(d, meta),
		Timeout:    d.Timeout(schema.TimeoutCreate),
		MinTimeout: 10 * time.Second,
		Delay:      30 * time.Second, // Wait 30 secs before starting
	}

	// Wait, catching any errors
	_, err = stateConf.WaitForState()
	if err != nil {
		return err
	}

	return resourceAwsDmsReplicationTaskRead(d, meta)
}

func resourceAwsDmsReplicationTaskRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).dmsconn

	response, err := conn.DescribeReplicationTasks(&dms.DescribeReplicationTasksInput{
		Filters: []*dms.Filter{
			{
				Name:   aws.String("replication-task-id"),
				Values: []*string{aws.String(d.Id())}, // Must use d.Id() to work with import.
			},
		},
	})
	if err != nil {
		if dmserr, ok := err.(awserr.Error); ok && dmserr.Code() == "ResourceNotFoundFault" {
			log.Printf("[DEBUG] DMS Replication Task %q Not Found", d.Id())
			d.SetId("")
			return nil
		}
		return err
	}

	err = resourceAwsDmsReplicationTaskSetState(d, response.ReplicationTasks[0])
	if err != nil {
		return err
	}

	tagsResp, err := conn.ListTagsForResource(&dms.ListTagsForResourceInput{
		ResourceArn: aws.String(d.Get("replication_task_arn").(string)),
	})
	if err != nil {
		return err
	}
	d.Set("tags", dmsTagsToMap(tagsResp.TagList))

	return nil
}

func resourceAwsDmsReplicationTaskUpdate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).dmsconn

	request := &dms.ModifyReplicationTaskInput{
		ReplicationTaskArn: aws.String(d.Get("replication_task_arn").(string)),
	}
	hasChanges := false

	if d.HasChange("cdc_start_time") {
		seconds, err := strconv.ParseInt(d.Get("cdc_start_time").(string), 10, 64)
		if err != nil {
			return fmt.Errorf("[ERROR] DMS update replication task. Invalid CRC Unix timestamp: %s", err)
		}
		request.CdcStartTime = aws.Time(time.Unix(seconds, 0))
		hasChanges = true
	}

	if d.HasChange("migration_type") {
		request.MigrationType = aws.String(d.Get("migration_type").(string))
		hasChanges = true
	}

	if d.HasChange("replication_task_settings") {
		request.ReplicationTaskSettings = aws.String(d.Get("replication_task_settings").(string))
		hasChanges = true
	}

	if d.HasChange("table_mappings") {
		request.TableMappings = aws.String(d.Get("table_mappings").(string))
		hasChanges = true
	}

	if d.HasChange("tags") {
		err := dmsSetTags(d.Get("replication_task_arn").(string), d, meta)
		if err != nil {
			return err
		}
	}

	if hasChanges {
		log.Println("[DEBUG] DMS update replication task:", request)

		_, err := conn.ModifyReplicationTask(request)
		if err != nil {
			return err
		}

		stateConf := &resource.StateChangeConf{
			Pending:    []string{"modifying"},
			Target:     []string{"ready", "stopped", "failed"},
			Refresh:    resourceAwsDmsReplicationTaskStateRefreshFunc(d, meta),
			Timeout:    d.Timeout(schema.TimeoutCreate),
			MinTimeout: 10 * time.Second,
			Delay:      30 * time.Second, // Wait 30 secs before starting
		}

		// Wait, catching any errors
		_, err = stateConf.WaitForState()
		if err != nil {
			return err
		}

		return resourceAwsDmsReplicationTaskRead(d, meta)
	}

	return nil
}

func resourceAwsDmsReplicationTaskDelete(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).dmsconn

	request := &dms.DeleteReplicationTaskInput{
		ReplicationTaskArn: aws.String(d.Get("replication_task_arn").(string)),
	}

	log.Printf("[DEBUG] DMS delete replication task: %#v", request)

	_, err := conn.DeleteReplicationTask(request)
	if err != nil {
		if dmserr, ok := err.(awserr.Error); ok && dmserr.Code() == "ResourceNotFoundFault" {
			log.Printf("[DEBUG] DMS Replication Task %q Not Found", d.Id())
			d.SetId("")
			return nil
		}
		return err
	}

	stateConf := &resource.StateChangeConf{
		Pending:    []string{"deleting"},
		Target:     []string{},
		Refresh:    resourceAwsDmsReplicationTaskStateRefreshFunc(d, meta),
		Timeout:    d.Timeout(schema.TimeoutCreate),
		MinTimeout: 10 * time.Second,
		Delay:      30 * time.Second, // Wait 30 secs before starting
	}

	// Wait, catching any errors
	_, err = stateConf.WaitForState()
	if err != nil {
		return err
	}

	return nil
}

func resourceAwsDmsReplicationTaskSetState(d *schema.ResourceData, task *dms.ReplicationTask) error {
	d.SetId(*task.ReplicationTaskIdentifier)

	d.Set("migration_type", task.MigrationType)
	d.Set("replication_instance_arn", task.ReplicationInstanceArn)
	d.Set("replication_task_arn", task.ReplicationTaskArn)
	d.Set("replication_task_id", task.ReplicationTaskIdentifier)
	d.Set("replication_task_settings", task.ReplicationTaskSettings)
	d.Set("source_endpoint_arn", task.SourceEndpointArn)
	d.Set("table_mappings", task.TableMappings)
	d.Set("target_endpoint_arn", task.TargetEndpointArn)

	return nil
}

func resourceAwsDmsReplicationTaskStateRefreshFunc(
	d *schema.ResourceData, meta interface{}) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		conn := meta.(*AWSClient).dmsconn

		v, err := conn.DescribeReplicationTasks(&dms.DescribeReplicationTasksInput{
			Filters: []*dms.Filter{
				{
					Name:   aws.String("replication-task-id"),
					Values: []*string{aws.String(d.Id())}, // Must use d.Id() to work with import.
				},
			},
		})
		if err != nil {
			if dmserr, ok := err.(awserr.Error); ok && dmserr.Code() == "ResourceNotFoundFault" {
				return nil, "", nil
			}
			log.Printf("Error on retrieving DMS Replication Task when waiting: %s", err)
			return nil, "", err
		}

		if v == nil {
			return nil, "", nil
		}

		if v.ReplicationTasks != nil {
			log.Printf("[DEBUG] DMS Replication Task status for instance %s: %s", d.Id(), *v.ReplicationTasks[0].Status)
		}

		return v, *v.ReplicationTasks[0].Status, nil
	}
}


<|start_filename|>vendor/github.com/hashicorp/terraform/communicator/communicator_test.go<|end_filename|>
package communicator

import (
	"testing"

	"github.com/hashicorp/terraform/terraform"
)

func TestCommunicator_new(t *testing.T) {
	r := &terraform.InstanceState{
		Ephemeral: terraform.EphemeralState{
			ConnInfo: map[string]string{
				"type": "telnet",
			},
		},
	}
	if _, err := New(r); err == nil {
		t.Fatalf("expected error with telnet")
	}

	r.Ephemeral.ConnInfo["type"] = "ssh"
	if _, err := New(r); err != nil {
		t.Fatalf("err: %v", err)
	}

	r.Ephemeral.ConnInfo["type"] = "winrm"
	if _, err := New(r); err != nil {
		t.Fatalf("err: %v", err)
	}
}


<|start_filename|>vendor/github.com/zclconf/go-cty/cty/value.go<|end_filename|>
package cty

// Value represents a value of a particular type, and is the interface by
// which operations are executed on typed values.
//
// Value has two different classes of method. Operation methods stay entirely
// within the type system (methods accept and return Value instances) and
// are intended for use in implementing a language in terms of cty, while
// integration methods either enter or leave the type system, working with
// native Go values. Operation methods are guaranteed to support all of the
// expected short-circuit behavior for unknown and dynamic values, while
// integration methods may not.
//
// The philosophy for the operations API is that it's the caller's
// responsibility to ensure that the given types and values satisfy the
// specified invariants during a separate type check, so that the caller is
// able to return errors to its user from the application's own perspective.
//
// Consequently the design of these methods assumes such checks have already
// been done and panics if any invariants turn out not to be satisfied. These
// panic errors are not intended to be handled, but rather indicate a bug in
// the calling application that should be fixed with more checks prior to
// executing operations.
//
// A related consequence of this philosophy is that no automatic type
// conversions are done. If a method specifies that its argument must be
// number then it's the caller's responsibility to do that conversion before
// the call, thus allowing the application to have more constrained conversion
// rules than are offered by the built-in converter where necessary.
type Value struct {
	ty Type
	v  interface{}
}

// Type returns the type of the value.
func (val Value) Type() Type {
	return val.ty
}

// IsKnown returns true if the value is known. That is, if it is not
// the result of the unknown value constructor Unknown(...), and is not
// the result of an operation on another unknown value.
//
// Unknown values are only produced either directly or as a result of
// operating on other unknown values, and so an application that never
// introduces Unknown values can be guaranteed to never receive any either.
func (val Value) IsKnown() bool {
	return val.v != unknown
}

// IsNull returns true if the value is null. Values of any type can be
// null, but any operations on a null value will panic. No operation ever
// produces null, so an application that never introduces Null values can
// be guaranteed to never receive any either.
func (val Value) IsNull() bool {
	return val.v == nil
}

// NilVal is an invalid Value that can be used as a placeholder when returning
// with an error from a function that returns (Value, error).
//
// NilVal is *not* a valid error and so no operations may be performed on it.
// Any attempt to use it will result in a panic.
//
// This should not be confused with the idea of a Null value, as returned by
// NullVal. NilVal is a nil within the *Go* type system, and is invalid in
// the cty type system. Null values *do* exist in the cty type system.
var NilVal = Value{
	ty: Type{typeImpl: nil},
	v:  nil,
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_dx_connection.go<|end_filename|>
package aws

import (
	"fmt"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/directconnect"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsDxConnection() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsDxConnectionCreate,
		Read:   resourceAwsDxConnectionRead,
		Delete: resourceAwsDxConnectionDelete,

		Schema: map[string]*schema.Schema{
			"name": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"bandwidth": &schema.Schema{
				Type:         schema.TypeString,
				Required:     true,
				ForceNew:     true,
				ValidateFunc: validateDxConnectionBandWidth,
			},
			"location": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
		},
	}
}

func resourceAwsDxConnectionCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).dxconn

	input := &directconnect.CreateConnectionInput{
		Bandwidth:      aws.String(d.Get("bandwidth").(string)),
		ConnectionName: aws.String(d.Get("name").(string)),
		Location:       aws.String(d.Get("location").(string)),
	}
	resp, err := conn.CreateConnection(input)
	if err != nil {
		return err
	}
	d.SetId(*resp.ConnectionId)
	return resourceAwsDxConnectionRead(d, meta)
}

func resourceAwsDxConnectionRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).dxconn

	connectionId := d.Id()
	input := &directconnect.DescribeConnectionsInput{
		ConnectionId: aws.String(connectionId),
	}
	resp, err := conn.DescribeConnections(input)
	if err != nil {
		return err
	}
	if len(resp.Connections) < 1 {
		d.SetId("")
		return nil
	}
	if len(resp.Connections) != 1 {
		return fmt.Errorf("[ERROR] Number of DX Connection (%s) isn't one, got %d", connectionId, len(resp.Connections))
	}
	if d.Id() != *resp.Connections[0].ConnectionId {
		return fmt.Errorf("[ERROR] DX Connection (%s) not found", connectionId)
	}
	return nil
}

func resourceAwsDxConnectionDelete(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).dxconn

	input := &directconnect.DeleteConnectionInput{
		ConnectionId: aws.String(d.Id()),
	}
	_, err := conn.DeleteConnection(input)
	if err != nil {
		return err
	}
	deleteStateConf := &resource.StateChangeConf{
		Pending:    []string{directconnect.ConnectionStatePending, directconnect.ConnectionStateOrdering, directconnect.ConnectionStateAvailable, directconnect.ConnectionStateRequested, directconnect.ConnectionStateDeleting},
		Target:     []string{directconnect.ConnectionStateDeleted},
		Refresh:    dxConnectionRefreshStateFunc(conn, d.Id()),
		Timeout:    10 * time.Minute,
		Delay:      10 * time.Second,
		MinTimeout: 3 * time.Second,
	}
	_, err = deleteStateConf.WaitForState()
	if err != nil {
		return fmt.Errorf("Error waiting for Dx Connection (%s) to be deleted: %s", d.Id(), err)
	}
	d.SetId("")
	return nil
}

func dxConnectionRefreshStateFunc(conn *directconnect.DirectConnect, connId string) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		input := &directconnect.DescribeConnectionsInput{
			ConnectionId: aws.String(connId),
		}
		resp, err := conn.DescribeConnections(input)
		if err != nil {
			return nil, "failed", err
		}
		return resp, *resp.Connections[0].ConnectionState, nil
	}
}


<|start_filename|>vendor/github.com/hashicorp/terraform/backend/atlas/backend_test.go<|end_filename|>
package atlas

import (
	"os"
	"testing"

	"github.com/hashicorp/terraform/backend"
	"github.com/hashicorp/terraform/config"
	"github.com/hashicorp/terraform/terraform"
)

func TestImpl(t *testing.T) {
	var _ backend.Backend = new(Backend)
	var _ backend.CLI = new(Backend)
}

func TestConfigure_envAddr(t *testing.T) {
	defer os.Setenv("ATLAS_ADDRESS", os.Getenv("ATLAS_ADDRESS"))
	os.Setenv("ATLAS_ADDRESS", "http://foo.com")

	b := &Backend{}
	err := b.Configure(terraform.NewResourceConfig(config.TestRawConfig(t, map[string]interface{}{
		"name": "foo/bar",
	})))
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	if b.stateClient.Server != "http://foo.com" {
		t.Fatalf("bad: %#v", b.stateClient)
	}
}

func TestConfigure_envToken(t *testing.T) {
	defer os.Setenv("ATLAS_TOKEN", os.Getenv("ATLAS_TOKEN"))
	os.Setenv("ATLAS_TOKEN", "foo")

	b := &Backend{}
	err := b.Configure(terraform.NewResourceConfig(config.TestRawConfig(t, map[string]interface{}{
		"name": "foo/bar",
	})))
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	if b.stateClient.AccessToken != "foo" {
		t.Fatalf("bad: %#v", b.stateClient)
	}
}


<|start_filename|>vendor/github.com/mitchellh/packer/builder/amazon/common/step_modify_ebs_instance.go<|end_filename|>
package common

import (
	"context"
	"fmt"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/hashicorp/packer/helper/multistep"
	"github.com/hashicorp/packer/packer"
)

type StepModifyEBSBackedInstance struct {
	EnableAMIENASupport      bool
	EnableAMISriovNetSupport bool
}

func (s *StepModifyEBSBackedInstance) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
	ec2conn := state.Get("ec2").(*ec2.EC2)
	instance := state.Get("instance").(*ec2.Instance)
	ui := state.Get("ui").(packer.Ui)

	// Set SriovNetSupport to "simple". See http://goo.gl/icuXh5
	// As of February 2017, this applies to C3, C4, D2, I2, R3, and M4 (excluding m4.16xlarge)
	if s.EnableAMISriovNetSupport {
		ui.Say("Enabling Enhanced Networking (SR-IOV)...")
		simple := "simple"
		_, err := ec2conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
			InstanceId:      instance.InstanceId,
			SriovNetSupport: &ec2.AttributeValue{Value: &simple},
		})
		if err != nil {
			err := fmt.Errorf("Error enabling Enhanced Networking (SR-IOV) on %s: %s", *instance.InstanceId, err)
			state.Put("error", err)
			ui.Error(err.Error())
			return multistep.ActionHalt
		}
	}

	// Set EnaSupport to true.
	// As of February 2017, this applies to C5, I3, P2, R4, X1, and m4.16xlarge
	if s.EnableAMIENASupport {
		ui.Say("Enabling Enhanced Networking (ENA)...")
		_, err := ec2conn.ModifyInstanceAttribute(&ec2.ModifyInstanceAttributeInput{
			InstanceId: instance.InstanceId,
			EnaSupport: &ec2.AttributeBooleanValue{Value: aws.Bool(true)},
		})
		if err != nil {
			err := fmt.Errorf("Error enabling Enhanced Networking (ENA) on %s: %s", *instance.InstanceId, err)
			state.Put("error", err)
			ui.Error(err.Error())
			return multistep.ActionHalt
		}
	}

	return multistep.ActionContinue
}

func (s *StepModifyEBSBackedInstance) Cleanup(state multistep.StateBag) {
	// No cleanup...
}


<|start_filename|>vendor/github.com/hashicorp/terraform/command/plugins_test.go<|end_filename|>
package command

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"reflect"
	"testing"

	"github.com/hashicorp/terraform/plugin/discovery"
	"github.com/hashicorp/terraform/terraform"
)

func TestMultiVersionProviderResolver(t *testing.T) {
	available := make(discovery.PluginMetaSet)
	available.Add(discovery.PluginMeta{
		Name:    "plugin",
		Version: "1.0.0",
		Path:    "test-fixtures/empty-file",
	})

	resolver := &multiVersionProviderResolver{
		Internal: map[string]terraform.ResourceProviderFactory{
			"internal": func() (terraform.ResourceProvider, error) {
				return &terraform.MockResourceProvider{
					ResourcesReturn: []terraform.ResourceType{
						{
							Name: "internal_foo",
						},
					},
				}, nil
			},
		},
		Available: available,
	}

	t.Run("plugin matches", func(t *testing.T) {
		reqd := discovery.PluginRequirements{
			"plugin": &discovery.PluginConstraints{
				Versions: discovery.ConstraintStr("1.0.0").MustParse(),
			},
		}
		got, err := resolver.ResolveProviders(reqd)
		if err != nil {
			t.Fatalf("unexpected error: %s", err)
		}
		if ct := len(got); ct != 1 {
			t.Errorf("wrong number of results %d; want 1", ct)
		}
		if _, exists := got["plugin"]; !exists {
			t.Errorf("provider \"plugin\" not in result")
		}
	})
	t.Run("plugin doesn't match", func(t *testing.T) {
		reqd := discovery.PluginRequirements{
			"plugin": &discovery.PluginConstraints{
				Versions: discovery.ConstraintStr("2.0.0").MustParse(),
			},
		}
		_, err := resolver.ResolveProviders(reqd)
		if err == nil {
			t.Errorf("resolved successfully, but want error")
		}
	})
	t.Run("internal matches", func(t *testing.T) {
		reqd := discovery.PluginRequirements{
			"internal": &discovery.PluginConstraints{
				Versions: discovery.AllVersions,
			},
		}
		got, err := resolver.ResolveProviders(reqd)
		if err != nil {
			t.Fatalf("unexpected error: %s", err)
		}
		if ct := len(got); ct != 1 {
			t.Errorf("wrong number of results %d; want 1", ct)
		}
		if _, exists := got["internal"]; !exists {
			t.Errorf("provider \"internal\" not in result")
		}
	})
	t.Run("internal with version constraint", func(t *testing.T) {
		// Version constraints are not permitted for internal providers
		reqd := discovery.PluginRequirements{
			"internal": &discovery.PluginConstraints{
				Versions: discovery.ConstraintStr("2.0.0").MustParse(),
			},
		}
		_, err := resolver.ResolveProviders(reqd)
		if err == nil {
			t.Errorf("resolved successfully, but want error")
		}
	})
}

func TestPluginPath(t *testing.T) {
	td, err := ioutil.TempDir("", "tf")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(td)
	defer testChdir(t, td)()

	pluginPath := []string{"a", "b", "c"}

	m := Meta{}
	if err := m.storePluginPath(pluginPath); err != nil {
		t.Fatal(err)
	}

	restoredPath, err := m.loadPluginPath()
	if err != nil {
		t.Fatal(err)
	}

	if !reflect.DeepEqual(pluginPath, restoredPath) {
		t.Fatalf("expected plugin path %#v, got %#v", pluginPath, restoredPath)
	}
}

func TestInternalProviders(t *testing.T) {
	m := Meta{}
	internal := m.internalProviders()
	tfProvider, err := internal["terraform"]()
	if err != nil {
		t.Fatal(err)
	}

	dataSources := tfProvider.DataSources()
	found := false
	for _, ds := range dataSources {
		if ds.Name == "terraform_remote_state" {
			found = true
		}
	}
	if !found {
		t.Errorf("didn't find terraform_remote_state in internal \"terraform\" provider")
	}
}

// mockProviderInstaller is a discovery.PluginInstaller implementation that
// is a mock for discovery.ProviderInstaller.
type mockProviderInstaller struct {
	// A map of provider names to available versions.
	// The tests expect the versions to be in order from newest to oldest.
	Providers map[string][]string

	Dir               string
	PurgeUnusedCalled bool
}

func (i *mockProviderInstaller) FileName(provider, version string) string {
	return fmt.Sprintf("terraform-provider-%s_v%s_x4", provider, version)
}

func (i *mockProviderInstaller) Get(provider string, req discovery.Constraints) (discovery.PluginMeta, error) {
	noMeta := discovery.PluginMeta{}
	versions := i.Providers[provider]
	if len(versions) == 0 {
		return noMeta, fmt.Errorf("provider %q not found", provider)
	}

	err := os.MkdirAll(i.Dir, 0755)
	if err != nil {
		return noMeta, fmt.Errorf("error creating plugins directory: %s", err)
	}

	for _, v := range versions {
		version, err := discovery.VersionStr(v).Parse()
		if err != nil {
			panic(err)
		}

		if req.Allows(version) {
			// provider filename
			name := i.FileName(provider, v)
			path := filepath.Join(i.Dir, name)
			f, err := os.Create(path)
			if err != nil {
				return noMeta, fmt.Errorf("error fetching provider: %s", err)
			}
			f.Close()
			return discovery.PluginMeta{
				Name:    provider,
				Version: discovery.VersionStr(v),
				Path:    path,
			}, nil
		}
	}

	return noMeta, fmt.Errorf("no suitable version for provider %q found with constraints %s", provider, req)
}

func (i *mockProviderInstaller) PurgeUnused(map[string]discovery.PluginMeta) (discovery.PluginMetaSet, error) {
	i.PurgeUnusedCalled = true
	ret := make(discovery.PluginMetaSet)
	ret.Add(discovery.PluginMeta{
		Name:    "test",
		Version: "0.0.0",
		Path:    "mock-test",
	})
	return ret, nil
}

type callbackPluginInstaller func(provider string, req discovery.Constraints) (discovery.PluginMeta, error)

func (cb callbackPluginInstaller) Get(provider string, req discovery.Constraints) (discovery.PluginMeta, error) {
	return cb(provider, req)
}

func (cb callbackPluginInstaller) PurgeUnused(map[string]discovery.PluginMeta) (discovery.PluginMetaSet, error) {
	// does nothing
	return make(discovery.PluginMetaSet), nil
}


<|start_filename|>vendor/github.com/mitchellh/packer/vendor/github.com/joyent/triton-go/compute/services.go<|end_filename|>
//
// Copyright (c) 2018, Joyent, Inc. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

package compute

import (
	"context"
	"encoding/json"
	"net/http"
	"path"
	"sort"

	"github.com/joyent/triton-go/client"
	"github.com/pkg/errors"
)

type ServicesClient struct {
	client *client.Client
}

type Service struct {
	Name     string
	Endpoint string
}

type ListServicesInput struct{}

func (c *ServicesClient) List(ctx context.Context, _ *ListServicesInput) ([]*Service, error) {
	fullPath := path.Join("/", c.client.AccountName, "services")
	reqInputs := client.RequestInput{
		Method: http.MethodGet,
		Path:   fullPath,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to list services")
	}

	var intermediate map[string]string
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&intermediate); err != nil {
		return nil, errors.Wrap(err, "unable to decode list services response")
	}

	keys := make([]string, len(intermediate))
	i := 0
	for k := range intermediate {
		keys[i] = k
		i++
	}
	sort.Strings(keys)

	result := make([]*Service, len(intermediate))
	i = 0
	for _, key := range keys {
		result[i] = &Service{
			Name:     key,
			Endpoint: intermediate[key],
		}
		i++
	}

	return result, nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/arn.go<|end_filename|>
package aws

import (
	"github.com/aws/aws-sdk-go/aws/arn"
	"github.com/aws/aws-sdk-go/service/iam"
)

func arnString(partition, region, service, accountId, resource string) string {
	return arn.ARN{
		Partition: partition,
		Region:    region,
		Service:   service,
		AccountID: accountId,
		Resource:  resource,
	}.String()
}

// See http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-iam
func iamArnString(partition, accountId, resource string) string {
	return arnString(
		partition,
		"",
		iam.ServiceName,
		accountId,
		resource)
}


<|start_filename|>vendor/github.com/mitchellh/packer/packer/multi_error.go<|end_filename|>
package packer

import (
	"fmt"
	"strings"
)

// MultiError is an error type to track multiple errors. This is used to
// accumulate errors in cases such as configuration parsing, and returning
// them as a single error.
type MultiError struct {
	Errors []error
}

func (e *MultiError) Error() string {
	points := make([]string, len(e.Errors))
	for i, err := range e.Errors {
		points[i] = fmt.Sprintf("* %s", err)
	}

	return fmt.Sprintf(
		"%d error(s) occurred:\n\n%s",
		len(e.Errors), strings.Join(points, "\n"))
}

// MultiErrorAppend is a helper function that will append more errors
// onto a MultiError in order to create a larger multi-error. If the
// original error is not a MultiError, it will be turned into one.
func MultiErrorAppend(err error, errs ...error) *MultiError {
	if err == nil {
		err = new(MultiError)
	}

	switch err := err.(type) {
	case *MultiError:
		if err == nil {
			err = new(MultiError)
		}

		err.Errors = append(err.Errors, errs...)
		return err
	default:
		newErrs := make([]error, len(errs)+1)
		newErrs[0] = err
		copy(newErrs[1:], errs)
		return &MultiError{
			Errors: newErrs,
		}
	}
}


<|start_filename|>vendor/github.com/hashicorp/terraform/tools/terraform-bundle/package.go<|end_filename|>
package main

import (
	"archive/zip"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
	"time"

	"flag"

	"io"

	getter "github.com/hashicorp/go-getter"
	"github.com/hashicorp/terraform/plugin"
	"github.com/hashicorp/terraform/plugin/discovery"
	"github.com/mitchellh/cli"
)

type PackageCommand struct {
	ui cli.Ui
}

func (c *PackageCommand) Run(args []string) int {
	flags := flag.NewFlagSet("package", flag.ExitOnError)
	osPtr := flags.String("os", "", "Target operating system")
	archPtr := flags.String("arch", "", "Target CPU architecture")
	err := flags.Parse(args)
	if err != nil {
		c.ui.Error(err.Error())
		return 1
	}

	osName := runtime.GOOS
	archName := runtime.GOARCH
	if *osPtr != "" {
		osName = *osPtr
	}
	if *archPtr != "" {
		archName = *archPtr
	}

	if flags.NArg() != 1 {
		c.ui.Error("Configuration filename is required")
		return 1
	}
	configFn := flags.Arg(0)

	config, err := LoadConfigFile(configFn)
	if err != nil {
		c.ui.Error(fmt.Sprintf("Failed to read config: %s", err))
		return 1
	}

	if discovery.ConstraintStr("< 0.10.0-beta1").MustParse().Allows(config.Terraform.Version.MustParse()) {
		c.ui.Error("Bundles can be created only for Terraform 0.10 or newer")
		return 1
	}

	workDir, err := ioutil.TempDir("", "terraform-bundle")
	if err != nil {
		c.ui.Error(fmt.Sprintf("Could not create temporary dir: %s", err))
		return 1
	}
	defer os.RemoveAll(workDir)

	c.ui.Info(fmt.Sprintf("Fetching Terraform %s core package...", config.Terraform.Version))

	coreZipURL := c.coreURL(config.Terraform.Version, osName, archName)
	err = getter.Get(workDir, coreZipURL)
	if err != nil {
		c.ui.Error(fmt.Sprintf("Failed to fetch core package from %s: %s", coreZipURL, err))
	}

	installer := &discovery.ProviderInstaller{
		Dir: workDir,

		// FIXME: This is incorrect because it uses the protocol version of
		// this tool, rather than of the Terraform binary we just downloaded.
		// But we can't get this information from a Terraform binary, so
		// we'll just ignore this for now as we only have one protocol version
		// in play anyway. If a new protocol version shows up later we will
		// probably deal with this by just matching version ranges and
		// hard-coding the knowledge of which Terraform version uses which
		// protocol version.
		PluginProtocolVersion: plugin.Handshake.ProtocolVersion,

		OS:   osName,
		Arch: archName,
		Ui:   c.ui,
	}

	if len(config.Providers) > 0 {
		c.ui.Output(fmt.Sprintf("Checking for available provider plugins on %s...",
			discovery.GetReleaseHost()))
	}

	for name, constraints := range config.Providers {
		for _, constraint := range constraints {
			c.ui.Output(fmt.Sprintf("- Resolving %q provider (%s)...",
				name, constraint))
			_, err := installer.Get(name, constraint.MustParse())
			if err != nil {
				c.ui.Error(fmt.Sprintf("- Failed to resolve %s provider %s: %s", name, constraint, err))
				return 1
			}
		}
	}

	files, err := ioutil.ReadDir(workDir)
	if err != nil {
		c.ui.Error(fmt.Sprintf("Failed to read work directory %s: %s", workDir, err))
		return 1
	}

	// If we get this far then our workDir now contains the union of the
	// contents of all the zip files we downloaded above. We can now create
	// our output file.
	outFn := c.bundleFilename(config.Terraform.Version, time.Now(), osName, archName)
	c.ui.Info(fmt.Sprintf("Creating %s ...", outFn))
	outF, err := os.OpenFile(outFn, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, os.ModePerm)
	if err != nil {
		c.ui.Error(fmt.Sprintf("Failed to create %s: %s", outFn, err))
		return 1
	}
	outZ := zip.NewWriter(outF)
	defer func() {
		err := outZ.Close()
		if err != nil {
			c.ui.Error(fmt.Sprintf("Failed to close %s: %s", outFn, err))
			os.Exit(1)
		}
		err = outF.Close()
		if err != nil {
			c.ui.Error(fmt.Sprintf("Failed to close %s: %s", outFn, err))
			os.Exit(1)
		}
	}()

	for _, file := range files {
		if file.IsDir() {
			// should never happen unless something tampers with our tmpdir
			continue
		}

		fn := filepath.Join(workDir, file.Name())
		r, err := os.Open(fn)
		if err != nil {
			c.ui.Error(fmt.Sprintf("Failed to open %s: %s", fn, err))
			return 1
		}
		hdr, err := zip.FileInfoHeader(file)
		if err != nil {
			c.ui.Error(fmt.Sprintf("Failed to add zip entry for %s: %s", fn, err))
			return 1
		}
		w, err := outZ.CreateHeader(hdr)
		if err != nil {
			c.ui.Error(fmt.Sprintf("Failed to add zip entry for %s: %s", fn, err))
			return 1
		}
		_, err = io.Copy(w, r)
		if err != nil {
			c.ui.Error(fmt.Sprintf("Failed to write %s to bundle: %s", fn, err))
			return 1
		}
	}

	c.ui.Info("All done!")

	return 0
}

func (c *PackageCommand) bundleFilename(version discovery.VersionStr, time time.Time, osName, archName string) string {
	time = time.UTC()
	return fmt.Sprintf(
		"terraform_%s-bundle%04d%02d%02d%02d_%s_%s.zip",
		version,
		time.Year(), time.Month(), time.Day(), time.Hour(),
		osName, archName,
	)
}

func (c *PackageCommand) coreURL(version discovery.VersionStr, osName, archName string) string {
	return fmt.Sprintf(
		"%s/terraform/%s/terraform_%s_%s_%s.zip",
		discovery.GetReleaseHost(), version, version, osName, archName,
	)
}

func (c *PackageCommand) Synopsis() string {
	return "Produces a bundle archive"
}

func (c *PackageCommand) Help() string {
	return `Usage: terraform-bundle package [options] <config-file>

Uses the given bundle configuration file to produce a zip file in the
current working directory containing a Terraform binary along with zero or
more provider plugin binaries.

Options:
  -os=name    Target operating system the archive will be built for. Defaults
              to that of the system where the command is being run.

  -arch=name  Target CPU architecture the archive will be built for. Defaults
              to that of the system where the command is being run.

The resulting zip file can be used to more easily install Terraform and
a fixed set of providers together on a server, so that Terraform's provider
auto-installation mechanism can be avoided.

To build an archive for Terraform Enterprise, use:
  -os=linux -arch=amd64

Note that the given configuration file is a format specific to this command,
not a normal Terraform configuration file. The file format looks like this:

  terraform {
    # Version of Terraform to include in the bundle. An exact version number
	# is required.
    version = "0.10.0"
  }

  # Define which provider plugins are to be included
  providers {
    # Include the newest "aws" provider version in the 1.0 series.
    aws = ["~> 1.0"]

    # Include both the newest 1.0 and 2.0 versions of the "google" provider.
    # Each item in these lists allows a distinct version to be added. If the
	# two expressions match different versions then _both_ are included in
	# the bundle archive.
    google = ["~> 1.0", "~> 2.0"]
  }

`
}


<|start_filename|>vendor/github.com/mitchellh/packer/packer/artifact_mock.go<|end_filename|>
package packer

// MockArtifact is an implementation of Artifact that can be used for tests.
type MockArtifact struct {
	BuilderIdValue string
	FilesValue     []string
	IdValue        string
	StateValues    map[string]interface{}
	DestroyCalled  bool
}

func (a *MockArtifact) BuilderId() string {
	if a.BuilderIdValue == "" {
		return "bid"
	}

	return a.BuilderIdValue
}

func (a *MockArtifact) Files() []string {
	if a.FilesValue == nil {
		return []string{"a", "b"}
	}

	return a.FilesValue
}

func (a *MockArtifact) Id() string {
	id := a.IdValue
	if id == "" {
		id = "id"
	}

	return id
}

func (*MockArtifact) String() string {
	return "string"
}

func (a *MockArtifact) State(name string) interface{} {
	value, _ := a.StateValues[name]
	return value
}

func (a *MockArtifact) Destroy() error {
	a.DestroyCalled = true
	return nil
}


<|start_filename|>vendor/github.com/zclconf/go-cty/cty/msgpack/roundtrip_test.go<|end_filename|>
package msgpack

import (
	"fmt"
	"math/big"
	"testing"

	"github.com/zclconf/go-cty/cty"
)

func TestRoundTrip(t *testing.T) {
	bigNumber := &big.Float{}
	bigNumber.Parse("9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", 10)

	tests := []struct {
		Value cty.Value
		Type  cty.Type
	}{

		{
			cty.StringVal("hello"),
			cty.String,
		},
		{
			cty.StringVal(""),
			cty.String,
		},
		{
			cty.NullVal(cty.String),
			cty.String,
		},
		{
			cty.UnknownVal(cty.String),
			cty.String,
		},

		{
			cty.True,
			cty.Bool,
		},
		{
			cty.False,
			cty.Bool,
		},
		{
			cty.NullVal(cty.Bool),
			cty.Bool,
		},
		{
			cty.UnknownVal(cty.Bool),
			cty.Bool,
		},

		{
			cty.NumberIntVal(1),
			cty.Number,
		},
		{
			cty.NumberFloatVal(1.5),
			cty.Number,
		},
		{
			cty.NumberVal(bigNumber),
			cty.Number,
		},
		{
			cty.PositiveInfinity,
			cty.Number,
		},
		{
			cty.NegativeInfinity,
			cty.Number,
		},

		{
			cty.ListVal([]cty.Value{
				cty.StringVal("hello"),
			}),
			cty.List(cty.String),
		},
		{
			cty.ListVal([]cty.Value{
				cty.UnknownVal(cty.String),
			}),
			cty.List(cty.String),
		},
		{
			cty.ListVal([]cty.Value{
				cty.NullVal(cty.String),
			}),
			cty.List(cty.String),
		},
		{
			cty.NullVal(cty.List(cty.String)),
			cty.List(cty.String),
		},
		{
			cty.ListValEmpty(cty.String),
			cty.List(cty.String),
		},

		{
			cty.SetVal([]cty.Value{
				cty.StringVal("hello"),
			}),
			cty.Set(cty.String),
		},
		{
			cty.SetVal([]cty.Value{
				cty.UnknownVal(cty.String),
			}),
			cty.Set(cty.String),
		},
		{
			cty.SetVal([]cty.Value{
				cty.NullVal(cty.String),
			}),
			cty.Set(cty.String),
		},
		{
			cty.SetValEmpty(cty.String),
			cty.Set(cty.String),
		},

		{
			cty.MapVal(map[string]cty.Value{
				"greeting": cty.StringVal("hello"),
			}),
			cty.Map(cty.String),
		},
		{
			cty.MapVal(map[string]cty.Value{
				"greeting": cty.UnknownVal(cty.String),
			}),
			cty.Map(cty.String),
		},
		{
			cty.MapVal(map[string]cty.Value{
				"greeting": cty.NullVal(cty.String),
			}),
			cty.Map(cty.String),
		},
		{
			cty.MapValEmpty(cty.String),
			cty.Map(cty.String),
		},

		{
			cty.TupleVal([]cty.Value{
				cty.StringVal("hello"),
			}),
			cty.Tuple([]cty.Type{cty.String}),
		},
		{
			cty.TupleVal([]cty.Value{
				cty.UnknownVal(cty.String),
			}),
			cty.Tuple([]cty.Type{cty.String}),
		},
		{
			cty.TupleVal([]cty.Value{
				cty.NullVal(cty.String),
			}),
			cty.Tuple([]cty.Type{cty.String}),
		},
		{
			cty.EmptyTupleVal,
			cty.EmptyTuple,
		},

		{
			cty.ObjectVal(map[string]cty.Value{
				"greeting": cty.StringVal("hello"),
			}),
			cty.Object(map[string]cty.Type{
				"greeting": cty.String,
			}),
		},
		{
			cty.ObjectVal(map[string]cty.Value{
				"greeting": cty.UnknownVal(cty.String),
			}),
			cty.Object(map[string]cty.Type{
				"greeting": cty.String,
			}),
		},
		{
			cty.ObjectVal(map[string]cty.Value{
				"greeting": cty.NullVal(cty.String),
			}),
			cty.Object(map[string]cty.Type{
				"greeting": cty.String,
			}),
		},
		{
			cty.EmptyObjectVal,
			cty.EmptyObject,
		},

		{
			cty.NullVal(cty.String),
			cty.DynamicPseudoType,
		},
		{
			cty.DynamicVal,
			cty.DynamicPseudoType,
		},
		{
			cty.ListVal([]cty.Value{
				cty.StringVal("hello"),
			}),
			cty.List(cty.DynamicPseudoType),
		},
		{
			cty.ListVal([]cty.Value{
				cty.NullVal(cty.String),
			}),
			cty.List(cty.DynamicPseudoType),
		},
		{
			cty.ListVal([]cty.Value{
				cty.DynamicVal,
			}),
			cty.List(cty.DynamicPseudoType),
		},
	}

	for _, test := range tests {
		t.Run(fmt.Sprintf("%#v as %#v", test.Value, test.Type), func(t *testing.T) {
			b, err := Marshal(test.Value, test.Type)
			if err != nil {
				t.Fatal(err)
			}

			t.Logf("encoded as %x", b)

			got, err := Unmarshal(b, test.Type)
			if err != nil {
				t.Fatal(err)
			}

			if !got.RawEquals(test.Value) {
				t.Errorf(
					"value did not round-trip\ninput:  %#v\nresult: %#v",
					test.Value, got,
				)
			}
		})
	}
}


<|start_filename|>vendor/github.com/mitchellh/packer/common/step_provision.go<|end_filename|>
package common

import (
	"context"
	"log"
	"time"

	"github.com/hashicorp/packer/helper/multistep"
	"github.com/hashicorp/packer/packer"
)

// StepProvision runs the provisioners.
//
// Uses:
//   communicator packer.Communicator
//   hook         packer.Hook
//   ui           packer.Ui
//
// Produces:
//   <nothing>
type StepProvision struct {
	Comm packer.Communicator
}

func (s *StepProvision) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
	comm := s.Comm
	if comm == nil {
		raw, ok := state.Get("communicator").(packer.Communicator)
		if ok {
			comm = raw.(packer.Communicator)
		}
	}
	hook := state.Get("hook").(packer.Hook)
	ui := state.Get("ui").(packer.Ui)

	// Run the provisioner in a goroutine so we can continually check
	// for cancellations...
	log.Println("Running the provision hook")
	errCh := make(chan error, 1)
	go func() {
		errCh <- hook.Run(packer.HookProvision, ui, comm, nil)
	}()

	for {
		select {
		case err := <-errCh:
			if err != nil {
				state.Put("error", err)
				return multistep.ActionHalt
			}

			return multistep.ActionContinue
		case <-time.After(1 * time.Second):
			if _, ok := state.GetOk(multistep.StateCancelled); ok {
				log.Println("Cancelling provisioning due to interrupt...")
				hook.Cancel()
				return multistep.ActionHalt
			}
		}
	}
}

func (*StepProvision) Cleanup(multistep.StateBag) {}


<|start_filename|>vendor/github.com/coreos/ignition/config/validate/validate.go<|end_filename|>
// Copyright 2015 CoreOS, 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.

package validate

import (
	"fmt"
	"io"
	"reflect"
	"strings"

	"github.com/coreos/ignition/config/validate/report"
)

type validator interface {
	Validate() report.Report
}

// AstNode abstracts the differences between yaml and json nodes, providing a
// common interface
type AstNode interface {
	// ValueLineCol returns the line, column, and highlight string of the value of
	// this node in the source.
	ValueLineCol(source io.ReadSeeker) (int, int, string)

	// KeyLineCol returns the line, column, and highlight string of the key for the
	// value of this node in the source.
	KeyLineCol(source io.ReadSeeker) (int, int, string)

	// LiteralValue returns the value of this node.
	LiteralValue() interface{}

	// SliceChild returns the child node at the index specified. If this node is not
	// a slice node, an empty AstNode and false is returned.
	SliceChild(index int) (AstNode, bool)

	// KeyValueMap returns a map of keys and values. If this node is not a mapping
	// node, nil and false are returned.
	KeyValueMap() (map[string]AstNode, bool)

	// Tag returns the struct tag used in the config structure used to unmarshal.
	Tag() string
}

// Validate walks down a struct tree calling Validate on every node that implements it, building
// A report of all the errors, warnings, info, and deprecations it encounters. If checkUnusedKeys
// is true, Validate will generate warnings for unused keys in the ast, otherwise it will not.
func Validate(vObj reflect.Value, ast AstNode, source io.ReadSeeker, checkUnusedKeys bool) (r report.Report) {
	if !vObj.IsValid() {
		return
	}

	line, col, highlight := 0, 0, ""
	if ast != nil {
		line, col, highlight = ast.ValueLineCol(source)
	}

	// See if we A) can call Validate on vObj, and B) should call Validate. Validate should NOT be called
	// when vObj is nil, as it will panic or when vObj is a pointer to a value with Validate implemented with a
	// value receiver. This is to prevent Validate being called twice, as otherwise it would be called on the
	// pointer version (due to go's automatic deferencing) and once when the pointer is deferenced below. The only
	// time Validate should be called on a pointer is when the function is implemented with a pointer reciever.
	if obj, ok := vObj.Interface().(validator); ok &&
		((vObj.Kind() != reflect.Ptr) ||
			(!vObj.IsNil() && !vObj.Elem().Type().Implements(reflect.TypeOf((*validator)(nil)).Elem()))) {
		sub_r := obj.Validate()
		sub_r.AddPosition(line, col, highlight)
		r.Merge(sub_r)

		// Dont recurse on invalid inner nodes, it mostly leads to bogus messages
		if sub_r.IsFatal() {
			return
		}
	}

	switch vObj.Kind() {
	case reflect.Ptr:
		sub_report := Validate(vObj.Elem(), ast, source, checkUnusedKeys)
		sub_report.AddPosition(line, col, "")
		r.Merge(sub_report)
	case reflect.Struct:
		sub_report := validateStruct(vObj, ast, source, checkUnusedKeys)
		sub_report.AddPosition(line, col, "")
		r.Merge(sub_report)
	case reflect.Slice:
		for i := 0; i < vObj.Len(); i++ {
			sub_node := ast
			if ast != nil {
				if n, ok := ast.SliceChild(i); ok {
					sub_node = n
				}
			}
			sub_report := Validate(vObj.Index(i), sub_node, source, checkUnusedKeys)
			sub_report.AddPosition(line, col, "")
			r.Merge(sub_report)
		}
	}
	return
}

func ValidateWithoutSource(cfg reflect.Value) (report report.Report) {
	return Validate(cfg, nil, nil, false)
}

type field struct {
	Type  reflect.StructField
	Value reflect.Value
}

// getFields returns a field of all the fields in the struct, including the fields of
// embedded structs and structs inside interface{}'s
func getFields(vObj reflect.Value) []field {
	if vObj.Kind() != reflect.Struct {
		return nil
	}
	ret := []field{}
	for i := 0; i < vObj.Type().NumField(); i++ {
		if vObj.Type().Field(i).Anonymous {
			// in the case of an embedded type that is an alias to interface, extract the
			// real type contained by the interface
			realObj := reflect.ValueOf(vObj.Field(i).Interface())
			ret = append(ret, getFields(realObj)...)
		} else {
			ret = append(ret, field{Type: vObj.Type().Field(i), Value: vObj.Field(i)})
		}
	}
	return ret
}

func validateStruct(vObj reflect.Value, ast AstNode, source io.ReadSeeker, checkUnusedKeys bool) report.Report {
	r := report.Report{}

	// isFromObject will be true if this struct was unmarshalled from a JSON object.
	keys, isFromObject := map[string]AstNode{}, false
	if ast != nil {
		keys, isFromObject = ast.KeyValueMap()
	}

	// Maintain a set of key's that have been used.
	usedKeys := map[string]struct{}{}

	// Maintain a list of all the tags in the struct for fuzzy matching later.
	tags := []string{}

	for _, f := range getFields(vObj) {
		// Default to nil AstNode if the field's corrosponding node cannot be found.
		var sub_node AstNode
		// Default to passing a nil source if the field's corrosponding node cannot be found.
		// This ensures the line numbers reported from all sub-structs are 0 and will be changed by AddPosition
		var src io.ReadSeeker

		// Try to determine the json.Node that corrosponds with the struct field
		if isFromObject {
			tag := strings.SplitN(f.Type.Tag.Get(ast.Tag()), ",", 2)[0]
			// Save the tag so we have a list of all the tags in the struct
			tags = append(tags, tag)
			// mark that this key was used
			usedKeys[tag] = struct{}{}

			if sub, ok := keys[tag]; ok {
				// Found it
				sub_node = sub
				src = source
			}
		}

		// Default to deepest node if the node's type isn't an object,
		// such as when a json string actually unmarshal to structs (like with version)
		line, col := 0, 0
		if ast != nil {
			line, col, _ = ast.ValueLineCol(src)
		}

		// If there's a Validate<Name> func for the given field, call it
		funct := vObj.MethodByName("Validate" + f.Type.Name)
		if funct.IsValid() {
			res := funct.Call(nil)
			sub_report := res[0].Interface().(report.Report)
			sub_report.AddPosition(line, col, "")
			r.Merge(sub_report)
		}

		sub_report := Validate(f.Value, sub_node, src, checkUnusedKeys)
		sub_report.AddPosition(line, col, "")
		r.Merge(sub_report)
	}
	if !isFromObject || !checkUnusedKeys {
		// If this struct was not unmarshalled from a JSON object, there cannot be unused keys.
		return r
	}

	for k, v := range keys {
		if _, hasKey := usedKeys[k]; hasKey {
			continue
		}
		line, col, highlight := v.KeyLineCol(source)
		typo := similar(k, tags)

		r.Add(report.Entry{
			Kind:      report.EntryWarning,
			Message:   fmt.Sprintf("Config has unrecognized key: %s", k),
			Line:      line,
			Column:    col,
			Highlight: highlight,
		})

		if typo != "" {
			r.Add(report.Entry{
				Kind:      report.EntryInfo,
				Message:   fmt.Sprintf("Did you mean %s instead of %s", typo, k),
				Line:      line,
				Column:    col,
				Highlight: highlight,
			})
		}
	}

	return r
}

// similar returns a string in candidates that is similar to str. Currently it just does case
// insensitive comparison, but it should be updated to use levenstein distances to catch typos
func similar(str string, candidates []string) string {
	for _, candidate := range candidates {
		if strings.EqualFold(str, candidate) {
			return candidate
		}
	}
	return ""
}


<|start_filename|>vendor/github.com/posener/complete/complete.go<|end_filename|>
// Package complete provides a tool for bash writing bash completion in go.
//
// Writing bash completion scripts is a hard work. This package provides an easy way
// to create bash completion scripts for any command, and also an easy way to install/uninstall
// the completion of the command.
package complete

import (
	"flag"
	"fmt"
	"os"
	"strings"

	"github.com/posener/complete/cmd"
)

const (
	envComplete = "COMP_LINE"
	envDebug    = "COMP_DEBUG"
)

// Complete structs define completion for a command with CLI options
type Complete struct {
	Command Command
	cmd.CLI
}

// New creates a new complete command.
// name is the name of command we want to auto complete.
// IMPORTANT: it must be the same name - if the auto complete
// completes the 'go' command, name must be equal to "go".
// command is the struct of the command completion.
func New(name string, command Command) *Complete {
	return &Complete{
		Command: command,
		CLI:     cmd.CLI{Name: name},
	}
}

// Run runs the completion and add installation flags beforehand.
// The flags are added to the main flag CommandLine variable.
func (c *Complete) Run() bool {
	c.AddFlags(nil)
	flag.Parse()
	return c.Complete()
}

// Complete a command from completion line in environment variable,
// and print out the complete options.
// returns success if the completion ran or if the cli matched
// any of the given flags, false otherwise
// For installation: it assumes that flags were added and parsed before
// it was called.
func (c *Complete) Complete() bool {
	line, ok := getLine()
	if !ok {
		// make sure flags parsed,
		// in case they were not added in the main program
		return c.CLI.Run()
	}
	Log("Completing line: %s", line)

	a := newArgs(line)

	options := c.Command.Predict(a)

	Log("Completion: %s", options)
	output(options)
	return true
}

func getLine() ([]string, bool) {
	line := os.Getenv(envComplete)
	if line == "" {
		return nil, false
	}
	return strings.Split(line, " "), true
}

func output(options []string) {
	Log("")
	// stdout of program defines the complete options
	for _, option := range options {
		fmt.Println(option)
	}
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/peeker.go<|end_filename|>
package hclsyntax

import (
	"github.com/hashicorp/hcl2/hcl"
)

type peeker struct {
	Tokens    Tokens
	NextIndex int

	IncludeComments      bool
	IncludeNewlinesStack []bool
}

func newPeeker(tokens Tokens, includeComments bool) *peeker {
	return &peeker{
		Tokens:          tokens,
		IncludeComments: includeComments,

		IncludeNewlinesStack: []bool{true},
	}
}

func (p *peeker) Peek() Token {
	ret, _ := p.nextToken()
	return ret
}

func (p *peeker) Read() Token {
	ret, nextIdx := p.nextToken()
	p.NextIndex = nextIdx
	return ret
}

func (p *peeker) NextRange() hcl.Range {
	return p.Peek().Range
}

func (p *peeker) PrevRange() hcl.Range {
	if p.NextIndex == 0 {
		return p.NextRange()
	}

	return p.Tokens[p.NextIndex-1].Range
}

func (p *peeker) nextToken() (Token, int) {
	for i := p.NextIndex; i < len(p.Tokens); i++ {
		tok := p.Tokens[i]
		switch tok.Type {
		case TokenComment:
			if !p.IncludeComments {
				// Single-line comment tokens, starting with # or //, absorb
				// the trailing newline that terminates them as part of their
				// bytes. When we're filtering out comments, we must as a
				// special case transform these to newline tokens in order
				// to properly parse newline-terminated block items.

				if p.includingNewlines() {
					if len(tok.Bytes) > 0 && tok.Bytes[len(tok.Bytes)-1] == '\n' {
						fakeNewline := Token{
							Type:  TokenNewline,
							Bytes: tok.Bytes[len(tok.Bytes)-1 : len(tok.Bytes)],

							// We use the whole token range as the newline
							// range, even though that's a little... weird,
							// because otherwise we'd need to go count
							// characters again in order to figure out the
							// column of the newline, and that complexity
							// isn't justified when ranges of newlines are
							// so rarely printed anyway.
							Range: tok.Range,
						}
						return fakeNewline, i + 1
					}
				}

				continue
			}
		case TokenNewline:
			if !p.includingNewlines() {
				continue
			}
		}

		return tok, i + 1
	}

	// if we fall out here then we'll return the EOF token, and leave
	// our index pointed off the end of the array so we'll keep
	// returning EOF in future too.
	return p.Tokens[len(p.Tokens)-1], len(p.Tokens)
}

func (p *peeker) includingNewlines() bool {
	return p.IncludeNewlinesStack[len(p.IncludeNewlinesStack)-1]
}

func (p *peeker) PushIncludeNewlines(include bool) {
	p.IncludeNewlinesStack = append(p.IncludeNewlinesStack, include)
}

func (p *peeker) PopIncludeNewlines() bool {
	stack := p.IncludeNewlinesStack
	remain, ret := stack[:len(stack)-1], stack[len(stack)-1]
	p.IncludeNewlinesStack = remain
	return ret
}


<|start_filename|>vendor/github.com/hashicorp/terraform/backend/local/backend_apply_test.go<|end_filename|>
package local

import (
	"context"
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"testing"

	"github.com/hashicorp/terraform/backend"
	"github.com/hashicorp/terraform/config/module"
	"github.com/hashicorp/terraform/state"
	"github.com/hashicorp/terraform/terraform"
	"github.com/mitchellh/cli"
)

func TestLocal_applyBasic(t *testing.T) {
	b := TestLocal(t)
	p := TestLocalProvider(t, b, "test")

	p.ApplyReturn = &terraform.InstanceState{ID: "yes"}

	mod, modCleanup := module.TestTree(t, "./test-fixtures/apply")
	defer modCleanup()

	op := testOperationApply()
	op.Module = mod

	run, err := b.Operation(context.Background(), op)
	if err != nil {
		t.Fatalf("bad: %s", err)
	}
	<-run.Done()
	if run.Err != nil {
		t.Fatalf("err: %s", err)
	}

	if p.RefreshCalled {
		t.Fatal("refresh should not be called")
	}

	if !p.DiffCalled {
		t.Fatal("diff should be called")
	}

	if !p.ApplyCalled {
		t.Fatal("apply should be called")
	}

	checkState(t, b.StateOutPath, `
test_instance.foo:
  ID = yes
  provider = provider.test
	`)
}

func TestLocal_applyEmptyDir(t *testing.T) {
	b := TestLocal(t)
	p := TestLocalProvider(t, b, "test")

	p.ApplyReturn = &terraform.InstanceState{ID: "yes"}

	op := testOperationApply()
	op.Module = nil

	run, err := b.Operation(context.Background(), op)
	if err != nil {
		t.Fatalf("bad: %s", err)
	}
	<-run.Done()
	if run.Err == nil {
		t.Fatal("should error")
	}

	if p.ApplyCalled {
		t.Fatal("apply should not be called")
	}

	if _, err := os.Stat(b.StateOutPath); err == nil {
		t.Fatal("should not exist")
	}
}

func TestLocal_applyEmptyDirDestroy(t *testing.T) {
	b := TestLocal(t)
	p := TestLocalProvider(t, b, "test")

	p.ApplyReturn = nil

	op := testOperationApply()
	op.Module = nil
	op.Destroy = true

	run, err := b.Operation(context.Background(), op)
	if err != nil {
		t.Fatalf("bad: %s", err)
	}
	<-run.Done()
	if run.Err != nil {
		t.Fatalf("err: %s", err)
	}

	if p.ApplyCalled {
		t.Fatal("apply should not be called")
	}

	checkState(t, b.StateOutPath, `<no state>`)
}

func TestLocal_applyError(t *testing.T) {
	b := TestLocal(t)
	p := TestLocalProvider(t, b, "test")

	var lock sync.Mutex
	errored := false
	p.ApplyFn = func(
		info *terraform.InstanceInfo,
		s *terraform.InstanceState,
		d *terraform.InstanceDiff) (*terraform.InstanceState, error) {
		lock.Lock()
		defer lock.Unlock()

		if !errored && info.Id == "test_instance.bar" {
			errored = true
			return nil, fmt.Errorf("error")
		}

		return &terraform.InstanceState{ID: "foo"}, nil
	}
	p.DiffFn = func(
		*terraform.InstanceInfo,
		*terraform.InstanceState,
		*terraform.ResourceConfig) (*terraform.InstanceDiff, error) {
		return &terraform.InstanceDiff{
			Attributes: map[string]*terraform.ResourceAttrDiff{
				"ami": &terraform.ResourceAttrDiff{
					New: "bar",
				},
			},
		}, nil
	}

	mod, modCleanup := module.TestTree(t, "./test-fixtures/apply-error")
	defer modCleanup()

	op := testOperationApply()
	op.Module = mod

	run, err := b.Operation(context.Background(), op)
	if err != nil {
		t.Fatalf("bad: %s", err)
	}
	<-run.Done()
	if run.Err == nil {
		t.Fatal("should error")
	}

	checkState(t, b.StateOutPath, `
test_instance.foo:
  ID = foo
  provider = provider.test
	`)
}

func TestLocal_applyBackendFail(t *testing.T) {
	mod, modCleanup := module.TestTree(t, "./test-fixtures/apply")
	defer modCleanup()

	b := TestLocal(t)
	wd, err := os.Getwd()
	if err != nil {
		t.Fatalf("failed to get current working directory")
	}
	err = os.Chdir(filepath.Dir(b.StatePath))
	if err != nil {
		t.Fatalf("failed to set temporary working directory")
	}
	defer os.Chdir(wd)

	b.Backend = &backendWithFailingState{}
	b.CLI = new(cli.MockUi)
	p := TestLocalProvider(t, b, "test")

	p.ApplyReturn = &terraform.InstanceState{ID: "yes"}

	op := testOperationApply()
	op.Module = mod

	run, err := b.Operation(context.Background(), op)
	if err != nil {
		t.Fatalf("bad: %s", err)
	}
	<-run.Done()
	if run.Err == nil {
		t.Fatalf("apply succeeded; want error")
	}

	errStr := run.Err.Error()
	if !strings.Contains(errStr, "terraform state push errored.tfstate") {
		t.Fatalf("wrong error message:\n%s", errStr)
	}

	msgStr := b.CLI.(*cli.MockUi).ErrorWriter.String()
	if !strings.Contains(msgStr, "Failed to save state: fake failure") {
		t.Fatalf("missing original error message in output:\n%s", msgStr)
	}

	// The fallback behavior should've created a file errored.tfstate in the
	// current working directory.
	checkState(t, "errored.tfstate", `
test_instance.foo:
  ID = yes
  provider = provider.test
	`)
}

type backendWithFailingState struct {
	Local
}

func (b *backendWithFailingState) State(name string) (state.State, error) {
	return &failingState{
		&state.LocalState{
			Path: "failing-state.tfstate",
		},
	}, nil
}

type failingState struct {
	*state.LocalState
}

func (s failingState) WriteState(state *terraform.State) error {
	return errors.New("fake failure")
}

func testOperationApply() *backend.Operation {
	return &backend.Operation{
		Type: backend.OperationTypeApply,
	}
}

// testApplyState is just a common state that we use for testing refresh.
func testApplyState() *terraform.State {
	return &terraform.State{
		Version: 2,
		Modules: []*terraform.ModuleState{
			&terraform.ModuleState{
				Path: []string{"root"},
				Resources: map[string]*terraform.ResourceState{
					"test_instance.foo": &terraform.ResourceState{
						Type: "test_instance",
						Primary: &terraform.InstanceState{
							ID: "bar",
						},
					},
				},
			},
		},
	}
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_cloudwatch_log_group.go<|end_filename|>
package aws

import (
	"fmt"
	"log"

	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
	"github.com/hashicorp/errwrap"
)

func resourceAwsCloudWatchLogGroup() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsCloudWatchLogGroupCreate,
		Read:   resourceAwsCloudWatchLogGroupRead,
		Update: resourceAwsCloudWatchLogGroupUpdate,
		Delete: resourceAwsCloudWatchLogGroupDelete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"name": {
				Type:          schema.TypeString,
				Optional:      true,
				Computed:      true,
				ForceNew:      true,
				ConflictsWith: []string{"name_prefix"},
				ValidateFunc:  validateLogGroupName,
			},
			"name_prefix": {
				Type:         schema.TypeString,
				Optional:     true,
				ForceNew:     true,
				ValidateFunc: validateLogGroupNamePrefix,
			},

			"retention_in_days": {
				Type:     schema.TypeInt,
				Optional: true,
				Default:  0,
			},

			"kms_key_id": {
				Type:     schema.TypeString,
				Optional: true,
			},

			"arn": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"tags": tagsSchema(),
		},
	}
}

func resourceAwsCloudWatchLogGroupCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).cloudwatchlogsconn

	var logGroupName string
	if v, ok := d.GetOk("name"); ok {
		logGroupName = v.(string)
	} else if v, ok := d.GetOk("name_prefix"); ok {
		logGroupName = resource.PrefixedUniqueId(v.(string))
	} else {
		logGroupName = resource.UniqueId()
	}

	log.Printf("[DEBUG] Creating CloudWatch Log Group: %s", logGroupName)

	params := &cloudwatchlogs.CreateLogGroupInput{
		LogGroupName: aws.String(logGroupName),
	}

	if v, ok := d.GetOk("kms_key_id"); ok {
		params.KmsKeyId = aws.String(v.(string))
	}

	_, err := conn.CreateLogGroup(params)
	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "ResourceAlreadyExistsException" {
			return fmt.Errorf("Creating CloudWatch Log Group failed: %s:  The CloudWatch Log Group '%s' already exists.", err, d.Get("name").(string))
		}
		return fmt.Errorf("Creating CloudWatch Log Group failed: %s '%s'", err, d.Get("name"))
	}

	d.SetId(logGroupName)

	log.Println("[INFO] CloudWatch Log Group created")

	return resourceAwsCloudWatchLogGroupUpdate(d, meta)
}

func resourceAwsCloudWatchLogGroupRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).cloudwatchlogsconn
	log.Printf("[DEBUG] Reading CloudWatch Log Group: %q", d.Get("name").(string))
	lg, exists, err := lookupCloudWatchLogGroup(conn, d.Id(), nil)
	if err != nil {
		return err
	}

	if !exists {
		log.Printf("[DEBUG] CloudWatch Group %q Not Found", d.Id())
		d.SetId("")
		return nil
	}

	log.Printf("[DEBUG] Found Log Group: %#v", *lg)

	d.Set("arn", lg.Arn)
	d.Set("name", lg.LogGroupName)
	d.Set("kms_key_id", lg.KmsKeyId)

	if lg.RetentionInDays != nil {
		d.Set("retention_in_days", lg.RetentionInDays)
	}

	if !meta.(*AWSClient).IsChinaCloud() && !meta.(*AWSClient).IsGovCloud() {
		tags, err := flattenCloudWatchTags(d, conn)
		if err != nil {
			return err
		}
		d.Set("tags", tags)
	}

	return nil
}

func lookupCloudWatchLogGroup(conn *cloudwatchlogs.CloudWatchLogs,
	name string, nextToken *string) (*cloudwatchlogs.LogGroup, bool, error) {
	input := &cloudwatchlogs.DescribeLogGroupsInput{
		LogGroupNamePrefix: aws.String(name),
		NextToken:          nextToken,
	}
	resp, err := conn.DescribeLogGroups(input)
	if err != nil {
		return nil, true, err
	}

	for _, lg := range resp.LogGroups {
		if *lg.LogGroupName == name {
			return lg, true, nil
		}
	}

	if resp.NextToken != nil {
		return lookupCloudWatchLogGroup(conn, name, resp.NextToken)
	}

	return nil, false, nil
}

func resourceAwsCloudWatchLogGroupUpdate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).cloudwatchlogsconn

	name := d.Id()
	log.Printf("[DEBUG] Updating CloudWatch Log Group: %q", name)

	if d.HasChange("retention_in_days") {
		var err error

		if v, ok := d.GetOk("retention_in_days"); ok {
			input := cloudwatchlogs.PutRetentionPolicyInput{
				LogGroupName:    aws.String(name),
				RetentionInDays: aws.Int64(int64(v.(int))),
			}
			log.Printf("[DEBUG] Setting retention for CloudWatch Log Group: %q: %s", name, input)
			_, err = conn.PutRetentionPolicy(&input)
		} else {
			log.Printf("[DEBUG] Deleting retention for CloudWatch Log Group: %q", name)
			_, err = conn.DeleteRetentionPolicy(&cloudwatchlogs.DeleteRetentionPolicyInput{
				LogGroupName: aws.String(name),
			})
		}

		if err != nil {
			return err
		}
	}

	restricted := meta.(*AWSClient).IsChinaCloud() || meta.(*AWSClient).IsGovCloud()

	if !restricted && d.HasChange("tags") {
		oraw, nraw := d.GetChange("tags")
		o := oraw.(map[string]interface{})
		n := nraw.(map[string]interface{})
		create, remove := diffCloudWatchTags(o, n)

		if len(remove) > 0 {
			log.Printf("[DEBUG] Removing tags from %s", name)
			_, err := conn.UntagLogGroup(&cloudwatchlogs.UntagLogGroupInput{
				LogGroupName: aws.String(name),
				Tags:         remove,
			})
			if err != nil {
				return err
			}
		}

		if len(create) > 0 {
			log.Printf("[DEBUG] Creating tags on %s", name)
			_, err := conn.TagLogGroup(&cloudwatchlogs.TagLogGroupInput{
				LogGroupName: aws.String(name),
				Tags:         create,
			})
			if err != nil {
				return err
			}
		}
	}

	if d.HasChange("kms_key_id") && !d.IsNewResource() {
		_, newKey := d.GetChange("kms_key_id")

		if newKey.(string) == "" {
			_, err := conn.DisassociateKmsKey(&cloudwatchlogs.DisassociateKmsKeyInput{
				LogGroupName: aws.String(name),
			})
			if err != nil {
				return err
			}
		} else {
			_, err := conn.AssociateKmsKey(&cloudwatchlogs.AssociateKmsKeyInput{
				LogGroupName: aws.String(name),
				KmsKeyId:     aws.String(newKey.(string)),
			})
			if err != nil {
				return err
			}
		}
	}

	return resourceAwsCloudWatchLogGroupRead(d, meta)
}

func diffCloudWatchTags(oldTags map[string]interface{}, newTags map[string]interface{}) (map[string]*string, []*string) {
	create := make(map[string]*string)
	for k, v := range newTags {
		create[k] = aws.String(v.(string))
	}

	var remove []*string
	for t, _ := range oldTags {
		_, ok := create[t]
		if !ok {
			remove = append(remove, aws.String(t))
		}
	}

	return create, remove
}

func resourceAwsCloudWatchLogGroupDelete(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).cloudwatchlogsconn
	log.Printf("[INFO] Deleting CloudWatch Log Group: %s", d.Id())
	_, err := conn.DeleteLogGroup(&cloudwatchlogs.DeleteLogGroupInput{
		LogGroupName: aws.String(d.Get("name").(string)),
	})
	if err != nil {
		return fmt.Errorf("Error deleting CloudWatch Log Group: %s", err)
	}
	log.Println("[INFO] CloudWatch Log Group deleted")

	d.SetId("")

	return nil
}

func flattenCloudWatchTags(d *schema.ResourceData, conn *cloudwatchlogs.CloudWatchLogs) (map[string]interface{}, error) {
	tagsOutput, err := conn.ListTagsLogGroup(&cloudwatchlogs.ListTagsLogGroupInput{
		LogGroupName: aws.String(d.Get("name").(string)),
	})
	if err != nil {
		return nil, errwrap.Wrapf("Error Getting CloudWatch Logs Tag List: {{err}}", err)
	}
	if tagsOutput != nil {
		output := make(map[string]interface{}, len(tagsOutput.Tags))

		for i, v := range tagsOutput.Tags {
			output[i] = *v
		}

		return output, nil
	}

	return make(map[string]interface{}), nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/backend/local/backend_refresh_test.go<|end_filename|>
package local

import (
	"context"
	"fmt"
	"testing"

	"github.com/hashicorp/terraform/backend"
	"github.com/hashicorp/terraform/config/module"
	"github.com/hashicorp/terraform/terraform"
)

func TestLocal_refresh(t *testing.T) {
	b := TestLocal(t)
	p := TestLocalProvider(t, b, "test")
	terraform.TestStateFile(t, b.StatePath, testRefreshState())

	p.RefreshFn = nil
	p.RefreshReturn = &terraform.InstanceState{ID: "yes"}

	mod, modCleanup := module.TestTree(t, "./test-fixtures/refresh")
	defer modCleanup()

	op := testOperationRefresh()
	op.Module = mod

	run, err := b.Operation(context.Background(), op)
	if err != nil {
		t.Fatalf("bad: %s", err)
	}
	<-run.Done()

	if !p.RefreshCalled {
		t.Fatal("refresh should be called")
	}

	checkState(t, b.StateOutPath, `
test_instance.foo:
  ID = yes
  provider = provider.test
	`)
}

func TestLocal_refreshNilModule(t *testing.T) {
	b := TestLocal(t)
	p := TestLocalProvider(t, b, "test")
	terraform.TestStateFile(t, b.StatePath, testRefreshState())

	p.RefreshFn = nil
	p.RefreshReturn = &terraform.InstanceState{ID: "yes"}

	op := testOperationRefresh()
	op.Module = nil

	run, err := b.Operation(context.Background(), op)
	if err != nil {
		t.Fatalf("bad: %s", err)
	}
	<-run.Done()

	if !p.RefreshCalled {
		t.Fatal("refresh should be called")
	}

	checkState(t, b.StateOutPath, `
test_instance.foo:
  ID = yes
  provider = provider.test
	`)
}

// GH-12174
func TestLocal_refreshNilModuleWithInput(t *testing.T) {
	b := TestLocal(t)
	p := TestLocalProvider(t, b, "test")
	terraform.TestStateFile(t, b.StatePath, testRefreshState())

	p.RefreshFn = nil
	p.RefreshReturn = &terraform.InstanceState{ID: "yes"}

	b.OpInput = true

	op := testOperationRefresh()
	op.Module = nil

	run, err := b.Operation(context.Background(), op)
	if err != nil {
		t.Fatalf("bad: %s", err)
	}
	<-run.Done()

	if !p.RefreshCalled {
		t.Fatal("refresh should be called")
	}

	checkState(t, b.StateOutPath, `
test_instance.foo:
  ID = yes
  provider = provider.test
	`)
}

func TestLocal_refreshInput(t *testing.T) {
	b := TestLocal(t)
	p := TestLocalProvider(t, b, "test")
	terraform.TestStateFile(t, b.StatePath, testRefreshState())

	p.ConfigureFn = func(c *terraform.ResourceConfig) error {
		if v, ok := c.Get("value"); !ok || v != "bar" {
			return fmt.Errorf("no value set")
		}

		return nil
	}

	p.RefreshFn = nil
	p.RefreshReturn = &terraform.InstanceState{ID: "yes"}

	mod, modCleanup := module.TestTree(t, "./test-fixtures/refresh-var-unset")
	defer modCleanup()

	// Enable input asking since it is normally disabled by default
	b.OpInput = true
	b.ContextOpts.UIInput = &terraform.MockUIInput{InputReturnString: "bar"}

	op := testOperationRefresh()
	op.Module = mod
	op.UIIn = b.ContextOpts.UIInput

	run, err := b.Operation(context.Background(), op)
	if err != nil {
		t.Fatalf("bad: %s", err)
	}
	<-run.Done()

	if !p.RefreshCalled {
		t.Fatal("refresh should be called")
	}

	checkState(t, b.StateOutPath, `
test_instance.foo:
  ID = yes
  provider = provider.test
	`)
}

func TestLocal_refreshValidate(t *testing.T) {
	b := TestLocal(t)
	p := TestLocalProvider(t, b, "test")
	terraform.TestStateFile(t, b.StatePath, testRefreshState())

	p.RefreshFn = nil
	p.RefreshReturn = &terraform.InstanceState{ID: "yes"}

	mod, modCleanup := module.TestTree(t, "./test-fixtures/refresh")
	defer modCleanup()

	// Enable validation
	b.OpValidation = true

	op := testOperationRefresh()
	op.Module = mod

	run, err := b.Operation(context.Background(), op)
	if err != nil {
		t.Fatalf("bad: %s", err)
	}
	<-run.Done()

	if !p.ValidateCalled {
		t.Fatal("validate should be called")
	}

	checkState(t, b.StateOutPath, `
test_instance.foo:
  ID = yes
  provider = provider.test
	`)
}

func testOperationRefresh() *backend.Operation {
	return &backend.Operation{
		Type: backend.OperationTypeRefresh,
	}
}

// testRefreshState is just a common state that we use for testing refresh.
func testRefreshState() *terraform.State {
	return &terraform.State{
		Version: 2,
		Modules: []*terraform.ModuleState{
			&terraform.ModuleState{
				Path: []string{"root"},
				Resources: map[string]*terraform.ResourceState{
					"test_instance.foo": &terraform.ResourceState{
						Type: "test_instance",
						Primary: &terraform.InstanceState{
							ID: "bar",
						},
					},
				},
				Outputs: map[string]*terraform.OutputState{},
			},
		},
	}
}


<|start_filename|>vendor/github.com/mitchellh/packer/vendor/github.com/mitchellh/go-fs/fat/boot_sector.go<|end_filename|>
package fat

import (
	"encoding/binary"
	"errors"
	"fmt"
	"github.com/mitchellh/go-fs"
	"unicode"
)

type MediaType uint8

// The standard value for "fixed", non-removable media, directly
// from the FAT specification.
const MediaFixed MediaType = 0xF8

type BootSectorCommon struct {
	OEMName             string
	BytesPerSector      uint16
	SectorsPerCluster   uint8
	ReservedSectorCount uint16
	NumFATs             uint8
	RootEntryCount      uint16
	TotalSectors        uint32
	Media               MediaType
	SectorsPerFat       uint32
	SectorsPerTrack     uint16
	NumHeads            uint16
}

// DecodeBootSector takes a BlockDevice and decodes the FAT boot sector
// from it.
func DecodeBootSector(device fs.BlockDevice) (*BootSectorCommon, error) {
	var sector [512]byte
	if _, err := device.ReadAt(sector[:], 0); err != nil {
		return nil, err
	}

	if sector[510] != 0x55 || sector[511] != 0xAA {
		return nil, errors.New("corrupt boot sector signature")
	}

	result := new(BootSectorCommon)

	// BS_OEMName
	result.OEMName = string(sector[3:11])

	// BPB_BytsPerSec
	result.BytesPerSector = binary.LittleEndian.Uint16(sector[11:13])

	// BPB_SecPerClus
	result.SectorsPerCluster = sector[13]

	// BPB_RsvdSecCnt
	result.ReservedSectorCount = binary.LittleEndian.Uint16(sector[14:16])

	// BPB_NumFATs
	result.NumFATs = sector[16]

	// BPB_RootEntCnt
	result.RootEntryCount = binary.LittleEndian.Uint16(sector[17:19])

	// BPB_Media
	result.Media = MediaType(sector[21])

	// BPB_SecPerTrk
	result.SectorsPerTrack = binary.LittleEndian.Uint16(sector[24:26])

	// BPB_NumHeads
	result.NumHeads = binary.LittleEndian.Uint16(sector[26:28])

	// BPB_TotSec16 / BPB_TotSec32
	result.TotalSectors = uint32(binary.LittleEndian.Uint16(sector[19:21]))
	if result.TotalSectors == 0 {
		result.TotalSectors = binary.LittleEndian.Uint32(sector[32:36])
	}

	// BPB_FATSz16 / BPB_FATSz32
	result.SectorsPerFat = uint32(binary.LittleEndian.Uint16(sector[22:24]))
	if result.SectorsPerFat == 0 {
		result.SectorsPerFat = binary.LittleEndian.Uint32(sector[36:40])
	}

	return result, nil
}

func (b *BootSectorCommon) Bytes() ([]byte, error) {
	var sector [512]byte

	// BS_jmpBoot
	sector[0] = 0xEB
	sector[1] = 0x3C
	sector[2] = 0x90

	// BS_OEMName
	if len(b.OEMName) > 8 {
		return nil, errors.New("OEMName must be 8 bytes or less")
	}

	for i, r := range b.OEMName {
		if r > unicode.MaxASCII {
			return nil, fmt.Errorf("'%s' in OEM name not a valid ASCII char. Must be ASCII.", r)
		}

		sector[0x3+i] = byte(r)
	}

	// BPB_BytsPerSec
	binary.LittleEndian.PutUint16(sector[11:13], b.BytesPerSector)

	// BPB_SecPerClus
	sector[13] = uint8(b.SectorsPerCluster)

	// BPB_RsvdSecCnt
	binary.LittleEndian.PutUint16(sector[14:16], b.ReservedSectorCount)

	// BPB_NumFATs
	sector[16] = b.NumFATs

	// BPB_RootEntCnt
	binary.LittleEndian.PutUint16(sector[17:19], b.RootEntryCount)

	// BPB_Media
	sector[21] = byte(b.Media)

	// BPB_SecPerTrk
	binary.LittleEndian.PutUint16(sector[24:26], b.SectorsPerTrack)

	// BPB_Numheads
	binary.LittleEndian.PutUint16(sector[26:28], b.NumHeads)

	// BPB_Hiddsec
	// sector[28:32] - it is always set to 0 because we don't partition drives yet.

	// Important signature of every FAT boot sector
	sector[510] = 0x55
	sector[511] = 0xAA

	return sector[:], nil
}

// BytesPerCluster returns the number of bytes per cluster.
func (b *BootSectorCommon) BytesPerCluster() uint32 {
	return uint32(b.SectorsPerCluster) * uint32(b.BytesPerSector)
}

// ClusterOffset returns the offset of the data section of a particular
// cluster.
func (b *BootSectorCommon) ClusterOffset(n int) uint32 {
	offset := b.DataOffset()
	offset += (uint32(n) - FirstCluster) * b.BytesPerCluster()
	return offset
}

// DataOffset returns the offset of the data section of the disk.
func (b *BootSectorCommon) DataOffset() uint32 {
	offset := uint32(b.RootDirOffset())
	offset += uint32(b.RootEntryCount * DirectoryEntrySize)
	return offset
}

// FATOffset returns the offset in bytes for the given index of the FAT
func (b *BootSectorCommon) FATOffset(n int) int {
	offset := uint32(b.ReservedSectorCount * b.BytesPerSector)
	offset += b.SectorsPerFat * uint32(b.BytesPerSector) * uint32(n)
	return int(offset)
}

// Calculates the FAT type that this boot sector represents.
func (b *BootSectorCommon) FATType() FATType {
	var rootDirSectors uint32
	rootDirSectors = (uint32(b.RootEntryCount) * 32) + (uint32(b.BytesPerSector) - 1)
	rootDirSectors /= uint32(b.BytesPerSector)
	dataSectors := b.SectorsPerFat * uint32(b.NumFATs)
	dataSectors += uint32(b.ReservedSectorCount)
	dataSectors += rootDirSectors
	dataSectors = b.TotalSectors - dataSectors
	countClusters := dataSectors / uint32(b.SectorsPerCluster)

	switch {
	case countClusters < 4085:
		return FAT12
	case countClusters < 65525:
		return FAT16
	default:
		return FAT32
	}
}

// RootDirOffset returns the byte offset when the root directory
// entries for FAT12/16 filesystems start. NOTE: This is absolutely useless
// for FAT32 because the root directory is just the beginning of the data
// region.
func (b *BootSectorCommon) RootDirOffset() int {
	offset := b.FATOffset(0)
	offset += int(uint32(b.NumFATs) * b.SectorsPerFat * uint32(b.BytesPerSector))
	return offset
}

// BootSectorFat16 is the BootSector for FAT12 and FAT16 filesystems.
// It contains the common fields to all FAT filesystems and also some
// unique.
type BootSectorFat16 struct {
	BootSectorCommon

	DriveNumber         uint8
	VolumeID            uint32
	VolumeLabel         string
	FileSystemTypeLabel string
}

func (b *BootSectorFat16) Bytes() ([]byte, error) {
	sector, err := b.BootSectorCommon.Bytes()
	if err != nil {
		return nil, err
	}

	// BPB_TotSec16 AND BPB_TotSec32
	if b.TotalSectors < 0x10000 {
		binary.LittleEndian.PutUint16(sector[19:21], uint16(b.TotalSectors))
	} else {
		binary.LittleEndian.PutUint32(sector[32:36], b.TotalSectors)
	}

	// BPB_FATSz16
	if b.SectorsPerFat > 0x10000 {
		return nil, fmt.Errorf("SectorsPerFat value too big for non-FAT32: %d", b.SectorsPerFat)
	}

	binary.LittleEndian.PutUint16(sector[22:24], uint16(b.SectorsPerFat))

	// BS_DrvNum
	sector[36] = b.DriveNumber

	// BS_BootSig
	sector[38] = 0x29

	// BS_VolID
	binary.LittleEndian.PutUint32(sector[39:43], b.VolumeID)

	// BS_VolLab
	if len(b.VolumeLabel) > 11 {
		return nil, errors.New("VolumeLabel must be 11 bytes or less")
	}

	for i, r := range b.VolumeLabel {
		if r > unicode.MaxASCII {
			return nil, fmt.Errorf("'%s' in VolumeLabel not a valid ASCII char. Must be ASCII.", r)
		}

		sector[43+i] = byte(r)
	}

	// BS_FilSysType
	if len(b.FileSystemTypeLabel) > 8 {
		return nil, errors.New("FileSystemTypeLabel must be 8 bytes or less")
	}

	for i, r := range b.FileSystemTypeLabel {
		if r > unicode.MaxASCII {
			return nil, fmt.Errorf("'%s' in FileSystemTypeLabel not a valid ASCII char. Must be ASCII.", r)
		}

		sector[54+i] = byte(r)
	}

	return sector, nil
}

type BootSectorFat32 struct {
	BootSectorCommon

	RootCluster         uint32
	FSInfoSector        uint16
	BackupBootSector    uint16
	DriveNumber         uint8
	VolumeID            uint32
	VolumeLabel         string
	FileSystemTypeLabel string
}

func (b *BootSectorFat32) Bytes() ([]byte, error) {
	sector, err := b.BootSectorCommon.Bytes()
	if err != nil {
		return nil, err
	}

	// BPB_RootEntCount - must be 0
	sector[17] = 0
	sector[18] = 0

	// BPB_FATSz32
	binary.LittleEndian.PutUint32(sector[36:40], b.SectorsPerFat)

	// BPB_ExtFlags - Unused?

	// BPB_FSVer. Explicitly set to 0 because that is really important
	// to get correct.
	sector[42] = 0
	sector[43] = 0

	// BPB_RootClus
	binary.LittleEndian.PutUint32(sector[44:48], b.RootCluster)

	// BPB_FSInfo
	binary.LittleEndian.PutUint16(sector[48:50], b.FSInfoSector)

	// BPB_BkBootSec
	binary.LittleEndian.PutUint16(sector[50:52], b.BackupBootSector)

	// BS_DrvNum
	sector[64] = b.DriveNumber

	// BS_BootSig
	sector[66] = 0x29

	// BS_VolID
	binary.LittleEndian.PutUint32(sector[67:71], b.VolumeID)

	// BS_VolLab
	if len(b.VolumeLabel) > 11 {
		return nil, errors.New("VolumeLabel must be 11 bytes or less")
	}

	for i, r := range b.VolumeLabel {
		if r > unicode.MaxASCII {
			return nil, fmt.Errorf("'%s' in VolumeLabel not a valid ASCII char. Must be ASCII.", r)
		}

		sector[71+i] = byte(r)
	}

	// BS_FilSysType
	if len(b.FileSystemTypeLabel) > 8 {
		return nil, errors.New("FileSystemTypeLabel must be 8 bytes or less")
	}

	for i, r := range b.FileSystemTypeLabel {
		if r > unicode.MaxASCII {
			return nil, fmt.Errorf("'%s' in FileSystemTypeLabel not a valid ASCII char. Must be ASCII.", r)
		}

		sector[82+i] = byte(r)
	}

	return sector, nil
}


<|start_filename|>vendor/github.com/mitchellh/packer/provisioner/shell/provisioner.go<|end_filename|>
// This package implements a provisioner for Packer that executes
// shell scripts within the remote machine.
package shell

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"math/rand"
	"os"
	"sort"
	"strings"
	"time"

	"github.com/hashicorp/packer/common"
	"github.com/hashicorp/packer/helper/config"
	"github.com/hashicorp/packer/packer"
	"github.com/hashicorp/packer/template/interpolate"
)

type Config struct {
	common.PackerConfig `mapstructure:",squash"`

	// If true, the script contains binary and line endings will not be
	// converted from Windows to Unix-style.
	Binary bool

	// An inline script to execute. Multiple strings are all executed
	// in the context of a single shell.
	Inline []string

	// The shebang value used when running inline scripts.
	InlineShebang string `mapstructure:"inline_shebang"`

	// The local path of the shell script to upload and execute.
	Script string

	// An array of multiple scripts to run.
	Scripts []string

	// An array of environment variables that will be injected before
	// your command(s) are executed.
	Vars []string `mapstructure:"environment_vars"`

	// The remote folder where the local shell script will be uploaded to.
	// This should be set to a pre-existing directory, it defaults to /tmp
	RemoteFolder string `mapstructure:"remote_folder"`

	// The remote file name of the local shell script.
	// This defaults to script_nnn.sh
	RemoteFile string `mapstructure:"remote_file"`

	// The remote path where the local shell script will be uploaded to.
	// This should be set to a writable file that is in a pre-existing directory.
	// This defaults to remote_folder/remote_file
	RemotePath string `mapstructure:"remote_path"`

	// The command used to execute the script. The '{{ .Path }}' variable
	// should be used to specify where the script goes, {{ .Vars }}
	// can be used to inject the environment_vars into the environment.
	ExecuteCommand string `mapstructure:"execute_command"`

	// The timeout for retrying to start the process. Until this timeout
	// is reached, if the provisioner can't start a process, it retries.
	// This can be set high to allow for reboots.
	RawStartRetryTimeout string `mapstructure:"start_retry_timeout"`

	// Whether to clean scripts up
	SkipClean bool `mapstructure:"skip_clean"`

	ExpectDisconnect bool `mapstructure:"expect_disconnect"`

	startRetryTimeout time.Duration
	ctx               interpolate.Context
}

type Provisioner struct {
	config Config
}

type ExecuteCommandTemplate struct {
	Vars string
	Path string
}

func (p *Provisioner) Prepare(raws ...interface{}) error {
	err := config.Decode(&p.config, &config.DecodeOpts{
		Interpolate:        true,
		InterpolateContext: &p.config.ctx,
		InterpolateFilter: &interpolate.RenderFilter{
			Exclude: []string{
				"execute_command",
			},
		},
	}, raws...)
	if err != nil {
		return err
	}

	if p.config.ExecuteCommand == "" {
		p.config.ExecuteCommand = "chmod +x {{.Path}}; {{.Vars}} {{.Path}}"
	}

	if p.config.Inline != nil && len(p.config.Inline) == 0 {
		p.config.Inline = nil
	}

	if p.config.InlineShebang == "" {
		p.config.InlineShebang = "/bin/sh -e"
	}

	if p.config.RawStartRetryTimeout == "" {
		p.config.RawStartRetryTimeout = "5m"
	}

	if p.config.RemoteFolder == "" {
		p.config.RemoteFolder = "/tmp"
	}

	if p.config.RemoteFile == "" {
		p.config.RemoteFile = fmt.Sprintf("script_%d.sh", rand.Intn(9999))
	}

	if p.config.RemotePath == "" {
		p.config.RemotePath = fmt.Sprintf(
			"%s/%s", p.config.RemoteFolder, p.config.RemoteFile)
	}

	if p.config.Scripts == nil {
		p.config.Scripts = make([]string, 0)
	}

	if p.config.Vars == nil {
		p.config.Vars = make([]string, 0)
	}

	var errs *packer.MultiError
	if p.config.Script != "" && len(p.config.Scripts) > 0 {
		errs = packer.MultiErrorAppend(errs,
			errors.New("Only one of script or scripts can be specified."))
	}

	if p.config.Script != "" {
		p.config.Scripts = []string{p.config.Script}
	}

	if len(p.config.Scripts) == 0 && p.config.Inline == nil {
		errs = packer.MultiErrorAppend(errs,
			errors.New("Either a script file or inline script must be specified."))
	} else if len(p.config.Scripts) > 0 && p.config.Inline != nil {
		errs = packer.MultiErrorAppend(errs,
			errors.New("Only a script file or an inline script can be specified, not both."))
	}

	for _, path := range p.config.Scripts {
		if _, err := os.Stat(path); err != nil {
			errs = packer.MultiErrorAppend(errs,
				fmt.Errorf("Bad script '%s': %s", path, err))
		}
	}

	// Do a check for bad environment variables, such as '=foo', 'foobar'
	for _, kv := range p.config.Vars {
		vs := strings.SplitN(kv, "=", 2)
		if len(vs) != 2 || vs[0] == "" {
			errs = packer.MultiErrorAppend(errs,
				fmt.Errorf("Environment variable not in format 'key=value': %s", kv))
		}
	}

	if p.config.RawStartRetryTimeout != "" {
		p.config.startRetryTimeout, err = time.ParseDuration(p.config.RawStartRetryTimeout)
		if err != nil {
			errs = packer.MultiErrorAppend(
				errs, fmt.Errorf("Failed parsing start_retry_timeout: %s", err))
		}
	}

	if errs != nil && len(errs.Errors) > 0 {
		return errs
	}

	return nil
}

func (p *Provisioner) Provision(ui packer.Ui, comm packer.Communicator) error {
	scripts := make([]string, len(p.config.Scripts))
	copy(scripts, p.config.Scripts)

	// If we have an inline script, then turn that into a temporary
	// shell script and use that.
	if p.config.Inline != nil {
		tf, err := ioutil.TempFile("", "packer-shell")
		if err != nil {
			return fmt.Errorf("Error preparing shell script: %s", err)
		}
		defer os.Remove(tf.Name())

		// Set the path to the temporary file
		scripts = append(scripts, tf.Name())

		// Write our contents to it
		writer := bufio.NewWriter(tf)
		writer.WriteString(fmt.Sprintf("#!%s\n", p.config.InlineShebang))
		for _, command := range p.config.Inline {
			if _, err := writer.WriteString(command + "\n"); err != nil {
				return fmt.Errorf("Error preparing shell script: %s", err)
			}
		}

		if err := writer.Flush(); err != nil {
			return fmt.Errorf("Error preparing shell script: %s", err)
		}

		tf.Close()
	}

	// Create environment variables to set before executing the command
	flattenedEnvVars := p.createFlattenedEnvVars()

	for _, path := range scripts {
		ui.Say(fmt.Sprintf("Provisioning with shell script: %s", path))

		log.Printf("Opening %s for reading", path)
		f, err := os.Open(path)
		if err != nil {
			return fmt.Errorf("Error opening shell script: %s", err)
		}
		defer f.Close()

		// Compile the command
		p.config.ctx.Data = &ExecuteCommandTemplate{
			Vars: flattenedEnvVars,
			Path: p.config.RemotePath,
		}
		command, err := interpolate.Render(p.config.ExecuteCommand, &p.config.ctx)
		if err != nil {
			return fmt.Errorf("Error processing command: %s", err)
		}

		// Upload the file and run the command. Do this in the context of
		// a single retryable function so that we don't end up with
		// the case that the upload succeeded, a restart is initiated,
		// and then the command is executed but the file doesn't exist
		// any longer.
		var cmd *packer.RemoteCmd
		err = p.retryable(func() error {
			if _, err := f.Seek(0, 0); err != nil {
				return err
			}

			var r io.Reader = f
			if !p.config.Binary {
				r = &UnixReader{Reader: r}
			}

			if err := comm.Upload(p.config.RemotePath, r, nil); err != nil {
				return fmt.Errorf("Error uploading script: %s", err)
			}

			cmd = &packer.RemoteCmd{
				Command: fmt.Sprintf("chmod 0755 %s", p.config.RemotePath),
			}
			if err := comm.Start(cmd); err != nil {
				return fmt.Errorf(
					"Error chmodding script file to 0755 in remote "+
						"machine: %s", err)
			}
			cmd.Wait()

			cmd = &packer.RemoteCmd{Command: command}
			return cmd.StartWithUi(comm, ui)
		})

		if err != nil {
			return err
		}

		// If the exit code indicates a remote disconnect, fail unless
		// we were expecting it.
		if cmd.ExitStatus == packer.CmdDisconnect {
			if !p.config.ExpectDisconnect {
				return fmt.Errorf("Script disconnected unexpectedly. " +
					"If you expected your script to disconnect, i.e. from a " +
					"restart, you can try adding `\"expect_disconnect\": true` " +
					"to the shell provisioner parameters.")
			}
		} else if cmd.ExitStatus != 0 {
			return fmt.Errorf("Script exited with non-zero exit status: %d", cmd.ExitStatus)
		}

		if !p.config.SkipClean {

			// Delete the temporary file we created. We retry this a few times
			// since if the above rebooted we have to wait until the reboot
			// completes.
			err = p.retryable(func() error {
				cmd = &packer.RemoteCmd{
					Command: fmt.Sprintf("rm -f %s", p.config.RemotePath),
				}
				if err := comm.Start(cmd); err != nil {
					return fmt.Errorf(
						"Error removing temporary script at %s: %s",
						p.config.RemotePath, err)
				}
				cmd.Wait()
				// treat disconnects as retryable by returning an error
				if cmd.ExitStatus == packer.CmdDisconnect {
					return fmt.Errorf("Disconnect while removing temporary script.")
				}
				return nil
			})
			if err != nil {
				return err
			}

			if cmd.ExitStatus != 0 {
				return fmt.Errorf(
					"Error removing temporary script at %s!",
					p.config.RemotePath)
			}
		}
	}

	return nil
}

func (p *Provisioner) Cancel() {
	// Just hard quit. It isn't a big deal if what we're doing keeps
	// running on the other side.
	os.Exit(0)
}

// retryable will retry the given function over and over until a
// non-error is returned.
func (p *Provisioner) retryable(f func() error) error {
	startTimeout := time.After(p.config.startRetryTimeout)
	for {
		var err error
		if err = f(); err == nil {
			return nil
		}

		// Create an error and log it
		err = fmt.Errorf("Retryable error: %s", err)
		log.Print(err.Error())

		// Check if we timed out, otherwise we retry. It is safe to
		// retry since the only error case above is if the command
		// failed to START.
		select {
		case <-startTimeout:
			return err
		default:
			time.Sleep(2 * time.Second)
		}
	}
}

func (p *Provisioner) createFlattenedEnvVars() (flattened string) {
	flattened = ""
	envVars := make(map[string]string)

	// Always available Packer provided env vars
	envVars["PACKER_BUILD_NAME"] = fmt.Sprintf("%s", p.config.PackerBuildName)
	envVars["PACKER_BUILDER_TYPE"] = fmt.Sprintf("%s", p.config.PackerBuilderType)
	httpAddr := common.GetHTTPAddr()
	if httpAddr != "" {
		envVars["PACKER_HTTP_ADDR"] = fmt.Sprintf("%s", httpAddr)
	}

	// Split vars into key/value components
	for _, envVar := range p.config.Vars {
		keyValue := strings.SplitN(envVar, "=", 2)
		// Store pair, replacing any single quotes in value so they parse
		// correctly with required environment variable format
		envVars[keyValue[0]] = strings.Replace(keyValue[1], "'", `'"'"'`, -1)
	}

	// Create a list of env var keys in sorted order
	var keys []string
	for k := range envVars {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	// Re-assemble vars surrounding value with single quotes and flatten
	for _, key := range keys {
		flattened += fmt.Sprintf("%s='%s' ", key, envVars[key])
	}
	return
}


<|start_filename|>vendor/github.com/hashicorp/hcl2/cmd/hcldec/spec.go<|end_filename|>
package main

import (
	"fmt"

	"github.com/hashicorp/hcl2/ext/userfunc"
	"github.com/hashicorp/hcl2/gohcl"
	"github.com/hashicorp/hcl2/hcl"
	"github.com/hashicorp/hcl2/hcldec"
	"github.com/zclconf/go-cty/cty"
	"github.com/zclconf/go-cty/cty/function"
)

type specFileContent struct {
	Variables map[string]cty.Value
	Functions map[string]function.Function
	RootSpec  hcldec.Spec
}

var specCtx = &hcl.EvalContext{
	Functions: specFuncs,
}

func loadSpecFile(filename string) (specFileContent, hcl.Diagnostics) {
	file, diags := parser.ParseHCLFile(filename)
	if diags.HasErrors() {
		return specFileContent{RootSpec: errSpec}, diags
	}

	vars, funcs, specBody, declDiags := decodeSpecDecls(file.Body)
	diags = append(diags, declDiags...)

	spec, specDiags := decodeSpecRoot(specBody)
	diags = append(diags, specDiags...)

	return specFileContent{
		Variables: vars,
		Functions: funcs,
		RootSpec:  spec,
	}, diags
}

func decodeSpecDecls(body hcl.Body) (map[string]cty.Value, map[string]function.Function, hcl.Body, hcl.Diagnostics) {
	funcs, body, diags := userfunc.DecodeUserFunctions(body, "function", func() *hcl.EvalContext {
		return specCtx
	})

	content, body, moreDiags := body.PartialContent(&hcl.BodySchema{
		Blocks: []hcl.BlockHeaderSchema{
			{
				Type: "variables",
			},
		},
	})
	diags = append(diags, moreDiags...)

	vars := make(map[string]cty.Value)
	for _, block := range content.Blocks {
		// We only have one block type in our schema, so we can assume all
		// blocks are of that type.
		attrs, moreDiags := block.Body.JustAttributes()
		diags = append(diags, moreDiags...)

		for name, attr := range attrs {
			val, moreDiags := attr.Expr.Value(specCtx)
			diags = append(diags, moreDiags...)
			vars[name] = val
		}
	}

	return vars, funcs, body, diags
}

func decodeSpecRoot(body hcl.Body) (hcldec.Spec, hcl.Diagnostics) {
	content, diags := body.Content(specSchemaUnlabelled)

	if len(content.Blocks) == 0 {
		if diags.HasErrors() {
			// If we already have errors then they probably explain
			// why we have no blocks, so we'll skip our additional
			// error message added below.
			return errSpec, diags
		}

		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Missing spec block",
			Detail:   "A spec file must have exactly one root block specifying how to map to a JSON value.",
			Subject:  body.MissingItemRange().Ptr(),
		})
		return errSpec, diags
	}

	if len(content.Blocks) > 1 {
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Extraneous spec block",
			Detail:   "A spec file must have exactly one root block specifying how to map to a JSON value.",
			Subject:  &content.Blocks[1].DefRange,
		})
		return errSpec, diags
	}

	spec, specDiags := decodeSpecBlock(content.Blocks[0])
	diags = append(diags, specDiags...)
	return spec, diags
}

func decodeSpecBlock(block *hcl.Block) (hcldec.Spec, hcl.Diagnostics) {
	var impliedName string
	if len(block.Labels) > 0 {
		impliedName = block.Labels[0]
	}

	switch block.Type {

	case "object":
		return decodeObjectSpec(block.Body)

	case "array":
		return decodeArraySpec(block.Body)

	case "attr":
		return decodeAttrSpec(block.Body, impliedName)

	case "block":
		return decodeBlockSpec(block.Body, impliedName)

	case "block_list":
		return decodeBlockListSpec(block.Body, impliedName)

	case "block_set":
		return decodeBlockSetSpec(block.Body, impliedName)

	case "block_map":
		return decodeBlockMapSpec(block.Body, impliedName)

	case "default":
		return decodeDefaultSpec(block.Body)

	case "transform":
		return decodeTransformSpec(block.Body)

	case "literal":
		return decodeLiteralSpec(block.Body)

	default:
		// Should never happen, because the above cases should be exhaustive
		// for our schema.
		var diags hcl.Diagnostics
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Invalid spec block",
			Detail:   fmt.Sprintf("Blocks of type %q are not expected here.", block.Type),
			Subject:  &block.TypeRange,
		})
		return errSpec, diags
	}
}

func decodeObjectSpec(body hcl.Body) (hcldec.Spec, hcl.Diagnostics) {
	content, diags := body.Content(specSchemaLabelled)

	spec := make(hcldec.ObjectSpec)
	for _, block := range content.Blocks {
		propSpec, propDiags := decodeSpecBlock(block)
		diags = append(diags, propDiags...)
		spec[block.Labels[0]] = propSpec
	}

	return spec, diags
}

func decodeArraySpec(body hcl.Body) (hcldec.Spec, hcl.Diagnostics) {
	content, diags := body.Content(specSchemaUnlabelled)

	spec := make(hcldec.TupleSpec, 0, len(content.Blocks))
	for _, block := range content.Blocks {
		elemSpec, elemDiags := decodeSpecBlock(block)
		diags = append(diags, elemDiags...)
		spec = append(spec, elemSpec)
	}

	return spec, diags
}

func decodeAttrSpec(body hcl.Body, impliedName string) (hcldec.Spec, hcl.Diagnostics) {
	type content struct {
		Name     *string        `hcl:"name"`
		Type     hcl.Expression `hcl:"type"`
		Required *bool          `hcl:"required"`
	}

	var args content
	diags := gohcl.DecodeBody(body, nil, &args)
	if diags.HasErrors() {
		return errSpec, diags
	}

	spec := &hcldec.AttrSpec{
		Name: impliedName,
	}

	if args.Required != nil {
		spec.Required = *args.Required
	}
	if args.Name != nil {
		spec.Name = *args.Name
	}

	var typeDiags hcl.Diagnostics
	spec.Type, typeDiags = evalTypeExpr(args.Type)
	diags = append(diags, typeDiags...)

	if spec.Name == "" {
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Missing name in attribute spec",
			Detail:   "The name attribute is required, to specify the attribute name that is expected in an input HCL file.",
			Subject:  body.MissingItemRange().Ptr(),
		})
		return errSpec, diags
	}

	return spec, diags
}

func decodeBlockSpec(body hcl.Body, impliedName string) (hcldec.Spec, hcl.Diagnostics) {
	type content struct {
		TypeName *string  `hcl:"block_type"`
		Required *bool    `hcl:"required"`
		Nested   hcl.Body `hcl:",remain"`
	}

	var args content
	diags := gohcl.DecodeBody(body, nil, &args)
	if diags.HasErrors() {
		return errSpec, diags
	}

	spec := &hcldec.BlockSpec{
		TypeName: impliedName,
	}

	if args.Required != nil {
		spec.Required = *args.Required
	}
	if args.TypeName != nil {
		spec.TypeName = *args.TypeName
	}

	nested, nestedDiags := decodeBlockNestedSpec(args.Nested)
	diags = append(diags, nestedDiags...)
	spec.Nested = nested

	return spec, diags
}

func decodeBlockListSpec(body hcl.Body, impliedName string) (hcldec.Spec, hcl.Diagnostics) {
	type content struct {
		TypeName *string  `hcl:"block_type"`
		MinItems *int     `hcl:"min_items"`
		MaxItems *int     `hcl:"max_items"`
		Nested   hcl.Body `hcl:",remain"`
	}

	var args content
	diags := gohcl.DecodeBody(body, nil, &args)
	if diags.HasErrors() {
		return errSpec, diags
	}

	spec := &hcldec.BlockListSpec{
		TypeName: impliedName,
	}

	if args.MinItems != nil {
		spec.MinItems = *args.MinItems
	}
	if args.MaxItems != nil {
		spec.MaxItems = *args.MaxItems
	}
	if args.TypeName != nil {
		spec.TypeName = *args.TypeName
	}

	nested, nestedDiags := decodeBlockNestedSpec(args.Nested)
	diags = append(diags, nestedDiags...)
	spec.Nested = nested

	if spec.TypeName == "" {
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Missing block_type in block_list spec",
			Detail:   "The block_type attribute is required, to specify the block type name that is expected in an input HCL file.",
			Subject:  body.MissingItemRange().Ptr(),
		})
		return errSpec, diags
	}

	return spec, diags
}

func decodeBlockSetSpec(body hcl.Body, impliedName string) (hcldec.Spec, hcl.Diagnostics) {
	type content struct {
		TypeName *string  `hcl:"block_type"`
		MinItems *int     `hcl:"min_items"`
		MaxItems *int     `hcl:"max_items"`
		Nested   hcl.Body `hcl:",remain"`
	}

	var args content
	diags := gohcl.DecodeBody(body, nil, &args)
	if diags.HasErrors() {
		return errSpec, diags
	}

	spec := &hcldec.BlockSetSpec{
		TypeName: impliedName,
	}

	if args.MinItems != nil {
		spec.MinItems = *args.MinItems
	}
	if args.MaxItems != nil {
		spec.MaxItems = *args.MaxItems
	}
	if args.TypeName != nil {
		spec.TypeName = *args.TypeName
	}

	nested, nestedDiags := decodeBlockNestedSpec(args.Nested)
	diags = append(diags, nestedDiags...)
	spec.Nested = nested

	if spec.TypeName == "" {
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Missing block_type in block_set spec",
			Detail:   "The block_type attribute is required, to specify the block type name that is expected in an input HCL file.",
			Subject:  body.MissingItemRange().Ptr(),
		})
		return errSpec, diags
	}

	return spec, diags
}

func decodeBlockMapSpec(body hcl.Body, impliedName string) (hcldec.Spec, hcl.Diagnostics) {
	type content struct {
		TypeName *string  `hcl:"block_type"`
		Labels   []string `hcl:"labels"`
		Nested   hcl.Body `hcl:",remain"`
	}

	var args content
	diags := gohcl.DecodeBody(body, nil, &args)
	if diags.HasErrors() {
		return errSpec, diags
	}

	spec := &hcldec.BlockMapSpec{
		TypeName: impliedName,
	}

	if args.TypeName != nil {
		spec.TypeName = *args.TypeName
	}
	spec.LabelNames = args.Labels

	nested, nestedDiags := decodeBlockNestedSpec(args.Nested)
	diags = append(diags, nestedDiags...)
	spec.Nested = nested

	if spec.TypeName == "" {
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Missing block_type in block_map spec",
			Detail:   "The block_type attribute is required, to specify the block type name that is expected in an input HCL file.",
			Subject:  body.MissingItemRange().Ptr(),
		})
		return errSpec, diags
	}
	if len(spec.LabelNames) < 1 {
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Invalid block label name list",
			Detail:   "A block_map must have at least one label specified.",
			Subject:  body.MissingItemRange().Ptr(),
		})
		return errSpec, diags
	}

	return spec, diags
}

func decodeBlockNestedSpec(body hcl.Body) (hcldec.Spec, hcl.Diagnostics) {
	content, diags := body.Content(specSchemaUnlabelled)

	if len(content.Blocks) == 0 {
		if diags.HasErrors() {
			// If we already have errors then they probably explain
			// why we have no blocks, so we'll skip our additional
			// error message added below.
			return errSpec, diags
		}

		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Missing spec block",
			Detail:   "A block spec must have exactly one child spec specifying how to decode block contents.",
			Subject:  body.MissingItemRange().Ptr(),
		})
		return errSpec, diags
	}

	if len(content.Blocks) > 1 {
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Extraneous spec block",
			Detail:   "A block spec must have exactly one child spec specifying how to decode block contents.",
			Subject:  &content.Blocks[1].DefRange,
		})
		return errSpec, diags
	}

	spec, specDiags := decodeSpecBlock(content.Blocks[0])
	diags = append(diags, specDiags...)
	return spec, diags
}

func decodeLiteralSpec(body hcl.Body) (hcldec.Spec, hcl.Diagnostics) {
	type content struct {
		Value cty.Value `hcl:"value"`
	}

	var args content
	diags := gohcl.DecodeBody(body, specCtx, &args)
	if diags.HasErrors() {
		return errSpec, diags
	}

	return &hcldec.LiteralSpec{
		Value: args.Value,
	}, diags
}

func decodeDefaultSpec(body hcl.Body) (hcldec.Spec, hcl.Diagnostics) {
	content, diags := body.Content(specSchemaUnlabelled)

	if len(content.Blocks) == 0 {
		if diags.HasErrors() {
			// If we already have errors then they probably explain
			// why we have no blocks, so we'll skip our additional
			// error message added below.
			return errSpec, diags
		}

		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Missing spec block",
			Detail:   "A default block must have at least one nested spec, each specifying a possible outcome.",
			Subject:  body.MissingItemRange().Ptr(),
		})
		return errSpec, diags
	}

	if len(content.Blocks) == 1 && !diags.HasErrors() {
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagWarning,
			Summary:  "Useless default block",
			Detail:   "A default block with only one spec is equivalent to using that spec alone.",
			Subject:  &content.Blocks[1].DefRange,
		})
	}

	var spec hcldec.Spec
	for _, block := range content.Blocks {
		candidateSpec, candidateDiags := decodeSpecBlock(block)
		diags = append(diags, candidateDiags...)
		if candidateDiags.HasErrors() {
			continue
		}

		if spec == nil {
			spec = candidateSpec
		} else {
			spec = &hcldec.DefaultSpec{
				Primary: spec,
				Default: candidateSpec,
			}
		}
	}

	return spec, diags
}

func decodeTransformSpec(body hcl.Body) (hcldec.Spec, hcl.Diagnostics) {
	type content struct {
		Result hcl.Expression `hcl:"result"`
		Nested hcl.Body       `hcl:",remain"`
	}

	var args content
	diags := gohcl.DecodeBody(body, nil, &args)
	if diags.HasErrors() {
		return errSpec, diags
	}

	spec := &hcldec.TransformExprSpec{
		Expr:         args.Result,
		VarName:      "nested",
		TransformCtx: specCtx,
	}

	nestedContent, nestedDiags := args.Nested.Content(specSchemaUnlabelled)
	diags = append(diags, nestedDiags...)

	if len(nestedContent.Blocks) != 1 {
		if nestedDiags.HasErrors() {
			// If we already have errors then they probably explain
			// why we have the wrong number of blocks, so we'll skip our
			// additional error message added below.
			return errSpec, diags
		}

		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Invalid transform spec",
			Detail:   "A transform spec block must have exactly one nested spec block.",
			Subject:  body.MissingItemRange().Ptr(),
		})
		return errSpec, diags
	}

	nestedSpec, nestedDiags := decodeSpecBlock(nestedContent.Blocks[0])
	diags = append(diags, nestedDiags...)
	spec.Wrapped = nestedSpec

	return spec, diags
}

var errSpec = &hcldec.LiteralSpec{
	Value: cty.NullVal(cty.DynamicPseudoType),
}

var specBlockTypes = []string{
	"object",
	"array",

	"literal",

	"attr",

	"block",
	"block_list",
	"block_map",
	"block_set",

	"default",
	"transform",
}

var specSchemaUnlabelled *hcl.BodySchema
var specSchemaLabelled *hcl.BodySchema

var specSchemaLabelledLabels = []string{"key"}

func init() {
	specSchemaLabelled = &hcl.BodySchema{
		Blocks: make([]hcl.BlockHeaderSchema, 0, len(specBlockTypes)),
	}
	specSchemaUnlabelled = &hcl.BodySchema{
		Blocks: make([]hcl.BlockHeaderSchema, 0, len(specBlockTypes)),
	}

	for _, name := range specBlockTypes {
		specSchemaLabelled.Blocks = append(
			specSchemaLabelled.Blocks,
			hcl.BlockHeaderSchema{
				Type:       name,
				LabelNames: specSchemaLabelledLabels,
			},
		)
		specSchemaUnlabelled.Blocks = append(
			specSchemaUnlabelled.Blocks,
			hcl.BlockHeaderSchema{
				Type: name,
			},
		)
	}
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/iam_policy_model.go<|end_filename|>
package aws

import (
	"encoding/json"
	"sort"
)

type IAMPolicyDoc struct {
	Version    string                `json:",omitempty"`
	Id         string                `json:",omitempty"`
	Statements []*IAMPolicyStatement `json:"Statement"`
}

type IAMPolicyStatement struct {
	Sid           string
	Effect        string                         `json:",omitempty"`
	Actions       interface{}                    `json:"Action,omitempty"`
	NotActions    interface{}                    `json:"NotAction,omitempty"`
	Resources     interface{}                    `json:"Resource,omitempty"`
	NotResources  interface{}                    `json:"NotResource,omitempty"`
	Principals    IAMPolicyStatementPrincipalSet `json:"Principal,omitempty"`
	NotPrincipals IAMPolicyStatementPrincipalSet `json:"NotPrincipal,omitempty"`
	Conditions    IAMPolicyStatementConditionSet `json:"Condition,omitempty"`
}

type IAMPolicyStatementPrincipal struct {
	Type        string
	Identifiers interface{}
}

type IAMPolicyStatementCondition struct {
	Test     string
	Variable string
	Values   interface{}
}

type IAMPolicyStatementPrincipalSet []IAMPolicyStatementPrincipal
type IAMPolicyStatementConditionSet []IAMPolicyStatementCondition

func (ps IAMPolicyStatementPrincipalSet) MarshalJSON() ([]byte, error) {
	raw := map[string]interface{}{}

	// As a special case, IAM considers the string value "*" to be
	// equivalent to "AWS": "*", and normalizes policies as such.
	// We'll follow their lead and do the same normalization here.
	// IAM also considers {"*": "*"} to be equivalent to this.
	if len(ps) == 1 {
		p := ps[0]
		if p.Type == "AWS" || p.Type == "*" {
			if sv, ok := p.Identifiers.(string); ok && sv == "*" {
				return []byte(`"*"`), nil
			}

			if av, ok := p.Identifiers.([]string); ok && len(av) == 1 && av[0] == "*" {
				return []byte(`"*"`), nil
			}
		}
	}

	for _, p := range ps {
		switch i := p.Identifiers.(type) {
		case []string:
			if _, ok := raw[p.Type]; !ok {
				raw[p.Type] = make([]string, 0, len(i))
			}
			sort.Sort(sort.Reverse(sort.StringSlice(i)))
			raw[p.Type] = append(raw[p.Type].([]string), i...)
		case string:
			raw[p.Type] = i
		default:
			panic("Unsupported data type for IAMPolicyStatementPrincipalSet")
		}
	}

	return json.Marshal(&raw)
}

func (cs IAMPolicyStatementConditionSet) MarshalJSON() ([]byte, error) {
	raw := map[string]map[string]interface{}{}

	for _, c := range cs {
		if _, ok := raw[c.Test]; !ok {
			raw[c.Test] = map[string]interface{}{}
		}
		switch i := c.Values.(type) {
		case []string:
			if _, ok := raw[c.Test][c.Variable]; !ok {
				raw[c.Test][c.Variable] = make([]string, 0, len(i))
			}
			sort.Sort(sort.Reverse(sort.StringSlice(i)))
			raw[c.Test][c.Variable] = append(raw[c.Test][c.Variable].([]string), i...)
		case string:
			raw[c.Test][c.Variable] = i
		default:
			panic("Unsupported data type for IAMPolicyStatementConditionSet")
		}
	}

	return json.Marshal(&raw)
}

func iamPolicyDecodeConfigStringList(lI []interface{}) interface{} {
	if len(lI) == 1 {
		return lI[0].(string)
	}
	ret := make([]string, len(lI))
	for i, vI := range lI {
		ret[i] = vI.(string)
	}
	sort.Sort(sort.Reverse(sort.StringSlice(ret)))
	return ret
}


<|start_filename|>vendor/github.com/hashicorp/hcl2/hcldec/variables_test.go<|end_filename|>
package hcldec

import (
	"fmt"
	"reflect"
	"testing"

	"github.com/hashicorp/hcl2/hcl/hclsyntax"
	"github.com/hashicorp/hcl2/hcl"
)

func TestVariables(t *testing.T) {
	tests := []struct {
		config string
		spec   Spec
		want   []hcl.Traversal
	}{
		{
			``,
			&ObjectSpec{},
			nil,
		},
		{
			"a = foo\n",
			&ObjectSpec{},
			nil, // "a" is not actually used, so "foo" is not required
		},
		{
			"a = foo\n",
			&AttrSpec{
				Name: "a",
			},
			[]hcl.Traversal{
				{
					hcl.TraverseRoot{
						Name: "foo",
						SrcRange: hcl.Range{
							Start: hcl.Pos{Line: 1, Column: 5, Byte: 4},
							End:   hcl.Pos{Line: 1, Column: 8, Byte: 7},
						},
					},
				},
			},
		},
		{
			"a = foo\n",
			&ObjectSpec{
				"a": &AttrSpec{
					Name: "a",
				},
			},
			[]hcl.Traversal{
				{
					hcl.TraverseRoot{
						Name: "foo",
						SrcRange: hcl.Range{
							Start: hcl.Pos{Line: 1, Column: 5, Byte: 4},
							End:   hcl.Pos{Line: 1, Column: 8, Byte: 7},
						},
					},
				},
			},
		},
		{
			`
b {
  a = foo
}
`,
			&BlockSpec{
				TypeName: "b",
				Nested: &AttrSpec{
					Name: "a",
				},
			},
			[]hcl.Traversal{
				{
					hcl.TraverseRoot{
						Name: "foo",
						SrcRange: hcl.Range{
							Start: hcl.Pos{Line: 3, Column: 7, Byte: 11},
							End:   hcl.Pos{Line: 3, Column: 10, Byte: 14},
						},
					},
				},
			},
		},
		{
			`
b {
  a = foo
}
b {
  a = bar
}
c {
  a = baz
}
`,
			&BlockListSpec{
				TypeName: "b",
				Nested: &AttrSpec{
					Name: "a",
				},
			},
			[]hcl.Traversal{
				{
					hcl.TraverseRoot{
						Name: "foo",
						SrcRange: hcl.Range{
							Start: hcl.Pos{Line: 3, Column: 7, Byte: 11},
							End:   hcl.Pos{Line: 3, Column: 10, Byte: 14},
						},
					},
				},
				{
					hcl.TraverseRoot{
						Name: "bar",
						SrcRange: hcl.Range{
							Start: hcl.Pos{Line: 6, Column: 7, Byte: 27},
							End:   hcl.Pos{Line: 6, Column: 10, Byte: 30},
						},
					},
				},
			},
		},
	}

	for i, test := range tests {
		t.Run(fmt.Sprintf("%02d-%s", i, test.config), func(t *testing.T) {
			file, diags := hclsyntax.ParseConfig([]byte(test.config), "", hcl.Pos{Line: 1, Column: 1, Byte: 0})
			if len(diags) != 0 {
				t.Errorf("wrong number of diagnostics from ParseConfig %d; want %d", len(diags), 0)
				for _, diag := range diags {
					t.Logf(" - %s", diag.Error())
				}
			}
			body := file.Body

			got := Variables(body, test.spec)

			if !reflect.DeepEqual(got, test.want) {
				t.Errorf("wrong result\ngot:  %#v\nwant: %#v", got, test.want)
			}
		})
	}

}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/hashicorp/hcl2/hclwrite/tokens.go<|end_filename|>
package hclwrite

import (
	"bytes"
	"io"

	"github.com/apparentlymart/go-textseg/textseg"
	"github.com/hashicorp/hcl2/hcl/hclsyntax"
)

// TokenGen is an abstract type that can append tokens to a list. It is the
// low-level foundation underlying the zclwrite AST; the AST provides a
// convenient abstraction over raw token sequences to facilitate common tasks,
// but it's also possible to directly manipulate the tree of token generators
// to make changes that the AST API doesn't directly allow.
type TokenGen interface {
	EachToken(TokenCallback)
}

// TokenCallback is used with TokenGen implementations to specify the action
// that is to be taken for each token in the flattened token sequence.
type TokenCallback func(*Token)

// Token is a single sequence of bytes annotated with a type. It is similar
// in purpose to zclsyntax.Token, but discards the source position information
// since that is not useful in code generation.
type Token struct {
	Type  hclsyntax.TokenType
	Bytes []byte

	// We record the number of spaces before each token so that we can
	// reproduce the exact layout of the original file when we're making
	// surgical changes in-place. When _new_ code is created it will always
	// be in the canonical style, but we preserve layout of existing code.
	SpacesBefore int
}

// Tokens is a flat list of tokens.
type Tokens []*Token

func (ts Tokens) WriteTo(wr io.Writer) (int, error) {
	seq := &TokenSeq{ts}
	return seq.WriteTo(wr)
}

func (ts Tokens) Bytes() []byte {
	buf := &bytes.Buffer{}
	ts.WriteTo(buf)
	return buf.Bytes()
}

// Columns returns the number of columns (grapheme clusters) the token sequence
// occupies. The result is not meaningful if there are newline or single-line
// comment tokens in the sequence.
func (ts Tokens) Columns() int {
	ret := 0
	for _, token := range ts {
		ret += token.SpacesBefore // spaces are always worth one column each
		ct, _ := textseg.TokenCount(token.Bytes, textseg.ScanGraphemeClusters)
		ret += ct
	}
	return ret
}

// TokenSeq combines zero or more TokenGens together to produce a flat sequence
// of tokens from a tree of TokenGens.
type TokenSeq []TokenGen

func (t *Token) EachToken(cb TokenCallback) {
	cb(t)
}

func (ts Tokens) EachToken(cb TokenCallback) {
	for _, t := range ts {
		cb(t)
	}
}

func (ts *TokenSeq) EachToken(cb TokenCallback) {
	if ts == nil {
		return
	}
	for _, gen := range *ts {
		gen.EachToken(cb)
	}
}

// Tokens returns the flat list of tokens represented by the receiving
// token sequence.
func (ts *TokenSeq) Tokens() Tokens {
	var tokens Tokens
	ts.EachToken(func(token *Token) {
		tokens = append(tokens, token)
	})
	return tokens
}

// WriteTo takes an io.Writer and writes the bytes for each token to it,
// along with the spacing that separates each token. In other words, this
// allows serializing the tokens to a file or other such byte stream.
func (ts *TokenSeq) WriteTo(wr io.Writer) (int, error) {
	// We know we're going to be writing a lot of small chunks of repeated
	// space characters, so we'll prepare a buffer of these that we can
	// easily pass to wr.Write without any further allocation.
	spaces := make([]byte, 40)
	for i := range spaces {
		spaces[i] = ' '
	}

	var n int
	var err error
	ts.EachToken(func(token *Token) {
		if err != nil {
			return
		}

		for spacesBefore := token.SpacesBefore; spacesBefore > 0; spacesBefore -= len(spaces) {
			thisChunk := spacesBefore
			if thisChunk > len(spaces) {
				thisChunk = len(spaces)
			}
			var thisN int
			thisN, err = wr.Write(spaces[:thisChunk])
			n += thisN
			if err != nil {
				return
			}
		}

		var thisN int
		thisN, err = wr.Write(token.Bytes)
		n += thisN
	})

	return n, err
}

// SoloToken returns the single token represented by the receiving sequence,
// or nil if the sequence does not represent exactly one token.
func (ts *TokenSeq) SoloToken() *Token {
	var ret *Token
	found := false
	ts.EachToken(func(tok *Token) {
		if ret == nil && !found {
			ret = tok
			found = true
		} else if ret != nil && found {
			ret = nil
		}
	})
	return ret
}

// IsIdent returns true if and only if the token sequence represents a single
// ident token whose name matches the given string.
func (ts *TokenSeq) IsIdent(name []byte) bool {
	tok := ts.SoloToken()
	if tok == nil {
		return false
	}
	if tok.Type != hclsyntax.TokenIdent {
		return false
	}
	return bytes.Equal(tok.Bytes, name)
}

// TokenSeqEmpty is a TokenSeq that contains no tokens. It can be used anywhere,
// but its primary purpose is to be assigned as a replacement for a non-empty
// TokenSeq when eliminating a section of an input file.
var TokenSeqEmpty = TokenSeq([]TokenGen(nil))


<|start_filename|>vendor/github.com/mitchellh/packer/vendor/github.com/joyent/triton-go/compute/datacenters.go<|end_filename|>
//
// Copyright (c) 2018, Joyent, Inc. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

package compute

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"path"
	"sort"

	"github.com/joyent/triton-go/client"
	"github.com/joyent/triton-go/errors"
	pkgerrors "github.com/pkg/errors"
)

type DataCentersClient struct {
	client *client.Client
}

type DataCenter struct {
	Name string `json:"name"`
	URL  string `json:"url"`
}

type ListDataCentersInput struct{}

func (c *DataCentersClient) List(ctx context.Context, _ *ListDataCentersInput) ([]*DataCenter, error) {
	fullPath := path.Join("/", c.client.AccountName, "datacenters")

	reqInputs := client.RequestInput{
		Method: http.MethodGet,
		Path:   fullPath,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, pkgerrors.Wrap(err, "unable to list data centers")
	}

	var intermediate map[string]string
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&intermediate); err != nil {
		return nil, pkgerrors.Wrap(err, "unable to decode list data centers response")
	}

	keys := make([]string, len(intermediate))
	i := 0
	for k := range intermediate {
		keys[i] = k
		i++
	}
	sort.Strings(keys)

	result := make([]*DataCenter, len(intermediate))
	i = 0
	for _, key := range keys {
		result[i] = &DataCenter{
			Name: key,
			URL:  intermediate[key],
		}
		i++
	}

	return result, nil
}

type GetDataCenterInput struct {
	Name string
}

func (c *DataCentersClient) Get(ctx context.Context, input *GetDataCenterInput) (*DataCenter, error) {
	dcs, err := c.List(ctx, &ListDataCentersInput{})
	if err != nil {
		return nil, pkgerrors.Wrap(err, "unable to get data center")
	}

	for _, dc := range dcs {
		if dc.Name == input.Name {
			return &DataCenter{
				Name: input.Name,
				URL:  dc.URL,
			}, nil
		}
	}

	return nil, &errors.APIError{
		StatusCode: http.StatusNotFound,
		Code:       "ResourceNotFound",
		Message:    fmt.Sprintf("data center %q not found", input.Name),
	}
}


<|start_filename|>vendor/github.com/mitchellh/packer/packer/hook_test.go<|end_filename|>
package packer

import (
	"sync"
	"testing"
	"time"
)

// A helper Hook implementation for testing cancels.
type CancelHook struct {
	sync.Mutex
	cancelCh chan struct{}
	doneCh   chan struct{}

	Cancelled bool
}

func (h *CancelHook) Run(string, Ui, Communicator, interface{}) error {
	h.Lock()
	h.cancelCh = make(chan struct{})
	h.doneCh = make(chan struct{})
	h.Unlock()

	defer close(h.doneCh)

	select {
	case <-h.cancelCh:
		h.Cancelled = true
	case <-time.After(1 * time.Second):
	}

	return nil
}

func (h *CancelHook) Cancel() {
	h.Lock()
	close(h.cancelCh)
	h.Unlock()

	<-h.doneCh
}

func TestDispatchHook_Implements(t *testing.T) {
	var _ Hook = new(DispatchHook)
}

func TestDispatchHook_Run_NoHooks(t *testing.T) {
	// Just make sure nothing blows up
	dh := &DispatchHook{}
	dh.Run("foo", nil, nil, nil)
}

func TestDispatchHook_Run(t *testing.T) {
	hook := &MockHook{}

	mapping := make(map[string][]Hook)
	mapping["foo"] = []Hook{hook}
	dh := &DispatchHook{Mapping: mapping}
	dh.Run("foo", nil, nil, 42)

	if !hook.RunCalled {
		t.Fatal("should be called")
	}
	if hook.RunName != "foo" {
		t.Fatalf("bad: %s", hook.RunName)
	}
	if hook.RunData != 42 {
		t.Fatalf("bad: %#v", hook.RunData)
	}
}

func TestDispatchHook_cancel(t *testing.T) {
	hook := new(CancelHook)

	dh := &DispatchHook{
		Mapping: map[string][]Hook{
			"foo": {hook},
		},
	}

	go dh.Run("foo", nil, nil, 42)
	time.Sleep(100 * time.Millisecond)
	dh.Cancel()

	if !hook.Cancelled {
		t.Fatal("hook should've cancelled")
	}
}


<|start_filename|>vendor/github.com/hashicorp/terraform/terraform/user_agent.go<|end_filename|>
package terraform

import (
	"fmt"
	"runtime"

	"github.com/hashicorp/terraform/version"
)

// The standard Terraform User-Agent format
const UserAgent = "Terraform %s (%s)"

// Generate a UserAgent string
func UserAgentString() string {
	return fmt.Sprintf(UserAgent, version.String(), runtime.Version())
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_kms_alias.go<|end_filename|>
package aws

import (
	"fmt"
	"log"
	"regexp"
	"time"

	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/arn"
	"github.com/aws/aws-sdk-go/service/kms"
)

func resourceAwsKmsAlias() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsKmsAliasCreate,
		Read:   resourceAwsKmsAliasRead,
		Update: resourceAwsKmsAliasUpdate,
		Delete: resourceAwsKmsAliasDelete,

		Importer: &schema.ResourceImporter{
			State: resourceAwsKmsAliasImport,
		},

		Schema: map[string]*schema.Schema{
			"arn": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"name": {
				Type:          schema.TypeString,
				Optional:      true,
				ForceNew:      true,
				ConflictsWith: []string{"name_prefix"},
				ValidateFunc:  validateAwsKmsName,
			},
			"name_prefix": {
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				ValidateFunc: func(v interface{}, k string) (ws []string, es []error) {
					value := v.(string)
					if !regexp.MustCompile(`^(alias\/)[a-zA-Z0-9:/_-]+$`).MatchString(value) {
						es = append(es, fmt.Errorf(
							"%q must begin with 'alias/' and be comprised of only [a-zA-Z0-9:/_-]", k))
					}
					return
				},
			},
			"target_key_id": {
				Type:     schema.TypeString,
				Required: true,
			},
			"target_key_arn": {
				Type:     schema.TypeString,
				Computed: true,
			},
		},
	}
}

func resourceAwsKmsAliasCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).kmsconn

	var name string
	if v, ok := d.GetOk("name"); ok {
		name = v.(string)
	} else if v, ok := d.GetOk("name_prefix"); ok {
		name = resource.PrefixedUniqueId(v.(string))
	} else {
		name = resource.PrefixedUniqueId("alias/")
	}

	targetKeyId := d.Get("target_key_id").(string)

	log.Printf("[DEBUG] KMS alias create name: %s, target_key: %s", name, targetKeyId)

	req := &kms.CreateAliasInput{
		AliasName:   aws.String(name),
		TargetKeyId: aws.String(targetKeyId),
	}

	// KMS is eventually consistent
	_, err := retryOnAwsCode("NotFoundException", func() (interface{}, error) {
		return conn.CreateAlias(req)
	})
	if err != nil {
		return err
	}
	d.SetId(name)
	return resourceAwsKmsAliasRead(d, meta)
}

func resourceAwsKmsAliasRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).kmsconn

	var alias *kms.AliasListEntry
	var err error
	if d.IsNewResource() {
		alias, err = retryFindKmsAliasByName(conn, d.Id())
	} else {
		alias, err = findKmsAliasByName(conn, d.Id(), nil)
	}
	if err != nil {
		return err
	}
	if alias == nil {
		log.Printf("[DEBUG] Removing KMS Alias (%s) as it's already gone", d.Id())
		d.SetId("")
		return nil
	}

	log.Printf("[DEBUG] Found KMS Alias: %s", alias)

	d.Set("arn", alias.AliasArn)
	d.Set("target_key_id", alias.TargetKeyId)

	aliasARN, err := arn.Parse(*alias.AliasArn)
	if err != nil {
		return err
	}
	targetKeyARN := arn.ARN{
		Partition: aliasARN.Partition,
		Service:   aliasARN.Service,
		Region:    aliasARN.Region,
		AccountID: aliasARN.AccountID,
		Resource:  fmt.Sprintf("key/%s", *alias.TargetKeyId),
	}
	d.Set("target_key_arn", targetKeyARN.String())

	return nil
}

func resourceAwsKmsAliasUpdate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).kmsconn

	if d.HasChange("target_key_id") {
		err := resourceAwsKmsAliasTargetUpdate(conn, d)
		if err != nil {
			return err
		}
		return resourceAwsKmsAliasRead(d, meta)
	}
	return nil
}

func resourceAwsKmsAliasTargetUpdate(conn *kms.KMS, d *schema.ResourceData) error {
	name := d.Get("name").(string)
	targetKeyId := d.Get("target_key_id").(string)

	log.Printf("[DEBUG] KMS alias: %s, update target: %s", name, targetKeyId)

	req := &kms.UpdateAliasInput{
		AliasName:   aws.String(name),
		TargetKeyId: aws.String(targetKeyId),
	}
	_, err := conn.UpdateAlias(req)

	return err
}

func resourceAwsKmsAliasDelete(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).kmsconn

	req := &kms.DeleteAliasInput{
		AliasName: aws.String(d.Id()),
	}
	_, err := conn.DeleteAlias(req)
	if err != nil {
		return err
	}

	log.Printf("[DEBUG] KMS Alias: (%s) deleted.", d.Id())
	d.SetId("")
	return nil
}

func retryFindKmsAliasByName(conn *kms.KMS, name string) (*kms.AliasListEntry, error) {
	var resp *kms.AliasListEntry
	err := resource.Retry(1*time.Minute, func() *resource.RetryError {
		var err error
		resp, err = findKmsAliasByName(conn, name, nil)
		if err != nil {
			return resource.NonRetryableError(err)
		}
		if resp == nil {
			return resource.RetryableError(err)
		}
		return nil
	})
	return resp, err
}

// API by default limits results to 50 aliases
// This is how we make sure we won't miss any alias
// See http://docs.aws.amazon.com/kms/latest/APIReference/API_ListAliases.html
func findKmsAliasByName(conn *kms.KMS, name string, marker *string) (*kms.AliasListEntry, error) {
	req := kms.ListAliasesInput{
		Limit: aws.Int64(int64(100)),
	}
	if marker != nil {
		req.Marker = marker
	}

	log.Printf("[DEBUG] Listing KMS aliases: %s", req)
	resp, err := conn.ListAliases(&req)
	if err != nil {
		return nil, err
	}

	for _, entry := range resp.Aliases {
		if *entry.AliasName == name {
			return entry, nil
		}
	}
	if *resp.Truncated {
		log.Printf("[DEBUG] KMS alias list is truncated, listing more via %s", *resp.NextMarker)
		return findKmsAliasByName(conn, name, resp.NextMarker)
	}

	return nil, nil
}

func resourceAwsKmsAliasImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
	d.Set("name", d.Id())
	return []*schema.ResourceData{d}, nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_appautoscaling_scheduled_action.go<|end_filename|>
package aws

import (
	"fmt"
	"log"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/applicationautoscaling"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"
)

const awsAppautoscalingScheduleTimeLayout = "2006-01-02T15:04:05Z"

func resourceAwsAppautoscalingScheduledAction() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsAppautoscalingScheduledActionPut,
		Read:   resourceAwsAppautoscalingScheduledActionRead,
		Delete: resourceAwsAppautoscalingScheduledActionDelete,

		Schema: map[string]*schema.Schema{
			"name": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"service_namespace": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"resource_id": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"scalable_dimension": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
			},
			"scalable_target_action": &schema.Schema{
				Type:     schema.TypeList,
				Optional: true,
				ForceNew: true,
				MaxItems: 1,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"max_capacity": &schema.Schema{
							Type:     schema.TypeInt,
							Optional: true,
							ForceNew: true,
						},
						"min_capacity": &schema.Schema{
							Type:     schema.TypeInt,
							Optional: true,
							ForceNew: true,
						},
					},
				},
			},
			"schedule": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
			},
			"start_time": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
			},
			"end_time": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
			},
			"arn": &schema.Schema{
				Type:     schema.TypeString,
				Computed: true,
			},
		},
	}
}

func resourceAwsAppautoscalingScheduledActionPut(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).appautoscalingconn

	input := &applicationautoscaling.PutScheduledActionInput{
		ScheduledActionName: aws.String(d.Get("name").(string)),
		ServiceNamespace:    aws.String(d.Get("service_namespace").(string)),
		ResourceId:          aws.String(d.Get("resource_id").(string)),
	}
	if v, ok := d.GetOk("scalable_dimension"); ok {
		input.ScalableDimension = aws.String(v.(string))
	}
	if v, ok := d.GetOk("schedule"); ok {
		input.Schedule = aws.String(v.(string))
	}
	if v, ok := d.GetOk("scalable_target_action"); ok {
		sta := &applicationautoscaling.ScalableTargetAction{}
		raw := v.([]interface{})[0].(map[string]interface{})
		if max, ok := raw["max_capacity"]; ok {
			sta.MaxCapacity = aws.Int64(int64(max.(int)))
		}
		if min, ok := raw["min_capacity"]; ok {
			sta.MinCapacity = aws.Int64(int64(min.(int)))
		}
		input.ScalableTargetAction = sta
	}
	if v, ok := d.GetOk("start_time"); ok {
		t, err := time.Parse(awsAppautoscalingScheduleTimeLayout, v.(string))
		if err != nil {
			return fmt.Errorf("Error Parsing Appautoscaling Scheduled Action Start Time: %s", err.Error())
		}
		input.StartTime = aws.Time(t)
	}
	if v, ok := d.GetOk("end_time"); ok {
		t, err := time.Parse(awsAppautoscalingScheduleTimeLayout, v.(string))
		if err != nil {
			return fmt.Errorf("Error Parsing Appautoscaling Scheduled Action End Time: %s", err.Error())
		}
		input.EndTime = aws.Time(t)
	}

	err := resource.Retry(5*time.Minute, func() *resource.RetryError {
		_, err := conn.PutScheduledAction(input)
		if err != nil {
			if isAWSErr(err, applicationautoscaling.ErrCodeObjectNotFoundException, "") {
				return resource.RetryableError(err)
			}
			return resource.NonRetryableError(err)
		}
		return nil
	})

	if err != nil {
		return err
	}

	d.SetId(d.Get("name").(string) + "-" + d.Get("service_namespace").(string) + "-" + d.Get("resource_id").(string))
	return resourceAwsAppautoscalingScheduledActionRead(d, meta)
}

func resourceAwsAppautoscalingScheduledActionRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).appautoscalingconn

	saName := d.Get("name").(string)
	input := &applicationautoscaling.DescribeScheduledActionsInput{
		ScheduledActionNames: []*string{aws.String(saName)},
		ServiceNamespace:     aws.String(d.Get("service_namespace").(string)),
	}
	resp, err := conn.DescribeScheduledActions(input)
	if err != nil {
		return err
	}
	if len(resp.ScheduledActions) < 1 {
		log.Printf("[WARN] Application Autoscaling Scheduled Action (%s) not found, removing from state", d.Id())
		d.SetId("")
		return nil
	}
	if len(resp.ScheduledActions) != 1 {
		return fmt.Errorf("Expected 1 scheduled action under %s, found %d", saName, len(resp.ScheduledActions))
	}
	if *resp.ScheduledActions[0].ScheduledActionName != saName {
		return fmt.Errorf("Scheduled Action (%s) not found", saName)
	}
	d.Set("arn", resp.ScheduledActions[0].ScheduledActionARN)
	return nil
}

func resourceAwsAppautoscalingScheduledActionDelete(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).appautoscalingconn

	input := &applicationautoscaling.DeleteScheduledActionInput{
		ScheduledActionName: aws.String(d.Get("name").(string)),
		ServiceNamespace:    aws.String(d.Get("service_namespace").(string)),
		ResourceId:          aws.String(d.Get("resource_id").(string)),
	}
	if v, ok := d.GetOk("scalable_dimension"); ok {
		input.ScalableDimension = aws.String(v.(string))
	}
	_, err := conn.DeleteScheduledAction(input)
	if err != nil {
		if isAWSErr(err, applicationautoscaling.ErrCodeObjectNotFoundException, "") {
			log.Printf("[WARN] Application Autoscaling Scheduled Action (%s) already gone, removing from state", d.Id())
			d.SetId("")
			return nil
		}
		return err
	}
	d.SetId("")
	return nil
}


<|start_filename|>vendor/github.com/mitchellh/packer/vendor/github.com/joyent/triton-go/compute/volumes.go<|end_filename|>
//
// Copyright (c) 2018, Joyent, Inc. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

package compute

import (
	"context"
	"encoding/json"
	"net/http"
	"net/url"
	"path"

	"github.com/joyent/triton-go/client"
	"github.com/pkg/errors"
)

type VolumesClient struct {
	client *client.Client
}

type Volume struct {
	ID             string   `json:"id"`
	Name           string   `json:"name"`
	Owner          string   `json:"owner_uuid"`
	Type           string   `json:"type"`
	FileSystemPath string   `json:"filesystem_path"`
	Size           int64    `json:"size"`
	State          string   `json:"state"`
	Networks       []string `json:"networks"`
	Refs           []string `json:"refs"`
}

type ListVolumesInput struct {
	Name  string
	Size  string
	State string
	Type  string
}

func (c *VolumesClient) List(ctx context.Context, input *ListVolumesInput) ([]*Volume, error) {
	fullPath := path.Join("/", c.client.AccountName, "volumes")

	query := &url.Values{}
	if input.Name != "" {
		query.Set("name", input.Name)
	}
	if input.Size != "" {
		query.Set("size", input.Size)
	}
	if input.State != "" {
		query.Set("state", input.State)
	}
	if input.Type != "" {
		query.Set("type", input.Type)
	}

	reqInputs := client.RequestInput{
		Method: http.MethodGet,
		Path:   fullPath,
		Query:  query,
	}
	resp, err := c.client.ExecuteRequest(ctx, reqInputs)
	if resp != nil {
		defer resp.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to list volumes")
	}

	var result []*Volume
	decoder := json.NewDecoder(resp)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode list volumes response")
	}

	return result, nil
}

type CreateVolumeInput struct {
	Name     string
	Size     int64
	Networks []string
	Type     string
}

func (input *CreateVolumeInput) toAPI() map[string]interface{} {
	result := make(map[string]interface{}, 0)

	if input.Name != "" {
		result["name"] = input.Name
	}

	if input.Size != 0 {
		result["size"] = input.Size
	}

	if input.Type != "" {
		result["type"] = input.Type
	}

	if len(input.Networks) > 0 {
		result["networks"] = input.Networks
	}

	return result
}

func (c *VolumesClient) Create(ctx context.Context, input *CreateVolumeInput) (*Volume, error) {
	fullPath := path.Join("/", c.client.AccountName, "volumes")

	reqInputs := client.RequestInput{
		Method: http.MethodPost,
		Path:   fullPath,
		Body:   input.toAPI(),
	}
	resp, err := c.client.ExecuteRequest(ctx, reqInputs)
	if err != nil {
		return nil, errors.Wrap(err, "unable to create volume")
	}
	if resp != nil {
		defer resp.Close()
	}

	var result *Volume
	decoder := json.NewDecoder(resp)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode create volume response")
	}

	return result, nil
}

type DeleteVolumeInput struct {
	ID string
}

func (c *VolumesClient) Delete(ctx context.Context, input *DeleteVolumeInput) error {
	fullPath := path.Join("/", c.client.AccountName, "volumes", input.ID)
	reqInputs := client.RequestInput{
		Method: http.MethodDelete,
		Path:   fullPath,
	}
	resp, err := c.client.ExecuteRequestRaw(ctx, reqInputs)
	if err != nil {
		return errors.Wrap(err, "unable to delete volume")
	}
	if resp == nil {
		return errors.Wrap(err, "unable to delete volume")
	}
	if resp.Body != nil {
		defer resp.Body.Close()
	}
	if resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusGone {
		return nil
	}

	return nil
}

type GetVolumeInput struct {
	ID string
}

func (c *VolumesClient) Get(ctx context.Context, input *GetVolumeInput) (*Volume, error) {
	fullPath := path.Join("/", c.client.AccountName, "volumes", input.ID)
	reqInputs := client.RequestInput{
		Method: http.MethodGet,
		Path:   fullPath,
	}
	resp, err := c.client.ExecuteRequestRaw(ctx, reqInputs)
	if err != nil {
		return nil, errors.Wrap(err, "unable to get volume")
	}
	if resp == nil {
		return nil, errors.Wrap(err, "unable to get volume")
	}
	if resp.Body != nil {
		defer resp.Body.Close()
	}

	var result *Volume
	decoder := json.NewDecoder(resp.Body)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode get volume volume")
	}

	return result, nil
}

type UpdateVolumeInput struct {
	ID   string `json:"-"`
	Name string `json:"name"`
}

func (c *VolumesClient) Update(ctx context.Context, input *UpdateVolumeInput) error {
	fullPath := path.Join("/", c.client.AccountName, "volumes", input.ID)

	reqInputs := client.RequestInput{
		Method: http.MethodPost,
		Path:   fullPath,
		Body:   input,
	}
	resp, err := c.client.ExecuteRequest(ctx, reqInputs)
	if err != nil {
		return errors.Wrap(err, "unable to update volume")
	}
	if resp != nil {
		defer resp.Close()
	}

	return nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/communicator/ssh/provisioner.go<|end_filename|>
package ssh

import (
	"bytes"
	"encoding/pem"
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/hashicorp/terraform/communicator/shared"
	"github.com/hashicorp/terraform/terraform"
	"github.com/mitchellh/mapstructure"
	"github.com/xanzy/ssh-agent"
	"golang.org/x/crypto/ssh"
	"golang.org/x/crypto/ssh/agent"
)

const (
	// DefaultUser is used if there is no user given
	DefaultUser = "root"

	// DefaultPort is used if there is no port given
	DefaultPort = 22

	// DefaultScriptPath is used as the path to copy the file to
	// for remote execution if not provided otherwise.
	DefaultScriptPath = "/tmp/terraform_%RAND%.sh"

	// DefaultTimeout is used if there is no timeout given
	DefaultTimeout = 5 * time.Minute
)

// connectionInfo is decoded from the ConnInfo of the resource. These are the
// only keys we look at. If a PrivateKey is given, that is used instead
// of a password.
type connectionInfo struct {
	User       string
	Password   string
	PrivateKey string `mapstructure:"private_key"`
	Host       string
	Port       int
	Agent      bool
	Timeout    string
	ScriptPath string        `mapstructure:"script_path"`
	TimeoutVal time.Duration `mapstructure:"-"`

	BastionUser       string `mapstructure:"bastion_user"`
	BastionPassword   string `mapstructure:"bastion_password"`
	BastionPrivateKey string `mapstructure:"bastion_private_key"`
	BastionHost       string `mapstructure:"bastion_host"`
	BastionPort       int    `mapstructure:"bastion_port"`

	AgentIdentity string `mapstructure:"agent_identity"`
}

// parseConnectionInfo is used to convert the ConnInfo of the InstanceState into
// a ConnectionInfo struct
func parseConnectionInfo(s *terraform.InstanceState) (*connectionInfo, error) {
	connInfo := &connectionInfo{}
	decConf := &mapstructure.DecoderConfig{
		WeaklyTypedInput: true,
		Result:           connInfo,
	}
	dec, err := mapstructure.NewDecoder(decConf)
	if err != nil {
		return nil, err
	}
	if err := dec.Decode(s.Ephemeral.ConnInfo); err != nil {
		return nil, err
	}

	// To default Agent to true, we need to check the raw string, since the
	// decoded boolean can't represent "absence of config".
	//
	// And if SSH_AUTH_SOCK is not set, there's no agent to connect to, so we
	// shouldn't try.
	if s.Ephemeral.ConnInfo["agent"] == "" && os.Getenv("SSH_AUTH_SOCK") != "" {
		connInfo.Agent = true
	}

	if connInfo.User == "" {
		connInfo.User = DefaultUser
	}

	// Format the host if needed.
	// Needed for IPv6 support.
	connInfo.Host = shared.IpFormat(connInfo.Host)

	if connInfo.Port == 0 {
		connInfo.Port = DefaultPort
	}
	if connInfo.ScriptPath == "" {
		connInfo.ScriptPath = DefaultScriptPath
	}
	if connInfo.Timeout != "" {
		connInfo.TimeoutVal = safeDuration(connInfo.Timeout, DefaultTimeout)
	} else {
		connInfo.TimeoutVal = DefaultTimeout
	}

	// Default all bastion config attrs to their non-bastion counterparts
	if connInfo.BastionHost != "" {
		// Format the bastion host if needed.
		// Needed for IPv6 support.
		connInfo.BastionHost = shared.IpFormat(connInfo.BastionHost)

		if connInfo.BastionUser == "" {
			connInfo.BastionUser = connInfo.User
		}
		if connInfo.BastionPassword == "" {
			connInfo.BastionPassword = connInfo.Password
		}
		if connInfo.BastionPrivateKey == "" {
			connInfo.BastionPrivateKey = connInfo.PrivateKey
		}
		if connInfo.BastionPort == 0 {
			connInfo.BastionPort = connInfo.Port
		}
	}

	return connInfo, nil
}

// safeDuration returns either the parsed duration or a default value
func safeDuration(dur string, defaultDur time.Duration) time.Duration {
	d, err := time.ParseDuration(dur)
	if err != nil {
		log.Printf("Invalid duration '%s', using default of %s", dur, defaultDur)
		return defaultDur
	}
	return d
}

// prepareSSHConfig is used to turn the *ConnectionInfo provided into a
// usable *SSHConfig for client initialization.
func prepareSSHConfig(connInfo *connectionInfo) (*sshConfig, error) {
	sshAgent, err := connectToAgent(connInfo)
	if err != nil {
		return nil, err
	}

	sshConf, err := buildSSHClientConfig(sshClientConfigOpts{
		user:       connInfo.User,
		privateKey: connInfo.PrivateKey,
		password:   <PASSWORD>,
		sshAgent:   sshAgent,
	})
	if err != nil {
		return nil, err
	}

	var bastionConf *ssh.ClientConfig
	if connInfo.BastionHost != "" {
		bastionConf, err = buildSSHClientConfig(sshClientConfigOpts{
			user:       connInfo.BastionUser,
			privateKey: connInfo.BastionPrivateKey,
			password:   <PASSWORD>,
			sshAgent:   sshAgent,
		})
		if err != nil {
			return nil, err
		}
	}

	host := fmt.Sprintf("%s:%d", connInfo.Host, connInfo.Port)
	connectFunc := ConnectFunc("tcp", host)

	if bastionConf != nil {
		bastionHost := fmt.Sprintf("%s:%d", connInfo.BastionHost, connInfo.BastionPort)
		connectFunc = BastionConnectFunc("tcp", bastionHost, bastionConf, "tcp", host)
	}

	config := &sshConfig{
		config:     sshConf,
		connection: connectFunc,
		sshAgent:   sshAgent,
	}
	return config, nil
}

type sshClientConfigOpts struct {
	privateKey string
	password   string
	sshAgent   *sshAgent
	user       string
}

func buildSSHClientConfig(opts sshClientConfigOpts) (*ssh.ClientConfig, error) {
	conf := &ssh.ClientConfig{
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
		User:            opts.user,
	}

	if opts.privateKey != "" {
		pubKeyAuth, err := readPrivateKey(opts.privateKey)
		if err != nil {
			return nil, err
		}
		conf.Auth = append(conf.Auth, pubKeyAuth)
	}

	if opts.password != "" {
		conf.Auth = append(conf.Auth, ssh.Password(opts.password))
		conf.Auth = append(conf.Auth, ssh.KeyboardInteractive(
			PasswordKeyboardInteractive(opts.password)))
	}

	if opts.sshAgent != nil {
		conf.Auth = append(conf.Auth, opts.sshAgent.Auth())
	}

	return conf, nil
}

func readPrivateKey(pk string) (ssh.AuthMethod, error) {
	// We parse the private key on our own first so that we can
	// show a nicer error if the private key has a password.
	block, _ := pem.Decode([]byte(pk))
	if block == nil {
		return nil, fmt.Errorf("Failed to read key %q: no key found", pk)
	}
	if block.Headers["Proc-Type"] == "4,ENCRYPTED" {
		return nil, fmt.Errorf(
			"Failed to read key %q: password protected keys are\n"+
				"not supported. Please decrypt the key prior to use.", pk)
	}

	signer, err := ssh.ParsePrivateKey([]byte(pk))
	if err != nil {
		return nil, fmt.Errorf("Failed to parse key file %q: %s", pk, err)
	}

	return ssh.PublicKeys(signer), nil
}

func connectToAgent(connInfo *connectionInfo) (*sshAgent, error) {
	if connInfo.Agent != true {
		// No agent configured
		return nil, nil
	}

	agent, conn, err := sshagent.New()
	if err != nil {
		return nil, err
	}

	// connection close is handled over in Communicator
	return &sshAgent{
		agent: agent,
		conn:  conn,
		id:    connInfo.AgentIdentity,
	}, nil

}

// A tiny wrapper around an agent.Agent to expose the ability to close its
// associated connection on request.
type sshAgent struct {
	agent agent.Agent
	conn  net.Conn
	id    string
}

func (a *sshAgent) Close() error {
	if a.conn == nil {
		return nil
	}

	return a.conn.Close()
}

// make an attempt to either read the identity file or find a corresponding
// public key file using the typical openssh naming convention.
// This returns the public key in wire format, or nil when a key is not found.
func findIDPublicKey(id string) []byte {
	for _, d := range idKeyData(id) {
		signer, err := ssh.ParsePrivateKey(d)
		if err == nil {
			log.Println("[DEBUG] parsed id private key")
			pk := signer.PublicKey()
			return pk.Marshal()
		}

		// try it as a publicKey
		pk, err := ssh.ParsePublicKey(d)
		if err == nil {
			log.Println("[DEBUG] parsed id public key")
			return pk.Marshal()
		}

		// finally try it as an authorized key
		pk, _, _, _, err = ssh.ParseAuthorizedKey(d)
		if err == nil {
			log.Println("[DEBUG] parsed id authorized key")
			return pk.Marshal()
		}
	}

	return nil
}

// Try to read an id file using the id as the file path. Also read the .pub
// file if it exists, as the id file may be encrypted. Return only the file
// data read. We don't need to know what data came from which path, as we will
// try parsing each as a private key, a public key and an authorized key
// regardless.
func idKeyData(id string) [][]byte {
	idPath, err := filepath.Abs(id)
	if err != nil {
		return nil
	}

	var fileData [][]byte

	paths := []string{idPath}

	if !strings.HasSuffix(idPath, ".pub") {
		paths = append(paths, idPath+".pub")
	}

	for _, p := range paths {
		d, err := ioutil.ReadFile(p)
		if err != nil {
			log.Printf("[DEBUG] error reading %q: %s", p, err)
			continue
		}
		log.Printf("[DEBUG] found identity data at %q", p)
		fileData = append(fileData, d)
	}

	return fileData
}

// sortSigners moves a signer with an agent comment field matching the
// agent_identity to the head of the list when attempting authentication. This
// helps when there are more keys loaded in an agent than the host will allow
// attempts.
func (s *sshAgent) sortSigners(signers []ssh.Signer) {
	if s.id == "" || len(signers) < 2 {
		return
	}

	// if we can locate the public key, either by extracting it from the id or
	// locating the .pub file, then we can more easily determine an exact match
	idPk := findIDPublicKey(s.id)

	// if we have a signer with a connect field that matches the id, send that
	// first, otherwise put close matches at the front of the list.
	head := 0
	for i := range signers {
		pk := signers[i].PublicKey()
		k, ok := pk.(*agent.Key)
		if !ok {
			continue
		}

		// check for an exact match first
		if bytes.Equal(pk.Marshal(), idPk) || s.id == k.Comment {
			signers[0], signers[i] = signers[i], signers[0]
			break
		}

		// no exact match yet, move it to the front if it's close. The agent
		// may have loaded as a full filepath, while the config refers to it by
		// filename only.
		if strings.HasSuffix(k.Comment, s.id) {
			signers[head], signers[i] = signers[i], signers[head]
			head++
			continue
		}
	}

	ss := []string{}
	for _, signer := range signers {
		pk := signer.PublicKey()
		k := pk.(*agent.Key)
		ss = append(ss, k.Comment)
	}
}

func (s *sshAgent) Signers() ([]ssh.Signer, error) {
	signers, err := s.agent.Signers()
	if err != nil {
		return nil, err
	}

	s.sortSigners(signers)
	return signers, nil
}

func (a *sshAgent) Auth() ssh.AuthMethod {
	return ssh.PublicKeysCallback(a.Signers)
}

func (a *sshAgent) ForwardToAgent(client *ssh.Client) error {
	return agent.ForwardToAgent(client, a.agent)
}


<|start_filename|>vendor/github.com/mitchellh/packer/vendor/github.com/joyent/triton-go/network/network.go<|end_filename|>
//
// Copyright (c) 2018, Joyent, Inc. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

package network

import (
	"context"
	"encoding/json"
	"net/http"
	"path"

	"github.com/joyent/triton-go/client"
	"github.com/pkg/errors"
)

type Network struct {
	Id                  string            `json:"id"`
	Name                string            `json:"name"`
	Public              bool              `json:"public"`
	Fabric              bool              `json:"fabric"`
	Description         string            `json:"description"`
	Subnet              string            `json:"subnet"`
	ProvisioningStartIP string            `json:"provision_start_ip"`
	ProvisioningEndIP   string            `json:"provision_end_ip"`
	Gateway             string            `json:"gateway"`
	Resolvers           []string          `json:"resolvers"`
	Routes              map[string]string `json:"routes"`
	InternetNAT         bool              `json:"internet_nat"`
}

type ListInput struct{}

func (c *NetworkClient) List(ctx context.Context, _ *ListInput) ([]*Network, error) {
	fullPath := path.Join("/", c.Client.AccountName, "networks")
	reqInputs := client.RequestInput{
		Method: http.MethodGet,
		Path:   fullPath,
	}
	respReader, err := c.Client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to list networks")
	}

	var result []*Network
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode list networks response")
	}

	return result, nil
}

type GetInput struct {
	ID string
}

func (c *NetworkClient) Get(ctx context.Context, input *GetInput) (*Network, error) {
	fullPath := path.Join("/", c.Client.AccountName, "networks", input.ID)
	reqInputs := client.RequestInput{
		Method: http.MethodGet,
		Path:   fullPath,
	}
	respReader, err := c.Client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to get network")
	}

	var result *Network
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode get network response")
	}

	return result, nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_emr_instance_group.go<|end_filename|>
package aws

import (
	"errors"
	"log"
	"time"

	"fmt"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/emr"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"
)

var emrInstanceGroupNotFound = errors.New("No matching EMR Instance Group")

func resourceAwsEMRInstanceGroup() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsEMRInstanceGroupCreate,
		Read:   resourceAwsEMRInstanceGroupRead,
		Update: resourceAwsEMRInstanceGroupUpdate,
		Delete: resourceAwsEMRInstanceGroupDelete,
		Schema: map[string]*schema.Schema{
			"cluster_id": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"instance_type": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"instance_count": {
				Type:     schema.TypeInt,
				Optional: true,
				Default:  0,
			},
			"running_instance_count": {
				Type:     schema.TypeInt,
				Computed: true,
			},
			"status": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"name": {
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
			},
			"ebs_optimized": {
				Type:     schema.TypeBool,
				Optional: true,
				ForceNew: true,
			},
			"ebs_config": {
				Type:     schema.TypeSet,
				Optional: true,
				ForceNew: true,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"iops": {
							Type:     schema.TypeInt,
							Optional: true,
						},
						"size": {
							Type:     schema.TypeInt,
							Required: true,
						},
						"type": {
							Type:         schema.TypeString,
							Required:     true,
							ValidateFunc: validateAwsEmrEbsVolumeType,
						},
						"volumes_per_instance": {
							Type:     schema.TypeInt,
							Optional: true,
						},
					},
				},
			},
		},
	}
}

// Populates an emr.EbsConfiguration struct
func readEmrEBSConfig(d *schema.ResourceData) *emr.EbsConfiguration {
	result := &emr.EbsConfiguration{}
	if v, ok := d.GetOk("ebs_optimized"); ok {
		result.EbsOptimized = aws.Bool(v.(bool))
	}

	ebsConfigs := make([]*emr.EbsBlockDeviceConfig, 0)
	if rawConfig, ok := d.GetOk("ebs_config"); ok {
		configList := rawConfig.(*schema.Set).List()
		for _, config := range configList {
			conf := config.(map[string]interface{})
			ebs := &emr.EbsBlockDeviceConfig{}
			volumeSpec := &emr.VolumeSpecification{
				SizeInGB:   aws.Int64(int64(conf["size"].(int))),
				VolumeType: aws.String(conf["type"].(string)),
			}
			if v, ok := conf["iops"].(int); ok && v != 0 {
				volumeSpec.Iops = aws.Int64(int64(v))
			}
			if v, ok := conf["volumes_per_instance"].(int); ok && v != 0 {
				ebs.VolumesPerInstance = aws.Int64(int64(v))
			}
			ebs.VolumeSpecification = volumeSpec
			ebsConfigs = append(ebsConfigs, ebs)
		}
	}
	result.EbsBlockDeviceConfigs = ebsConfigs
	return result
}

func resourceAwsEMRInstanceGroupCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).emrconn

	clusterId := d.Get("cluster_id").(string)
	instanceType := d.Get("instance_type").(string)
	instanceCount := d.Get("instance_count").(int)
	groupName := d.Get("name").(string)

	ebsConfig := readEmrEBSConfig(d)

	params := &emr.AddInstanceGroupsInput{
		InstanceGroups: []*emr.InstanceGroupConfig{
			{
				InstanceRole:     aws.String("TASK"),
				InstanceCount:    aws.Int64(int64(instanceCount)),
				InstanceType:     aws.String(instanceType),
				Name:             aws.String(groupName),
				EbsConfiguration: ebsConfig,
			},
		},
		JobFlowId: aws.String(clusterId),
	}

	log.Printf("[DEBUG] Creating EMR task group params: %s", params)
	resp, err := conn.AddInstanceGroups(params)
	if err != nil {
		return err
	}

	log.Printf("[DEBUG] Created EMR task group finished: %#v", resp)
	if resp == nil || len(resp.InstanceGroupIds) == 0 {
		return fmt.Errorf("Error creating instance groups: no instance group returned")
	}
	d.SetId(*resp.InstanceGroupIds[0])

	return nil
}

func resourceAwsEMRInstanceGroupRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).emrconn
	group, err := fetchEMRInstanceGroup(conn, d.Get("cluster_id").(string), d.Id())
	if err != nil {
		switch err {
		case emrInstanceGroupNotFound:
			log.Printf("[DEBUG] EMR Instance Group (%s) not found, removing", d.Id())
			d.SetId("")
			return nil
		default:
			return err
		}
	}

	// Guard against the chance of fetchEMRInstanceGroup returning nil group but
	// not a emrInstanceGroupNotFound error
	if group == nil {
		log.Printf("[DEBUG] EMR Instance Group (%s) not found, removing", d.Id())
		d.SetId("")
		return nil
	}

	d.Set("name", group.Name)
	d.Set("instance_count", group.RequestedInstanceCount)
	d.Set("running_instance_count", group.RunningInstanceCount)
	d.Set("instance_type", group.InstanceType)
	if group.Status != nil && group.Status.State != nil {
		d.Set("status", group.Status.State)
	}

	return nil
}

func fetchAllEMRInstanceGroups(conn *emr.EMR, clusterId string) ([]*emr.InstanceGroup, error) {
	req := &emr.ListInstanceGroupsInput{
		ClusterId: aws.String(clusterId),
	}

	var groups []*emr.InstanceGroup
	marker := aws.String("intitial")
	for marker != nil {
		log.Printf("[DEBUG] EMR Cluster Instance Marker: %s", *marker)
		respGrps, errGrps := conn.ListInstanceGroups(req)
		if errGrps != nil {
			return nil, fmt.Errorf("[ERR] Error reading EMR cluster (%s): %s", clusterId, errGrps)
		}
		if respGrps == nil {
			return nil, fmt.Errorf("[ERR] Error reading EMR Instance Group for cluster (%s)", clusterId)
		}

		if respGrps.InstanceGroups != nil {
			for _, g := range respGrps.InstanceGroups {
				groups = append(groups, g)
			}
		} else {
			log.Printf("[DEBUG] EMR Instance Group list was empty")
		}
		marker = respGrps.Marker
	}

	if len(groups) == 0 {
		return nil, fmt.Errorf("[WARN] No instance groups found for EMR Cluster (%s)", clusterId)
	}

	return groups, nil
}

func fetchEMRInstanceGroup(conn *emr.EMR, clusterId, groupId string) (*emr.InstanceGroup, error) {
	groups, err := fetchAllEMRInstanceGroups(conn, clusterId)
	if err != nil {
		return nil, err
	}

	var group *emr.InstanceGroup
	for _, ig := range groups {
		if groupId == *ig.Id {
			group = ig
			break
		}
	}

	if group != nil {
		return group, nil
	}

	return nil, emrInstanceGroupNotFound
}

func resourceAwsEMRInstanceGroupUpdate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).emrconn

	log.Printf("[DEBUG] Modify EMR task group")
	instanceCount := d.Get("instance_count").(int)

	params := &emr.ModifyInstanceGroupsInput{
		InstanceGroups: []*emr.InstanceGroupModifyConfig{
			{
				InstanceGroupId: aws.String(d.Id()),
				InstanceCount:   aws.Int64(int64(instanceCount)),
			},
		},
	}

	_, err := conn.ModifyInstanceGroups(params)
	if err != nil {
		return err
	}

	stateConf := &resource.StateChangeConf{
		Pending:    []string{"PROVISIONING", "BOOTSTRAPPING", "RESIZING"},
		Target:     []string{"RUNNING"},
		Refresh:    instanceGroupStateRefresh(conn, d.Get("cluster_id").(string), d.Id()),
		Timeout:    10 * time.Minute,
		Delay:      10 * time.Second,
		MinTimeout: 3 * time.Second,
	}

	_, err = stateConf.WaitForState()
	if err != nil {
		return fmt.Errorf(
			"Error waiting for instance (%s) to terminate: %s", d.Id(), err)
	}

	return resourceAwsEMRInstanceGroupRead(d, meta)
}

func instanceGroupStateRefresh(conn *emr.EMR, clusterID, igID string) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		group, err := fetchEMRInstanceGroup(conn, clusterID, igID)
		if err != nil {
			return nil, "Not Found", err
		}

		if group.Status == nil || group.Status.State == nil {
			log.Printf("[WARN] ERM Instance Group found, but without state")
			return nil, "Undefined", fmt.Errorf("Undefined EMR Cluster Instance Group state")
		}

		return group, *group.Status.State, nil
	}
}

func resourceAwsEMRInstanceGroupDelete(d *schema.ResourceData, meta interface{}) error {
	log.Printf("[WARN] AWS EMR Instance Group does not support DELETE; resizing cluster to zero before removing from state")
	conn := meta.(*AWSClient).emrconn
	params := &emr.ModifyInstanceGroupsInput{
		InstanceGroups: []*emr.InstanceGroupModifyConfig{
			{
				InstanceGroupId: aws.String(d.Id()),
				InstanceCount:   aws.Int64(0),
			},
		},
	}

	_, err := conn.ModifyInstanceGroups(params)
	if err != nil {
		return err
	}
	return nil
}


<|start_filename|>vendor/github.com/mitchellh/packer/vendor/github.com/hashicorp/atlas-go/v1/build_config.go<|end_filename|>
package atlas

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
)

// bcWrapper is the API wrapper since the server wraps the resulting object.
type bcWrapper struct {
	BuildConfig *BuildConfig `json:"build_configuration"`
}

// Atlas expects a list of key/value vars
type BuildVar struct {
	Key       string `json:"key"`
	Value     string `json:"value"`
	Sensitive bool   `json:"sensitive"`
}
type BuildVars []BuildVar

// BuildConfig represents a Packer build configuration.
type BuildConfig struct {
	// User is the namespace under which the build config lives
	User string `json:"username"`

	// Name is the actual name of the build config, unique in the scope
	// of the username.
	Name string `json:"name"`
}

// Slug returns the slug format for this BuildConfig (User/Name)
func (b *BuildConfig) Slug() string {
	return fmt.Sprintf("%s/%s", b.User, b.Name)
}

// BuildConfigVersion represents a single uploaded (or uploadable) version
// of a build configuration.
type BuildConfigVersion struct {
	// The fields below are the username/name combo to uniquely identify
	// a build config.
	User string `json:"username"`
	Name string `json:"name"`

	// Builds is the list of builds that this version supports.
	Builds []BuildConfigBuild
}

// Slug returns the slug format for this BuildConfigVersion (User/Name)
func (bv *BuildConfigVersion) Slug() string {
	return fmt.Sprintf("%s/%s", bv.User, bv.Name)
}

// BuildConfigBuild is a single build that is present in an uploaded
// build configuration.
type BuildConfigBuild struct {
	// Name is a unique name for this build
	Name string `json:"name"`

	// Type is the type of builder that this build needs to run on,
	// such as "amazon-ebs" or "qemu".
	Type string `json:"type"`

	// Artifact is true if this build results in one or more artifacts
	// being sent to Atlas
	Artifact bool `json:"artifact"`
}

// BuildConfig gets a single build configuration by user and name.
func (c *Client) BuildConfig(user, name string) (*BuildConfig, error) {
	log.Printf("[INFO] getting build configuration %s/%s", user, name)

	endpoint := fmt.Sprintf("/api/v1/packer/build-configurations/%s/%s", user, name)
	request, err := c.Request("GET", endpoint, nil)
	if err != nil {
		return nil, err
	}

	response, err := checkResp(c.HTTPClient.Do(request))
	if err != nil {
		return nil, err
	}

	var bc BuildConfig
	if err := decodeJSON(response, &bc); err != nil {
		return nil, err
	}

	return &bc, nil
}

// CreateBuildConfig creates a new build configuration.
func (c *Client) CreateBuildConfig(user, name string) (*BuildConfig, error) {
	log.Printf("[INFO] creating build configuration %s/%s", user, name)

	endpoint := "/api/v1/packer/build-configurations"
	body, err := json.Marshal(&bcWrapper{
		BuildConfig: &BuildConfig{
			User: user,
			Name: name,
		},
	})
	if err != nil {
		return nil, err
	}

	request, err := c.Request("POST", endpoint, &RequestOptions{
		Body: bytes.NewReader(body),
		Headers: map[string]string{
			"Content-Type": "application/json",
		},
	})
	if err != nil {
		return nil, err
	}

	response, err := checkResp(c.HTTPClient.Do(request))
	if err != nil {
		return nil, err
	}

	var bc BuildConfig
	if err := decodeJSON(response, &bc); err != nil {
		return nil, err
	}

	return &bc, nil
}

// UploadBuildConfigVersion creates a single build configuration version
// and uploads the template associated with it.
//
// Actual API: "Create Build Config Version"
func (c *Client) UploadBuildConfigVersion(v *BuildConfigVersion, metadata map[string]interface{},
	vars BuildVars, data io.Reader, size int64) error {

	log.Printf("[INFO] uploading build configuration version %s (%d bytes), with metadata %q",
		v.Slug(), size, metadata)

	endpoint := fmt.Sprintf("/api/v1/packer/build-configurations/%s/%s/versions",
		v.User, v.Name)

	var bodyData bcCreateWrapper
	bodyData.Version.Builds = v.Builds
	bodyData.Version.Metadata = metadata
	bodyData.Version.Vars = vars
	body, err := json.Marshal(bodyData)
	if err != nil {
		return err
	}

	request, err := c.Request("POST", endpoint, &RequestOptions{
		Body: bytes.NewReader(body),
		Headers: map[string]string{
			"Content-Type": "application/json",
		},
	})
	if err != nil {
		return err
	}

	response, err := checkResp(c.HTTPClient.Do(request))
	if err != nil {
		return err
	}

	var bv bcCreate
	if err := decodeJSON(response, &bv); err != nil {
		return err
	}

	if err := c.putFile(bv.UploadPath, data, size); err != nil {
		return err
	}

	return nil
}

// bcCreate is the struct returned when creating a build configuration.
type bcCreate struct {
	UploadPath string `json:"upload_path"`
}

// bcCreateWrapper is the wrapper for creating a build config.
type bcCreateWrapper struct {
	Version struct {
		Metadata map[string]interface{} `json:"metadata,omitempty"`
		Builds   []BuildConfigBuild     `json:"builds"`
		Vars     BuildVars              `json:"packer_vars,omitempty"`
	} `json:"version"`
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/hashicorp/hcl2/hcl/hclsyntax/doc.go<|end_filename|>
// Package hclsyntax contains the parser, AST, etc for zcl's native language,
// as opposed to the JSON variant.
//
// In normal use applications should rarely depend on this package directly,
// instead preferring the higher-level interface of the main hcl package and
// its companion hclparse.
package hclsyntax


<|start_filename|>vendor/github.com/mitchellh/packer/vendor/github.com/joyent/triton-go/network/fabrics.go<|end_filename|>
//
// Copyright (c) 2018, Joyent, Inc. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

package network

import (
	"context"
	"encoding/json"
	"net/http"
	"path"
	"strconv"

	"github.com/joyent/triton-go/client"
	"github.com/pkg/errors"
)

type FabricsClient struct {
	client *client.Client
}

type FabricVLAN struct {
	Name        string `json:"name"`
	ID          int    `json:"vlan_id"`
	Description string `json:"description"`
}

type ListVLANsInput struct{}

func (c *FabricsClient) ListVLANs(ctx context.Context, _ *ListVLANsInput) ([]*FabricVLAN, error) {
	fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans")
	reqInputs := client.RequestInput{
		Method: http.MethodGet,
		Path:   fullPath,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to list VLANs")
	}

	var result []*FabricVLAN
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode list VLANs response")
	}

	return result, nil
}

type CreateVLANInput struct {
	Name        string `json:"name"`
	ID          int    `json:"vlan_id"`
	Description string `json:"description,omitempty"`
}

func (c *FabricsClient) CreateVLAN(ctx context.Context, input *CreateVLANInput) (*FabricVLAN, error) {
	fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans")
	reqInputs := client.RequestInput{
		Method: http.MethodPost,
		Path:   fullPath,
		Body:   input,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to create VLAN")
	}

	var result *FabricVLAN
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode create VLAN response")
	}

	return result, nil
}

type UpdateVLANInput struct {
	ID          int    `json:"-"`
	Name        string `json:"name"`
	Description string `json:"description"`
}

func (c *FabricsClient) UpdateVLAN(ctx context.Context, input *UpdateVLANInput) (*FabricVLAN, error) {
	fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.ID))
	reqInputs := client.RequestInput{
		Method: http.MethodPut,
		Path:   fullPath,
		Body:   input,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to update VLAN")
	}

	var result *FabricVLAN
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode update VLAN response")
	}

	return result, nil
}

type GetVLANInput struct {
	ID int `json:"-"`
}

func (c *FabricsClient) GetVLAN(ctx context.Context, input *GetVLANInput) (*FabricVLAN, error) {
	fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.ID))
	reqInputs := client.RequestInput{
		Method: http.MethodGet,
		Path:   fullPath,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to get VLAN")
	}

	var result *FabricVLAN
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode get VLAN response")
	}

	return result, nil
}

type DeleteVLANInput struct {
	ID int `json:"-"`
}

func (c *FabricsClient) DeleteVLAN(ctx context.Context, input *DeleteVLANInput) error {
	fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.ID))
	reqInputs := client.RequestInput{
		Method: http.MethodDelete,
		Path:   fullPath,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return errors.Wrap(err, "unable to delete VLAN")
	}

	return nil
}

type ListFabricsInput struct {
	FabricVLANID int `json:"-"`
}

func (c *FabricsClient) List(ctx context.Context, input *ListFabricsInput) ([]*Network, error) {
	fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.FabricVLANID), "networks")
	reqInputs := client.RequestInput{
		Method: http.MethodGet,
		Path:   fullPath,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to list fabrics")
	}

	var result []*Network
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode list fabrics response")
	}

	return result, nil
}

type CreateFabricInput struct {
	FabricVLANID     int               `json:"-"`
	Name             string            `json:"name"`
	Description      string            `json:"description,omitempty"`
	Subnet           string            `json:"subnet"`
	ProvisionStartIP string            `json:"provision_start_ip"`
	ProvisionEndIP   string            `json:"provision_end_ip"`
	Gateway          string            `json:"gateway,omitempty"`
	Resolvers        []string          `json:"resolvers,omitempty"`
	Routes           map[string]string `json:"routes,omitempty"`
	InternetNAT      bool              `json:"internet_nat"`
}

func (c *FabricsClient) Create(ctx context.Context, input *CreateFabricInput) (*Network, error) {
	fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.FabricVLANID), "networks")
	reqInputs := client.RequestInput{
		Method: http.MethodPost,
		Path:   fullPath,
		Body:   input,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to create fabric")
	}

	var result *Network
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode create fabric response")
	}

	return result, nil
}

type GetFabricInput struct {
	FabricVLANID int    `json:"-"`
	NetworkID    string `json:"-"`
}

func (c *FabricsClient) Get(ctx context.Context, input *GetFabricInput) (*Network, error) {
	fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.FabricVLANID), "networks", input.NetworkID)
	reqInputs := client.RequestInput{
		Method: http.MethodGet,
		Path:   fullPath,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to get fabric")
	}

	var result *Network
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode get fabric response")
	}

	return result, nil
}

type DeleteFabricInput struct {
	FabricVLANID int    `json:"-"`
	NetworkID    string `json:"-"`
}

func (c *FabricsClient) Delete(ctx context.Context, input *DeleteFabricInput) error {
	fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.FabricVLANID), "networks", input.NetworkID)
	reqInputs := client.RequestInput{
		Method: http.MethodDelete,
		Path:   fullPath,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return errors.Wrap(err, "unable to delete fabric")
	}

	return nil
}


<|start_filename|>vendor/github.com/mitchellh/packer/vendor/github.com/approvals/go-approval-tests/reporters/all_failing.go<|end_filename|>
package reporters

var (
	clipboardScratchData = ""
)

type allFailing struct{}

// NewAllFailingTestReporter copies move file command to your clipboard
func NewAllFailingTestReporter() Reporter {
	return &allFailing{}
}

func (s *allFailing) Report(approved, received string) bool {
	move := getMoveCommandText(approved, received)
	clipboardScratchData = clipboardScratchData + move + "\n"
	return copyToClipboard(clipboardScratchData)
}


<|start_filename|>vendor/github.com/hashicorp/terraform/backend/local/backend_plan.go<|end_filename|>
package local

import (
	"bytes"
	"context"
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/hashicorp/errwrap"
	"github.com/hashicorp/go-multierror"
	"github.com/hashicorp/terraform/backend"
	"github.com/hashicorp/terraform/command/clistate"
	"github.com/hashicorp/terraform/command/format"
	"github.com/hashicorp/terraform/config/module"
	"github.com/hashicorp/terraform/state"
	"github.com/hashicorp/terraform/terraform"
)

func (b *Local) opPlan(
	ctx context.Context,
	op *backend.Operation,
	runningOp *backend.RunningOperation) {
	log.Printf("[INFO] backend/local: starting Plan operation")

	if b.CLI != nil && op.Plan != nil {
		b.CLI.Output(b.Colorize().Color(
			"[reset][bold][yellow]" +
				"The plan command received a saved plan file as input. This command\n" +
				"will output the saved plan. This will not modify the already-existing\n" +
				"plan. If you wish to generate a new plan, please pass in a configuration\n" +
				"directory as an argument.\n\n"))
	}

	// A local plan requires either a plan or a module
	if op.Plan == nil && op.Module == nil && !op.Destroy {
		runningOp.Err = fmt.Errorf(strings.TrimSpace(planErrNoConfig))
		return
	}

	// If we have a nil module at this point, then set it to an empty tree
	// to avoid any potential crashes.
	if op.Module == nil {
		op.Module = module.NewEmptyTree()
	}

	// Setup our count hook that keeps track of resource changes
	countHook := new(CountHook)
	if b.ContextOpts == nil {
		b.ContextOpts = new(terraform.ContextOpts)
	}
	old := b.ContextOpts.Hooks
	defer func() { b.ContextOpts.Hooks = old }()
	b.ContextOpts.Hooks = append(b.ContextOpts.Hooks, countHook)

	// Get our context
	tfCtx, opState, err := b.context(op)
	if err != nil {
		runningOp.Err = err
		return
	}

	if op.LockState {
		lockCtx, cancel := context.WithTimeout(ctx, op.StateLockTimeout)
		defer cancel()

		lockInfo := state.NewLockInfo()
		lockInfo.Operation = op.Type.String()
		lockID, err := clistate.Lock(lockCtx, opState, lockInfo, b.CLI, b.Colorize())
		if err != nil {
			runningOp.Err = errwrap.Wrapf("Error locking state: {{err}}", err)
			return
		}

		defer func() {
			if err := clistate.Unlock(opState, lockID, b.CLI, b.Colorize()); err != nil {
				runningOp.Err = multierror.Append(runningOp.Err, err)
			}
		}()
	}

	// Setup the state
	runningOp.State = tfCtx.State()

	// If we're refreshing before plan, perform that
	if op.PlanRefresh {
		log.Printf("[INFO] backend/local: plan calling Refresh")

		if b.CLI != nil {
			b.CLI.Output(b.Colorize().Color(strings.TrimSpace(planRefreshing) + "\n"))
		}

		_, err := tfCtx.Refresh()
		if err != nil {
			runningOp.Err = errwrap.Wrapf("Error refreshing state: {{err}}", err)
			return
		}
		if b.CLI != nil {
			b.CLI.Output("\n------------------------------------------------------------------------")
		}
	}

	// Perform the plan in a goroutine so we can be interrupted
	var plan *terraform.Plan
	var planErr error
	doneCh := make(chan struct{})
	go func() {
		defer close(doneCh)
		log.Printf("[INFO] backend/local: plan calling Plan")
		plan, planErr = tfCtx.Plan()
	}()

	select {
	case <-ctx.Done():
		if b.CLI != nil {
			b.CLI.Output("stopping plan operation...")
		}

		// Stop execution
		go tfCtx.Stop()

		// Wait for completion still
		<-doneCh
	case <-doneCh:
	}

	if planErr != nil {
		runningOp.Err = errwrap.Wrapf("Error running plan: {{err}}", planErr)
		return
	}
	// Record state
	runningOp.PlanEmpty = plan.Diff.Empty()

	// Save the plan to disk
	if path := op.PlanOutPath; path != "" {
		// Write the backend if we have one
		plan.Backend = op.PlanOutBackend

		// This works around a bug (#12871) which is no longer possible to
		// trigger but will exist for already corrupted upgrades.
		if plan.Backend != nil && plan.State != nil {
			plan.State.Remote = nil
		}

		log.Printf("[INFO] backend/local: writing plan output to: %s", path)
		f, err := os.Create(path)
		if err == nil {
			err = terraform.WritePlan(plan, f)
		}
		f.Close()
		if err != nil {
			runningOp.Err = fmt.Errorf("Error writing plan file: %s", err)
			return
		}
	}

	// Perform some output tasks if we have a CLI to output to.
	if b.CLI != nil {
		dispPlan := format.NewPlan(plan)
		if dispPlan.Empty() {
			b.CLI.Output("\n" + b.Colorize().Color(strings.TrimSpace(planNoChanges)))
			return
		}

		b.renderPlan(dispPlan)

		// Give the user some next-steps, unless we're running in an automation
		// tool which is presumed to provide its own UI for further actions.
		if !b.RunningInAutomation {

			b.CLI.Output("\n------------------------------------------------------------------------")

			if path := op.PlanOutPath; path == "" {
				b.CLI.Output(fmt.Sprintf(
					"\n" + strings.TrimSpace(planHeaderNoOutput) + "\n",
				))
			} else {
				b.CLI.Output(fmt.Sprintf(
					"\n"+strings.TrimSpace(planHeaderYesOutput)+"\n",
					path, path,
				))
			}

		}
	}
}

func (b *Local) renderPlan(dispPlan *format.Plan) {

	headerBuf := &bytes.Buffer{}
	fmt.Fprintf(headerBuf, "\n%s\n", strings.TrimSpace(planHeaderIntro))
	counts := dispPlan.ActionCounts()
	if counts[terraform.DiffCreate] > 0 {
		fmt.Fprintf(headerBuf, "%s create\n", format.DiffActionSymbol(terraform.DiffCreate))
	}
	if counts[terraform.DiffUpdate] > 0 {
		fmt.Fprintf(headerBuf, "%s update in-place\n", format.DiffActionSymbol(terraform.DiffUpdate))
	}
	if counts[terraform.DiffDestroy] > 0 {
		fmt.Fprintf(headerBuf, "%s destroy\n", format.DiffActionSymbol(terraform.DiffDestroy))
	}
	if counts[terraform.DiffDestroyCreate] > 0 {
		fmt.Fprintf(headerBuf, "%s destroy and then create replacement\n", format.DiffActionSymbol(terraform.DiffDestroyCreate))
	}
	if counts[terraform.DiffRefresh] > 0 {
		fmt.Fprintf(headerBuf, "%s read (data resources)\n", format.DiffActionSymbol(terraform.DiffRefresh))
	}

	b.CLI.Output(b.Colorize().Color(headerBuf.String()))

	b.CLI.Output("Terraform will perform the following actions:\n")

	b.CLI.Output(dispPlan.Format(b.Colorize()))

	stats := dispPlan.Stats()
	b.CLI.Output(b.Colorize().Color(fmt.Sprintf(
		"[reset][bold]Plan:[reset] "+
			"%d to add, %d to change, %d to destroy.",
		stats.ToAdd, stats.ToChange, stats.ToDestroy,
	)))
}

const planErrNoConfig = `
No configuration files found!

Plan requires configuration to be present. Planning without a configuration
would mark everything for destruction, which is normally not what is desired.
If you would like to destroy everything, please run plan with the "-destroy"
flag or create a single empty configuration file. Otherwise, please create
a Terraform configuration file in the path being executed and try again.
`

const planHeaderIntro = `
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
`

const planHeaderNoOutput = `
Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.
`

const planHeaderYesOutput = `
This plan was saved to: %s

To perform exactly these actions, run the following command to apply:
    terraform apply %q
`

const planNoChanges = `
[reset][bold][green]No changes. Infrastructure is up-to-date.[reset][green]

This means that Terraform did not detect any differences between your
configuration and real physical resources that exist. As a result, no
actions need to be performed.
`

const planRefreshing = `
[reset][bold]Refreshing Terraform state in-memory prior to plan...[reset]
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.
`


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_directory_service_directory.go<|end_filename|>
package aws

import (
	"fmt"
	"log"
	"time"

	"github.com/hashicorp/terraform/helper/schema"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/directoryservice"
	"github.com/hashicorp/terraform/helper/resource"
)

var directoryCreationFuncs = map[string]func(*directoryservice.DirectoryService, *schema.ResourceData) (string, error){
	"SimpleAD":    createSimpleDirectoryService,
	"MicrosoftAD": createActiveDirectoryService,
	"ADConnector": createDirectoryConnector,
}

func resourceAwsDirectoryServiceDirectory() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsDirectoryServiceDirectoryCreate,
		Read:   resourceAwsDirectoryServiceDirectoryRead,
		Update: resourceAwsDirectoryServiceDirectoryUpdate,
		Delete: resourceAwsDirectoryServiceDirectoryDelete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"name": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"password": {
				Type:      schema.TypeString,
				Required:  true,
				ForceNew:  true,
				Sensitive: true,
			},
			"size": {
				Type:     schema.TypeString,
				Optional: true,
				Default:  "Large",
				ForceNew: true,
			},
			"alias": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
				ForceNew: true,
			},
			"description": {
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
			},
			"short_name": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
				ForceNew: true,
			},
			"tags": tagsSchema(),
			"vpc_settings": {
				Type:     schema.TypeList,
				Optional: true,
				ForceNew: true,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"subnet_ids": {
							Type:     schema.TypeSet,
							Required: true,
							ForceNew: true,
							Elem:     &schema.Schema{Type: schema.TypeString},
							Set:      schema.HashString,
						},
						"vpc_id": {
							Type:     schema.TypeString,
							Required: true,
							ForceNew: true,
						},
					},
				},
			},
			"connect_settings": {
				Type:     schema.TypeList,
				Optional: true,
				ForceNew: true,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"customer_username": {
							Type:     schema.TypeString,
							Required: true,
							ForceNew: true,
						},
						"customer_dns_ips": {
							Type:     schema.TypeSet,
							Required: true,
							ForceNew: true,
							Elem:     &schema.Schema{Type: schema.TypeString},
							Set:      schema.HashString,
						},
						"subnet_ids": {
							Type:     schema.TypeSet,
							Required: true,
							ForceNew: true,
							Elem:     &schema.Schema{Type: schema.TypeString},
							Set:      schema.HashString,
						},
						"vpc_id": {
							Type:     schema.TypeString,
							Required: true,
							ForceNew: true,
						},
					},
				},
			},
			"enable_sso": {
				Type:     schema.TypeBool,
				Optional: true,
				Default:  false,
			},
			"access_url": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"dns_ip_addresses": {
				Type:     schema.TypeSet,
				Elem:     &schema.Schema{Type: schema.TypeString},
				Set:      schema.HashString,
				Computed: true,
			},
			"security_group_id": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"type": {
				Type:     schema.TypeString,
				Optional: true,
				Default:  "SimpleAD",
				ForceNew: true,
				ValidateFunc: func(v interface{}, k string) (ws []string, es []error) {
					validTypes := []string{"SimpleAD", "MicrosoftAD"}
					value := v.(string)
					for validType, _ := range directoryCreationFuncs {
						if validType == value {
							return
						}
					}
					es = append(es, fmt.Errorf("%q must be one of %q", k, validTypes))
					return
				},
			},
		},
	}
}

func buildVpcSettings(d *schema.ResourceData) (vpcSettings *directoryservice.DirectoryVpcSettings, err error) {
	if v, ok := d.GetOk("vpc_settings"); !ok {
		return nil, fmt.Errorf("vpc_settings is required for type = SimpleAD or MicrosoftAD")
	} else {
		settings := v.([]interface{})

		if len(settings) > 1 {
			return nil, fmt.Errorf("Only a single vpc_settings block is expected")
		} else if len(settings) == 1 {
			s := settings[0].(map[string]interface{})
			var subnetIds []*string
			for _, id := range s["subnet_ids"].(*schema.Set).List() {
				subnetIds = append(subnetIds, aws.String(id.(string)))
			}

			vpcSettings = &directoryservice.DirectoryVpcSettings{
				SubnetIds: subnetIds,
				VpcId:     aws.String(s["vpc_id"].(string)),
			}
		}
	}

	return vpcSettings, nil
}

func buildConnectSettings(d *schema.ResourceData) (connectSettings *directoryservice.DirectoryConnectSettings, err error) {
	if v, ok := d.GetOk("connect_settings"); !ok {
		return nil, fmt.Errorf("connect_settings is required for type = ADConnector")
	} else {
		settings := v.([]interface{})

		if len(settings) > 1 {
			return nil, fmt.Errorf("Only a single connect_settings block is expected")
		} else if len(settings) == 1 {
			s := settings[0].(map[string]interface{})

			var subnetIds []*string
			for _, id := range s["subnet_ids"].(*schema.Set).List() {
				subnetIds = append(subnetIds, aws.String(id.(string)))
			}

			var customerDnsIps []*string
			for _, id := range s["customer_dns_ips"].(*schema.Set).List() {
				customerDnsIps = append(customerDnsIps, aws.String(id.(string)))
			}

			connectSettings = &directoryservice.DirectoryConnectSettings{
				CustomerDnsIps:   customerDnsIps,
				CustomerUserName: aws.String(s["customer_username"].(string)),
				SubnetIds:        subnetIds,
				VpcId:            aws.String(s["vpc_id"].(string)),
			}
		}
	}

	return connectSettings, nil
}

func createDirectoryConnector(dsconn *directoryservice.DirectoryService, d *schema.ResourceData) (directoryId string, err error) {
	if _, ok := d.GetOk("size"); !ok {
		return "", fmt.Errorf("size is required for type = ADConnector")
	}

	input := directoryservice.ConnectDirectoryInput{
		Name:     aws.String(d.Get("name").(string)),
		Password: aws.String(d.Get("password").(string)),
		Size:     aws.String(d.Get("size").(string)),
	}

	if v, ok := d.GetOk("description"); ok {
		input.Description = aws.String(v.(string))
	}
	if v, ok := d.GetOk("short_name"); ok {
		input.ShortName = aws.String(v.(string))
	}

	input.ConnectSettings, err = buildConnectSettings(d)
	if err != nil {
		return "", err
	}

	log.Printf("[DEBUG] Creating Directory Connector: %s", input)
	out, err := dsconn.ConnectDirectory(&input)
	if err != nil {
		return "", err
	}
	log.Printf("[DEBUG] Directory Connector created: %s", out)

	return *out.DirectoryId, nil
}

func createSimpleDirectoryService(dsconn *directoryservice.DirectoryService, d *schema.ResourceData) (directoryId string, err error) {
	if _, ok := d.GetOk("size"); !ok {
		return "", fmt.Errorf("size is required for type = SimpleAD")
	}

	input := directoryservice.CreateDirectoryInput{
		Name:     aws.String(d.Get("name").(string)),
		Password: aws.String(d.Get("password").(string)),
		Size:     aws.String(d.Get("size").(string)),
	}

	if v, ok := d.GetOk("description"); ok {
		input.Description = aws.String(v.(string))
	}
	if v, ok := d.GetOk("short_name"); ok {
		input.ShortName = aws.String(v.(string))
	}

	input.VpcSettings, err = buildVpcSettings(d)
	if err != nil {
		return "", err
	}

	log.Printf("[DEBUG] Creating Simple Directory Service: %s", input)
	out, err := dsconn.CreateDirectory(&input)
	if err != nil {
		return "", err
	}
	log.Printf("[DEBUG] Simple Directory Service created: %s", out)

	return *out.DirectoryId, nil
}

func createActiveDirectoryService(dsconn *directoryservice.DirectoryService, d *schema.ResourceData) (directoryId string, err error) {
	input := directoryservice.CreateMicrosoftADInput{
		Name:     aws.String(d.Get("name").(string)),
		Password: aws.String(d.Get("password").(string)),
	}

	if v, ok := d.GetOk("description"); ok {
		input.Description = aws.String(v.(string))
	}
	if v, ok := d.GetOk("short_name"); ok {
		input.ShortName = aws.String(v.(string))
	}

	input.VpcSettings, err = buildVpcSettings(d)
	if err != nil {
		return "", err
	}

	log.Printf("[DEBUG] Creating Microsoft AD Directory Service: %s", input)
	out, err := dsconn.CreateMicrosoftAD(&input)
	if err != nil {
		return "", err
	}
	log.Printf("[DEBUG] Microsoft AD Directory Service created: %s", out)

	return *out.DirectoryId, nil
}

func resourceAwsDirectoryServiceDirectoryCreate(d *schema.ResourceData, meta interface{}) error {
	dsconn := meta.(*AWSClient).dsconn

	creationFunc, ok := directoryCreationFuncs[d.Get("type").(string)]
	if !ok {
		// Shouldn't happen as this is validated above
		return fmt.Errorf("Unsupported directory type: %s", d.Get("type"))
	}

	directoryId, err := creationFunc(dsconn, d)
	if err != nil {
		return err
	}

	d.SetId(directoryId)

	// Wait for creation
	log.Printf("[DEBUG] Waiting for DS (%q) to become available", d.Id())
	stateConf := &resource.StateChangeConf{
		Pending: []string{"Requested", "Creating", "Created"},
		Target:  []string{"Active"},
		Refresh: func() (interface{}, string, error) {
			resp, err := dsconn.DescribeDirectories(&directoryservice.DescribeDirectoriesInput{
				DirectoryIds: []*string{aws.String(d.Id())},
			})
			if err != nil {
				log.Printf("Error during creation of DS: %q", err.Error())
				return nil, "", err
			}

			ds := resp.DirectoryDescriptions[0]
			log.Printf("[DEBUG] Creation of DS %q is in following stage: %q.",
				d.Id(), *ds.Stage)
			return ds, *ds.Stage, nil
		},
		Timeout: 60 * time.Minute,
	}
	if _, err := stateConf.WaitForState(); err != nil {
		return fmt.Errorf(
			"Error waiting for Directory Service (%s) to become available: %s",
			d.Id(), err)
	}

	if v, ok := d.GetOk("alias"); ok {
		d.SetPartial("alias")

		input := directoryservice.CreateAliasInput{
			DirectoryId: aws.String(d.Id()),
			Alias:       aws.String(v.(string)),
		}

		log.Printf("[DEBUG] Assigning alias %q to DS directory %q",
			v.(string), d.Id())
		out, err := dsconn.CreateAlias(&input)
		if err != nil {
			return err
		}
		log.Printf("[DEBUG] Alias %q assigned to DS directory %q",
			*out.Alias, *out.DirectoryId)
	}

	return resourceAwsDirectoryServiceDirectoryUpdate(d, meta)
}

func resourceAwsDirectoryServiceDirectoryUpdate(d *schema.ResourceData, meta interface{}) error {
	dsconn := meta.(*AWSClient).dsconn

	if d.HasChange("enable_sso") {
		d.SetPartial("enable_sso")
		var err error

		if v, ok := d.GetOk("enable_sso"); ok && v.(bool) {
			log.Printf("[DEBUG] Enabling SSO for DS directory %q", d.Id())
			_, err = dsconn.EnableSso(&directoryservice.EnableSsoInput{
				DirectoryId: aws.String(d.Id()),
			})
		} else {
			log.Printf("[DEBUG] Disabling SSO for DS directory %q", d.Id())
			_, err = dsconn.DisableSso(&directoryservice.DisableSsoInput{
				DirectoryId: aws.String(d.Id()),
			})
		}

		if err != nil {
			return err
		}
	}

	if err := setTagsDS(dsconn, d, d.Id()); err != nil {
		return err
	}

	return resourceAwsDirectoryServiceDirectoryRead(d, meta)
}

func resourceAwsDirectoryServiceDirectoryRead(d *schema.ResourceData, meta interface{}) error {
	dsconn := meta.(*AWSClient).dsconn

	input := directoryservice.DescribeDirectoriesInput{
		DirectoryIds: []*string{aws.String(d.Id())},
	}
	out, err := dsconn.DescribeDirectories(&input)
	if err != nil {
		return err

	}

	if len(out.DirectoryDescriptions) == 0 {
		log.Printf("[WARN] Directory %s not found", d.Id())
		d.SetId("")
		return nil
	}

	dir := out.DirectoryDescriptions[0]
	log.Printf("[DEBUG] Received DS directory: %s", dir)

	d.Set("access_url", *dir.AccessUrl)
	d.Set("alias", *dir.Alias)
	if dir.Description != nil {
		d.Set("description", *dir.Description)
	}

	if *dir.Type == "ADConnector" {
		d.Set("dns_ip_addresses", schema.NewSet(schema.HashString, flattenStringList(dir.ConnectSettings.ConnectIps)))
	} else {
		d.Set("dns_ip_addresses", schema.NewSet(schema.HashString, flattenStringList(dir.DnsIpAddrs)))
	}
	d.Set("name", *dir.Name)
	if dir.ShortName != nil {
		d.Set("short_name", *dir.ShortName)
	}
	if dir.Size != nil {
		d.Set("size", *dir.Size)
	}
	d.Set("type", *dir.Type)
	d.Set("vpc_settings", flattenDSVpcSettings(dir.VpcSettings))
	d.Set("connect_settings", flattenDSConnectSettings(dir.DnsIpAddrs, dir.ConnectSettings))
	d.Set("enable_sso", *dir.SsoEnabled)

	if dir.VpcSettings != nil {
		d.Set("security_group_id", *dir.VpcSettings.SecurityGroupId)
	}

	tagList, err := dsconn.ListTagsForResource(&directoryservice.ListTagsForResourceInput{
		ResourceId: aws.String(d.Id()),
	})
	if err != nil {
		return fmt.Errorf("Failed to get Directory service tags (id: %s): %s", d.Id(), err)
	}
	d.Set("tags", tagsToMapDS(tagList.Tags))

	return nil
}

func resourceAwsDirectoryServiceDirectoryDelete(d *schema.ResourceData, meta interface{}) error {
	dsconn := meta.(*AWSClient).dsconn

	input := directoryservice.DeleteDirectoryInput{
		DirectoryId: aws.String(d.Id()),
	}

	log.Printf("[DEBUG] Delete Directory input: %s", input)
	_, err := dsconn.DeleteDirectory(&input)
	if err != nil {
		return err
	}

	// Wait for deletion
	log.Printf("[DEBUG] Waiting for DS (%q) to be deleted", d.Id())
	stateConf := &resource.StateChangeConf{
		Pending: []string{"Deleting"},
		Target:  []string{"Deleted"},
		Refresh: func() (interface{}, string, error) {
			resp, err := dsconn.DescribeDirectories(&directoryservice.DescribeDirectoriesInput{
				DirectoryIds: []*string{aws.String(d.Id())},
			})
			if err != nil {
				if dserr, ok := err.(awserr.Error); ok && dserr.Code() == "EntityDoesNotExistException" {
					return 42, "Deleted", nil
				}
				return nil, "error", err
			}

			if len(resp.DirectoryDescriptions) == 0 {
				return 42, "Deleted", nil
			}

			ds := resp.DirectoryDescriptions[0]
			log.Printf("[DEBUG] Deletion of DS %q is in following stage: %q.",
				d.Id(), *ds.Stage)
			return ds, *ds.Stage, nil
		},
		Timeout: 60 * time.Minute,
	}
	if _, err := stateConf.WaitForState(); err != nil {
		return fmt.Errorf(
			"Error waiting for Directory Service (%s) to be deleted: %q",
			d.Id(), err.Error())
	}

	return nil
}


<|start_filename|>vendor/github.com/zclconf/go-cty/cty/object_type_test.go<|end_filename|>
package cty

import (
	"fmt"
	"testing"
)

func TestObjectTypeEquals(t *testing.T) {
	tests := []struct {
		LHS      Type // Must be typeObject
		RHS      Type
		Expected bool
	}{
		{
			Object(map[string]Type{}),
			Object(map[string]Type{}),
			true,
		},
		{
			Object(map[string]Type{
				"name": String,
			}),
			Object(map[string]Type{
				"name": String,
			}),
			true,
		},
		{
			Object(map[string]Type{
				"person": Object(map[string]Type{
					"name": String,
				}),
			}),
			Object(map[string]Type{
				"person": Object(map[string]Type{
					"name": String,
				}),
			}),
			true,
		},
		{
			Object(map[string]Type{
				"name": String,
			}),
			Object(map[string]Type{}),
			false,
		},
		{
			Object(map[string]Type{
				"name": String,
			}),
			Object(map[string]Type{
				"name": Number,
			}),
			false,
		},
		{
			Object(map[string]Type{
				"name": String,
			}),
			Object(map[string]Type{
				"nombre": String,
			}),
			false,
		},
		{
			Object(map[string]Type{
				"name": String,
			}),
			Object(map[string]Type{
				"name": String,
				"age":  Number,
			}),
			false,
		},
		{
			Object(map[string]Type{
				"person": Object(map[string]Type{
					"name": String,
				}),
			}),
			Object(map[string]Type{
				"person": Object(map[string]Type{
					"name": String,
					"age":  Number,
				}),
			}),
			false,
		},
	}

	for _, test := range tests {
		t.Run(fmt.Sprintf("%#v.Equals(%#v)", test.LHS, test.RHS), func(t *testing.T) {
			got := test.LHS.Equals(test.RHS)
			if got != test.Expected {
				t.Errorf("Equals returned %#v; want %#v", got, test.Expected)
			}
		})
	}
}


<|start_filename|>vendor/github.com/hashicorp/go-getter/decompress_gzip_test.go<|end_filename|>
package getter

import (
	"path/filepath"
	"testing"
)

func TestGzipDecompressor(t *testing.T) {
	cases := []TestDecompressCase{
		{
			"single.gz",
			false,
			false,
			nil,
			"d3b07384d113edec49eaa6238ad5ff00",
		},

		{
			"single.gz",
			true,
			true,
			nil,
			"",
		},
	}

	for i, tc := range cases {
		cases[i].Input = filepath.Join("./test-fixtures", "decompress-gz", tc.Input)
	}

	TestDecompressor(t, new(GzipDecompressor), cases)
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_db_option_group.go<|end_filename|>
package aws

import (
	"bytes"
	"fmt"
	"log"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/rds"
	"github.com/hashicorp/terraform/helper/hashcode"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsDbOptionGroup() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsDbOptionGroupCreate,
		Read:   resourceAwsDbOptionGroupRead,
		Update: resourceAwsDbOptionGroupUpdate,
		Delete: resourceAwsDbOptionGroupDelete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Timeouts: &schema.ResourceTimeout{
			Delete: schema.DefaultTimeout(15 * time.Minute),
		},

		Schema: map[string]*schema.Schema{
			"arn": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"name": {
				Type:          schema.TypeString,
				Optional:      true,
				Computed:      true,
				ForceNew:      true,
				ConflictsWith: []string{"name_prefix"},
				ValidateFunc:  validateDbOptionGroupName,
			},
			"name_prefix": {
				Type:         schema.TypeString,
				Optional:     true,
				Computed:     true,
				ForceNew:     true,
				ValidateFunc: validateDbOptionGroupNamePrefix,
			},
			"engine_name": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"major_engine_version": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"option_group_description": {
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				Default:  "Managed by Terraform",
			},

			"option": {
				Type:     schema.TypeSet,
				Optional: true,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"option_name": {
							Type:     schema.TypeString,
							Required: true,
						},
						"option_settings": {
							Type:     schema.TypeSet,
							Optional: true,
							Elem: &schema.Resource{
								Schema: map[string]*schema.Schema{
									"name": {
										Type:     schema.TypeString,
										Required: true,
									},
									"value": {
										Type:     schema.TypeString,
										Required: true,
									},
								},
							},
						},
						"port": {
							Type:     schema.TypeInt,
							Optional: true,
						},
						"db_security_group_memberships": {
							Type:     schema.TypeSet,
							Optional: true,
							Elem:     &schema.Schema{Type: schema.TypeString},
							Set:      schema.HashString,
						},
						"vpc_security_group_memberships": {
							Type:     schema.TypeSet,
							Optional: true,
							Elem:     &schema.Schema{Type: schema.TypeString},
							Set:      schema.HashString,
						},
					},
				},
				Set: resourceAwsDbOptionHash,
			},

			"tags": tagsSchema(),
		},
	}
}

func resourceAwsDbOptionGroupCreate(d *schema.ResourceData, meta interface{}) error {
	rdsconn := meta.(*AWSClient).rdsconn
	tags := tagsFromMapRDS(d.Get("tags").(map[string]interface{}))

	var groupName string
	if v, ok := d.GetOk("name"); ok {
		groupName = v.(string)
	} else if v, ok := d.GetOk("name_prefix"); ok {
		groupName = resource.PrefixedUniqueId(v.(string))
	} else {
		groupName = resource.UniqueId()
	}

	createOpts := &rds.CreateOptionGroupInput{
		EngineName:             aws.String(d.Get("engine_name").(string)),
		MajorEngineVersion:     aws.String(d.Get("major_engine_version").(string)),
		OptionGroupDescription: aws.String(d.Get("option_group_description").(string)),
		OptionGroupName:        aws.String(groupName),
		Tags:                   tags,
	}

	log.Printf("[DEBUG] Create DB Option Group: %#v", createOpts)
	_, err := rdsconn.CreateOptionGroup(createOpts)
	if err != nil {
		return fmt.Errorf("Error creating DB Option Group: %s", err)
	}

	d.SetId(strings.ToLower(groupName))
	log.Printf("[INFO] DB Option Group ID: %s", d.Id())

	return resourceAwsDbOptionGroupUpdate(d, meta)
}

func resourceAwsDbOptionGroupRead(d *schema.ResourceData, meta interface{}) error {
	rdsconn := meta.(*AWSClient).rdsconn
	params := &rds.DescribeOptionGroupsInput{
		OptionGroupName: aws.String(d.Id()),
	}

	log.Printf("[DEBUG] Describe DB Option Group: %#v", params)
	options, err := rdsconn.DescribeOptionGroups(params)
	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			if "OptionGroupNotFoundFault" == awsErr.Code() {
				d.SetId("")
				log.Printf("[DEBUG] DB Option Group (%s) not found", d.Get("name").(string))
				return nil
			}
		}
		return fmt.Errorf("Error Describing DB Option Group: %s", err)
	}

	var option *rds.OptionGroup
	for _, ogl := range options.OptionGroupsList {
		if *ogl.OptionGroupName == d.Id() {
			option = ogl
			break
		}
	}

	if option == nil {
		return fmt.Errorf("Unable to find Option Group: %#v", options.OptionGroupsList)
	}

	d.Set("name", option.OptionGroupName)
	d.Set("major_engine_version", option.MajorEngineVersion)
	d.Set("engine_name", option.EngineName)
	d.Set("option_group_description", option.OptionGroupDescription)
	if len(option.Options) != 0 {
		d.Set("option", flattenOptions(option.Options))
	}

	optionGroup := options.OptionGroupsList[0]
	arn, err := buildRDSOptionGroupARN(d.Id(), meta.(*AWSClient).partition, meta.(*AWSClient).accountid, meta.(*AWSClient).region)
	if err != nil {
		name := "<empty>"
		if optionGroup.OptionGroupName != nil && *optionGroup.OptionGroupName != "" {
			name = *optionGroup.OptionGroupName
		}
		log.Printf("[DEBUG] Error building ARN for DB Option Group, not setting Tags for Option Group %s", name)
	} else {
		d.Set("arn", arn)
		resp, err := rdsconn.ListTagsForResource(&rds.ListTagsForResourceInput{
			ResourceName: aws.String(arn),
		})

		if err != nil {
			log.Printf("[DEBUG] Error retrieving tags for ARN: %s", arn)
		}

		var dt []*rds.Tag
		if len(resp.TagList) > 0 {
			dt = resp.TagList
		}
		d.Set("tags", tagsToMapRDS(dt))
	}

	return nil
}

func optionInList(optionName string, list []*string) bool {
	for _, opt := range list {
		if *opt == optionName {
			return true
		}
	}
	return false
}

func resourceAwsDbOptionGroupUpdate(d *schema.ResourceData, meta interface{}) error {
	rdsconn := meta.(*AWSClient).rdsconn
	if d.HasChange("option") {
		o, n := d.GetChange("option")
		if o == nil {
			o = new(schema.Set)
		}
		if n == nil {
			n = new(schema.Set)
		}

		os := o.(*schema.Set)
		ns := n.(*schema.Set)
		addOptions, addErr := expandOptionConfiguration(ns.Difference(os).List())
		if addErr != nil {
			return addErr
		}

		addingOptionNames, err := flattenOptionNames(ns.Difference(os).List())
		if err != nil {
			return err
		}

		removeOptions := []*string{}
		opts, err := flattenOptionNames(os.Difference(ns).List())
		if err != nil {
			return err
		}

		for _, optionName := range opts {
			if optionInList(*optionName, addingOptionNames) {
				continue
			}
			removeOptions = append(removeOptions, optionName)
		}

		modifyOpts := &rds.ModifyOptionGroupInput{
			OptionGroupName:  aws.String(d.Id()),
			ApplyImmediately: aws.Bool(true),
		}

		if len(addOptions) > 0 {
			modifyOpts.OptionsToInclude = addOptions
		}

		if len(removeOptions) > 0 {
			modifyOpts.OptionsToRemove = removeOptions
		}

		log.Printf("[DEBUG] Modify DB Option Group: %s", modifyOpts)
		_, err = rdsconn.ModifyOptionGroup(modifyOpts)
		if err != nil {
			return fmt.Errorf("Error modifying DB Option Group: %s", err)
		}
		d.SetPartial("option")

	}

	if arn, err := buildRDSOptionGroupARN(d.Id(), meta.(*AWSClient).partition, meta.(*AWSClient).accountid, meta.(*AWSClient).region); err == nil {
		if err := setTagsRDS(rdsconn, d, arn); err != nil {
			return err
		} else {
			d.SetPartial("tags")
		}
	}

	return resourceAwsDbOptionGroupRead(d, meta)
}

func resourceAwsDbOptionGroupDelete(d *schema.ResourceData, meta interface{}) error {
	rdsconn := meta.(*AWSClient).rdsconn

	deleteOpts := &rds.DeleteOptionGroupInput{
		OptionGroupName: aws.String(d.Id()),
	}

	log.Printf("[DEBUG] Delete DB Option Group: %#v", deleteOpts)
	ret := resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
		_, err := rdsconn.DeleteOptionGroup(deleteOpts)
		if err != nil {
			if awsErr, ok := err.(awserr.Error); ok {
				if awsErr.Code() == "InvalidOptionGroupStateFault" {
					log.Printf("[DEBUG] AWS believes the RDS Option Group is still in use, retrying")
					return resource.RetryableError(awsErr)
				}
			}
			return resource.NonRetryableError(err)
		}
		return nil
	})
	if ret != nil {
		return fmt.Errorf("Error Deleting DB Option Group: %s", ret)
	}
	return nil
}

func flattenOptionNames(configured []interface{}) ([]*string, error) {
	var optionNames []*string
	for _, pRaw := range configured {
		data := pRaw.(map[string]interface{})
		optionNames = append(optionNames, aws.String(data["option_name"].(string)))
	}

	return optionNames, nil
}

func resourceAwsDbOptionHash(v interface{}) int {
	var buf bytes.Buffer
	m := v.(map[string]interface{})
	buf.WriteString(fmt.Sprintf("%s-", m["option_name"].(string)))
	if _, ok := m["port"]; ok {
		buf.WriteString(fmt.Sprintf("%d-", m["port"].(int)))
	}

	for _, oRaw := range m["option_settings"].(*schema.Set).List() {
		o := oRaw.(map[string]interface{})
		buf.WriteString(fmt.Sprintf("%s-", o["name"].(string)))
		buf.WriteString(fmt.Sprintf("%s-", o["value"].(string)))
	}

	for _, vpcRaw := range m["vpc_security_group_memberships"].(*schema.Set).List() {
		buf.WriteString(fmt.Sprintf("%s-", vpcRaw.(string)))
	}

	for _, sgRaw := range m["db_security_group_memberships"].(*schema.Set).List() {
		buf.WriteString(fmt.Sprintf("%s-", sgRaw.(string)))
	}
	return hashcode.String(buf.String())
}

func buildRDSOptionGroupARN(identifier, partition, accountid, region string) (string, error) {
	if partition == "" {
		return "", fmt.Errorf("Unable to construct RDS Option Group ARN because of missing AWS partition")
	}
	if accountid == "" {
		return "", fmt.Errorf("Unable to construct RDS Option Group ARN because of missing AWS Account ID")
	}
	arn := fmt.Sprintf("arn:%s:rds:%s:%s:og:%s", partition, region, accountid, identifier)
	return arn, nil
}


<|start_filename|>vendor/github.com/mitchellh/packer/packer/post_processor_mock.go<|end_filename|>
package packer

// MockPostProcessor is an implementation of PostProcessor that can be
// used for tests.
type MockPostProcessor struct {
	ArtifactId string
	Keep       bool
	Error      error

	ConfigureCalled  bool
	ConfigureConfigs []interface{}
	ConfigureError   error

	PostProcessCalled   bool
	PostProcessArtifact Artifact
	PostProcessUi       Ui
}

func (t *MockPostProcessor) Configure(configs ...interface{}) error {
	t.ConfigureCalled = true
	t.ConfigureConfigs = configs
	return t.ConfigureError
}

func (t *MockPostProcessor) PostProcess(ui Ui, a Artifact) (Artifact, bool, error) {
	t.PostProcessCalled = true
	t.PostProcessArtifact = a
	t.PostProcessUi = ui

	return &MockArtifact{
		IdValue: t.ArtifactId,
	}, t.Keep, t.Error
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_config_delivery_channel.go<|end_filename|>
package aws

import (
	"fmt"
	"log"
	"time"

	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/configservice"
)

func resourceAwsConfigDeliveryChannel() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsConfigDeliveryChannelPut,
		Read:   resourceAwsConfigDeliveryChannelRead,
		Update: resourceAwsConfigDeliveryChannelPut,
		Delete: resourceAwsConfigDeliveryChannelDelete,

		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"name": {
				Type:         schema.TypeString,
				Optional:     true,
				ForceNew:     true,
				Default:      "default",
				ValidateFunc: validateMaxLength(256),
			},
			"s3_bucket_name": {
				Type:     schema.TypeString,
				Required: true,
			},
			"s3_key_prefix": {
				Type:     schema.TypeString,
				Optional: true,
			},
			"sns_topic_arn": {
				Type:         schema.TypeString,
				Optional:     true,
				ValidateFunc: validateArn,
			},
			"snapshot_delivery_properties": {
				Type:     schema.TypeList,
				Optional: true,
				MaxItems: 1,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"delivery_frequency": {
							Type:         schema.TypeString,
							Optional:     true,
							ValidateFunc: validateConfigExecutionFrequency,
						},
					},
				},
			},
		},
	}
}

func resourceAwsConfigDeliveryChannelPut(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).configconn

	name := d.Get("name").(string)
	channel := configservice.DeliveryChannel{
		Name:         aws.String(name),
		S3BucketName: aws.String(d.Get("s3_bucket_name").(string)),
	}

	if v, ok := d.GetOk("s3_key_prefix"); ok {
		channel.S3KeyPrefix = aws.String(v.(string))
	}
	if v, ok := d.GetOk("sns_topic_arn"); ok {
		channel.SnsTopicARN = aws.String(v.(string))
	}

	if p, ok := d.GetOk("snapshot_delivery_properties"); ok {
		propertiesBlocks := p.([]interface{})
		block := propertiesBlocks[0].(map[string]interface{})

		if v, ok := block["delivery_frequency"]; ok {
			channel.ConfigSnapshotDeliveryProperties = &configservice.ConfigSnapshotDeliveryProperties{
				DeliveryFrequency: aws.String(v.(string)),
			}
		}
	}

	input := configservice.PutDeliveryChannelInput{DeliveryChannel: &channel}

	err := resource.Retry(2*time.Minute, func() *resource.RetryError {
		_, err := conn.PutDeliveryChannel(&input)
		if err == nil {
			return nil
		}

		awsErr, ok := err.(awserr.Error)
		if ok && awsErr.Code() == "InsufficientDeliveryPolicyException" {
			return resource.RetryableError(err)
		}

		return resource.NonRetryableError(err)
	})
	if err != nil {
		return fmt.Errorf("Creating Delivery Channel failed: %s", err)
	}

	d.SetId(name)

	return resourceAwsConfigDeliveryChannelRead(d, meta)
}

func resourceAwsConfigDeliveryChannelRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).configconn

	input := configservice.DescribeDeliveryChannelsInput{
		DeliveryChannelNames: []*string{aws.String(d.Id())},
	}
	out, err := conn.DescribeDeliveryChannels(&input)
	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			if awsErr.Code() == "NoSuchDeliveryChannelException" {
				log.Printf("[WARN] Delivery Channel %q is gone (NoSuchDeliveryChannelException)", d.Id())
				d.SetId("")
				return nil
			}
		}
		return fmt.Errorf("Getting Delivery Channel failed: %s", err)
	}

	if len(out.DeliveryChannels) < 1 {
		log.Printf("[WARN] Delivery Channel %q is gone (no channels found)", d.Id())
		d.SetId("")
		return nil
	}

	if len(out.DeliveryChannels) > 1 {
		return fmt.Errorf("Received %d delivery channels under %s (expected exactly 1): %s",
			len(out.DeliveryChannels), d.Id(), out.DeliveryChannels)
	}

	channel := out.DeliveryChannels[0]

	d.Set("name", channel.Name)
	d.Set("s3_bucket_name", channel.S3BucketName)
	d.Set("s3_key_prefix", channel.S3KeyPrefix)
	d.Set("sns_topic_arn", channel.SnsTopicARN)

	if channel.ConfigSnapshotDeliveryProperties != nil {
		d.Set("snapshot_delivery_properties", flattenConfigSnapshotDeliveryProperties(channel.ConfigSnapshotDeliveryProperties))
	}

	return nil
}

func resourceAwsConfigDeliveryChannelDelete(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).configconn
	input := configservice.DeleteDeliveryChannelInput{
		DeliveryChannelName: aws.String(d.Id()),
	}

	err := resource.Retry(30*time.Second, func() *resource.RetryError {
		_, err := conn.DeleteDeliveryChannel(&input)
		if err != nil {
			if isAWSErr(err, configservice.ErrCodeLastDeliveryChannelDeleteFailedException, "there is a running configuration recorder") {
				return resource.RetryableError(err)
			}

			return resource.NonRetryableError(err)
		}
		return nil
	})
	if err != nil {
		return fmt.Errorf("Unable to delete delivery channel: %s", err)
	}

	d.SetId("")
	return nil
}


<|start_filename|>vendor/github.com/hashicorp/go-getter/decompress_bzip2_test.go<|end_filename|>
package getter

import (
	"path/filepath"
	"testing"
)

func TestBzip2Decompressor(t *testing.T) {
	cases := []TestDecompressCase{
		{
			"single.bz2",
			false,
			false,
			nil,
			"d3b07384d113edec49eaa6238ad5ff00",
		},

		{
			"single.bz2",
			true,
			true,
			nil,
			"",
		},
	}

	for i, tc := range cases {
		cases[i].Input = filepath.Join("./test-fixtures", "decompress-bz2", tc.Input)
	}

	TestDecompressor(t, new(Bzip2Decompressor), cases)
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_elastic_beanstalk_application.go<|end_filename|>
package aws

import (
	"fmt"
	"log"
	"time"

	"github.com/hashicorp/terraform/helper/schema"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/elasticbeanstalk"
	"github.com/hashicorp/terraform/helper/resource"
)

func resourceAwsElasticBeanstalkApplication() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsElasticBeanstalkApplicationCreate,
		Read:   resourceAwsElasticBeanstalkApplicationRead,
		Update: resourceAwsElasticBeanstalkApplicationUpdate,
		Delete: resourceAwsElasticBeanstalkApplicationDelete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"name": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"description": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: false,
			},
		},
	}
}

func resourceAwsElasticBeanstalkApplicationCreate(d *schema.ResourceData, meta interface{}) error {
	beanstalkConn := meta.(*AWSClient).elasticbeanstalkconn

	// Get the name and description
	name := d.Get("name").(string)
	description := d.Get("description").(string)

	log.Printf("[DEBUG] Elastic Beanstalk application create: %s, description: %s", name, description)

	req := &elasticbeanstalk.CreateApplicationInput{
		ApplicationName: aws.String(name),
		Description:     aws.String(description),
	}

	_, err := beanstalkConn.CreateApplication(req)
	if err != nil {
		return err
	}

	d.SetId(name)

	return resourceAwsElasticBeanstalkApplicationRead(d, meta)
}

func resourceAwsElasticBeanstalkApplicationUpdate(d *schema.ResourceData, meta interface{}) error {
	beanstalkConn := meta.(*AWSClient).elasticbeanstalkconn

	if d.HasChange("description") {
		if err := resourceAwsElasticBeanstalkApplicationDescriptionUpdate(beanstalkConn, d); err != nil {
			return err
		}
	}

	return resourceAwsElasticBeanstalkApplicationRead(d, meta)
}

func resourceAwsElasticBeanstalkApplicationDescriptionUpdate(beanstalkConn *elasticbeanstalk.ElasticBeanstalk, d *schema.ResourceData) error {
	name := d.Get("name").(string)
	description := d.Get("description").(string)

	log.Printf("[DEBUG] Elastic Beanstalk application: %s, update description: %s", name, description)

	_, err := beanstalkConn.UpdateApplication(&elasticbeanstalk.UpdateApplicationInput{
		ApplicationName: aws.String(name),
		Description:     aws.String(description),
	})

	return err
}

func resourceAwsElasticBeanstalkApplicationRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).elasticbeanstalkconn

	var app *elasticbeanstalk.ApplicationDescription
	err := resource.Retry(30*time.Second, func() *resource.RetryError {
		var err error
		app, err = getBeanstalkApplication(d.Id(), conn)
		if err != nil {
			return resource.NonRetryableError(err)
		}

		if app == nil {
			if d.IsNewResource() {
				return resource.RetryableError(fmt.Errorf("Elastic Beanstalk Application %q not found.", d.Id()))
			}
			return resource.NonRetryableError(err)
		}
		return nil
	})
	if err != nil {
		return err
	}

	d.Set("name", app.ApplicationName)
	d.Set("description", app.Description)
	return nil
}

func resourceAwsElasticBeanstalkApplicationDelete(d *schema.ResourceData, meta interface{}) error {
	beanstalkConn := meta.(*AWSClient).elasticbeanstalkconn

	_, err := beanstalkConn.DeleteApplication(&elasticbeanstalk.DeleteApplicationInput{
		ApplicationName: aws.String(d.Id()),
	})
	if err != nil {
		return err
	}

	return resource.Retry(10*time.Second, func() *resource.RetryError {
		app, err := getBeanstalkApplication(d.Id(), meta.(*AWSClient).elasticbeanstalkconn)
		if err != nil {
			return resource.NonRetryableError(err)
		}

		if app != nil {
			return resource.RetryableError(
				fmt.Errorf("Beanstalk Application (%s) still exists: %s", d.Id(), err))
		}
		return nil
	})
}

func getBeanstalkApplication(id string, conn *elasticbeanstalk.ElasticBeanstalk) (*elasticbeanstalk.ApplicationDescription, error) {
	resp, err := conn.DescribeApplications(&elasticbeanstalk.DescribeApplicationsInput{
		ApplicationNames: []*string{aws.String(id)},
	})
	if err != nil {
		if isAWSErr(err, "InvalidBeanstalkAppID.NotFound", "") {
			return nil, nil
		}
		return nil, err
	}

	if len(resp.Applications) > 1 {
		return nil, fmt.Errorf("Error %d Applications matched, expected 1", len(resp.Applications))
	}

	if len(resp.Applications) == 0 {
		return nil, nil
	}

	return resp.Applications[0], nil
}


<|start_filename|>vendor/github.com/libvirt/libvirt-go-xml/secret_test.go<|end_filename|>
/*
 * This file is part of the libvirt-go-xml project
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * Copyright (C) 2016 Red Hat, Inc.
 *
 */

package libvirtxml

import (
	"strings"
	"testing"
)

var secretTestData = []struct {
	Object   *Secret
	Expected []string
}{
	{
		Object: &Secret{
			Description: "Demo",
		},
		Expected: []string{
			`<secret>`,
			`  <description>Demo</description>`,
			`</secret>`,
		},
	},
	{
		Object: &Secret{
			Description: "Demo",
			Private:     "yes",
			Ephemeral:   "yes",
			UUID:        "55806c7d-8e93-456f-829b-607d8c198367",
		},
		Expected: []string{
			`<secret ephemeral="yes" private="yes">`,
			`  <description>Demo</description>`,
			`  <uuid>55806c7d-8e93-456f-829b-607d8c198367</uuid>`,
			`</secret>`,
		},
	},
	{
		Object: &Secret{
			Description: "Demo",
			Private:     "yes",
			Ephemeral:   "yes",
			UUID:        "55806c7d-8e93-456f-829b-607d8c198367",
			Usage: &SecretUsage{
				Type:   "volume",
				Volume: "/var/lib/libvirt/images/puppyname.img",
			},
		},
		Expected: []string{
			`<secret ephemeral="yes" private="yes">`,
			`  <description>Demo</description>`,
			`  <uuid>55806c7d-8e93-456f-829b-607d8c198367</uuid>`,
			`  <usage type="volume">`,
			`    <volume>/var/lib/libvirt/images/puppyname.img</volume>`,
			`  </usage>`,
			`</secret>`,
		},
	},
	{
		Object: &Secret{
			Description: "Demo",
			Private:     "yes",
			Ephemeral:   "yes",
			UUID:        "55806c7d-8e93-456f-829b-607d8c198367",
			Usage: &SecretUsage{
				Type: "ceph",
				Name: "mycluster",
			},
		},
		Expected: []string{
			`<secret ephemeral="yes" private="yes">`,
			`  <description>Demo</description>`,
			`  <uuid>55806c7d-8e93-456f-829b-607d8c198367</uuid>`,
			`  <usage type="ceph">`,
			`    <name>mycluster</name>`,
			`  </usage>`,
			`</secret>`,
		},
	},
	{
		Object: &Secret{
			Description: "Demo",
			Private:     "yes",
			Ephemeral:   "yes",
			UUID:        "55806c7d-8e93-456f-829b-607d8c198367",
			Usage: &SecretUsage{
				Type:   "iscsi",
				Target: "libvirtiscsi",
			},
		},
		Expected: []string{
			`<secret ephemeral="yes" private="yes">`,
			`  <description>Demo</description>`,
			`  <uuid>55806c7d-8e93-456f-829b-607d8c198367</uuid>`,
			`  <usage type="iscsi">`,
			`    <target>libvirtiscsi</target>`,
			`  </usage>`,
			`</secret>`,
		},
	},
	{
		Object: &Secret{
			Description: "Demo",
			Private:     "yes",
			Ephemeral:   "yes",
			UUID:        "55806c7d-8e93-456f-829b-607d8c198367",
			Usage: &SecretUsage{
				Type: "tls",
				Name: "Demo cert",
			},
		},
		Expected: []string{
			`<secret ephemeral="yes" private="yes">`,
			`  <description>Demo</description>`,
			`  <uuid>55806c7d-8e93-456f-829b-607d8c198367</uuid>`,
			`  <usage type="tls">`,
			`    <name>Demo cert</name>`,
			`  </usage>`,
			`</secret>`,
		},
	},
}

func TestSecret(t *testing.T) {
	for _, test := range secretTestData {
		doc, err := test.Object.Marshal()
		if err != nil {
			t.Fatal(err)
		}

		expect := strings.Join(test.Expected, "\n")

		if doc != expect {
			t.Fatal("Bad xml:\n", string(doc), "\n does not match\n", expect, "\n")
		}
	}
}


<|start_filename|>vendor/github.com/mitchellh/packer/vendor/github.com/approvals/go-approval-tests/approvals_test.TestVerifyBadJSONBytes.approved.json<|end_filename|>
error while parsing JSON
error:
  invalid character 'f' looking for beginning of object key string
JSON:
  { foo: "bar", "age": 42, "bark": "woof" }


<|start_filename|>vendor/github.com/mitchellh/packer/builder/amazon/common/template_funcs.go<|end_filename|>
package common

import (
	"bytes"
	"text/template"
)

func isalphanumeric(b byte) bool {
	if '0' <= b && b <= '9' {
		return true
	}
	if 'a' <= b && b <= 'z' {
		return true
	}
	if 'A' <= b && b <= 'Z' {
		return true
	}
	return false
}

// Clean up AMI name by replacing invalid characters with "-"
// For allowed characters see docs for Name parameter
// at http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateImage.html
func templateCleanAMIName(s string) string {
	allowed := []byte{'(', ')', '[', ']', ' ', '.', '/', '-', '\'', '@', '_'}
	b := []byte(s)
	newb := make([]byte, len(b))
	for i, c := range b {
		if isalphanumeric(c) || bytes.IndexByte(allowed, c) != -1 {
			newb[i] = c
		} else {
			newb[i] = '-'
		}
	}
	return string(newb[:])
}

var TemplateFuncs = template.FuncMap{
	"clean_ami_name": templateCleanAMIName,
}


<|start_filename|>vendor/github.com/hashicorp/terraform/command/plan_test.go<|end_filename|>
package command

import (
	"bytes"
	"io/ioutil"
	"os"
	"path/filepath"
	"reflect"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/hashicorp/terraform/helper/copy"
	"github.com/hashicorp/terraform/terraform"
	"github.com/mitchellh/cli"
)

func TestPlan(t *testing.T) {
	cwd, err := os.Getwd()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if err := os.Chdir(testFixturePath("plan")); err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Chdir(cwd)

	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
		},
	}

	args := []string{}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}
}

func TestPlan_lockedState(t *testing.T) {
	cwd, err := os.Getwd()
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	testPath := testFixturePath("plan")
	unlock, err := testLockState("./testdata", filepath.Join(testPath, DefaultStateFilename))
	if err != nil {
		t.Fatal(err)
	}
	defer unlock()

	if err := os.Chdir(testPath); err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Chdir(cwd)

	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
		},
	}

	args := []string{}
	if code := c.Run(args); code == 0 {
		t.Fatal("expected error")
	}

	output := ui.ErrorWriter.String()
	if !strings.Contains(output, "lock") {
		t.Fatal("command output does not look like a lock error:", output)
	}
}

func TestPlan_plan(t *testing.T) {
	tmp, cwd := testCwd(t)
	defer testFixCwd(t, tmp, cwd)

	planPath := testPlanFile(t, &terraform.Plan{
		Module: testModule(t, "apply"),
	})

	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
		},
	}

	args := []string{planPath}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	if p.RefreshCalled {
		t.Fatal("refresh should not be called")
	}
}

func TestPlan_destroy(t *testing.T) {
	originalState := &terraform.State{
		Modules: []*terraform.ModuleState{
			&terraform.ModuleState{
				Path: []string{"root"},
				Resources: map[string]*terraform.ResourceState{
					"test_instance.foo": &terraform.ResourceState{
						Type: "test_instance",
						Primary: &terraform.InstanceState{
							ID: "bar",
						},
					},
				},
			},
		},
	}

	outPath := testTempFile(t)
	statePath := testStateFile(t, originalState)

	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
		},
	}

	args := []string{
		"-destroy",
		"-out", outPath,
		"-state", statePath,
		testFixturePath("plan"),
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	if !p.RefreshCalled {
		t.Fatal("refresh should be called")
	}

	plan := testReadPlan(t, outPath)
	for _, m := range plan.Diff.Modules {
		for _, r := range m.Resources {
			if !r.Destroy {
				t.Fatalf("bad: %#v", r)
			}
		}
	}
}

func TestPlan_noState(t *testing.T) {
	tmp, cwd := testCwd(t)
	defer testFixCwd(t, tmp, cwd)

	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
		},
	}

	args := []string{
		testFixturePath("plan"),
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	// Verify that refresh was called
	if p.RefreshCalled {
		t.Fatal("refresh should not be called")
	}

	// Verify that the provider was called with the existing state
	actual := strings.TrimSpace(p.DiffState.String())
	expected := strings.TrimSpace(testPlanNoStateStr)
	if actual != expected {
		t.Fatalf("bad:\n\n%s", actual)
	}
}

func TestPlan_outPath(t *testing.T) {
	tmp, cwd := testCwd(t)
	defer testFixCwd(t, tmp, cwd)

	tf, err := ioutil.TempFile("", "tf")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	outPath := tf.Name()
	os.Remove(tf.Name())

	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
		},
	}

	p.DiffReturn = &terraform.InstanceDiff{
		Destroy: true,
	}

	args := []string{
		"-out", outPath,
		testFixturePath("plan"),
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	f, err := os.Open(outPath)
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer f.Close()

	if _, err := terraform.ReadPlan(f); err != nil {
		t.Fatalf("err: %s", err)
	}
}

func TestPlan_outPathNoChange(t *testing.T) {
	originalState := &terraform.State{
		Modules: []*terraform.ModuleState{
			&terraform.ModuleState{
				Path: []string{"root"},
				Resources: map[string]*terraform.ResourceState{
					"test_instance.foo": &terraform.ResourceState{
						Type: "test_instance",
						Primary: &terraform.InstanceState{
							ID: "bar",
						},
					},
				},
			},
		},
	}
	statePath := testStateFile(t, originalState)

	tf, err := ioutil.TempFile("", "tf")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	outPath := tf.Name()
	os.Remove(tf.Name())

	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
		},
	}

	args := []string{
		"-out", outPath,
		"-state", statePath,
		testFixturePath("plan"),
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	plan := testReadPlan(t, outPath)
	if !plan.Diff.Empty() {
		t.Fatalf("Expected empty plan to be written to plan file, got: %s", plan)
	}
}

// When using "-out" with a backend, the plan should encode the backend config
func TestPlan_outBackend(t *testing.T) {
	// Create a temporary working directory that is empty
	td := tempDir(t)
	copy.CopyDir(testFixturePath("plan-out-backend"), td)
	defer os.RemoveAll(td)
	defer testChdir(t, td)()

	// Our state
	originalState := &terraform.State{
		Modules: []*terraform.ModuleState{
			&terraform.ModuleState{
				Path: []string{"root"},
				Resources: map[string]*terraform.ResourceState{
					"test_instance.foo": &terraform.ResourceState{
						Type: "test_instance",
						Primary: &terraform.InstanceState{
							ID: "bar",
						},
					},
				},
			},
		},
	}
	originalState.Init()

	// Setup our backend state
	dataState, srv := testBackendState(t, originalState, 200)
	defer srv.Close()
	testStateFileRemote(t, dataState)

	outPath := "foo"
	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
		},
	}

	args := []string{
		"-out", outPath,
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	plan := testReadPlan(t, outPath)
	if !plan.Diff.Empty() {
		t.Fatalf("Expected empty plan to be written to plan file, got: %s", plan)
	}

	if plan.Backend.Empty() {
		t.Fatal("should have backend info")
	}
	if !reflect.DeepEqual(plan.Backend, dataState.Backend) {
		t.Fatalf("bad: %#v", plan.Backend)
	}
}

// When using "-out" with a legacy remote state, the plan should encode
// the backend config
func TestPlan_outBackendLegacy(t *testing.T) {
	// Create a temporary working directory that is empty
	td := tempDir(t)
	copy.CopyDir(testFixturePath("plan-out-backend-legacy"), td)
	defer os.RemoveAll(td)
	defer testChdir(t, td)()

	// Our state
	originalState := &terraform.State{
		Modules: []*terraform.ModuleState{
			&terraform.ModuleState{
				Path: []string{"root"},
				Resources: map[string]*terraform.ResourceState{
					"test_instance.foo": &terraform.ResourceState{
						Type: "test_instance",
						Primary: &terraform.InstanceState{
							ID: "bar",
						},
					},
				},
			},
		},
	}
	originalState.Init()

	// Setup our legacy state
	remoteState, srv := testRemoteState(t, originalState, 200)
	defer srv.Close()
	dataState := terraform.NewState()
	dataState.Remote = remoteState
	testStateFileRemote(t, dataState)

	outPath := "foo"
	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
		},
	}

	args := []string{
		"-out", outPath,
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	plan := testReadPlan(t, outPath)
	if !plan.Diff.Empty() {
		t.Fatalf("Expected empty plan to be written to plan file, got: %s", plan)
	}

	if plan.State.Remote.Empty() {
		t.Fatal("should have remote info")
	}
}

func TestPlan_refresh(t *testing.T) {
	tmp, cwd := testCwd(t)
	defer testFixCwd(t, tmp, cwd)

	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
		},
	}

	args := []string{
		"-refresh=false",
		testFixturePath("plan"),
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	if p.RefreshCalled {
		t.Fatal("refresh should not be called")
	}
}

func TestPlan_state(t *testing.T) {
	// Write out some prior state
	tf, err := ioutil.TempFile("", "tf")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	statePath := tf.Name()
	defer os.Remove(tf.Name())

	originalState := testState()
	err = terraform.WriteState(originalState, tf)
	tf.Close()
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
		},
	}

	args := []string{
		"-state", statePath,
		testFixturePath("plan"),
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	// Verify that the provider was called with the existing state
	actual := strings.TrimSpace(p.DiffState.String())
	expected := strings.TrimSpace(testPlanStateStr)
	if actual != expected {
		t.Fatalf("bad:\n\n%s", actual)
	}
}

func TestPlan_stateDefault(t *testing.T) {
	originalState := testState()

	// Write the state file in a temporary directory with the
	// default filename.
	td, err := ioutil.TempDir("", "tf")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	statePath := filepath.Join(td, DefaultStateFilename)

	f, err := os.Create(statePath)
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	err = terraform.WriteState(originalState, f)
	f.Close()
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	// Change to that directory
	cwd, err := os.Getwd()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if err := os.Chdir(filepath.Dir(statePath)); err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Chdir(cwd)

	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
		},
	}

	args := []string{
		testFixturePath("plan"),
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	// Verify that the provider was called with the existing state
	actual := strings.TrimSpace(p.DiffState.String())
	expected := strings.TrimSpace(testPlanStateDefaultStr)
	if actual != expected {
		t.Fatalf("bad:\n\n%s", actual)
	}
}

func TestPlan_stateFuture(t *testing.T) {
	originalState := testState()
	originalState.TFVersion = "99.99.99"
	statePath := testStateFile(t, originalState)

	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
		},
	}

	args := []string{
		"-state", statePath,
		testFixturePath("plan"),
	}
	if code := c.Run(args); code == 0 {
		t.Fatal("should fail")
	}

	f, err := os.Open(statePath)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	newState, err := terraform.ReadState(f)
	f.Close()
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	if !newState.Equal(originalState) {
		t.Fatalf("bad: %#v", newState)
	}
	if newState.TFVersion != originalState.TFVersion {
		t.Fatalf("bad: %#v", newState)
	}
}

func TestPlan_statePast(t *testing.T) {
	originalState := testState()
	originalState.TFVersion = "0.1.0"
	statePath := testStateFile(t, originalState)

	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
		},
	}

	args := []string{
		"-state", statePath,
		testFixturePath("plan"),
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}
}

func TestPlan_validate(t *testing.T) {
	// This is triggered by not asking for input so we have to set this to false
	test = false
	defer func() { test = true }()

	cwd, err := os.Getwd()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if err := os.Chdir(testFixturePath("plan-invalid")); err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Chdir(cwd)

	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
		},
	}

	args := []string{}
	if code := c.Run(args); code != 1 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	actual := ui.ErrorWriter.String()
	if !strings.Contains(actual, "cannot be computed") {
		t.Fatalf("bad: %s", actual)
	}
}

func TestPlan_vars(t *testing.T) {
	tmp, cwd := testCwd(t)
	defer testFixCwd(t, tmp, cwd)

	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
		},
	}

	actual := ""
	p.DiffFn = func(
		info *terraform.InstanceInfo,
		s *terraform.InstanceState,
		c *terraform.ResourceConfig) (*terraform.InstanceDiff, error) {
		if v, ok := c.Config["value"]; ok {
			actual = v.(string)
		}

		return nil, nil
	}

	args := []string{
		"-var", "foo=bar",
		testFixturePath("plan-vars"),
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	if actual != "bar" {
		t.Fatal("didn't work")
	}
}

func TestPlan_varsUnset(t *testing.T) {
	tmp, cwd := testCwd(t)
	defer testFixCwd(t, tmp, cwd)

	// Disable test mode so input would be asked
	test = false
	defer func() { test = true }()

	defaultInputReader = bytes.NewBufferString("bar\n")

	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
		},
	}

	args := []string{
		testFixturePath("plan-vars"),
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}
}

func TestPlan_varFile(t *testing.T) {
	tmp, cwd := testCwd(t)
	defer testFixCwd(t, tmp, cwd)

	varFilePath := testTempFile(t)
	if err := ioutil.WriteFile(varFilePath, []byte(planVarFile), 0644); err != nil {
		t.Fatalf("err: %s", err)
	}

	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
		},
	}

	actual := ""
	p.DiffFn = func(
		info *terraform.InstanceInfo,
		s *terraform.InstanceState,
		c *terraform.ResourceConfig) (*terraform.InstanceDiff, error) {
		if v, ok := c.Config["value"]; ok {
			actual = v.(string)
		}

		return nil, nil
	}

	args := []string{
		"-var-file", varFilePath,
		testFixturePath("plan-vars"),
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	if actual != "bar" {
		t.Fatal("didn't work")
	}
}

func TestPlan_varFileDefault(t *testing.T) {
	varFileDir := testTempDir(t)
	varFilePath := filepath.Join(varFileDir, "terraform.tfvars")
	if err := ioutil.WriteFile(varFilePath, []byte(planVarFile), 0644); err != nil {
		t.Fatalf("err: %s", err)
	}

	cwd, err := os.Getwd()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if err := os.Chdir(varFileDir); err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Chdir(cwd)

	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
		},
	}

	actual := ""
	p.DiffFn = func(
		info *terraform.InstanceInfo,
		s *terraform.InstanceState,
		c *terraform.ResourceConfig) (*terraform.InstanceDiff, error) {
		if v, ok := c.Config["value"]; ok {
			actual = v.(string)
		}

		return nil, nil
	}

	args := []string{
		testFixturePath("plan-vars"),
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	if actual != "bar" {
		t.Fatal("didn't work")
	}
}

func TestPlan_detailedExitcode(t *testing.T) {
	cwd, err := os.Getwd()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if err := os.Chdir(testFixturePath("plan")); err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Chdir(cwd)

	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
		},
	}

	args := []string{"-detailed-exitcode"}
	if code := c.Run(args); code != 2 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}
}

func TestPlan_detailedExitcode_emptyDiff(t *testing.T) {
	cwd, err := os.Getwd()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if err := os.Chdir(testFixturePath("plan-emptydiff")); err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Chdir(cwd)

	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
		},
	}

	args := []string{"-detailed-exitcode"}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}
}

func TestPlan_shutdown(t *testing.T) {
	cancelled := make(chan struct{})

	shutdownCh := make(chan struct{})
	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(p),
			Ui:               ui,
			ShutdownCh:       shutdownCh,
		},
	}

	p.StopFn = func() error {
		close(cancelled)
		return nil
	}

	var once sync.Once

	p.DiffFn = func(
		*terraform.InstanceInfo,
		*terraform.InstanceState,
		*terraform.ResourceConfig) (*terraform.InstanceDiff, error) {

		once.Do(func() {
			shutdownCh <- struct{}{}
		})

		return &terraform.InstanceDiff{
			Attributes: map[string]*terraform.ResourceAttrDiff{
				"ami": &terraform.ResourceAttrDiff{
					New: "bar",
				},
			},
		}, nil
	}

	if code := c.Run([]string{testFixturePath("apply-shutdown")}); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	select {
	case <-cancelled:
	case <-time.After(5 * time.Second):
		t.Fatal("command not cancelled")
	}
}

const planVarFile = `
foo = "bar"
`

const testPlanNoStateStr = `
<not created>
`

const testPlanStateStr = `
ID = bar
Tainted = false
`

const testPlanStateDefaultStr = `
ID = bar
Tainted = false
`


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/packer-community/winrmcp/winrmcp/cp.go<|end_filename|>
package winrmcp

import (
	"encoding/base64"
	"fmt"
	"io"
	"log"
	"os"
	"sync"

	"github.com/masterzen/winrm"
	"github.com/nu7hatch/gouuid"
)

func doCopy(client *winrm.Client, config *Config, in io.Reader, toPath string) error {
	tempFile, err := tempFileName()
	if err != nil {
		return fmt.Errorf("Error generating unique filename: %v", err)
	}
	tempPath := "$env:TEMP\\" + tempFile

	if os.Getenv("WINRMCP_DEBUG") != "" {
		log.Printf("Copying file to %s\n", tempPath)
	}

	err = uploadContent(client, config.MaxOperationsPerShell, "%TEMP%\\"+tempFile, in)
	if err != nil {
		return fmt.Errorf("Error uploading file to %s: %v", tempPath, err)
	}

	if os.Getenv("WINRMCP_DEBUG") != "" {
		log.Printf("Moving file from %s to %s", tempPath, toPath)
	}

	err = restoreContent(client, tempPath, toPath)
	if err != nil {
		return fmt.Errorf("Error restoring file from %s to %s: %v", tempPath, toPath, err)
	}

	if os.Getenv("WINRMCP_DEBUG") != "" {
		log.Printf("Removing temporary file %s", tempPath)
	}

	err = cleanupContent(client, tempPath)
	if err != nil {
		return fmt.Errorf("Error removing temporary file %s: %v", tempPath, err)
	}

	return nil
}

func uploadContent(client *winrm.Client, maxChunks int, filePath string, reader io.Reader) error {
	var err error
	done := false
	for !done {
		done, err = uploadChunks(client, filePath, maxChunks, reader)
		if err != nil {
			return err
		}
	}

	return nil
}

func uploadChunks(client *winrm.Client, filePath string, maxChunks int, reader io.Reader) (bool, error) {
	shell, err := client.CreateShell()
	if err != nil {
		return false, fmt.Errorf("Couldn't create shell: %v", err)
	}
	defer shell.Close()

	// Upload the file in chunks to get around the Windows command line size limit.
	// Base64 encodes each set of three bytes into four bytes. In addition the output
	// is padded to always be a multiple of four.
	//
	//   ceil(n / 3) * 4 = m1 - m2
	//
	//   where:
	//     n  = bytes
	//     m1 = max (8192 character command limit.)
	//     m2 = len(filePath)

	chunkSize := ((8000 - len(filePath)) / 4) * 3
	chunk := make([]byte, chunkSize)

	if maxChunks == 0 {
		maxChunks = 1
	}

	for i := 0; i < maxChunks; i++ {
		n, err := reader.Read(chunk)

		if err != nil && err != io.EOF {
			return false, err
		}
		if n == 0 {
			return true, nil
		}

		content := base64.StdEncoding.EncodeToString(chunk[:n])
		if err = appendContent(shell, filePath, content); err != nil {
			return false, err
		}
	}

	return false, nil
}

func restoreContent(client *winrm.Client, fromPath, toPath string) error {
	shell, err := client.CreateShell()
	if err != nil {
		return err
	}

	defer shell.Close()
	script := fmt.Sprintf(`
		$tmp_file_path = [System.IO.Path]::GetFullPath("%s")
		$dest_file_path = [System.IO.Path]::GetFullPath("%s".Trim("'"))
		if (Test-Path $dest_file_path) {
			rm $dest_file_path
		}
		else {
			$dest_dir = ([System.IO.Path]::GetDirectoryName($dest_file_path))
			New-Item -ItemType directory -Force -ErrorAction SilentlyContinue -Path $dest_dir | Out-Null
		}

		if (Test-Path $tmp_file_path) {
			$reader = [System.IO.File]::OpenText($tmp_file_path)
			$writer = [System.IO.File]::OpenWrite($dest_file_path)
			try {
				for(;;) {
					$base64_line = $reader.ReadLine()
					if ($base64_line -eq $null) { break }
					$bytes = [System.Convert]::FromBase64String($base64_line)
					$writer.write($bytes, 0, $bytes.Length)
				}
			}
			finally {
				$reader.Close()
				$writer.Close()
			}
		} else {
			echo $null > $dest_file_path
		}
	`, fromPath, toPath)

	cmd, err := shell.Execute(winrm.Powershell(script))
	if err != nil {
		return err
	}
	defer cmd.Close()

	var wg sync.WaitGroup
	copyFunc := func(w io.Writer, r io.Reader) {
		defer wg.Done()
		io.Copy(w, r)
	}

	wg.Add(2)
	go copyFunc(os.Stdout, cmd.Stdout)
	go copyFunc(os.Stderr, cmd.Stderr)

	cmd.Wait()
	wg.Wait()

	if cmd.ExitCode() != 0 {
		return fmt.Errorf("restore operation returned code=%d", cmd.ExitCode())
	}
	return nil
}

func cleanupContent(client *winrm.Client, filePath string) error {
	shell, err := client.CreateShell()
	if err != nil {
		return err
	}

	defer shell.Close()
	cmd, err := shell.Execute("powershell", "Remove-Item", filePath, "-ErrorAction SilentlyContinue")
	if err != nil {
		return err
	}

	cmd.Wait()
	cmd.Close()
	return nil
}

func appendContent(shell *winrm.Shell, filePath, content string) error {
	cmd, err := shell.Execute(fmt.Sprintf("echo %s >> \"%s\"", content, filePath))

	if err != nil {
		return err
	}

	defer cmd.Close()
	var wg sync.WaitGroup
	copyFunc := func(w io.Writer, r io.Reader) {
		defer wg.Done()
		io.Copy(w, r)
	}

	wg.Add(2)
	go copyFunc(os.Stdout, cmd.Stdout)
	go copyFunc(os.Stderr, cmd.Stderr)

	cmd.Wait()
	wg.Wait()

	if cmd.ExitCode() != 0 {
		return fmt.Errorf("upload operation returned code=%d", cmd.ExitCode())
	}

	return nil
}

func tempFileName() (string, error) {
	uniquePart, err := uuid.NewV4()
	if err != nil {
		return "", err
	}

	return fmt.Sprintf("winrmcp-%s.tmp", uniquePart), nil
}


<|start_filename|>vendor/github.com/hashicorp/go-getter/decompress_tbz2_test.go<|end_filename|>
package getter

import (
	"path/filepath"
	"testing"
)

func TestTarBzip2Decompressor(t *testing.T) {
	orderingPaths := []string{"workers/", "workers/mq/", "workers/mq/__init__.py"}

	cases := []TestDecompressCase{
		{
			"empty.tar.bz2",
			false,
			true,
			nil,
			"",
		},

		{
			"single.tar.bz2",
			false,
			false,
			nil,
			"d3b07384d113edec49eaa6238ad5ff00",
		},

		{
			"single.tar.bz2",
			true,
			false,
			[]string{"file"},
			"",
		},

		{
			"multiple.tar.bz2",
			true,
			false,
			[]string{"file1", "file2"},
			"",
		},

		{
			"multiple.tar.bz2",
			false,
			true,
			nil,
			"",
		},

		// Tests when the file is listed before the parent folder
		{
			"ordering.tar.bz2",
			true,
			false,
			orderingPaths,
			"",
		},
	}

	for i, tc := range cases {
		cases[i].Input = filepath.Join("./test-fixtures", "decompress-tbz2", tc.Input)
	}

	TestDecompressor(t, new(TarBzip2Decompressor), cases)
}


<|start_filename|>vendor/github.com/mitchellh/packer/packer/post_processor.go<|end_filename|>
package packer

// A PostProcessor is responsible for taking an artifact of a build
// and doing some sort of post-processing to turn this into another
// artifact. An example of a post-processor would be something that takes
// the result of a build, compresses it, and returns a new artifact containing
// a single file of the prior artifact compressed.
type PostProcessor interface {
	// Configure is responsible for setting up configuration, storing
	// the state for later, and returning and errors, such as validation
	// errors.
	Configure(...interface{}) error

	// PostProcess takes a previously created Artifact and produces another
	// Artifact. If an error occurs, it should return that error. If `keep`
	// is to true, then the previous artifact is forcibly kept.
	PostProcess(Ui, Artifact) (a Artifact, keep bool, err error)
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/aws/aws-sdk-go/service/dynamodb/errors.go<|end_filename|>
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.

package dynamodb

const (

	// ErrCodeBackupInUseException for service response error code
	// "BackupInUseException".
	//
	// There is another ongoing conflicting backup control plane operation on the
	// table. The backups is either being created, deleted or restored to a table.
	ErrCodeBackupInUseException = "BackupInUseException"

	// ErrCodeBackupNotFoundException for service response error code
	// "BackupNotFoundException".
	//
	// Backup not found for the given BackupARN.
	ErrCodeBackupNotFoundException = "BackupNotFoundException"

	// ErrCodeConditionalCheckFailedException for service response error code
	// "ConditionalCheckFailedException".
	//
	// A condition specified in the operation could not be evaluated.
	ErrCodeConditionalCheckFailedException = "ConditionalCheckFailedException"

	// ErrCodeContinuousBackupsUnavailableException for service response error code
	// "ContinuousBackupsUnavailableException".
	//
	// Backups have not yet been enabled for this table.
	ErrCodeContinuousBackupsUnavailableException = "ContinuousBackupsUnavailableException"

	// ErrCodeGlobalTableAlreadyExistsException for service response error code
	// "GlobalTableAlreadyExistsException".
	//
	// The specified global table already exists.
	ErrCodeGlobalTableAlreadyExistsException = "GlobalTableAlreadyExistsException"

	// ErrCodeGlobalTableNotFoundException for service response error code
	// "GlobalTableNotFoundException".
	//
	// The specified global table does not exist.
	ErrCodeGlobalTableNotFoundException = "GlobalTableNotFoundException"

	// ErrCodeInternalServerError for service response error code
	// "InternalServerError".
	//
	// An error occurred on the server side.
	ErrCodeInternalServerError = "InternalServerError"

	// ErrCodeItemCollectionSizeLimitExceededException for service response error code
	// "ItemCollectionSizeLimitExceededException".
	//
	// An item collection is too large. This exception is only returned for tables
	// that have one or more local secondary indexes.
	ErrCodeItemCollectionSizeLimitExceededException = "ItemCollectionSizeLimitExceededException"

	// ErrCodeLimitExceededException for service response error code
	// "LimitExceededException".
	//
	// The number of concurrent table requests (cumulative number of tables in the
	// CREATING, DELETING or UPDATING state) exceeds the maximum allowed of 10.
	//
	// Also, for tables with secondary indexes, only one of those tables can be
	// in the CREATING state at any point in time. Do not attempt to create more
	// than one such table simultaneously.
	//
	// The total limit of tables in the ACTIVE state is 250.
	ErrCodeLimitExceededException = "LimitExceededException"

	// ErrCodeProvisionedThroughputExceededException for service response error code
	// "ProvisionedThroughputExceededException".
	//
	// Your request rate is too high. The AWS SDKs for DynamoDB automatically retry
	// requests that receive this exception. Your request is eventually successful,
	// unless your retry queue is too large to finish. Reduce the frequency of requests
	// and use exponential backoff. For more information, go to Error Retries and
	// Exponential Backoff (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff)
	// in the Amazon DynamoDB Developer Guide.
	ErrCodeProvisionedThroughputExceededException = "ProvisionedThroughputExceededException"

	// ErrCodeReplicaAlreadyExistsException for service response error code
	// "ReplicaAlreadyExistsException".
	//
	// The specified replica is already part of the global table.
	ErrCodeReplicaAlreadyExistsException = "ReplicaAlreadyExistsException"

	// ErrCodeReplicaNotFoundException for service response error code
	// "ReplicaNotFoundException".
	//
	// The specified replica is no longer part of the global table.
	ErrCodeReplicaNotFoundException = "ReplicaNotFoundException"

	// ErrCodeResourceInUseException for service response error code
	// "ResourceInUseException".
	//
	// The operation conflicts with the resource's availability. For example, you
	// attempted to recreate an existing table, or tried to delete a table currently
	// in the CREATING state.
	ErrCodeResourceInUseException = "ResourceInUseException"

	// ErrCodeResourceNotFoundException for service response error code
	// "ResourceNotFoundException".
	//
	// The operation tried to access a nonexistent table or index. The resource
	// might not be specified correctly, or its status might not be ACTIVE.
	ErrCodeResourceNotFoundException = "ResourceNotFoundException"

	// ErrCodeTableAlreadyExistsException for service response error code
	// "TableAlreadyExistsException".
	//
	// A table with the name already exists.
	ErrCodeTableAlreadyExistsException = "TableAlreadyExistsException"

	// ErrCodeTableInUseException for service response error code
	// "TableInUseException".
	//
	// A table by that name is either being created or deleted.
	ErrCodeTableInUseException = "TableInUseException"

	// ErrCodeTableNotFoundException for service response error code
	// "TableNotFoundException".
	//
	// A table with the name TableName does not currently exist within the subscriber's
	// account.
	ErrCodeTableNotFoundException = "TableNotFoundException"
)


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_iam_account_password_policy.go<|end_filename|>
package aws

import (
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/iam"

	"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsIamAccountPasswordPolicy() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsIamAccountPasswordPolicyUpdate,
		Read:   resourceAwsIamAccountPasswordPolicyRead,
		Update: resourceAwsIamAccountPasswordPolicyUpdate,
		Delete: resourceAwsIamAccountPasswordPolicyDelete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"allow_users_to_change_password": &schema.Schema{
				Type:     schema.TypeBool,
				Optional: true,
				Default:  true,
			},
			"expire_passwords": &schema.Schema{
				Type:     schema.TypeBool,
				Computed: true,
			},
			"hard_expiry": &schema.Schema{
				Type:     schema.TypeBool,
				Optional: true,
				Computed: true,
			},
			"max_password_age": &schema.Schema{
				Type:     schema.TypeInt,
				Optional: true,
				Computed: true,
			},
			"minimum_password_length": &schema.Schema{
				Type:     schema.TypeInt,
				Optional: true,
				Default:  6,
			},
			"password_reuse_prevention": &schema.Schema{
				Type:     schema.TypeInt,
				Optional: true,
				Computed: true,
			},
			"require_lowercase_characters": &schema.Schema{
				Type:     schema.TypeBool,
				Optional: true,
				Computed: true,
			},
			"require_numbers": &schema.Schema{
				Type:     schema.TypeBool,
				Optional: true,
				Computed: true,
			},
			"require_symbols": &schema.Schema{
				Type:     schema.TypeBool,
				Optional: true,
				Computed: true,
			},
			"require_uppercase_characters": &schema.Schema{
				Type:     schema.TypeBool,
				Optional: true,
				Computed: true,
			},
		},
	}
}

func resourceAwsIamAccountPasswordPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
	iamconn := meta.(*AWSClient).iamconn

	input := &iam.UpdateAccountPasswordPolicyInput{}

	if v, ok := d.GetOk("allow_users_to_change_password"); ok {
		input.AllowUsersToChangePassword = aws.Bool(v.(bool))
	}
	if v, ok := d.GetOk("hard_expiry"); ok {
		input.HardExpiry = aws.Bool(v.(bool))
	}
	if v, ok := d.GetOk("max_password_age"); ok {
		input.MaxPasswordAge = aws.Int64(int64(v.(int)))
	}
	if v, ok := d.GetOk("minimum_password_length"); ok {
		input.MinimumPasswordLength = aws.Int64(int64(v.(int)))
	}
	if v, ok := d.GetOk("password_reuse_prevention"); ok {
		input.PasswordReusePrevention = aws.Int64(int64(v.(int)))
	}
	if v, ok := d.GetOk("require_lowercase_characters"); ok {
		input.RequireLowercaseCharacters = aws.Bool(v.(bool))
	}
	if v, ok := d.GetOk("require_numbers"); ok {
		input.RequireNumbers = aws.Bool(v.(bool))
	}
	if v, ok := d.GetOk("require_symbols"); ok {
		input.RequireSymbols = aws.Bool(v.(bool))
	}
	if v, ok := d.GetOk("require_uppercase_characters"); ok {
		input.RequireUppercaseCharacters = aws.Bool(v.(bool))
	}

	log.Printf("[DEBUG] Updating IAM account password policy: %s", input)
	_, err := iamconn.UpdateAccountPasswordPolicy(input)
	if err != nil {
		return fmt.Errorf("Error updating IAM Password Policy: %s", err)
	}
	log.Println("[DEBUG] IAM account password policy updated")

	d.SetId("iam-account-password-policy")

	return resourceAwsIamAccountPasswordPolicyRead(d, meta)
}

func resourceAwsIamAccountPasswordPolicyRead(d *schema.ResourceData, meta interface{}) error {
	iamconn := meta.(*AWSClient).iamconn

	input := &iam.GetAccountPasswordPolicyInput{}
	resp, err := iamconn.GetAccountPasswordPolicy(input)
	if err != nil {
		awsErr, ok := err.(awserr.Error)
		if ok && awsErr.Code() == "NoSuchEntity" {
			log.Printf("[WARN] IAM account password policy is gone (i.e. default)")
			d.SetId("")
			return nil
		}
		return fmt.Errorf("Error reading IAM account password policy: %s", err)
	}

	log.Printf("[DEBUG] Received IAM account password policy: %s", resp)

	policy := resp.PasswordPolicy

	d.Set("allow_users_to_change_password", policy.AllowUsersToChangePassword)
	d.Set("expire_passwords", policy.ExpirePasswords)
	d.Set("hard_expiry", policy.HardExpiry)
	d.Set("max_password_age", policy.MaxPasswordAge)
	d.Set("minimum_password_length", policy.MinimumPasswordLength)
	d.Set("password_reuse_prevention", policy.PasswordReusePrevention)
	d.Set("require_lowercase_characters", policy.RequireLowercaseCharacters)
	d.Set("require_numbers", policy.RequireNumbers)
	d.Set("require_symbols", policy.RequireSymbols)
	d.Set("require_uppercase_characters", policy.RequireUppercaseCharacters)

	return nil
}

func resourceAwsIamAccountPasswordPolicyDelete(d *schema.ResourceData, meta interface{}) error {
	iamconn := meta.(*AWSClient).iamconn

	log.Println("[DEBUG] Deleting IAM account password policy")
	input := &iam.DeleteAccountPasswordPolicyInput{}
	if _, err := iamconn.DeleteAccountPasswordPolicy(input); err != nil {
		return fmt.Errorf("Error deleting IAM Password Policy: %s", err)
	}
	d.SetId("")
	log.Println("[DEBUG] Deleted IAM account password policy")

	return nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/network_acl_entry.go<|end_filename|>
package aws

import (
	"fmt"
	"net"
	"strconv"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/ec2"
)

func expandNetworkAclEntries(configured []interface{}, entryType string) ([]*ec2.NetworkAclEntry, error) {
	entries := make([]*ec2.NetworkAclEntry, 0, len(configured))
	for _, eRaw := range configured {
		data := eRaw.(map[string]interface{})
		protocol := data["protocol"].(string)
		p, err := strconv.Atoi(protocol)
		if err != nil {
			var ok bool
			p, ok = protocolIntegers()[protocol]
			if !ok {
				return nil, fmt.Errorf("Invalid Protocol %s for rule %#v", protocol, data)
			}
		}

		e := &ec2.NetworkAclEntry{
			Protocol: aws.String(strconv.Itoa(p)),
			PortRange: &ec2.PortRange{
				From: aws.Int64(int64(data["from_port"].(int))),
				To:   aws.Int64(int64(data["to_port"].(int))),
			},
			Egress:     aws.Bool(entryType == "egress"),
			RuleAction: aws.String(data["action"].(string)),
			RuleNumber: aws.Int64(int64(data["rule_no"].(int))),
		}

		if v, ok := data["ipv6_cidr_block"]; ok {
			e.Ipv6CidrBlock = aws.String(v.(string))
		}

		if v, ok := data["cidr_block"]; ok {
			e.CidrBlock = aws.String(v.(string))
		}

		// Specify additional required fields for ICMP
		if p == 1 {
			e.IcmpTypeCode = &ec2.IcmpTypeCode{}
			if v, ok := data["icmp_code"]; ok {
				e.IcmpTypeCode.Code = aws.Int64(int64(v.(int)))
			}
			if v, ok := data["icmp_type"]; ok {
				e.IcmpTypeCode.Type = aws.Int64(int64(v.(int)))
			}
		}

		entries = append(entries, e)
	}
	return entries, nil
}

func flattenNetworkAclEntries(list []*ec2.NetworkAclEntry) []map[string]interface{} {
	entries := make([]map[string]interface{}, 0, len(list))

	for _, entry := range list {

		newEntry := map[string]interface{}{
			"from_port": *entry.PortRange.From,
			"to_port":   *entry.PortRange.To,
			"action":    *entry.RuleAction,
			"rule_no":   *entry.RuleNumber,
			"protocol":  *entry.Protocol,
		}

		if entry.CidrBlock != nil {
			newEntry["cidr_block"] = *entry.CidrBlock
		}

		if entry.Ipv6CidrBlock != nil {
			newEntry["ipv6_cidr_block"] = *entry.Ipv6CidrBlock
		}

		entries = append(entries, newEntry)
	}

	return entries

}

func protocolStrings(protocolIntegers map[string]int) map[int]string {
	protocolStrings := make(map[int]string, len(protocolIntegers))
	for k, v := range protocolIntegers {
		protocolStrings[v] = k
	}

	return protocolStrings
}

func protocolIntegers() map[string]int {
	var protocolIntegers = make(map[string]int)
	protocolIntegers = map[string]int{
		// defined at https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
		"ah":   51,
		"esp":  50,
		"udp":  17,
		"tcp":  6,
		"icmp": 1,
		"all":  -1,
		"vrrp": 112,
	}
	return protocolIntegers
}

// expectedPortPair stores a pair of ports we expect to see together.
type expectedPortPair struct {
	to_port   int64
	from_port int64
}

// validatePorts ensures the ports and protocol match expected
// values.
func validatePorts(to int64, from int64, expected expectedPortPair) bool {
	if to != expected.to_port || from != expected.from_port {
		return false
	}

	return true
}

// validateCIDRBlock ensures the passed CIDR block represents an implied
// network, and not an overly-specified IP address.
func validateCIDRBlock(cidr string) error {
	_, ipnet, err := net.ParseCIDR(cidr)
	if err != nil {
		return err
	}
	if ipnet.String() != cidr {
		return fmt.Errorf("%s is not a valid mask; did you mean %s?", cidr, ipnet)
	}

	return nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/command/workspace_new.go<|end_filename|>
package command

import (
	"context"
	"fmt"
	"os"
	"strings"

	"github.com/hashicorp/terraform/command/clistate"
	"github.com/hashicorp/terraform/state"
	"github.com/hashicorp/terraform/terraform"
	"github.com/mitchellh/cli"
	"github.com/posener/complete"
)

type WorkspaceNewCommand struct {
	Meta
	LegacyName bool
}

func (c *WorkspaceNewCommand) Run(args []string) int {
	args, err := c.Meta.process(args, true)
	if err != nil {
		return 1
	}

	envCommandShowWarning(c.Ui, c.LegacyName)

	statePath := ""

	cmdFlags := c.Meta.flagSet("workspace new")
	cmdFlags.StringVar(&statePath, "state", "", "terraform state file")
	cmdFlags.Usage = func() { c.Ui.Error(c.Help()) }
	if err := cmdFlags.Parse(args); err != nil {
		return 1
	}
	args = cmdFlags.Args()
	if len(args) == 0 {
		c.Ui.Error("Expected a single argument: NAME.\n")
		return cli.RunResultHelp
	}

	newEnv := args[0]

	if !validWorkspaceName(newEnv) {
		c.Ui.Error(fmt.Sprintf(envInvalidName, newEnv))
		return 1
	}

	// You can't ask to create a workspace when you're overriding the
	// workspace name to be something different.
	if current, isOverridden := c.WorkspaceOverridden(); current != newEnv && isOverridden {
		c.Ui.Error(envIsOverriddenNewError)
		return 1
	}

	configPath, err := ModulePath(args[1:])
	if err != nil {
		c.Ui.Error(err.Error())
		return 1
	}

	conf, err := c.Config(configPath)
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Failed to load root config module: %s", err))
	}

	// Load the backend
	b, err := c.Backend(&BackendOpts{
		Config: conf,
	})

	if err != nil {
		c.Ui.Error(fmt.Sprintf("Failed to load backend: %s", err))
		return 1
	}

	states, err := b.States()
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Failed to get configured named states: %s", err))
		return 1
	}
	for _, s := range states {
		if newEnv == s {
			c.Ui.Error(fmt.Sprintf(envExists, newEnv))
			return 1
		}
	}

	_, err = b.State(newEnv)
	if err != nil {
		c.Ui.Error(err.Error())
		return 1
	}

	// now set the current workspace locally
	if err := c.SetWorkspace(newEnv); err != nil {
		c.Ui.Error(fmt.Sprintf("Error selecting new workspace: %s", err))
		return 1
	}

	c.Ui.Output(c.Colorize().Color(fmt.Sprintf(
		strings.TrimSpace(envCreated), newEnv)))

	if statePath == "" {
		// if we're not loading a state, then we're done
		return 0
	}

	// load the new Backend state
	sMgr, err := b.State(newEnv)
	if err != nil {
		c.Ui.Error(err.Error())
		return 1
	}

	if c.stateLock {
		lockCtx, cancel := context.WithTimeout(context.Background(), c.stateLockTimeout)
		defer cancel()

		// Lock the state if we can
		lockInfo := state.NewLockInfo()
		lockInfo.Operation = "workspace new"
		lockID, err := clistate.Lock(lockCtx, sMgr, lockInfo, c.Ui, c.Colorize())
		if err != nil {
			c.Ui.Error(fmt.Sprintf("Error locking state: %s", err))
			return 1
		}
		defer clistate.Unlock(sMgr, lockID, c.Ui, c.Colorize())
	}

	// read the existing state file
	stateFile, err := os.Open(statePath)
	if err != nil {
		c.Ui.Error(err.Error())
		return 1
	}

	s, err := terraform.ReadState(stateFile)
	if err != nil {
		c.Ui.Error(err.Error())
		return 1
	}

	// save the existing state in the new Backend.
	err = sMgr.WriteState(s)
	if err != nil {
		c.Ui.Error(err.Error())
		return 1
	}
	err = sMgr.PersistState()
	if err != nil {
		c.Ui.Error(err.Error())
		return 1
	}

	return 0
}

func (c *WorkspaceNewCommand) AutocompleteArgs() complete.Predictor {
	return completePredictSequence{
		complete.PredictNothing, // the "new" subcommand itself (already matched)
		complete.PredictAnything,
		complete.PredictDirs(""),
	}
}

func (c *WorkspaceNewCommand) AutocompleteFlags() complete.Flags {
	return complete.Flags{
		"-state": complete.PredictFiles("*.tfstate"),
	}
}

func (c *WorkspaceNewCommand) Help() string {
	helpText := `
Usage: terraform workspace new [OPTIONS] NAME [DIR]

  Create a new Terraform workspace.


Options:

    -state=path    Copy an existing state file into the new workspace.
`
	return strings.TrimSpace(helpText)
}

func (c *WorkspaceNewCommand) Synopsis() string {
	return "Create a new workspace"
}


<|start_filename|>vendor/github.com/mitchellh/packer/vendor/github.com/approvals/go-approval-tests/reporters/reporter.go<|end_filename|>
package reporters

// Reporter are called on failing approvals.
type Reporter interface {
	// Report is called when the approved and received file do not match.
	Report(approved, received string) bool
}

// FirstWorkingReporter reports using the first possible reporter.
type FirstWorkingReporter struct {
	Reporters []Reporter
}

// Report is called when the approved and received file do not match.
func (s *FirstWorkingReporter) Report(approved, received string) bool {
	for _, reporter := range s.Reporters {
		result := reporter.Report(approved, received)
		if result {
			return true
		}
	}

	return false
}

// NewFirstWorkingReporter creates in the order reporters are passed in.
func NewFirstWorkingReporter(reporters ...Reporter) Reporter {
	return &FirstWorkingReporter{
		Reporters: reporters,
	}
}

// MultiReporter reports all reporters.
type MultiReporter struct {
	Reporters []Reporter
}

// Report is called when the approved and received file do not match.
func (s *MultiReporter) Report(approved, received string) bool {
	result := false
	for _, reporter := range s.Reporters {
		result = reporter.Report(approved, received) || result
	}

	return result
}

// NewMultiReporter calls all reporters.
func NewMultiReporter(reporters ...Reporter) Reporter {
	return &MultiReporter{
		Reporters: reporters,
	}
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/hashicorp/hcl2/hcl/json/parser.go<|end_filename|>
package json

import (
	"encoding/json"
	"fmt"
	"math/big"

	"github.com/hashicorp/hcl2/hcl"
)

func parseFileContent(buf []byte, filename string) (node, hcl.Diagnostics) {
	tokens := scan(buf, pos{
		Filename: filename,
		Pos: hcl.Pos{
			Byte:   0,
			Line:   1,
			Column: 1,
		},
	})
	p := newPeeker(tokens)
	node, diags := parseValue(p)
	if len(diags) == 0 && p.Peek().Type != tokenEOF {
		diags = diags.Append(&hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Extraneous data after value",
			Detail:   "Extra characters appear after the JSON value.",
			Subject:  p.Peek().Range.Ptr(),
		})
	}
	return node, diags
}

func parseValue(p *peeker) (node, hcl.Diagnostics) {
	tok := p.Peek()

	wrapInvalid := func(n node, diags hcl.Diagnostics) (node, hcl.Diagnostics) {
		if n != nil {
			return n, diags
		}
		return invalidVal{tok.Range}, diags
	}

	switch tok.Type {
	case tokenBraceO:
		return wrapInvalid(parseObject(p))
	case tokenBrackO:
		return wrapInvalid(parseArray(p))
	case tokenNumber:
		return wrapInvalid(parseNumber(p))
	case tokenString:
		return wrapInvalid(parseString(p))
	case tokenKeyword:
		return wrapInvalid(parseKeyword(p))
	case tokenBraceC:
		return wrapInvalid(nil, hcl.Diagnostics{
			{
				Severity: hcl.DiagError,
				Summary:  "Missing attribute value",
				Detail:   "A JSON value must start with a brace, a bracket, a number, a string, or a keyword.",
				Subject:  &tok.Range,
			},
		})
	case tokenBrackC:
		return wrapInvalid(nil, hcl.Diagnostics{
			{
				Severity: hcl.DiagError,
				Summary:  "Missing array element value",
				Detail:   "A JSON value must start with a brace, a bracket, a number, a string, or a keyword.",
				Subject:  &tok.Range,
			},
		})
	case tokenEOF:
		return wrapInvalid(nil, hcl.Diagnostics{
			{
				Severity: hcl.DiagError,
				Summary:  "Missing value",
				Detail:   "The JSON data ends prematurely.",
				Subject:  &tok.Range,
			},
		})
	default:
		return wrapInvalid(nil, hcl.Diagnostics{
			{
				Severity: hcl.DiagError,
				Summary:  "Invalid start of value",
				Detail:   "A JSON value must start with a brace, a bracket, a number, a string, or a keyword.",
				Subject:  &tok.Range,
			},
		})
	}
}

func tokenCanStartValue(tok token) bool {
	switch tok.Type {
	case tokenBraceO, tokenBrackO, tokenNumber, tokenString, tokenKeyword:
		return true
	default:
		return false
	}
}

func parseObject(p *peeker) (node, hcl.Diagnostics) {
	var diags hcl.Diagnostics

	open := p.Read()
	attrs := map[string]*objectAttr{}

	// recover is used to shift the peeker to what seems to be the end of
	// our object, so that when we encounter an error we leave the peeker
	// at a reasonable point in the token stream to continue parsing.
	recover := func(tok token) {
		open := 1
		for {
			switch tok.Type {
			case tokenBraceO:
				open++
			case tokenBraceC:
				open--
				if open <= 1 {
					return
				}
			case tokenEOF:
				// Ran out of source before we were able to recover,
				// so we'll bail here and let the caller deal with it.
				return
			}
			tok = p.Read()
		}
	}

Token:
	for {
		if p.Peek().Type == tokenBraceC {
			break Token
		}

		keyNode, keyDiags := parseValue(p)
		diags = diags.Extend(keyDiags)
		if keyNode == nil {
			return nil, diags
		}

		keyStrNode, ok := keyNode.(*stringVal)
		if !ok {
			return nil, diags.Append(&hcl.Diagnostic{
				Severity: hcl.DiagError,
				Summary:  "Invalid object attribute name",
				Detail:   "A JSON object attribute name must be a string",
				Subject:  keyNode.StartRange().Ptr(),
			})
		}

		key := keyStrNode.Value

		colon := p.Read()
		if colon.Type != tokenColon {
			recover(colon)

			if colon.Type == tokenBraceC || colon.Type == tokenComma {
				// Catch common mistake of using braces instead of brackets
				// for an object.
				return nil, diags.Append(&hcl.Diagnostic{
					Severity: hcl.DiagError,
					Summary:  "Missing object value",
					Detail:   "A JSON object attribute must have a value, introduced by a colon.",
					Subject:  &colon.Range,
				})
			}

			if colon.Type == tokenEquals {
				// Possible confusion with native zcl syntax.
				return nil, diags.Append(&hcl.Diagnostic{
					Severity: hcl.DiagError,
					Summary:  "Missing attribute value colon",
					Detail:   "JSON uses a colon as its name/value delimiter, not an equals sign.",
					Subject:  &colon.Range,
				})
			}

			return nil, diags.Append(&hcl.Diagnostic{
				Severity: hcl.DiagError,
				Summary:  "Missing attribute value colon",
				Detail:   "A colon must appear between an object attribute's name and its value.",
				Subject:  &colon.Range,
			})
		}

		valNode, valDiags := parseValue(p)
		diags = diags.Extend(valDiags)
		if valNode == nil {
			return nil, diags
		}

		if existing := attrs[key]; existing != nil {
			// Generate a diagnostic for the duplicate key, but continue parsing
			// anyway since this is a semantic error we can recover from.
			diags = diags.Append(&hcl.Diagnostic{
				Severity: hcl.DiagError,
				Summary:  "Duplicate JSON object property",
				Detail: fmt.Sprintf(
					"An property named %q was previously introduced at %s",
					key, existing.NameRange.String(),
				),
				Subject: &keyStrNode.SrcRange,
			})
		}
		attrs[key] = &objectAttr{
			Name:      key,
			Value:     valNode,
			NameRange: keyStrNode.SrcRange,
		}

		switch p.Peek().Type {
		case tokenComma:
			comma := p.Read()
			if p.Peek().Type == tokenBraceC {
				// Special error message for this common mistake
				return nil, diags.Append(&hcl.Diagnostic{
					Severity: hcl.DiagError,
					Summary:  "Trailing comma in object",
					Detail:   "JSON does not permit a trailing comma after the final attribute in an object.",
					Subject:  &comma.Range,
				})
			}
			continue Token
		case tokenEOF:
			return nil, diags.Append(&hcl.Diagnostic{
				Severity: hcl.DiagError,
				Summary:  "Unclosed object",
				Detail:   "No closing brace was found for this JSON object.",
				Subject:  &open.Range,
			})
		case tokenBrackC:
			// Consume the bracket anyway, so that we don't return with the peeker
			// at a strange place.
			p.Read()
			return nil, diags.Append(&hcl.Diagnostic{
				Severity: hcl.DiagError,
				Summary:  "Mismatched braces",
				Detail:   "A JSON object must be closed with a brace, not a bracket.",
				Subject:  p.Peek().Range.Ptr(),
			})
		case tokenBraceC:
			break Token
		default:
			recover(p.Read())
			return nil, diags.Append(&hcl.Diagnostic{
				Severity: hcl.DiagError,
				Summary:  "Missing attribute seperator comma",
				Detail:   "A comma must appear between each attribute declaration in an object.",
				Subject:  p.Peek().Range.Ptr(),
			})
		}

	}

	close := p.Read()
	return &objectVal{
		Attrs:      attrs,
		SrcRange:   hcl.RangeBetween(open.Range, close.Range),
		OpenRange:  open.Range,
		CloseRange: close.Range,
	}, diags
}

func parseArray(p *peeker) (node, hcl.Diagnostics) {
	var diags hcl.Diagnostics

	open := p.Read()
	vals := []node{}

	// recover is used to shift the peeker to what seems to be the end of
	// our array, so that when we encounter an error we leave the peeker
	// at a reasonable point in the token stream to continue parsing.
	recover := func(tok token) {
		open := 1
		for {
			switch tok.Type {
			case tokenBrackO:
				open++
			case tokenBrackC:
				open--
				if open <= 1 {
					return
				}
			case tokenEOF:
				// Ran out of source before we were able to recover,
				// so we'll bail here and let the caller deal with it.
				return
			}
			tok = p.Read()
		}
	}

Token:
	for {
		if p.Peek().Type == tokenBrackC {
			break Token
		}

		valNode, valDiags := parseValue(p)
		diags = diags.Extend(valDiags)
		if valNode == nil {
			return nil, diags
		}

		vals = append(vals, valNode)

		switch p.Peek().Type {
		case tokenComma:
			comma := p.Read()
			if p.Peek().Type == tokenBrackC {
				// Special error message for this common mistake
				return nil, diags.Append(&hcl.Diagnostic{
					Severity: hcl.DiagError,
					Summary:  "Trailing comma in array",
					Detail:   "JSON does not permit a trailing comma after the final attribute in an array.",
					Subject:  &comma.Range,
				})
			}
			continue Token
		case tokenColon:
			recover(p.Read())
			return nil, diags.Append(&hcl.Diagnostic{
				Severity: hcl.DiagError,
				Summary:  "Invalid array value",
				Detail:   "A colon is not used to introduce values in a JSON array.",
				Subject:  p.Peek().Range.Ptr(),
			})
		case tokenEOF:
			recover(p.Read())
			return nil, diags.Append(&hcl.Diagnostic{
				Severity: hcl.DiagError,
				Summary:  "Unclosed object",
				Detail:   "No closing bracket was found for this JSON array.",
				Subject:  &open.Range,
			})
		case tokenBraceC:
			recover(p.Read())
			return nil, diags.Append(&hcl.Diagnostic{
				Severity: hcl.DiagError,
				Summary:  "Mismatched brackets",
				Detail:   "A JSON array must be closed with a bracket, not a brace.",
				Subject:  p.Peek().Range.Ptr(),
			})
		case tokenBrackC:
			break Token
		default:
			recover(p.Read())
			return nil, diags.Append(&hcl.Diagnostic{
				Severity: hcl.DiagError,
				Summary:  "Missing attribute seperator comma",
				Detail:   "A comma must appear between each value in an array.",
				Subject:  p.Peek().Range.Ptr(),
			})
		}

	}

	close := p.Read()
	return &arrayVal{
		Values:    vals,
		SrcRange:  hcl.RangeBetween(open.Range, close.Range),
		OpenRange: open.Range,
	}, diags
}

func parseNumber(p *peeker) (node, hcl.Diagnostics) {
	tok := p.Read()

	// Use encoding/json to validate the number syntax.
	// TODO: Do this more directly to produce better diagnostics.
	var num json.Number
	err := json.Unmarshal(tok.Bytes, &num)
	if err != nil {
		return nil, hcl.Diagnostics{
			{
				Severity: hcl.DiagError,
				Summary:  "Invalid JSON number",
				Detail:   fmt.Sprintf("There is a syntax error in the given JSON number."),
				Subject:  &tok.Range,
			},
		}
	}

	f, _, err := (&big.Float{}).Parse(string(num), 10)
	if err != nil {
		// Should never happen if above passed, since JSON numbers are a subset
		// of what big.Float can parse...
		return nil, hcl.Diagnostics{
			{
				Severity: hcl.DiagError,
				Summary:  "Invalid JSON number",
				Detail:   fmt.Sprintf("There is a syntax error in the given JSON number."),
				Subject:  &tok.Range,
			},
		}
	}

	return &numberVal{
		Value:    f,
		SrcRange: tok.Range,
	}, nil
}

func parseString(p *peeker) (node, hcl.Diagnostics) {
	tok := p.Read()
	var str string
	err := json.Unmarshal(tok.Bytes, &str)

	if err != nil {
		var errRange hcl.Range
		if serr, ok := err.(*json.SyntaxError); ok {
			errOfs := serr.Offset
			errPos := tok.Range.Start
			errPos.Byte += int(errOfs)

			// TODO: Use the byte offset to properly count unicode
			// characters for the column, and mark the whole of the
			// character that was wrong as part of our range.
			errPos.Column += int(errOfs)

			errEndPos := errPos
			errEndPos.Byte++
			errEndPos.Column++

			errRange = hcl.Range{
				Filename: tok.Range.Filename,
				Start:    errPos,
				End:      errEndPos,
			}
		} else {
			errRange = tok.Range
		}

		var contextRange *hcl.Range
		if errRange != tok.Range {
			contextRange = &tok.Range
		}

		// FIXME: Eventually we should parse strings directly here so
		// we can produce a more useful error message in the face fo things
		// such as invalid escapes, etc.
		return nil, hcl.Diagnostics{
			{
				Severity: hcl.DiagError,
				Summary:  "Invalid JSON string",
				Detail:   fmt.Sprintf("There is a syntax error in the given JSON string."),
				Subject:  &errRange,
				Context:  contextRange,
			},
		}
	}

	return &stringVal{
		Value:    str,
		SrcRange: tok.Range,
	}, nil
}

func parseKeyword(p *peeker) (node, hcl.Diagnostics) {
	tok := p.Read()
	s := string(tok.Bytes)

	switch s {
	case "true":
		return &booleanVal{
			Value:    true,
			SrcRange: tok.Range,
		}, nil
	case "false":
		return &booleanVal{
			Value:    false,
			SrcRange: tok.Range,
		}, nil
	case "null":
		return &nullVal{
			SrcRange: tok.Range,
		}, nil
	case "undefined", "NaN", "Infinity":
		return nil, hcl.Diagnostics{
			{
				Severity: hcl.DiagError,
				Summary:  "Invalid JSON keyword",
				Detail:   fmt.Sprintf("The JavaScript identifier %q cannot be used in JSON.", s),
				Subject:  &tok.Range,
			},
		}
	default:
		var dym string
		if suggest := keywordSuggestion(s); suggest != "" {
			dym = fmt.Sprintf(" Did you mean %q?", suggest)
		}

		return nil, hcl.Diagnostics{
			{
				Severity: hcl.DiagError,
				Summary:  "Invalid JSON keyword",
				Detail:   fmt.Sprintf("%q is not a valid JSON keyword.%s", s, dym),
				Subject:  &tok.Range,
			},
		}
	}
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/hashicorp/hcl2/hcldec/public.go<|end_filename|>
package hcldec

import (
	"github.com/hashicorp/hcl2/hcl"
	"github.com/zclconf/go-cty/cty"
)

// Decode interprets the given body using the given specification and returns
// the resulting value. If the given body is not valid per the spec, error
// diagnostics are returned and the returned value is likely to be incomplete.
//
// The ctx argument may be nil, in which case any references to variables or
// functions will produce error diagnostics.
func Decode(body hcl.Body, spec Spec, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) {
	val, _, diags := decode(body, nil, ctx, spec, false)
	return val, diags
}

// PartialDecode is like Decode except that it permits "leftover" items in
// the top-level body, which are returned as a new body to allow for
// further processing.
//
// Any descendent block bodies are _not_ decoded partially and thus must
// be fully described by the given specification.
func PartialDecode(body hcl.Body, spec Spec, ctx *hcl.EvalContext) (cty.Value, hcl.Body, hcl.Diagnostics) {
	return decode(body, nil, ctx, spec, true)
}

// ImpliedType returns the value type that should result from decoding the
// given spec.
func ImpliedType(spec Spec) cty.Type {
	return impliedType(spec)
}

// SourceRange interprets the given body using the given specification and
// then returns the source range of the value that would be used to
// fulfill the spec.
//
// This can be used if application-level validation detects value errors, to
// obtain a reasonable SourceRange to use for generated diagnostics. It works
// best when applied to specific body items (e.g. using AttrSpec, BlockSpec, ...)
// as opposed to entire bodies using ObjectSpec, TupleSpec. The result will
// be less useful the broader the specification, so e.g. a spec that returns
// the entirety of all of the blocks of a given type is likely to be
// _particularly_ arbitrary and useless.
//
// If the given body is not valid per the given spec, the result is best-effort
// and may not actually be something ideal. It's expected that an application
// will already have used Decode or PartialDecode earlier and thus had an
// opportunity to detect and report spec violations.
func SourceRange(body hcl.Body, spec Spec) hcl.Range {
	return sourceRange(body, nil, spec)
}


<|start_filename|>vendor/github.com/zclconf/go-cty/cty/convert/conversion_primitive.go<|end_filename|>
package convert

import (
	"math/big"

	"github.com/zclconf/go-cty/cty"
)

var stringTrue = cty.StringVal("true")
var stringFalse = cty.StringVal("false")

var primitiveConversionsSafe = map[cty.Type]map[cty.Type]conversion{
	cty.Number: {
		cty.String: func(val cty.Value, path cty.Path) (cty.Value, error) {
			f := val.AsBigFloat()
			return cty.StringVal(f.Text('f', -1)), nil
		},
	},
	cty.Bool: {
		cty.String: func(val cty.Value, path cty.Path) (cty.Value, error) {
			if val.True() {
				return stringTrue, nil
			} else {
				return stringFalse, nil
			}
		},
	},
}

var primitiveConversionsUnsafe = map[cty.Type]map[cty.Type]conversion{
	cty.String: {
		cty.Number: func(val cty.Value, path cty.Path) (cty.Value, error) {
			f, _, err := (&big.Float{}).Parse(val.AsString(), 10)
			if err != nil {
				return cty.NilVal, path.NewErrorf("a number is required")
			}
			return cty.NumberVal(f), nil
		},
		cty.Bool: func(val cty.Value, path cty.Path) (cty.Value, error) {
			switch val.AsString() {
			case "true", "1":
				return cty.True, nil
			case "false", "0":
				return cty.False, nil
			default:
				return cty.NilVal, path.NewErrorf("a bool is required")
			}
		},
	},
}


<|start_filename|>vendor/github.com/coreos/go-systemd/machine1/dbus_test.go<|end_filename|>
/*
Copyright 2015 CoreOS 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.
*/

package machine1

import (
	"os/exec"
	"testing"

	"github.com/coreos/go-systemd/dbus"
)

const (
	testServiceName = "machined-test.service"
	machineName     = "testMachine"
)

func mustCreateTestProcess() (pid int) {
	systemdRun, err := exec.LookPath("systemd-run")
	if err != nil {
		panic(err.Error())
	}
	sleep, err := exec.LookPath("sleep")
	if err != nil {
		panic(err.Error())
	}
	cmd := exec.Command(systemdRun, "--unit="+testServiceName, sleep, "5000")
	err = cmd.Run()
	if err != nil {
		panic(err.Error())
	}
	dbusConn, err := dbus.New()
	if err != nil {
		panic(err.Error())
	}
	defer dbusConn.Close()
	mainPIDProperty, err := dbusConn.GetServiceProperty(testServiceName, "MainPID")
	if err != nil {
		panic(err.Error())
	}
	mainPID := mainPIDProperty.Value.Value().(uint32)
	return int(mainPID)
}

func TestMachine(t *testing.T) {
	leader := mustCreateTestProcess()

	conn, newErr := New()
	if newErr != nil {
		t.Fatal(newErr)
	}

	regErr := conn.RegisterMachine(machineName, nil, "go-systemd", "container", leader, "")
	if regErr != nil {
		t.Fatal(regErr)
	}

	machine, getErr := conn.GetMachine(machineName)
	if getErr != nil {
		t.Fatal(getErr)
	}
	if len(machine) == 0 {
		t.Fatalf("did not find machine named %s", machineName)
	}

	tErr := conn.TerminateMachine(machineName)
	if tErr != nil {
		t.Fatal(tErr)
	}

	machine, getErr = conn.GetMachine(machineName)
	if len(machine) != 0 {
		t.Fatalf("unexpectedly found machine named %s", machineName)
	} else if getErr == nil {
		t.Fatal("expected error but got nil")
	}
}


<|start_filename|>vendor/github.com/mitchellh/packer/packer/config_file_unix.go<|end_filename|>
// +build darwin freebsd linux netbsd openbsd solaris

package packer

import (
	"bytes"
	"errors"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

func configFile() (string, error) {
	dir, err := homeDir()
	if err != nil {
		return "", err
	}

	return filepath.Join(dir, ".packerconfig"), nil
}

func configDir() (string, error) {
	dir, err := homeDir()
	if err != nil {
		return "", err
	}

	return filepath.Join(dir, ".packer.d"), nil
}

func homeDir() (string, error) {
	// First prefer the HOME environmental variable
	if home := os.Getenv("HOME"); home != "" {
		log.Printf("Detected home directory from env var: %s", home)
		return home, nil
	}

	// If that fails, try the shell
	var stdout bytes.Buffer
	cmd := exec.Command("sh", "-c", "eval echo ~$USER")
	cmd.Stdout = &stdout
	if err := cmd.Run(); err != nil {
		return "", err
	}

	result := strings.TrimSpace(stdout.String())
	if result == "" {
		return "", errors.New("blank output")
	}

	return result, nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/backend/local/backend_refresh.go<|end_filename|>
package local

import (
	"context"
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/hashicorp/errwrap"
	"github.com/hashicorp/go-multierror"
	"github.com/hashicorp/terraform/backend"
	"github.com/hashicorp/terraform/command/clistate"
	"github.com/hashicorp/terraform/config/module"
	"github.com/hashicorp/terraform/state"
	"github.com/hashicorp/terraform/terraform"
)

func (b *Local) opRefresh(
	ctx context.Context,
	op *backend.Operation,
	runningOp *backend.RunningOperation) {
	// Check if our state exists if we're performing a refresh operation. We
	// only do this if we're managing state with this backend.
	if b.Backend == nil {
		if _, err := os.Stat(b.StatePath); err != nil {
			if os.IsNotExist(err) {
				err = nil
			}

			if err != nil {
				runningOp.Err = fmt.Errorf(
					"There was an error reading the Terraform state that is needed\n"+
						"for refreshing. The path and error are shown below.\n\n"+
						"Path: %s\n\nError: %s",
					b.StatePath, err)
				return
			}
		}
	}

	// If we have no config module given to use, create an empty tree to
	// avoid crashes when Terraform.Context is initialized.
	if op.Module == nil {
		op.Module = module.NewEmptyTree()
	}

	// Get our context
	tfCtx, opState, err := b.context(op)
	if err != nil {
		runningOp.Err = err
		return
	}

	if op.LockState {
		lockCtx, cancel := context.WithTimeout(ctx, op.StateLockTimeout)
		defer cancel()

		lockInfo := state.NewLockInfo()
		lockInfo.Operation = op.Type.String()
		lockID, err := clistate.Lock(lockCtx, opState, lockInfo, b.CLI, b.Colorize())
		if err != nil {
			runningOp.Err = errwrap.Wrapf("Error locking state: {{err}}", err)
			return
		}

		defer func() {
			if err := clistate.Unlock(opState, lockID, b.CLI, b.Colorize()); err != nil {
				runningOp.Err = multierror.Append(runningOp.Err, err)
			}
		}()
	}

	// Set our state
	runningOp.State = opState.State()
	if runningOp.State.Empty() || !runningOp.State.HasResources() {
		if b.CLI != nil {
			b.CLI.Output(b.Colorize().Color(
				strings.TrimSpace(refreshNoState) + "\n"))
		}
	}

	// Perform the refresh in a goroutine so we can be interrupted
	var newState *terraform.State
	var refreshErr error
	doneCh := make(chan struct{})
	go func() {
		defer close(doneCh)
		newState, refreshErr = tfCtx.Refresh()
		log.Printf("[INFO] backend/local: refresh calling Refresh")
	}()

	select {
	case <-ctx.Done():
		if b.CLI != nil {
			b.CLI.Output("stopping refresh operation...")
		}

		// Stop execution
		go tfCtx.Stop()

		// Wait for completion still
		<-doneCh
	case <-doneCh:
	}

	// write the resulting state to the running op
	runningOp.State = newState
	if refreshErr != nil {
		runningOp.Err = errwrap.Wrapf("Error refreshing state: {{err}}", refreshErr)
		return
	}

	// Write and persist the state
	if err := opState.WriteState(newState); err != nil {
		runningOp.Err = errwrap.Wrapf("Error writing state: {{err}}", err)
		return
	}
	if err := opState.PersistState(); err != nil {
		runningOp.Err = errwrap.Wrapf("Error saving state: {{err}}", err)
		return
	}
}

const refreshNoState = `
[reset][bold][yellow]Empty or non-existent state file.[reset][yellow]

Refresh will do nothing. Refresh does not error or return an erroneous
exit status because many automation scripts use refresh, plan, then apply
and may not have a state file yet for the first run.
`


<|start_filename|>vendor/github.com/hashicorp/hcl2/hclwrite/ast_test.go<|end_filename|>
package hclwrite

import (
	"fmt"
	"reflect"
	"testing"

	"github.com/davecgh/go-spew/spew"
	"github.com/hashicorp/hcl2/hcl/hclsyntax"
	"github.com/hashicorp/hcl2/hcl"
)

func TestBodyFindAttribute(t *testing.T) {
	tests := []struct {
		src  string
		name string
		want *TokenSeq
	}{
		{
			"",
			"a",
			nil,
		},
		{
			"a = 1\n",
			"a",
			&TokenSeq{
				Tokens{
					{
						Type:  hclsyntax.TokenIdent,
						Bytes: []byte{'a'},
					},
				},
			},
		},
		{
			"a = 1\nb = 1\nc = 1\n",
			"a",
			&TokenSeq{
				Tokens{
					{
						Type:  hclsyntax.TokenIdent,
						Bytes: []byte{'a'},
					},
				},
			},
		},
		{
			"a = 1\nb = 1\nc = 1\n",
			"b",
			&TokenSeq{
				Tokens{
					{
						Type:  hclsyntax.TokenIdent,
						Bytes: []byte{'b'},
					},
				},
			},
		},
		{
			"a = 1\nb = 1\nc = 1\n",
			"c",
			&TokenSeq{
				Tokens{
					{
						Type:  hclsyntax.TokenIdent,
						Bytes: []byte{'c'},
					},
				},
			},
		},
	}

	for _, test := range tests {
		t.Run(fmt.Sprintf("%s in %s", test.name, test.src), func(t *testing.T) {
			f, diags := ParseConfig([]byte(test.src), "", hcl.Pos{Line: 1, Column: 1})
			if len(diags) != 0 {
				for _, diag := range diags {
					t.Logf("- %s", diag.Error())
				}
				t.Fatalf("unexpected diagnostics")
			}

			attr := f.Body.FindAttribute(test.name)
			if attr == nil {
				if test.want != nil {
					t.Errorf("attribute found, but expecting not found")
				}
			} else {
				got := attr.NameTokens
				if !reflect.DeepEqual(got, test.want) {
					t.Errorf("wrong result\ngot:  %s\nwant: %s", spew.Sdump(got), spew.Sdump(test.want))
				}
			}
		})
	}
}


<|start_filename|>vendor/github.com/mitchellh/packer/vendor/github.com/denverdino/aliyungo/ram/policy.go<|end_filename|>
package ram

type Type string

const (
	Custom Type = "Custom"
	System Type = "System"
)

type PolicyRequest struct {
	PolicyName     string
	PolicyType     Type
	Description    string
	PolicyDocument string
	SetAsDefault   string
	VersionId      string
}
type PolicyListResponse struct {
	RamCommonResponse
	Policies struct {
		Policy []Policy
	}
}

type PolicyResponse struct {
	RamCommonResponse
	Policy Policy
}

type PolicyQueryRequest struct {
	PolicyType Type
	Marker     string
	MaxItems   int8
}

type PolicyQueryResponse struct {
	RamCommonResponse
	IsTruncated bool
	Marker      string
	Policies struct {
		Policy []Policy
	}
}

type PolicyVersionResponse struct {
	RamCommonResponse
	IsDefaultVersion bool
	VersionId        string
	CreateDate       string
	PolicyDocument   string
}

type AttachPolicyRequest struct {
	PolicyRequest
	UserName string
}

type AttachPolicyToRoleRequest struct {
	PolicyRequest
	RoleName string
}

type PolicyVersionResponseNew struct {
	RamCommonResponse
	PolicyVersion struct {
		IsDefaultVersion bool
		VersionId        string
		CreateDate       string
		PolicyDocument   string
	}
}

type AttachPolicyToGroupRequest struct {
	PolicyRequest
	GroupName string
}

type PolicyVersionsResponse struct {
	RamCommonResponse
	PolicyVersions struct {
		PolicyVersion []PolicyVersion
	}
}

type PolicyListEntitiesResponse struct {
	RamCommonResponse
	Groups struct {
		Group []Group
	}
	Users struct {
		User []User
	}
	Roles struct {
		Role []Role
	}
}

func (client *RamClient) CreatePolicy(policyReq PolicyRequest) (PolicyResponse, error) {
	var resp PolicyResponse
	err := client.Invoke("CreatePolicy", policyReq, &resp)
	if err != nil {
		return PolicyResponse{}, err
	}
	return resp, nil
}

func (client *RamClient) GetPolicy(policyReq PolicyRequest) (PolicyResponse, error) {
	var resp PolicyResponse
	err := client.Invoke("GetPolicy", policyReq, &resp)
	if err != nil {
		return PolicyResponse{}, err
	}
	return resp, nil
}

func (client *RamClient) DeletePolicy(policyReq PolicyRequest) (RamCommonResponse, error) {
	var resp RamCommonResponse
	err := client.Invoke("DeletePolicy", policyReq, &resp)
	if err != nil {
		return RamCommonResponse{}, err
	}
	return resp, nil
}

func (client *RamClient) ListPolicies(policyQuery PolicyQueryRequest) (PolicyQueryResponse, error) {
	var resp PolicyQueryResponse
	err := client.Invoke("ListPolicies", policyQuery, &resp)
	if err != nil {
		return PolicyQueryResponse{}, err
	}
	return resp, nil
}

func (client *RamClient) CreatePolicyVersion(policyReq PolicyRequest) (PolicyVersionResponse, error) {
	var resp PolicyVersionResponse
	err := client.Invoke("CreatePolicyVersion", policyReq, &resp)
	if err != nil {
		return PolicyVersionResponse{}, err
	}
	return resp, nil
}

func (client *RamClient) GetPolicyVersion(policyReq PolicyRequest) (PolicyVersionResponse, error) {
	var resp PolicyVersionResponse
	err := client.Invoke("GetPolicyVersion", policyReq, &resp)
	if err != nil {
		return PolicyVersionResponse{}, err
	}
	return resp, nil
}

func (client *RamClient) GetPolicyVersionNew(policyReq PolicyRequest) (PolicyVersionResponseNew, error) {
	var resp PolicyVersionResponseNew
	err := client.Invoke("GetPolicyVersion", policyReq, &resp)
	if err != nil {
		return PolicyVersionResponseNew{}, err
	}
	return resp, nil
}

func (client *RamClient) DeletePolicyVersion(policyReq PolicyRequest) (RamCommonResponse, error) {
	var resp RamCommonResponse
	err := client.Invoke("DeletePolicyVersion", policyReq, &resp)
	if err != nil {
		return RamCommonResponse{}, err
	}
	return resp, nil
}

func (client *RamClient) ListPolicyVersions(policyReq PolicyRequest) (PolicyVersionResponse, error) {
	var resp PolicyVersionResponse
	err := client.Invoke("ListPolicyVersions", policyReq, &resp)
	if err != nil {
		return PolicyVersionResponse{}, err
	}
	return resp, nil
}

func (client *RamClient) ListPolicyVersionsNew(policyReq PolicyRequest) (PolicyVersionsResponse, error) {
	var resp PolicyVersionsResponse
	err := client.Invoke("ListPolicyVersions", policyReq, &resp)
	if err != nil {
		return PolicyVersionsResponse{}, err
	}
	return resp, nil
}

func (client *RamClient) SetDefaultPolicyVersion(policyReq PolicyRequest) (RamCommonResponse, error) {
	var resp RamCommonResponse
	err := client.Invoke("SetDefaultPolicyVersion", policyReq, &resp)
	if err != nil {
		return RamCommonResponse{}, err
	}
	return resp, nil
}

func (client *RamClient) AttachPolicyToUser(attachPolicyRequest AttachPolicyRequest) (RamCommonResponse, error) {
	var resp RamCommonResponse
	err := client.Invoke("AttachPolicyToUser", attachPolicyRequest, &resp)
	if err != nil {
		return RamCommonResponse{}, err
	}
	return resp, nil
}

func (client *RamClient) DetachPolicyFromUser(attachPolicyRequest AttachPolicyRequest) (RamCommonResponse, error) {
	var resp RamCommonResponse
	err := client.Invoke("DetachPolicyFromUser", attachPolicyRequest, &resp)
	if err != nil {
		return RamCommonResponse{}, err
	}
	return resp, nil
}

func (client *RamClient) ListEntitiesForPolicy(policyReq PolicyRequest) (PolicyListEntitiesResponse, error) {
	var resp PolicyListEntitiesResponse
	err := client.Invoke("ListEntitiesForPolicy", policyReq, &resp)
	if err != nil {
		return PolicyListEntitiesResponse{}, err
	}
	return resp, nil
}

func (client *RamClient) ListPoliciesForUser(userQuery UserQueryRequest) (PolicyListResponse, error) {
	var resp PolicyListResponse
	err := client.Invoke("ListPoliciesForUser", userQuery, &resp)
	if err != nil {
		return PolicyListResponse{}, err
	}
	return resp, nil
}

//
//Role related
//
func (client *RamClient) AttachPolicyToRole(attachPolicyRequest AttachPolicyToRoleRequest) (RamCommonResponse, error) {
	var resp RamCommonResponse
	err := client.Invoke("AttachPolicyToRole", attachPolicyRequest, &resp)
	if err != nil {
		return RamCommonResponse{}, err
	}
	return resp, nil
}

func (client *RamClient) DetachPolicyFromRole(attachPolicyRequest AttachPolicyToRoleRequest) (RamCommonResponse, error) {
	var resp RamCommonResponse
	err := client.Invoke("DetachPolicyFromRole", attachPolicyRequest, &resp)
	if err != nil {
		return RamCommonResponse{}, err
	}
	return resp, nil
}

func (client *RamClient) ListPoliciesForRole(roleQuery RoleQueryRequest) (PolicyListResponse, error) {
	var resp PolicyListResponse
	err := client.Invoke("ListPoliciesForRole", roleQuery, &resp)
	if err != nil {
		return PolicyListResponse{}, err
	}
	return resp, nil
}

//
//Group related
//
func (client *RamClient) AttachPolicyToGroup(attachPolicyRequest AttachPolicyToGroupRequest) (RamCommonResponse, error) {
	var resp RamCommonResponse
	err := client.Invoke("AttachPolicyToGroup", attachPolicyRequest, &resp)
	if err != nil {
		return RamCommonResponse{}, err
	}
	return resp, nil
}

func (client *RamClient) DetachPolicyFromGroup(attachPolicyRequest AttachPolicyToGroupRequest) (RamCommonResponse, error) {
	var resp RamCommonResponse
	err := client.Invoke("DetachPolicyFromGroup", attachPolicyRequest, &resp)
	if err != nil {
		return RamCommonResponse{}, err
	}
	return resp, nil
}

func (client *RamClient) ListPoliciesForGroup(groupQuery GroupQueryRequest) (PolicyListResponse, error) {
	var resp PolicyListResponse
	err := client.Invoke("ListPoliciesForGroup", groupQuery, &resp)
	if err != nil {
		return PolicyListResponse{}, err
	}
	return resp, nil
}


<|start_filename|>vendor/github.com/mitchellh/packer/vendor/github.com/approvals/go-approval-tests/reporters/continuous_integration.go<|end_filename|>
package reporters

import (
	"os"
	"strconv"
)

type continuousIntegration struct{}

// NewContinuousIntegrationReporter creates a new reporter for CI.
//
// The reporter checks the environment variable CI for a value of true.
func NewContinuousIntegrationReporter() Reporter {
	return &continuousIntegration{}
}

func (s *continuousIntegration) Report(approved, received string) bool {
	value, exists := os.LookupEnv("CI")

	if exists {
		ci, err := strconv.ParseBool(value)
		if err == nil {
			return ci
		}
	}

	return false
}


<|start_filename|>vendor/github.com/hashicorp/go-plugin/server_test.go<|end_filename|>
package plugin

import (
	"io/ioutil"
	"net"
	"os"
	"testing"
)

func TestRmListener_impl(t *testing.T) {
	var _ net.Listener = new(rmListener)
}

func TestRmListener(t *testing.T) {
	l, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	tf, err := ioutil.TempFile("", "plugin")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	path := tf.Name()

	// Close the file
	if err := tf.Close(); err != nil {
		t.Fatalf("err: %s", err)
	}

	// Create the listener and test close
	rmL := &rmListener{
		Listener: l,
		Path:     path,
	}
	if err := rmL.Close(); err != nil {
		t.Fatalf("err: %s", err)
	}

	// File should be goe
	if _, err := os.Stat(path); err == nil || !os.IsNotExist(err) {
		t.Fatalf("err: %s", err)
	}
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/auth_helpers.go<|end_filename|>
package aws

import (
	"errors"
	"fmt"
	"log"
	"os"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	awsCredentials "github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
	"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
	"github.com/aws/aws-sdk-go/aws/defaults"
	"github.com/aws/aws-sdk-go/aws/ec2metadata"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/iam"
	"github.com/aws/aws-sdk-go/service/sts"
	"github.com/hashicorp/errwrap"
	"github.com/hashicorp/go-cleanhttp"
	"github.com/hashicorp/go-multierror"
)

func GetAccountInfo(iamconn *iam.IAM, stsconn *sts.STS, authProviderName string) (string, string, error) {
	var errors error
	// If we have creds from instance profile, we can use metadata API
	if authProviderName == ec2rolecreds.ProviderName {
		log.Println("[DEBUG] Trying to get account ID via AWS Metadata API")

		cfg := &aws.Config{}
		setOptionalEndpoint(cfg)
		sess, err := session.NewSession(cfg)
		if err != nil {
			return "", "", errwrap.Wrapf("Error creating AWS session: {{err}}", err)
		}

		metadataClient := ec2metadata.New(sess)
		info, err := metadataClient.IAMInfo()
		if err == nil {
			return parseAccountInfoFromArn(info.InstanceProfileArn)
		}
		log.Printf("[DEBUG] Failed to get account info from metadata service: %s", err)
		errors = multierror.Append(errors, err)
		// We can end up here if there's an issue with the instance metadata service
		// or if we're getting credentials from AdRoll's Hologram (in which case IAMInfo will
		// error out). In any event, if we can't get account info here, we should try
		// the other methods available.
		// If we have creds from something that looks like an IAM instance profile, but
		// we were unable to retrieve account info from the instance profile, it's probably
		// a safe assumption that we're not an IAM user
	} else {
		// Creds aren't from an IAM instance profile, so try try iam:GetUser
		log.Println("[DEBUG] Trying to get account ID via iam:GetUser")
		outUser, err := iamconn.GetUser(nil)
		if err == nil {
			return parseAccountInfoFromArn(*outUser.User.Arn)
		}
		errors = multierror.Append(errors, err)
		awsErr, ok := err.(awserr.Error)
		// AccessDenied and ValidationError can be raised
		// if credentials belong to federated profile, so we ignore these
		if !ok || (awsErr.Code() != "AccessDenied" && awsErr.Code() != "ValidationError" && awsErr.Code() != "InvalidClientTokenId") {
			return "", "", fmt.Errorf("Failed getting account ID via 'iam:GetUser': %s", err)
		}
		log.Printf("[DEBUG] Getting account ID via iam:GetUser failed: %s", err)
	}

	// Then try STS GetCallerIdentity
	log.Println("[DEBUG] Trying to get account ID via sts:GetCallerIdentity")
	outCallerIdentity, err := stsconn.GetCallerIdentity(&sts.GetCallerIdentityInput{})
	if err == nil {
		return parseAccountInfoFromArn(*outCallerIdentity.Arn)
	}
	log.Printf("[DEBUG] Getting account ID via sts:GetCallerIdentity failed: %s", err)
	errors = multierror.Append(errors, err)

	// Then try IAM ListRoles
	log.Println("[DEBUG] Trying to get account ID via iam:ListRoles")
	outRoles, err := iamconn.ListRoles(&iam.ListRolesInput{
		MaxItems: aws.Int64(int64(1)),
	})
	if err != nil {
		log.Printf("[DEBUG] Failed to get account ID via iam:ListRoles: %s", err)
		errors = multierror.Append(errors, err)
		return "", "", fmt.Errorf("Failed getting account ID via all available methods. Errors: %s", errors)
	}

	if len(outRoles.Roles) < 1 {
		err = fmt.Errorf("Failed to get account ID via iam:ListRoles: No roles available")
		log.Printf("[DEBUG] %s", err)
		errors = multierror.Append(errors, err)
		return "", "", fmt.Errorf("Failed getting account ID via all available methods. Errors: %s", errors)
	}

	return parseAccountInfoFromArn(*outRoles.Roles[0].Arn)
}

func parseAccountInfoFromArn(arn string) (string, string, error) {
	parts := strings.Split(arn, ":")
	if len(parts) < 5 {
		return "", "", fmt.Errorf("Unable to parse ID from invalid ARN: %q", arn)
	}
	return parts[1], parts[4], nil
}

// This function is responsible for reading credentials from the
// environment in the case that they're not explicitly specified
// in the Terraform configuration.
func GetCredentials(c *Config) (*awsCredentials.Credentials, error) {
	// build a chain provider, lazy-evaluated by aws-sdk
	providers := []awsCredentials.Provider{
		&awsCredentials.StaticProvider{Value: awsCredentials.Value{
			AccessKeyID:     c.AccessKey,
			SecretAccessKey: c.SecretKey,
			SessionToken:    c.Token,
		}},
		&awsCredentials.EnvProvider{},
		&awsCredentials.SharedCredentialsProvider{
			Filename: c.CredsFilename,
			Profile:  c.Profile,
		},
	}

	// Build isolated HTTP client to avoid issues with globally-shared settings
	client := cleanhttp.DefaultClient()

	// Keep the default timeout (100ms) low as we don't want to wait in non-EC2 environments
	client.Timeout = 100 * time.Millisecond

	const userTimeoutEnvVar = "AWS_METADATA_TIMEOUT"
	userTimeout := os.Getenv(userTimeoutEnvVar)
	if userTimeout != "" {
		newTimeout, err := time.ParseDuration(userTimeout)
		if err == nil {
			if newTimeout.Nanoseconds() > 0 {
				client.Timeout = newTimeout
			} else {
				log.Printf("[WARN] Non-positive value of %s (%s) is meaningless, ignoring", userTimeoutEnvVar, newTimeout.String())
			}
		} else {
			log.Printf("[WARN] Error converting %s to time.Duration: %s", userTimeoutEnvVar, err)
		}
	}

	log.Printf("[INFO] Setting AWS metadata API timeout to %s", client.Timeout.String())
	cfg := &aws.Config{
		HTTPClient: client,
	}
	usedEndpoint := setOptionalEndpoint(cfg)

	// Add the default AWS provider for ECS Task Roles if the relevant env variable is set
	if uri := os.Getenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"); len(uri) > 0 {
		providers = append(providers, defaults.RemoteCredProvider(*cfg, defaults.Handlers()))
		log.Print("[INFO] ECS container credentials detected, RemoteCredProvider added to auth chain")
	}

	if !c.SkipMetadataApiCheck {
		// Real AWS should reply to a simple metadata request.
		// We check it actually does to ensure something else didn't just
		// happen to be listening on the same IP:Port
		metadataClient := ec2metadata.New(session.New(cfg))
		if metadataClient.Available() {
			providers = append(providers, &ec2rolecreds.EC2RoleProvider{
				Client: metadataClient,
			})
			log.Print("[INFO] AWS EC2 instance detected via default metadata" +
				" API endpoint, EC2RoleProvider added to the auth chain")
		} else {
			if usedEndpoint == "" {
				usedEndpoint = "default location"
			}
			log.Printf("[INFO] Ignoring AWS metadata API endpoint at %s "+
				"as it doesn't return any instance-id", usedEndpoint)
		}
	}

	// This is the "normal" flow (i.e. not assuming a role)
	if c.AssumeRoleARN == "" {
		return awsCredentials.NewChainCredentials(providers), nil
	}

	// Otherwise we need to construct and STS client with the main credentials, and verify
	// that we can assume the defined role.
	log.Printf("[INFO] Attempting to AssumeRole %s (SessionName: %q, ExternalId: %q, Policy: %q)",
		c.AssumeRoleARN, c.AssumeRoleSessionName, c.AssumeRoleExternalID, c.AssumeRolePolicy)

	creds := awsCredentials.NewChainCredentials(providers)
	cp, err := creds.Get()
	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoCredentialProviders" {
			return nil, errors.New(`No valid credential sources found for AWS Provider.
  Please see https://terraform.io/docs/providers/aws/index.html for more information on
  providing credentials for the AWS Provider`)
		}

		return nil, fmt.Errorf("Error loading credentials for AWS Provider: %s", err)
	}

	log.Printf("[INFO] AWS Auth provider used: %q", cp.ProviderName)

	awsConfig := &aws.Config{
		Credentials:      creds,
		Region:           aws.String(c.Region),
		MaxRetries:       aws.Int(c.MaxRetries),
		HTTPClient:       cleanhttp.DefaultClient(),
		S3ForcePathStyle: aws.Bool(c.S3ForcePathStyle),
	}

	stsclient := sts.New(session.New(awsConfig))
	assumeRoleProvider := &stscreds.AssumeRoleProvider{
		Client:  stsclient,
		RoleARN: c.AssumeRoleARN,
	}
	if c.AssumeRoleSessionName != "" {
		assumeRoleProvider.RoleSessionName = c.AssumeRoleSessionName
	}
	if c.AssumeRoleExternalID != "" {
		assumeRoleProvider.ExternalID = aws.String(c.AssumeRoleExternalID)
	}
	if c.AssumeRolePolicy != "" {
		assumeRoleProvider.Policy = aws.String(c.AssumeRolePolicy)
	}

	providers = []awsCredentials.Provider{assumeRoleProvider}

	assumeRoleCreds := awsCredentials.NewChainCredentials(providers)
	_, err = assumeRoleCreds.Get()
	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoCredentialProviders" {
			return nil, fmt.Errorf("The role %q cannot be assumed.\n\n"+
				"  There are a number of possible causes of this - the most common are:\n"+
				"    * The credentials used in order to assume the role are invalid\n"+
				"    * The credentials do not have appropriate permission to assume the role\n"+
				"    * The role ARN is not valid",
				c.AssumeRoleARN)
		}

		return nil, fmt.Errorf("Error loading credentials for AWS Provider: %s", err)
	}

	return assumeRoleCreds, nil
}

func setOptionalEndpoint(cfg *aws.Config) string {
	endpoint := os.Getenv("AWS_METADATA_URL")
	if endpoint != "" {
		log.Printf("[INFO] Setting custom metadata endpoint: %q", endpoint)
		cfg.Endpoint = aws.String(endpoint)
		return endpoint
	}
	return ""
}


<|start_filename|>vendor/github.com/mitchellh/packer/vendor/github.com/joyent/triton-go/compute/images.go<|end_filename|>
//
// Copyright (c) 2018, Joyent, Inc. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

package compute

import (
	"context"
	"encoding/json"
	"net/http"
	"net/url"
	"path"
	"time"

	"github.com/joyent/triton-go/client"
	"github.com/pkg/errors"
)

type ImagesClient struct {
	client *client.Client
}

type ImageFile struct {
	Compression string `json:"compression"`
	SHA1        string `json:"sha1"`
	Size        int64  `json:"size"`
}

type Image struct {
	ID           string                 `json:"id"`
	Name         string                 `json:"name"`
	OS           string                 `json:"os"`
	Description  string                 `json:"description"`
	Version      string                 `json:"version"`
	Type         string                 `json:"type"`
	Requirements map[string]interface{} `json:"requirements"`
	Homepage     string                 `json:"homepage"`
	Files        []*ImageFile           `json:"files"`
	PublishedAt  time.Time              `json:"published_at"`
	Owner        string                 `json:"owner"`
	Public       bool                   `json:"public"`
	State        string                 `json:"state"`
	Tags         map[string]string      `json:"tags"`
	EULA         string                 `json:"eula"`
	ACL          []string               `json:"acl"`
}

type ListImagesInput struct {
	Name    string
	OS      string
	Version string
	Public  bool
	State   string
	Owner   string
	Type    string
}

func (c *ImagesClient) List(ctx context.Context, input *ListImagesInput) ([]*Image, error) {
	fullPath := path.Join("/", c.client.AccountName, "images")

	query := &url.Values{}
	if input.Name != "" {
		query.Set("name", input.Name)
	}
	if input.OS != "" {
		query.Set("os", input.OS)
	}
	if input.Version != "" {
		query.Set("version", input.Version)
	}
	if input.Public {
		query.Set("public", "true")
	}
	if input.State != "" {
		query.Set("state", input.State)
	}
	if input.Owner != "" {
		query.Set("owner", input.Owner)
	}
	if input.Type != "" {
		query.Set("type", input.Type)
	}

	reqInputs := client.RequestInput{
		Method: http.MethodGet,
		Path:   fullPath,
		Query:  query,
	}
	respReader, err := c.client.ExecuteRequestURIParams(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to list images")
	}

	var result []*Image
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode list images response")
	}

	return result, nil
}

type GetImageInput struct {
	ImageID string
}

func (c *ImagesClient) Get(ctx context.Context, input *GetImageInput) (*Image, error) {
	fullPath := path.Join("/", c.client.AccountName, "images", input.ImageID)
	reqInputs := client.RequestInput{
		Method: http.MethodGet,
		Path:   fullPath,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to get image")
	}

	var result *Image
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode get image response")
	}

	return result, nil
}

type DeleteImageInput struct {
	ImageID string
}

func (c *ImagesClient) Delete(ctx context.Context, input *DeleteImageInput) error {
	fullPath := path.Join("/", c.client.AccountName, "images", input.ImageID)
	reqInputs := client.RequestInput{
		Method: http.MethodDelete,
		Path:   fullPath,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return errors.Wrap(err, "unable to delete image")
	}

	return nil
}

type ExportImageInput struct {
	ImageID   string
	MantaPath string
}

type MantaLocation struct {
	MantaURL     string `json:"manta_url"`
	ImagePath    string `json:"image_path"`
	ManifestPath string `json:"manifest_path"`
}

func (c *ImagesClient) Export(ctx context.Context, input *ExportImageInput) (*MantaLocation, error) {
	fullPath := path.Join("/", c.client.AccountName, "images", input.ImageID)
	query := &url.Values{}
	query.Set("action", "export")

	reqInputs := client.RequestInput{
		Method: http.MethodPost,
		Path:   fullPath,
		Query:  query,
	}
	respReader, err := c.client.ExecuteRequestURIParams(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to export image")
	}

	var result *MantaLocation
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode export image response")
	}

	return result, nil
}

type CreateImageFromMachineInput struct {
	MachineID   string            `json:"machine"`
	Name        string            `json:"name"`
	Version     string            `json:"version,omitempty"`
	Description string            `json:"description,omitempty"`
	HomePage    string            `json:"homepage,omitempty"`
	EULA        string            `json:"eula,omitempty"`
	ACL         []string          `json:"acl,omitempty"`
	Tags        map[string]string `json:"tags,omitempty"`
}

func (c *ImagesClient) CreateFromMachine(ctx context.Context, input *CreateImageFromMachineInput) (*Image, error) {
	fullPath := path.Join("/", c.client.AccountName, "images")
	reqInputs := client.RequestInput{
		Method: http.MethodPost,
		Path:   fullPath,
		Body:   input,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to create machine from image")
	}

	var result *Image
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode create machine from image response")
	}

	return result, nil
}

type UpdateImageInput struct {
	ImageID     string            `json:"-"`
	Name        string            `json:"name,omitempty"`
	Version     string            `json:"version,omitempty"`
	Description string            `json:"description,omitempty"`
	HomePage    string            `json:"homepage,omitempty"`
	EULA        string            `json:"eula,omitempty"`
	ACL         []string          `json:"acl,omitempty"`
	Tags        map[string]string `json:"tags,omitempty"`
}

func (c *ImagesClient) Update(ctx context.Context, input *UpdateImageInput) (*Image, error) {
	fullPath := path.Join("/", c.client.AccountName, "images", input.ImageID)
	query := &url.Values{}
	query.Set("action", "update")

	reqInputs := client.RequestInput{
		Method: http.MethodPost,
		Path:   fullPath,
		Query:  query,
		Body:   input,
	}
	respReader, err := c.client.ExecuteRequestURIParams(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to update image")
	}

	var result *Image
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode update image response")
	}

	return result, nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/state/local_lock_unix.go<|end_filename|>
// +build !windows

package state

import (
	"os"
	"syscall"
)

// use fcntl POSIX locks for the most consistent behavior across platforms, and
// hopefully some campatibility over NFS and CIFS.
func (s *LocalState) lock() error {
	flock := &syscall.Flock_t{
		Type:   syscall.F_RDLCK | syscall.F_WRLCK,
		Whence: int16(os.SEEK_SET),
		Start:  0,
		Len:    0,
	}

	fd := s.stateFileOut.Fd()
	return syscall.FcntlFlock(fd, syscall.F_SETLK, flock)
}

func (s *LocalState) unlock() error {
	flock := &syscall.Flock_t{
		Type:   syscall.F_UNLCK,
		Whence: int16(os.SEEK_SET),
		Start:  0,
		Len:    0,
	}

	fd := s.stateFileOut.Fd()
	return syscall.FcntlFlock(fd, syscall.F_SETLK, flock)
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/hashicorp/hcl2/hcl/json/public.go<|end_filename|>
package json

import (
	"fmt"
	"io/ioutil"
	"os"

	"github.com/hashicorp/hcl2/hcl"
)

// Parse attempts to parse the given buffer as JSON and, if successful, returns
// a hcl.File for the zcl configuration represented by it.
//
// This is not a generic JSON parser. Instead, it deals only with the profile
// of JSON used to express zcl configuration.
//
// The returned file is valid only if the returned diagnostics returns false
// from its HasErrors method. If HasErrors returns true, the file represents
// the subset of data that was able to be parsed, which may be none.
func Parse(src []byte, filename string) (*hcl.File, hcl.Diagnostics) {
	rootNode, diags := parseFileContent(src, filename)
	if _, ok := rootNode.(*objectVal); !ok {
		diags = diags.Append(&hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Root value must be object",
			Detail:   "The root value in a JSON-based configuration must be a JSON object.",
			Subject:  rootNode.StartRange().Ptr(),
		})
		// Put in a placeholder objectVal just so the caller always gets
		// a valid file, even if it appears empty. This is useful for callers
		// that are doing static analysis of possibly-erroneous source code,
		// which will try to process the returned file even if we return
		// diagnostics of severity error. This way, they'll get a file that
		// has an empty body rather than a body that panics when probed.
		fakePos := hcl.Pos{
			Byte:   0,
			Line:   1,
			Column: 1,
		}
		fakeRange := hcl.Range{
			Filename: filename,
			Start:    fakePos,
			End:      fakePos,
		}
		rootNode = &objectVal{
			Attrs:     map[string]*objectAttr{},
			SrcRange:  fakeRange,
			OpenRange: fakeRange,
		}
	}
	file := &hcl.File{
		Body: &body{
			obj: rootNode.(*objectVal),
		},
		Bytes: src,
		Nav:   navigation{rootNode.(*objectVal)},
	}
	return file, diags
}

// ParseFile is a convenience wrapper around Parse that first attempts to load
// data from the given filename, passing the result to Parse if successful.
//
// If the file cannot be read, an error diagnostic with nil context is returned.
func ParseFile(filename string) (*hcl.File, hcl.Diagnostics) {
	f, err := os.Open(filename)
	if err != nil {
		return nil, hcl.Diagnostics{
			{
				Severity: hcl.DiagError,
				Summary:  "Failed to open file",
				Detail:   fmt.Sprintf("The file %q could not be opened.", filename),
			},
		}
	}
	defer f.Close()

	src, err := ioutil.ReadAll(f)
	if err != nil {
		return nil, hcl.Diagnostics{
			{
				Severity: hcl.DiagError,
				Summary:  "Failed to read file",
				Detail:   fmt.Sprintf("The file %q was opened, but an error occured while reading it.", filename),
			},
		}
	}

	return Parse(src, filename)
}

// ParseWithHIL is like Parse except the returned file will use the HIL
// template syntax for expressions in strings, rather than the native zcl
// template syntax.
//
// This is intended for providing backward compatibility for applications that
// used to use HCL/HIL and thus had a JSON-based format with HIL
// interpolations.
func ParseWithHIL(src []byte, filename string) (*hcl.File, hcl.Diagnostics) {
	file, diags := Parse(src, filename)
	if file != nil && file.Body != nil {
		file.Body.(*body).useHIL = true
	}
	return file, diags
}

// ParseFileWithHIL is like ParseWithHIL but it reads data from a file before
// parsing it.
func ParseFileWithHIL(filename string) (*hcl.File, hcl.Diagnostics) {
	file, diags := ParseFile(filename)
	if file != nil && file.Body != nil {
		file.Body.(*body).useHIL = true
	}
	return file, diags
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/data_source_aws_billing_service_account.go<|end_filename|>
package aws

import (
	"fmt"

	"github.com/hashicorp/terraform/helper/schema"
)

// See http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-getting-started.html#step-2
var billingAccountId = "386209384616"

func dataSourceAwsBillingServiceAccount() *schema.Resource {
	return &schema.Resource{
		Read: dataSourceAwsBillingServiceAccountRead,

		Schema: map[string]*schema.Schema{
			"arn": {
				Type:     schema.TypeString,
				Computed: true,
			},
		},
	}
}

func dataSourceAwsBillingServiceAccountRead(d *schema.ResourceData, meta interface{}) error {
	d.SetId(billingAccountId)
	d.Set("arn", fmt.Sprintf("arn:%s:iam::%s:root", meta.(*AWSClient).partition, billingAccountId))

	return nil
}


<|start_filename|>vendor/github.com/mitchellh/packer/vendor/github.com/denverdino/aliyungo/ecs/router_interface.go<|end_filename|>
package ecs

import (
	"github.com/denverdino/aliyungo/common"
)

type EcsCommonResponse struct {
	common.Response
}
type RouterType string
type InterfaceStatus string
type Role string
type Spec string

const (
	VRouter = RouterType("VRouter")
	VBR     = RouterType("VBR")

	Idl      = InterfaceStatus("Idl")
	Active   = InterfaceStatus("Active")
	Inactive = InterfaceStatus("Inactive")

	InitiatingSide = Role("InitiatingSide")
	AcceptingSide  = Role("AcceptingSide")

	Small1  = Spec("Small.1")
	Small2  = Spec("Small.2")
	Small5  = Spec("Small.5")
	Middle1 = Spec("Middle.1")
	Middle2 = Spec("Middle.2")
	Middle5 = Spec("Middle.5")
	Large1  = Spec("Large.1")
	Large2  = Spec("Large.2")
)

type CreateRouterInterfaceArgs struct {
	RegionId                 common.Region
	OppositeRegionId         common.Region
	RouterType               RouterType
	OppositeRouterType       RouterType
	RouterId                 string
	OppositeRouterId         string
	Role                     Role
	Spec                     Spec
	AccessPointId            string
	OppositeAccessPointId    string
	OppositeInterfaceId      string
	OppositeInterfaceOwnerId string
	Name                     string
	Description              string
	HealthCheckSourceIp      string
	HealthCheckTargetIp      string
}

type CreateRouterInterfaceResponse struct {
	common.Response
	RouterInterfaceId string
}

// CreateRouterInterface create Router interface
//
// You can read doc at https://help.aliyun.com/document_detail/36032.html?spm=5176.product27706.6.664.EbBsxC
func (client *Client) CreateRouterInterface(args *CreateRouterInterfaceArgs) (response *CreateRouterInterfaceResponse, err error) {
	response = &CreateRouterInterfaceResponse{}
	err = client.Invoke("CreateRouterInterface", args, &response)
	if err != nil {
		return response, err
	}
	return response, nil
}

type Filter struct {
	Key   string
	Value []string
}

type DescribeRouterInterfacesArgs struct {
	RegionId common.Region
	common.Pagination
	Filter   []Filter
}

type RouterInterfaceItemType struct {
	ChargeType                      string
	RouterInterfaceId               string
	AccessPointId                   string
	OppositeRegionId                string
	OppositeAccessPointId           string
	Role                            Role
	Spec                            Spec
	Name                            string
	Description                     string
	RouterId                        string
	RouterType                      RouterType
	CreationTime                    string
	Status                          string
	BusinessStatus                  string
	ConnectedTime                   string
	OppositeInterfaceId             string
	OppositeInterfaceSpec           string
	OppositeInterfaceStatus         string
	OppositeInterfaceBusinessStatus string
	OppositeRouterId                string
	OppositeRouterType              RouterType
	OppositeInterfaceOwnerId        string
	HealthCheckSourceIp             string
	HealthCheckTargetIp             string
}

type DescribeRouterInterfacesResponse struct {
	RouterInterfaceSet struct {
		RouterInterfaceType []RouterInterfaceItemType
	}
	common.PaginationResult
}

// DescribeRouterInterfaces describe Router interfaces
//
// You can read doc at https://help.aliyun.com/document_detail/36032.html?spm=5176.product27706.6.664.EbBsxC
func (client *Client) DescribeRouterInterfaces(args *DescribeRouterInterfacesArgs) (response *DescribeRouterInterfacesResponse, err error) {
	response = &DescribeRouterInterfacesResponse{}
	err = client.Invoke("DescribeRouterInterfaces", args, &response)
	if err != nil {
		return response, err
	}
	return response, nil
}

type OperateRouterInterfaceArgs struct {
	RegionId          common.Region
	RouterInterfaceId string
}

// ConnectRouterInterface
//
// You can read doc at https://help.aliyun.com/document_detail/36031.html?spm=5176.doc36035.6.666.wkyljN
func (client *Client) ConnectRouterInterface(args *OperateRouterInterfaceArgs) (response *EcsCommonResponse, err error) {
	response = &EcsCommonResponse{}
	err = client.Invoke("ConnectRouterInterface", args, &response)
	if err != nil {
		return response, err
	}
	return response, nil
}

// ActivateRouterInterface active Router Interface
//
// You can read doc at https://help.aliyun.com/document_detail/36030.html?spm=5176.doc36031.6.667.DAuZLD
func (client *Client) ActivateRouterInterface(args *OperateRouterInterfaceArgs) (response *EcsCommonResponse, err error) {
	response = &EcsCommonResponse{}
	err = client.Invoke("ActivateRouterInterface", args, &response)
	if err != nil {
		return response, err
	}
	return response, nil
}

// DeactivateRouterInterface deactivate Router Interface
//
// You can read doc at https://help.aliyun.com/document_detail/36033.html?spm=5176.doc36030.6.668.JqCWUz
func (client *Client) DeactivateRouterInterface(args *OperateRouterInterfaceArgs) (response *EcsCommonResponse, err error) {
	response = &EcsCommonResponse{}
	err = client.Invoke("DeactivateRouterInterface", args, &response)
	if err != nil {
		return response, err
	}
	return response, nil
}

type ModifyRouterInterfaceSpecArgs struct {
	RegionId          common.Region
	RouterInterfaceId string
	Spec              Spec
}

type ModifyRouterInterfaceSpecResponse struct {
	common.Response
	Spec Spec
}

// ModifyRouterInterfaceSpec
//
// You can read doc at https://help.aliyun.com/document_detail/36037.html?spm=5176.doc36036.6.669.McKiye
func (client *Client) ModifyRouterInterfaceSpec(args *ModifyRouterInterfaceSpecArgs) (response *ModifyRouterInterfaceSpecResponse, err error) {
	response = &ModifyRouterInterfaceSpecResponse{}
	err = client.Invoke("ModifyRouterInterfaceSpec", args, &response)
	if err != nil {
		return response, err
	}
	return response, nil
}

type ModifyRouterInterfaceAttributeArgs struct {
	RegionId                 common.Region
	RouterInterfaceId        string
	Name                     string
	Description              string
	OppositeInterfaceId      string
	OppositeRouterId         string
	OppositeInterfaceOwnerId string
	HealthCheckSourceIp      string
	HealthCheckTargetIp      string
}

// ModifyRouterInterfaceAttribute
//
// You can read doc at https://help.aliyun.com/document_detail/36036.html?spm=5176.doc36037.6.670.Dcz3xS
func (client *Client) ModifyRouterInterfaceAttribute(args *ModifyRouterInterfaceAttributeArgs) (response *EcsCommonResponse, err error) {
	response = &EcsCommonResponse{}
	err = client.Invoke("ModifyRouterInterfaceAttribute", args, &response)
	if err != nil {
		return response, err
	}
	return response, nil
}

// DeleteRouterInterface delete Router Interface
//
// You can read doc at https://help.aliyun.com/document_detail/36034.html?spm=5176.doc36036.6.671.y2xpNt
func (client *Client) DeleteRouterInterface(args *OperateRouterInterfaceArgs) (response *EcsCommonResponse, err error) {
	response = &EcsCommonResponse{}
	err = client.Invoke("DeleteRouterInterface", args, &response)
	if err != nil {
		return response, err
	}
	return response, nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_guardduty_member.go<|end_filename|>
package aws

import (
	"fmt"
	"log"
	"strings"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/guardduty"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsGuardDutyMember() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsGuardDutyMemberCreate,
		Read:   resourceAwsGuardDutyMemberRead,
		Delete: resourceAwsGuardDutyMemberDelete,

		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"account_id": {
				Type:         schema.TypeString,
				Required:     true,
				ForceNew:     true,
				ValidateFunc: validateAwsAccountId,
			},
			"detector_id": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"email": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
		},
	}
}

func resourceAwsGuardDutyMemberCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).guarddutyconn
	accountID := d.Get("account_id").(string)
	detectorID := d.Get("detector_id").(string)

	input := guardduty.CreateMembersInput{
		AccountDetails: []*guardduty.AccountDetail{{
			AccountId: aws.String(accountID),
			Email:     aws.String(d.Get("email").(string)),
		}},
		DetectorId: aws.String(detectorID),
	}

	log.Printf("[DEBUG] Creating GuardDuty Member: %s", input)
	_, err := conn.CreateMembers(&input)
	if err != nil {
		return fmt.Errorf("Creating GuardDuty Member failed: %s", err.Error())
	}
	d.SetId(fmt.Sprintf("%s:%s", detectorID, accountID))

	return resourceAwsGuardDutyMemberRead(d, meta)
}

func resourceAwsGuardDutyMemberRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).guarddutyconn

	accountID, detectorID, err := decodeGuardDutyMemberID(d.Id())
	if err != nil {
		return err
	}

	input := guardduty.GetMembersInput{
		AccountIds: []*string{aws.String(accountID)},
		DetectorId: aws.String(detectorID),
	}

	log.Printf("[DEBUG] Reading GuardDuty Member: %s", input)
	gmo, err := conn.GetMembers(&input)
	if err != nil {
		if isAWSErr(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the input detectorId is not owned by the current account.") {
			log.Printf("[WARN] GuardDuty detector %q not found, removing from state", d.Id())
			d.SetId("")
			return nil
		}
		return fmt.Errorf("Reading GuardDuty Member '%s' failed: %s", d.Id(), err.Error())
	}

	if gmo.Members == nil || (len(gmo.Members) < 1) {
		log.Printf("[WARN] GuardDuty Member %q not found, removing from state", d.Id())
		d.SetId("")
		return nil
	}
	member := gmo.Members[0]
	d.Set("account_id", member.AccountId)
	d.Set("detector_id", detectorID)
	d.Set("email", member.Email)

	return nil
}

func resourceAwsGuardDutyMemberDelete(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).guarddutyconn

	accountID, detectorID, err := decodeGuardDutyMemberID(d.Id())
	if err != nil {
		return err
	}

	input := guardduty.DeleteMembersInput{
		AccountIds: []*string{aws.String(accountID)},
		DetectorId: aws.String(detectorID),
	}

	log.Printf("[DEBUG] Delete GuardDuty Member: %s", input)
	_, err = conn.DeleteMembers(&input)
	if err != nil {
		return fmt.Errorf("Deleting GuardDuty Member '%s' failed: %s", d.Id(), err.Error())
	}
	return nil
}

func decodeGuardDutyMemberID(id string) (accountID, detectorID string, err error) {
	parts := strings.Split(id, ":")
	if len(parts) != 2 {
		err = fmt.Errorf("GuardDuty Member ID must be of the form <Detector ID>:<Member AWS Account ID>, was provided: %s", id)
		return
	}
	accountID = parts[1]
	detectorID = parts[0]
	return
}


<|start_filename|>vendor/github.com/mitchellh/packer/vendor/github.com/joyent/triton-go/network/firewall.go<|end_filename|>
//
// Copyright (c) 2018, Joyent, Inc. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

package network

import (
	"context"
	"encoding/json"
	"net/http"
	"path"
	"time"

	"github.com/joyent/triton-go/client"
	"github.com/pkg/errors"
)

type FirewallClient struct {
	client *client.Client
}

// FirewallRule represents a firewall rule
type FirewallRule struct {
	// ID is a unique identifier for this rule
	ID string `json:"id"`

	// Enabled indicates if the rule is enabled
	Enabled bool `json:"enabled"`

	// Rule is the firewall rule text
	Rule string `json:"rule"`

	// Global indicates if the rule is global. Optional.
	Global bool `json:"global"`

	// Description is a human-readable description for the rule. Optional
	Description string `json:"description"`
}

type ListRulesInput struct{}

func (c *FirewallClient) ListRules(ctx context.Context, _ *ListRulesInput) ([]*FirewallRule, error) {
	fullPath := path.Join("/", c.client.AccountName, "fwrules")
	reqInputs := client.RequestInput{
		Method: http.MethodGet,
		Path:   fullPath,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to list firewall rules")
	}

	var result []*FirewallRule
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode list firewall rules response")
	}

	return result, nil
}

type GetRuleInput struct {
	ID string
}

func (c *FirewallClient) GetRule(ctx context.Context, input *GetRuleInput) (*FirewallRule, error) {
	fullPath := path.Join("/", c.client.AccountName, "fwrules", input.ID)
	reqInputs := client.RequestInput{
		Method: http.MethodGet,
		Path:   fullPath,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to get firewall rule")
	}

	var result *FirewallRule
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode get firewall rule response")
	}

	return result, nil
}

type CreateRuleInput struct {
	Enabled     bool   `json:"enabled"`
	Rule        string `json:"rule"`
	Description string `json:"description,omitempty"`
}

func (c *FirewallClient) CreateRule(ctx context.Context, input *CreateRuleInput) (*FirewallRule, error) {
	fullPath := path.Join("/", c.client.AccountName, "fwrules")
	reqInputs := client.RequestInput{
		Method: http.MethodPost,
		Path:   fullPath,
		Body:   input,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to create firewall rule")
	}

	var result *FirewallRule
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode create firewall rule response")
	}

	return result, nil
}

type UpdateRuleInput struct {
	ID          string `json:"-"`
	Enabled     bool   `json:"enabled"`
	Rule        string `json:"rule"`
	Description string `json:"description,omitempty"`
}

func (c *FirewallClient) UpdateRule(ctx context.Context, input *UpdateRuleInput) (*FirewallRule, error) {
	fullPath := path.Join("/", c.client.AccountName, "fwrules", input.ID)
	reqInputs := client.RequestInput{
		Method: http.MethodPost,
		Path:   fullPath,
		Body:   input,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to update firewall rule")
	}

	var result *FirewallRule
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode update firewall rule response")
	}

	return result, nil
}

type EnableRuleInput struct {
	ID string `json:"-"`
}

func (c *FirewallClient) EnableRule(ctx context.Context, input *EnableRuleInput) (*FirewallRule, error) {
	fullPath := path.Join("/", c.client.AccountName, "fwrules", input.ID, "enable")
	reqInputs := client.RequestInput{
		Method: http.MethodPost,
		Path:   fullPath,
		Body:   input,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to enable firewall rule")
	}

	var result *FirewallRule
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode enable firewall rule response")
	}

	return result, nil
}

type DisableRuleInput struct {
	ID string `json:"-"`
}

func (c *FirewallClient) DisableRule(ctx context.Context, input *DisableRuleInput) (*FirewallRule, error) {
	fullPath := path.Join("/", c.client.AccountName, "fwrules", input.ID, "disable")
	reqInputs := client.RequestInput{
		Method: http.MethodPost,
		Path:   fullPath,
		Body:   input,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to disable firewall rule")
	}

	var result *FirewallRule
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode disable firewall rule response")
	}

	return result, nil
}

type DeleteRuleInput struct {
	ID string
}

func (c *FirewallClient) DeleteRule(ctx context.Context, input *DeleteRuleInput) error {
	fullPath := path.Join("/", c.client.AccountName, "fwrules", input.ID)
	reqInputs := client.RequestInput{
		Method: http.MethodDelete,
		Path:   fullPath,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return errors.Wrap(err, "unable to delete firewall rule")
	}

	return nil
}

type ListMachineRulesInput struct {
	MachineID string
}

func (c *FirewallClient) ListMachineRules(ctx context.Context, input *ListMachineRulesInput) ([]*FirewallRule, error) {
	fullPath := path.Join("/", c.client.AccountName, "machines", input.MachineID, "fwrules")
	reqInputs := client.RequestInput{
		Method: http.MethodGet,
		Path:   fullPath,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to list machine firewall rules")
	}

	var result []*FirewallRule
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode list machine firewall rules response")
	}

	return result, nil
}

type ListRuleMachinesInput struct {
	ID string
}

type Machine struct {
	ID              string                 `json:"id"`
	Name            string                 `json:"name"`
	Type            string                 `json:"type"`
	Brand           string                 `json:"brand"`
	State           string                 `json:"state"`
	Image           string                 `json:"image"`
	Memory          int                    `json:"memory"`
	Disk            int                    `json:"disk"`
	Metadata        map[string]string      `json:"metadata"`
	Tags            map[string]interface{} `json:"tags"`
	Created         time.Time              `json:"created"`
	Updated         time.Time              `json:"updated"`
	Docker          bool                   `json:"docker"`
	IPs             []string               `json:"ips"`
	Networks        []string               `json:"networks"`
	PrimaryIP       string                 `json:"primaryIp"`
	FirewallEnabled bool                   `json:"firewall_enabled"`
	ComputeNode     string                 `json:"compute_node"`
	Package         string                 `json:"package"`
}

func (c *FirewallClient) ListRuleMachines(ctx context.Context, input *ListRuleMachinesInput) ([]*Machine, error) {
	fullPath := path.Join("/", c.client.AccountName, "fwrules", input.ID, "machines")
	reqInputs := client.RequestInput{
		Method: http.MethodGet,
		Path:   fullPath,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to list firewall rule machines")
	}

	var result []*Machine
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode list firewall rule machines response")
	}

	return result, nil
}


<|start_filename|>vendor/github.com/hashicorp/go-getter/detect_file_test.go<|end_filename|>
package getter

import (
	"runtime"
	"testing"
)

type fileTest struct {
	in, pwd, out string
	err          bool
}

var fileTests = []fileTest{
	{"./foo", "/pwd", "file:///pwd/foo", false},
	{"./foo?foo=bar", "/pwd", "file:///pwd/foo?foo=bar", false},
	{"foo", "/pwd", "file:///pwd/foo", false},
}

var unixFileTests = []fileTest{
	{"/foo", "/pwd", "file:///foo", false},
	{"/foo?bar=baz", "/pwd", "file:///foo?bar=baz", false},
}

var winFileTests = []fileTest{
	{"/foo", "/pwd", "file:///pwd/foo", false},
	{`C:\`, `/pwd`, `file://C:/`, false},
	{`C:\?bar=baz`, `/pwd`, `file://C:/?bar=baz`, false},
}

func TestFileDetector(t *testing.T) {
	if runtime.GOOS == "windows" {
		fileTests = append(fileTests, winFileTests...)
	} else {
		fileTests = append(fileTests, unixFileTests...)
	}

	f := new(FileDetector)
	for i, tc := range fileTests {
		out, ok, err := f.Detect(tc.in, tc.pwd)
		if err != nil {
			t.Fatalf("err: %s", err)
		}
		if !ok {
			t.Fatal("not ok")
		}

		if out != tc.out {
			t.Fatalf("%d: bad: %#v", i, out)
		}
	}
}

var noPwdFileTests = []fileTest{
	{in: "./foo", pwd: "", out: "", err: true},
	{in: "foo", pwd: "", out: "", err: true},
}

var noPwdUnixFileTests = []fileTest{
	{in: "/foo", pwd: "", out: "file:///foo", err: false},
}

var noPwdWinFileTests = []fileTest{
	{in: "/foo", pwd: "", out: "", err: true},
	{in: `C:\`, pwd: ``, out: `file://C:/`, err: false},
}

func TestFileDetector_noPwd(t *testing.T) {
	if runtime.GOOS == "windows" {
		noPwdFileTests = append(noPwdFileTests, noPwdWinFileTests...)
	} else {
		noPwdFileTests = append(noPwdFileTests, noPwdUnixFileTests...)
	}

	f := new(FileDetector)
	for i, tc := range noPwdFileTests {
		out, ok, err := f.Detect(tc.in, tc.pwd)
		if err != nil != tc.err {
			t.Fatalf("%d: err: %s", i, err)
		}
		if !ok {
			t.Fatal("not ok")
		}

		if out != tc.out {
			t.Fatalf("%d: bad: %#v", i, out)
		}
	}
}


<|start_filename|>vendor/github.com/mitchellh/packer/vendor/github.com/hashicorp/atlas-go/archive/archive.go<|end_filename|>
// archive is package that helps create archives in a format that
// Atlas expects with its various upload endpoints.
package archive

import (
	"archive/tar"
	"bufio"
	"compress/gzip"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
)

// Archive is the resulting archive. The archive data is generally streamed
// so the io.ReadCloser can be used to backpressure the archive progress
// and avoid memory pressure.
type Archive struct {
	io.ReadCloser

	Size     int64
	Metadata map[string]string
}

// ArchiveOpts are the options for defining how the archive will be built.
type ArchiveOpts struct {
	// Exclude and Include are filters of files to include/exclude in
	// the archive when creating it from a directory. These filters should
	// be relative to the packaging directory and should be basic glob
	// patterns.
	Exclude []string
	Include []string

	// Extra is a mapping of extra files to include within the archive. The
	// key should be the path within the archive and the value should be
	// an absolute path to the file to put into the archive. These extra
	// files will override any other files in the archive.
	Extra map[string]string

	// VCS, if true, will detect and use a VCS system to determine what
	// files to include the archive.
	VCS bool
}

// IsSet says whether any options were set.
func (o *ArchiveOpts) IsSet() bool {
	return len(o.Exclude) > 0 || len(o.Include) > 0 || o.VCS
}

// Constants related to setting special values for Extra in ArchiveOpts.
const (
	// ExtraEntryDir just creates the Extra key as a directory entry.
	ExtraEntryDir = ""
)

// CreateArchive takes the given path and ArchiveOpts and archives it.
//
// The archive will be fully completed and put into a temporary file.
// This must be done to retrieve the content length of the archive which
// is needed for almost all operations involving archives with Atlas. Because
// of this, sufficient disk space will be required to buffer the archive.
func CreateArchive(path string, opts *ArchiveOpts) (*Archive, error) {
	log.Printf("[INFO] creating archive from %s", path)

	// Dereference any symlinks and determine the real path and info
	fi, err := os.Lstat(path)
	if err != nil {
		return nil, err
	}
	if fi.Mode()&os.ModeSymlink != 0 {
		path, fi, err = readLinkFull(path, fi)
		if err != nil {
			return nil, err
		}
	}

	// Windows
	path = filepath.ToSlash(path)

	// Direct file paths cannot have archive options
	if !fi.IsDir() && opts.IsSet() {
		return nil, fmt.Errorf(
			"options such as exclude, include, and VCS can't be set when " +
				"the path is a file.")
	}

	if fi.IsDir() {
		return archiveDir(path, opts)
	} else {
		return archiveFile(path)
	}
}

func archiveFile(path string) (*Archive, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}

	if _, err := gzip.NewReader(f); err == nil {
		// Reset the read offset for future reading
		if _, err := f.Seek(0, 0); err != nil {
			f.Close()
			return nil, err
		}

		// Get the file info for the size
		fi, err := f.Stat()
		if err != nil {
			f.Close()
			return nil, err
		}

		// This is a gzip file, let it through.
		return &Archive{ReadCloser: f, Size: fi.Size()}, nil
	}

	// Close the file, no use for it anymore
	f.Close()

	// We have a single file that is not gzipped. Compress it.
	path, err = filepath.Abs(path)
	if err != nil {
		return nil, err
	}

	// Act like we're compressing a directory, but only include this one
	// file.
	return archiveDir(filepath.Dir(path), &ArchiveOpts{
		Include: []string{filepath.Base(path)},
	})
}

func archiveDir(root string, opts *ArchiveOpts) (*Archive, error) {

	var vcsInclude []string
	var metadata map[string]string
	if opts.VCS {
		var err error

		if err = vcsPreflight(root); err != nil {
			return nil, err
		}

		vcsInclude, err = vcsFiles(root)
		if err != nil {
			return nil, err
		}

		metadata, err = vcsMetadata(root)
		if err != nil {
			return nil, err
		}
	}

	// Make sure the root path is absolute
	root, err := filepath.Abs(root)
	if err != nil {
		return nil, err
	}

	// Create the temporary file that we'll send the archive data to.
	archiveF, err := ioutil.TempFile("", "atlas-archive")
	if err != nil {
		return nil, err
	}

	// Create the wrapper for the result which will automatically
	// remove the temporary file on close.
	archiveWrapper := &readCloseRemover{F: archiveF}

	// Buffer the writer so that we can push as much data to disk at
	// a time as possible. 4M should be good.
	bufW := bufio.NewWriterSize(archiveF, 4096*1024)

	// Gzip compress all the output data
	gzipW := gzip.NewWriter(bufW)

	// Tar the file contents
	tarW := tar.NewWriter(gzipW)

	// First, walk the path and do the normal files
	werr := filepath.Walk(root, copyDirWalkFn(
		tarW, root, "", opts, vcsInclude))
	if werr == nil {
		// If that succeeded, handle the extra files
		werr = copyExtras(tarW, opts.Extra)
	}

	// Attempt to close all the things. If we get an error on the way
	// and we haven't had an error yet, then record that as the critical
	// error. But we still try to close everything.

	// Close the tar writer
	if err := tarW.Close(); err != nil && werr == nil {
		werr = err
	}

	// Close the gzip writer
	if err := gzipW.Close(); err != nil && werr == nil {
		werr = err
	}

	// Flush the buffer
	if err := bufW.Flush(); err != nil && werr == nil {
		werr = err
	}

	// If we had an error, then close the file (removing it) and
	// return the error.
	if werr != nil {
		archiveWrapper.Close()
		return nil, werr
	}

	// Seek to the beginning
	if _, err := archiveWrapper.F.Seek(0, 0); err != nil {
		archiveWrapper.Close()
		return nil, err
	}

	// Get the file information so we can get the size
	fi, err := archiveWrapper.F.Stat()
	if err != nil {
		archiveWrapper.Close()
		return nil, err
	}

	return &Archive{
		ReadCloser: archiveWrapper,
		Size:       fi.Size(),
		Metadata:   metadata,
	}, nil
}

func copyDirWalkFn(
	tarW *tar.Writer, root string, prefix string,
	opts *ArchiveOpts, vcsInclude []string) filepath.WalkFunc {

	errFunc := func(err error) filepath.WalkFunc {
		return func(string, os.FileInfo, error) error {
			return err
		}
	}

	// Windows
	root = filepath.ToSlash(root)

	var includeMap map[string]struct{}

	// If we have an include/exclude pattern set, then setup the lookup
	// table to determine what we want to include.
	if opts != nil && len(opts.Include) > 0 {
		includeMap = make(map[string]struct{})
		for _, pattern := range opts.Include {
			matches, err := filepath.Glob(filepath.Join(root, pattern))
			if err != nil {
				return errFunc(fmt.Errorf(
					"error checking include glob '%s': %s",
					pattern, err))
			}

			for _, path := range matches {
				// Windows
				path = filepath.ToSlash(path)
				subpath, err := filepath.Rel(root, path)
				subpath = filepath.ToSlash(subpath)

				if err != nil {
					return errFunc(err)
				}

				for {
					includeMap[subpath] = struct{}{}
					subpath = filepath.Dir(subpath)
					if subpath == "." {
						break
					}
				}
			}
		}
	}

	return func(path string, info os.FileInfo, err error) error {
		path = filepath.ToSlash(path)

		if err != nil {
			return err
		}

		// Get the relative path from the path since it contains the root
		// plus the path.
		subpath, err := filepath.Rel(root, path)
		if err != nil {
			return err
		}
		if subpath == "." {
			return nil
		}
		if prefix != "" {
			subpath = filepath.Join(prefix, subpath)
		}
		// Windows
		subpath = filepath.ToSlash(subpath)

		// If we have a list of VCS files, check that first
		skip := false
		if len(vcsInclude) > 0 {
			skip = true
			for _, f := range vcsInclude {
				if f == subpath {
					skip = false
					break
				}

				if info.IsDir() && strings.HasPrefix(f, subpath+"/") {
					skip = false
					break
				}
			}
		}

		// If include is present, we only include what is listed
		if len(includeMap) > 0 {
			if _, ok := includeMap[subpath]; !ok {
				skip = true
			}
		}

		// If exclude, it is one last gate to excluding files
		if opts != nil {
			for _, exclude := range opts.Exclude {
				match, err := filepath.Match(exclude, subpath)
				if err != nil {
					return err
				}
				if match {
					skip = true
					break
				}
			}
		}

		// If we have to skip this file, then skip it, properly skipping
		// children if we're a directory.
		if skip {
			if info.IsDir() {
				return filepath.SkipDir
			}

			return nil
		}

		// If this is a symlink, then we need to get the symlink target
		// rather than the symlink itself.
		if info.Mode()&os.ModeSymlink != 0 {
			target, info, err := readLinkFull(path, info)
			if err != nil {
				return err
			}

			// Copy the concrete entry for this path. This will either
			// be the file itself or just a directory entry.
			if err := copyConcreteEntry(tarW, subpath, target, info); err != nil {
				return err
			}

			if info.IsDir() {
				return filepath.Walk(target, copyDirWalkFn(
					tarW, target, subpath, opts, vcsInclude))
			}
			// return now so that we don't try to copy twice
			return nil
		}

		return copyConcreteEntry(tarW, subpath, path, info)
	}
}

func copyConcreteEntry(
	tarW *tar.Writer, entry string,
	path string, info os.FileInfo) error {
	// Windows
	path = filepath.ToSlash(path)

	// Build the file header for the tar entry
	header, err := tar.FileInfoHeader(info, path)
	if err != nil {
		return fmt.Errorf(
			"failed creating archive header: %s", path)
	}

	// Modify the header to properly be the full entry name
	header.Name = entry
	if info.IsDir() {
		header.Name += "/"
	}

	// Write the header first to the archive.
	if err := tarW.WriteHeader(header); err != nil {
		return fmt.Errorf(
			"failed writing archive header: %s", path)
	}

	// If it is a directory, then we're done (no body to write)
	if info.IsDir() {
		return nil
	}

	// Open the real file to write the data
	f, err := os.Open(path)
	if err != nil {
		return fmt.Errorf(
			"failed opening file '%s' to write compressed archive.", path)
	}
	defer f.Close()

	if _, err = io.Copy(tarW, f); err != nil {
		return fmt.Errorf(
			"failed copying file to archive: %s, %s", path, err)
	}

	return nil
}

func copyExtras(w *tar.Writer, extra map[string]string) error {
	var tmpDir string
	defer func() {
		if tmpDir != "" {
			os.RemoveAll(tmpDir)
		}
	}()

	for entry, path := range extra {
		// If the path is empty, then we set it to a generic empty directory
		if path == "" {
			// If tmpDir is still empty, then we create an empty dir
			if tmpDir == "" {
				td, err := ioutil.TempDir("", "archive")
				if err != nil {
					return err
				}

				tmpDir = td
			}

			path = tmpDir
		}

		info, err := os.Stat(path)
		if err != nil {
			return err
		}

		// No matter what, write the entry. If this is a directory,
		// it'll just write the directory header.
		if err := copyConcreteEntry(w, entry, path, info); err != nil {
			return err
		}

		// If this is a directory, then we walk the internal contents
		// and copy those as well.
		if info.IsDir() {
			err := filepath.Walk(path, copyDirWalkFn(
				w, path, entry, nil, nil))
			if err != nil {
				return err
			}
		}
	}

	return nil
}

func readLinkFull(path string, info os.FileInfo) (string, os.FileInfo, error) {
	target, err := filepath.EvalSymlinks(path)
	if err != nil {
		return "", nil, err
	}

	target, err = filepath.Abs(target)
	if err != nil {
		return "", nil, err
	}

	fi, err := os.Lstat(target)
	if err != nil {
		return "", nil, err
	}

	return target, fi, nil
}

// readCloseRemover is an io.ReadCloser implementation that will remove
// the file on Close(). We use this to clean up our temporary file for
// the archive.
type readCloseRemover struct {
	F *os.File
}

func (r *readCloseRemover) Read(p []byte) (int, error) {
	return r.F.Read(p)
}

func (r *readCloseRemover) Close() error {
	// First close the file
	err := r.F.Close()

	// Next make sure to remove it, or at least try, regardless of error
	// above.
	os.Remove(r.F.Name())

	return err
}


<|start_filename|>vendor/github.com/mitchellh/packer/vendor/github.com/joyent/triton-go/compute/ping.go<|end_filename|>
//
// Copyright (c) 2018, Joyent, Inc. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

package compute

import (
	"context"
	"encoding/json"
	"net/http"

	"github.com/joyent/triton-go/client"
	pkgerrors "github.com/pkg/errors"
)

const pingEndpoint = "/--ping"

type CloudAPI struct {
	Versions []string `json:"versions"`
}

type PingOutput struct {
	Ping     string   `json:"ping"`
	CloudAPI CloudAPI `json:"cloudapi"`
}

// Ping sends a request to the '/--ping' endpoint and returns a `pong` as well
// as a list of API version numbers your instance of CloudAPI is presenting.
func (c *ComputeClient) Ping(ctx context.Context) (*PingOutput, error) {
	reqInputs := client.RequestInput{
		Method: http.MethodGet,
		Path:   pingEndpoint,
	}
	response, err := c.Client.ExecuteRequestRaw(ctx, reqInputs)
	if err != nil {
		return nil, pkgerrors.Wrap(err, "unable to ping")
	}
	if response == nil {
		return nil, pkgerrors.Wrap(err, "unable to ping")
	}
	if response.Body != nil {
		defer response.Body.Close()
	}

	var result *PingOutput
	decoder := json.NewDecoder(response.Body)
	if err = decoder.Decode(&result); err != nil {
		if err != nil {
			return nil, pkgerrors.Wrap(err, "unable to decode ping response")
		}
	}

	return result, nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/data_source_aws_network_interface.go<|end_filename|>
package aws

import (
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/hashicorp/terraform/helper/schema"
)

func dataSourceAwsNetworkInterface() *schema.Resource {
	return &schema.Resource{
		Read: dataSourceAwsNetworkInterfaceRead,
		Schema: map[string]*schema.Schema{
			"id": {
				Type:     schema.TypeString,
				Required: true,
			},
			"association": {
				Type:     schema.TypeList,
				Computed: true,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"allocation_id": {
							Type:     schema.TypeString,
							Computed: true,
						},
						"association_id": {
							Type:     schema.TypeString,
							Computed: true,
						},
						"ip_owner_id": {
							Type:     schema.TypeString,
							Computed: true,
						},
						"public_dns_name": {
							Type:     schema.TypeString,
							Computed: true,
						},
						"public_ip": {
							Type:     schema.TypeString,
							Computed: true,
						},
					},
				},
			},
			"attachment": {
				Type:     schema.TypeList,
				Computed: true,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"attachment_id": {
							Type:     schema.TypeString,
							Computed: true,
						},
						"device_index": {
							Type:     schema.TypeInt,
							Computed: true,
						},
						"instance_id": {
							Type:     schema.TypeString,
							Computed: true,
						},
						"instance_owner_id": {
							Type:     schema.TypeString,
							Computed: true,
						},
					},
				},
			},
			"availability_zone": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"description": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"security_groups": {
				Type:     schema.TypeSet,
				Computed: true,
				Elem:     &schema.Schema{Type: schema.TypeString},
			},
			"interface_type": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"ipv6_addresses": {
				Type:     schema.TypeSet,
				Computed: true,
				Elem:     &schema.Schema{Type: schema.TypeString},
			},
			"mac_address": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"owner_id": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"private_dns_name": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"private_ip": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"private_ips": {
				Type:     schema.TypeList,
				Computed: true,
				Elem:     &schema.Schema{Type: schema.TypeString},
			},
			"requester_id": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"subnet_id": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"vpc_id": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"tags": tagsSchemaComputed(),
		},
	}
}

func dataSourceAwsNetworkInterfaceRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ec2conn

	input := &ec2.DescribeNetworkInterfacesInput{
		NetworkInterfaceIds: []*string{aws.String(d.Get("id").(string))},
	}

	log.Printf("[DEBUG] Reading Network Interface: %s", input)
	resp, err := conn.DescribeNetworkInterfaces(input)
	if err != nil {
		return err
	}
	if resp == nil || len(resp.NetworkInterfaces) == 0 {
		return fmt.Errorf("no matching network interface found")
	}
	if len(resp.NetworkInterfaces) > 1 {
		return fmt.Errorf("multiple network interfaces matched %s", d.Id())
	}

	eni := resp.NetworkInterfaces[0]

	d.SetId(*eni.NetworkInterfaceId)
	if eni.Association != nil {
		d.Set("association", flattenEc2NetworkInterfaceAssociation(eni.Association))
	}
	if eni.Attachment != nil {
		attachment := []interface{}{flattenAttachment(eni.Attachment)}
		d.Set("attachment", attachment)
	}
	d.Set("availability_zone", eni.AvailabilityZone)
	d.Set("description", eni.Description)
	d.Set("security_groups", flattenGroupIdentifiers(eni.Groups))
	d.Set("interface_type", eni.InterfaceType)
	d.Set("ipv6_addresses", flattenEc2NetworkInterfaceIpv6Address(eni.Ipv6Addresses))
	d.Set("mac_address", eni.MacAddress)
	d.Set("owner_id", eni.OwnerId)
	d.Set("private_dns_name", eni.PrivateDnsName)
	d.Set("private_id", eni.PrivateIpAddress)
	d.Set("private_ips", flattenNetworkInterfacesPrivateIPAddresses(eni.PrivateIpAddresses))
	d.Set("requester_id", eni.RequesterId)
	d.Set("subnet_id", eni.SubnetId)
	d.Set("vpc_id", eni.VpcId)
	d.Set("tags", tagsToMap(eni.TagSet))
	return nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_lb_target_group_attachment.go<|end_filename|>
package aws

import (
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/elbv2"
	"github.com/hashicorp/errwrap"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsLbTargetGroupAttachment() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsLbAttachmentCreate,
		Read:   resourceAwsLbAttachmentRead,
		Delete: resourceAwsLbAttachmentDelete,

		Schema: map[string]*schema.Schema{
			"target_group_arn": {
				Type:     schema.TypeString,
				ForceNew: true,
				Required: true,
			},

			"target_id": {
				Type:     schema.TypeString,
				ForceNew: true,
				Required: true,
			},

			"port": {
				Type:     schema.TypeInt,
				ForceNew: true,
				Optional: true,
			},

			"availability_zone": {
				Type:     schema.TypeString,
				ForceNew: true,
				Optional: true,
			},
		},
	}
}

func resourceAwsLbAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
	elbconn := meta.(*AWSClient).elbv2conn

	target := &elbv2.TargetDescription{
		Id: aws.String(d.Get("target_id").(string)),
	}

	if v, ok := d.GetOk("port"); ok {
		target.Port = aws.Int64(int64(v.(int)))
	}

	if v, ok := d.GetOk("availability_zone"); ok {
		target.AvailabilityZone = aws.String(v.(string))
	}

	params := &elbv2.RegisterTargetsInput{
		TargetGroupArn: aws.String(d.Get("target_group_arn").(string)),
		Targets:        []*elbv2.TargetDescription{target},
	}

	log.Printf("[INFO] Registering Target %s with Target Group %s", d.Get("target_id").(string),
		d.Get("target_group_arn").(string))

	_, err := elbconn.RegisterTargets(params)
	if err != nil {
		return errwrap.Wrapf("Error registering targets with target group: {{err}}", err)
	}

	d.SetId(resource.PrefixedUniqueId(fmt.Sprintf("%s-", d.Get("target_group_arn"))))

	return nil
}

func resourceAwsLbAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
	elbconn := meta.(*AWSClient).elbv2conn

	target := &elbv2.TargetDescription{
		Id: aws.String(d.Get("target_id").(string)),
	}

	if v, ok := d.GetOk("port"); ok {
		target.Port = aws.Int64(int64(v.(int)))
	}

	if v, ok := d.GetOk("availability_zone"); ok {
		target.AvailabilityZone = aws.String(v.(string))
	}

	params := &elbv2.DeregisterTargetsInput{
		TargetGroupArn: aws.String(d.Get("target_group_arn").(string)),
		Targets:        []*elbv2.TargetDescription{target},
	}

	_, err := elbconn.DeregisterTargets(params)
	if err != nil && !isTargetGroupNotFound(err) {
		return errwrap.Wrapf("Error deregistering Targets: {{err}}", err)
	}

	d.SetId("")

	return nil
}

// resourceAwsLbAttachmentRead requires all of the fields in order to describe the correct
// target, so there is no work to do beyond ensuring that the target and group still exist.
func resourceAwsLbAttachmentRead(d *schema.ResourceData, meta interface{}) error {
	elbconn := meta.(*AWSClient).elbv2conn

	target := &elbv2.TargetDescription{
		Id: aws.String(d.Get("target_id").(string)),
	}

	if v, ok := d.GetOk("port"); ok {
		target.Port = aws.Int64(int64(v.(int)))
	}

	if v, ok := d.GetOk("availability_zone"); ok {
		target.AvailabilityZone = aws.String(v.(string))
	}

	resp, err := elbconn.DescribeTargetHealth(&elbv2.DescribeTargetHealthInput{
		TargetGroupArn: aws.String(d.Get("target_group_arn").(string)),
		Targets:        []*elbv2.TargetDescription{target},
	})
	if err != nil {
		if isTargetGroupNotFound(err) {
			log.Printf("[WARN] Target group does not exist, removing target attachment %s", d.Id())
			d.SetId("")
			return nil
		}
		if isInvalidTarget(err) {
			log.Printf("[WARN] Target does not exist, removing target attachment %s", d.Id())
			d.SetId("")
			return nil
		}
		return errwrap.Wrapf("Error reading Target Health: {{err}}", err)
	}

	if len(resp.TargetHealthDescriptions) != 1 {
		log.Printf("[WARN] Target does not exist, removing target attachment %s", d.Id())
		d.SetId("")
		return nil
	}

	return nil
}

func isInvalidTarget(err error) bool {
	elberr, ok := err.(awserr.Error)
	return ok && elberr.Code() == "InvalidTarget"
}


<|start_filename|>vendor/github.com/mitchellh/packer/vendor/github.com/approvals/go-approval-tests/utils/testing_utils.go<|end_filename|>
package utils

import "testing"

// AssertEqual Example:
// AssertEqual(t, 10, number, "number")
func AssertEqual(t *testing.T, expected, actual interface{}, message string) {
	if expected != actual {
		t.Fatalf(message+"\n[expected != actual]\n[%s != %s]", expected, actual)
	}
}


<|start_filename|>vendor/github.com/posener/complete/predict_set.go<|end_filename|>
package complete

import "github.com/posener/complete/match"

// PredictSet expects specific set of terms, given in the options argument.
func PredictSet(options ...string) Predictor {
	return predictSet(options)
}

type predictSet []string

func (p predictSet) Predict(a Args) (prediction []string) {
	for _, m := range p {
		if match.Prefix(m, a.Last) {
			prediction = append(prediction, m)
		}
	}
	return
}


<|start_filename|>vendor/github.com/hashicorp/terraform/builtin/provisioners/file/resource_provisioner.go<|end_filename|>
package file

import (
	"context"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"time"

	"github.com/hashicorp/terraform/communicator"
	"github.com/hashicorp/terraform/helper/schema"
	"github.com/hashicorp/terraform/terraform"
	"github.com/mitchellh/go-homedir"
)

func Provisioner() terraform.ResourceProvisioner {
	return &schema.Provisioner{
		Schema: map[string]*schema.Schema{
			"source": &schema.Schema{
				Type:          schema.TypeString,
				Optional:      true,
				ConflictsWith: []string{"content"},
			},

			"content": &schema.Schema{
				Type:          schema.TypeString,
				Optional:      true,
				ConflictsWith: []string{"source"},
			},

			"destination": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
			},
		},

		ApplyFunc:    applyFn,
		ValidateFunc: validateFn,
	}
}

func applyFn(ctx context.Context) error {
	connState := ctx.Value(schema.ProvRawStateKey).(*terraform.InstanceState)
	data := ctx.Value(schema.ProvConfigDataKey).(*schema.ResourceData)

	// Get a new communicator
	comm, err := communicator.New(connState)
	if err != nil {
		return err
	}

	// Get the source
	src, deleteSource, err := getSrc(data)
	if err != nil {
		return err
	}
	if deleteSource {
		defer os.Remove(src)
	}

	// Begin the file copy
	dst := data.Get("destination").(string)
	resultCh := make(chan error, 1)
	go func() {
		resultCh <- copyFiles(comm, src, dst)
	}()

	// Allow the file copy to complete unless there is an interrupt.
	// If there is an interrupt we make no attempt to cleanly close
	// the connection currently. We just abruptly exit. Because Terraform
	// taints the resource, this is fine.
	select {
	case err := <-resultCh:
		return err
	case <-ctx.Done():
		return fmt.Errorf("file transfer interrupted")
	}
}

func validateFn(c *terraform.ResourceConfig) (ws []string, es []error) {
	if !c.IsSet("source") && !c.IsSet("content") {
		es = append(es, fmt.Errorf("Must provide one of 'source' or 'content'"))
	}

	return ws, es
}

// getSrc returns the file to use as source
func getSrc(data *schema.ResourceData) (string, bool, error) {
	src := data.Get("source").(string)
	if content, ok := data.GetOk("content"); ok {
		file, err := ioutil.TempFile("", "tf-file-content")
		if err != nil {
			return "", true, err
		}

		if _, err = file.WriteString(content.(string)); err != nil {
			return "", true, err
		}

		return file.Name(), true, nil
	}

	expansion, err := homedir.Expand(src)
	return expansion, false, err
}

// copyFiles is used to copy the files from a source to a destination
func copyFiles(comm communicator.Communicator, src, dst string) error {
	// Wait and retry until we establish the connection
	err := retryFunc(comm.Timeout(), func() error {
		err := comm.Connect(nil)
		return err
	})
	if err != nil {
		return err
	}
	defer comm.Disconnect()

	info, err := os.Stat(src)
	if err != nil {
		return err
	}

	// If we're uploading a directory, short circuit and do that
	if info.IsDir() {
		if err := comm.UploadDir(dst, src); err != nil {
			return fmt.Errorf("Upload failed: %v", err)
		}
		return nil
	}

	// We're uploading a file...
	f, err := os.Open(src)
	if err != nil {
		return err
	}
	defer f.Close()

	err = comm.Upload(dst, f)
	if err != nil {
		return fmt.Errorf("Upload failed: %v", err)
	}
	return err
}

// retryFunc is used to retry a function for a given duration
func retryFunc(timeout time.Duration, f func() error) error {
	finish := time.After(timeout)
	for {
		err := f()
		if err == nil {
			return nil
		}
		log.Printf("Retryable error: %v", err)

		select {
		case <-finish:
			return err
		case <-time.After(3 * time.Second):
		}
	}
}


<|start_filename|>vendor/github.com/hashicorp/terraform/plugin/discovery/get_test.go<|end_filename|>
package discovery

import (
	"archive/zip"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"reflect"
	"regexp"
	"strings"
	"testing"

	"github.com/mitchellh/cli"
)

const testProviderFile = "test provider binary"

// return the directory listing for the "test" provider
func testListingHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte(versionList))
}

func testChecksumHandler(w http.ResponseWriter, r *http.Request) {
	// this exact plugin has a signnature and checksum file
	if r.URL.Path == "/terraform-provider-template/0.1.0/terraform-provider-template_0.1.0_SHA256SUMS" {
		http.ServeFile(w, r, "testdata/terraform-provider-template_0.1.0_SHA256SUMS")
		return
	}
	if r.URL.Path == "/terraform-provider-template/0.1.0/terraform-provider-template_0.1.0_SHA256SUMS.sig" {
		http.ServeFile(w, r, "testdata/terraform-provider-template_0.1.0_SHA256SUMS.sig")
		return
	}

	// this this checksum file is corrupt and doesn't match the sig
	if r.URL.Path == "/terraform-provider-badsig/0.1.0/terraform-provider-badsig_0.1.0_SHA256SUMS" {
		http.ServeFile(w, r, "testdata/terraform-provider-badsig_0.1.0_SHA256SUMS")
		return
	}
	if r.URL.Path == "/terraform-provider-badsig/0.1.0/terraform-provider-badsig_0.1.0_SHA256SUMS.sig" {
		http.ServeFile(w, r, "testdata/terraform-provider-badsig_0.1.0_SHA256SUMS.sig")
		return
	}

	http.Error(w, "signtaure files not found", http.StatusNotFound)
}

// returns a 200 for a valid provider url, using the patch number for the
// plugin protocol version.
func testHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/terraform-provider-test/" {
		testListingHandler(w, r)
		return
	}

	parts := strings.Split(r.URL.Path, "/")
	if len(parts) != 4 {
		http.Error(w, "not found", http.StatusNotFound)
		return
	}

	filename := parts[3]

	reg := regexp.MustCompile(`(terraform-provider-test)_(\d).(\d).(\d)_([^_]+)_([^._]+).zip`)

	fileParts := reg.FindStringSubmatch(filename)
	if len(fileParts) != 7 {
		http.Error(w, "invalid provider: "+filename, http.StatusNotFound)
		return
	}

	w.Header().Set(protocolVersionHeader, fileParts[4])

	// write a dummy file
	z := zip.NewWriter(w)
	fn := fmt.Sprintf("%s_v%s.%s.%s_x%s", fileParts[1], fileParts[2], fileParts[3], fileParts[4], fileParts[4])
	f, err := z.Create(fn)
	if err != nil {
		panic(err)
	}
	io.WriteString(f, testProviderFile)
	z.Close()
}

func testReleaseServer() *httptest.Server {
	handler := http.NewServeMux()
	handler.HandleFunc("/terraform-provider-test/", testHandler)
	handler.HandleFunc("/terraform-provider-template/", testChecksumHandler)
	handler.HandleFunc("/terraform-provider-badsig/", testChecksumHandler)

	return httptest.NewServer(handler)
}

func TestMain(m *testing.M) {
	server := testReleaseServer()
	releaseHost = server.URL

	os.Exit(m.Run())
}

func TestVersionListing(t *testing.T) {
	i := &ProviderInstaller{}
	versions, err := i.listProviderVersions("test")
	if err != nil {
		t.Fatal(err)
	}

	Versions(versions).Sort()

	expected := []string{
		"1.2.4",
		"1.2.3",
		"1.2.1",
	}

	if len(versions) != len(expected) {
		t.Fatalf("Received wrong number of versions. expected: %q, got: %q", expected, versions)
	}

	for i, v := range versions {
		if v.String() != expected[i] {
			t.Fatalf("incorrect version: %q, expected %q", v, expected[i])
		}
	}
}

func TestCheckProtocolVersions(t *testing.T) {
	i := &ProviderInstaller{}
	if checkPlugin(i.providerURL("test", VersionStr("1.2.3").MustParse().String()), 4) {
		t.Fatal("protocol version 4 is not compatible")
	}

	if !checkPlugin(i.providerURL("test", VersionStr("1.2.3").MustParse().String()), 3) {
		t.Fatal("protocol version 3 should be compatible")
	}
}

func TestProviderInstallerGet(t *testing.T) {
	tmpDir, err := ioutil.TempDir("", "tf-plugin")
	if err != nil {
		t.Fatal(err)
	}

	defer os.RemoveAll(tmpDir)

	// attempt to use an incompatible protocol version
	i := &ProviderInstaller{
		Dir: tmpDir,
		PluginProtocolVersion: 5,
		SkipVerify:            true,
		Ui:                    cli.NewMockUi(),
	}
	_, err = i.Get("test", AllVersions)
	if err != ErrorNoVersionCompatible {
		t.Fatal("want error for incompatible version")
	}

	i = &ProviderInstaller{
		Dir: tmpDir,
		PluginProtocolVersion: 3,
		SkipVerify:            true,
		Ui:                    cli.NewMockUi(),
	}

	{
		_, err := i.Get("test", ConstraintStr(">9.0.0").MustParse())
		if err != ErrorNoSuitableVersion {
			t.Fatal("want error for mismatching constraints")
		}
	}

	{
		_, err := i.Get("nonexist", AllVersions)
		if err != ErrorNoSuchProvider {
			t.Fatal("want error for no such provider")
		}
	}

	gotMeta, err := i.Get("test", AllVersions)
	if err != nil {
		t.Fatal(err)
	}

	// we should have version 1.2.3
	dest := filepath.Join(tmpDir, "terraform-provider-test_v1.2.3_x3")

	wantMeta := PluginMeta{
		Name:    "test",
		Version: VersionStr("1.2.3"),
		Path:    dest,
	}
	if !reflect.DeepEqual(gotMeta, wantMeta) {
		t.Errorf("wrong result meta\ngot:  %#v\nwant: %#v", gotMeta, wantMeta)
	}

	f, err := ioutil.ReadFile(dest)
	if err != nil {
		t.Fatal(err)
	}

	// provider should have been unzipped
	if string(f) != testProviderFile {
		t.Fatalf("test provider contains: %q", f)
	}

}

func TestProviderInstallerPurgeUnused(t *testing.T) {
	tmpDir, err := ioutil.TempDir("", "tf-plugin")
	if err != nil {
		t.Fatal(err)
	}

	defer os.RemoveAll(tmpDir)

	unwantedPath := filepath.Join(tmpDir, "terraform-provider-test_v0.0.1_x2")
	wantedPath := filepath.Join(tmpDir, "terraform-provider-test_v1.2.3_x3")

	f, err := os.Create(unwantedPath)
	if err != nil {
		t.Fatal(err)
	}
	f.Close()
	f, err = os.Create(wantedPath)
	if err != nil {
		t.Fatal(err)
	}
	f.Close()

	i := &ProviderInstaller{
		Dir: tmpDir,
		PluginProtocolVersion: 3,
		SkipVerify:            true,
		Ui:                    cli.NewMockUi(),
	}
	purged, err := i.PurgeUnused(map[string]PluginMeta{
		"test": PluginMeta{
			Name:    "test",
			Version: VersionStr("1.2.3"),
			Path:    wantedPath,
		},
	})
	if err != nil {
		t.Fatal(err)
	}

	if got, want := purged.Count(), 1; got != want {
		t.Errorf("wrong purged count %d; want %d", got, want)
	}
	if got, want := purged.Newest().Path, unwantedPath; got != want {
		t.Errorf("wrong purged path %s; want %s", got, want)
	}

	files, err := ioutil.ReadDir(tmpDir)
	if err != nil {
		t.Fatal(err)
	}

	gotFilenames := make([]string, len(files))
	for i, info := range files {
		gotFilenames[i] = info.Name()
	}
	wantFilenames := []string{"terraform-provider-test_v1.2.3_x3"}

	if !reflect.DeepEqual(gotFilenames, wantFilenames) {
		t.Errorf("wrong filenames after purge\ngot:  %#v\nwant: %#v", gotFilenames, wantFilenames)
	}
}

// Test fetching a provider's checksum file while verifying its signature.
func TestProviderChecksum(t *testing.T) {
	i := &ProviderInstaller{}

	// we only need the checksum, as getter is doing the actual file comparison.
	sha256sum, err := i.getProviderChecksum("template", "0.1.0")
	if err != nil {
		t.Fatal(err)
	}

	// get the expected checksum for our os/arch
	sumData, err := ioutil.ReadFile("testdata/terraform-provider-template_0.1.0_SHA256SUMS")
	if err != nil {
		t.Fatal(err)
	}

	expected := checksumForFile(sumData, i.providerFileName("template", "0.1.0"))

	if sha256sum != expected {
		t.Fatalf("expected: %s\ngot %s\n", sha256sum, expected)
	}
}

// Test fetching a provider's checksum file witha bad signature
func TestProviderChecksumBadSignature(t *testing.T) {
	i := &ProviderInstaller{}

	// we only need the checksum, as getter is doing the actual file comparison.
	sha256sum, err := i.getProviderChecksum("badsig", "0.1.0")
	if err == nil {
		t.Fatal("expcted error")
	}

	if !strings.Contains(err.Error(), "signature") {
		t.Fatal("expected signature error, got:", err)
	}

	if sha256sum != "" {
		t.Fatal("expected no checksum, got:", sha256sum)
	}
}

const versionList = `<!DOCTYPE html>
<html>
<body>
  <ul>
  <li>
    <a href="../">../</a>
  </li>
  <li>
    <a href="/terraform-provider-test/1.2.3/">terraform-provider-test_1.2.3</a>
  </li>
  <li>
    <a href="/terraform-provider-test/1.2.1/">terraform-provider-test_1.2.1</a>
  </li>
  <li>
    <a href="/terraform-provider-test/1.2.4/">terraform-provider-test_1.2.4</a>
  </li>
  </ul>
  <footer>
    Proudly fronted by <a href="https://fastly.com/?utm_source=hashicorp" target="_TOP">Fastly</a>
  </footer>
</body>
</html>
`


<|start_filename|>vendor/github.com/mitchellh/packer/helper/multistep/multistep.go<|end_filename|>
// multistep is a library for building up complex actions using individual,
// discrete steps.
package multistep

import "context"

// A StepAction determines the next step to take regarding multi-step actions.
type StepAction uint

const (
	ActionContinue StepAction = iota
	ActionHalt
)

// This is the key set in the state bag when using the basic runner to
// signal that the step sequence was cancelled.
const StateCancelled = "cancelled"

// This is the key set in the state bag when a step halted the sequence.
const StateHalted = "halted"

// Step is a single step that is part of a potentially large sequence
// of other steps, responsible for performing some specific action.
type Step interface {
	// Run is called to perform the action. The passed through context will be
	// cancelled when the runner is cancelled. The second parameter is a "state
	// bag" of untyped things. Please be very careful about type-checking the
	// items in this bag.
	//
	// The return value determines whether multi-step sequences continue
	// or should halt.
	Run(context.Context, StateBag) StepAction

	// Cleanup is called in reverse order of the steps that have run
	// and allow steps to clean up after themselves. Do not assume if this
	// ran that the entire multi-step sequence completed successfully. This
	// method can be ran in the face of errors and cancellations as well.
	//
	// The parameter is the same "state bag" as Run, and represents the
	// state at the latest possible time prior to calling Cleanup.
	Cleanup(StateBag)
}

// Runner is a thing that runs one or more steps.
type Runner interface {
	// Run runs the steps with the given initial state.
	Run(StateBag)

	// Cancel cancels a potentially running stack of steps.
	Cancel()
}


<|start_filename|>vendor/github.com/mitchellh/packer/helper/multistep/statebag_test.go<|end_filename|>
package multistep

import (
	"testing"
)

func TestBasicStateBag_ImplRunner(t *testing.T) {
	var raw interface{}
	raw = &BasicStateBag{}
	if _, ok := raw.(StateBag); !ok {
		t.Fatalf("must be a StateBag")
	}
}

func TestBasicStateBag(t *testing.T) {
	b := new(BasicStateBag)
	if b.Get("foo") != nil {
		t.Fatalf("bad: %#v", b.Get("foo"))
	}

	if _, ok := b.GetOk("foo"); ok {
		t.Fatal("should not have foo")
	}

	b.Put("foo", "bar")

	if b.Get("foo").(string) != "bar" {
		t.Fatalf("bad")
	}
}


<|start_filename|>vendor/github.com/hashicorp/go-getter/source_test.go<|end_filename|>
package getter

import (
	"testing"
)

func TestSourceDirSubdir(t *testing.T) {
	cases := []struct {
		Input    string
		Dir, Sub string
	}{
		{
			"hashicorp.com",
			"hashicorp.com", "",
		},
		{
			"hashicorp.com//foo",
			"hashicorp.com", "foo",
		},
		{
			"hashicorp.com//foo?bar=baz",
			"hashicorp.com?bar=baz", "foo",
		},
		{
			"file://foo//bar",
			"file://foo", "bar",
		},
	}

	for i, tc := range cases {
		adir, asub := SourceDirSubdir(tc.Input)
		if adir != tc.Dir {
			t.Fatalf("%d: bad dir: %#v", i, adir)
		}
		if asub != tc.Sub {
			t.Fatalf("%d: bad sub: %#v", i, asub)
		}
	}
}


<|start_filename|>vendor/github.com/hashicorp/terraform/communicator/remote/command.go<|end_filename|>
package remote

import (
	"io"
	"sync"
)

// Cmd represents a remote command being prepared or run.
type Cmd struct {
	// Command is the command to run remotely. This is executed as if
	// it were a shell command, so you are expected to do any shell escaping
	// necessary.
	Command string

	// Stdin specifies the process's standard input. If Stdin is
	// nil, the process reads from an empty bytes.Buffer.
	Stdin io.Reader

	// Stdout and Stderr represent the process's standard output and
	// error.
	//
	// If either is nil, it will be set to ioutil.Discard.
	Stdout io.Writer
	Stderr io.Writer

	// This will be set to true when the remote command has exited. It
	// shouldn't be set manually by the user, but there is no harm in
	// doing so.
	Exited bool

	// Once Exited is true, this will contain the exit code of the process.
	ExitStatus int

	// Internal fields
	exitCh chan struct{}

	// This thing is a mutex, lock when making modifications concurrently
	sync.Mutex
}

// SetExited is a helper for setting that this process is exited. This
// should be called by communicators who are running a remote command in
// order to set that the command is done.
func (r *Cmd) SetExited(status int) {
	r.Lock()
	defer r.Unlock()

	if r.exitCh == nil {
		r.exitCh = make(chan struct{})
	}

	r.Exited = true
	r.ExitStatus = status
	close(r.exitCh)
}

// Wait waits for the remote command to complete.
func (r *Cmd) Wait() {
	// Make sure our condition variable is initialized.
	r.Lock()
	if r.exitCh == nil {
		r.exitCh = make(chan struct{})
	}
	r.Unlock()

	<-r.exitCh
}


<|start_filename|>vendor/github.com/zclconf/go-cty/cty/path.go<|end_filename|>
package cty

import (
	"errors"
	"fmt"
)

// A Path is a sequence of operations to locate a nested value within a
// data structure.
//
// The empty Path represents the given item. Any PathSteps within represent
// taking a single step down into a data structure.
//
// Path has some convenience methods for gradually constructing a path,
// but callers can also feel free to just produce a slice of PathStep manually
// and convert to this type, which may be more appropriate in environments
// where memory pressure is a concern.
type Path []PathStep

// PathStep represents a single step down into a data structure, as part
// of a Path. PathStep is a closed interface, meaning that the only
// permitted implementations are those within this package.
type PathStep interface {
	pathStepSigil() pathStepImpl
	Apply(Value) (Value, error)
}

// embed pathImpl into a struct to declare it a PathStep implementation
type pathStepImpl struct{}

func (p pathStepImpl) pathStepSigil() pathStepImpl {
	return p
}

// Index returns a new Path that is the reciever with an IndexStep appended
// to the end.
//
// This is provided as a convenient way to construct paths, but each call
// will create garbage so it should not be used where memory pressure is a
// concern.
func (p Path) Index(v Value) Path {
	ret := make(Path, len(p)+1)
	copy(ret, p)
	ret[len(p)] = IndexStep{
		Key: v,
	}
	return ret
}

// GetAttr returns a new Path that is the reciever with a GetAttrStep appended
// to the end.
//
// This is provided as a convenient way to construct paths, but each call
// will create garbage so it should not be used where memory pressure is a
// concern.
func (p Path) GetAttr(name string) Path {
	ret := make(Path, len(p)+1)
	copy(ret, p)
	ret[len(p)] = GetAttrStep{
		Name: name,
	}
	return ret
}

// Apply applies each of the steps in turn to successive values starting with
// the given value, and returns the result. If any step returns an error,
// the whole operation returns an error.
func (p Path) Apply(val Value) (Value, error) {
	var err error
	for i, step := range p {
		val, err = step.Apply(val)
		if err != nil {
			return NilVal, fmt.Errorf("at step %d: %s", i, err)
		}
	}
	return val, nil
}

// LastStep applies the given path up to the last step and then returns
// the resulting value and the final step.
//
// This is useful when dealing with assignment operations, since in that
// case the *value* of the last step is not important (and may not, in fact,
// present at all) and we care only about its location.
//
// Since LastStep applies all steps except the last, it will return errors
// for those steps in the same way as Apply does.
//
// If the path has *no* steps then the returned PathStep will be nil,
// representing that any operation should be applied directly to the
// given value.
func (p Path) LastStep(val Value) (Value, PathStep, error) {
	var err error

	if len(p) == 0 {
		return val, nil, nil
	}

	journey := p[:len(p)-1]
	val, err = journey.Apply(val)
	if err != nil {
		return NilVal, nil, err
	}
	return val, p[len(p)-1], nil
}

// Copy makes a shallow copy of the receiver. Often when paths are passed to
// caller code they come with the constraint that they are valid only until
// the caller returns, due to how they are constructed internally. Callers
// can use Copy to conveniently produce a copy of the value that _they_ control
// the validity of.
func (p Path) Copy() Path {
	ret := make(Path, len(p))
	copy(ret, p)
	return ret
}

// IndexStep is a Step implementation representing applying the index operation
// to a value, which must be of either a list, map, or set type.
//
// When describing a path through a *type* rather than a concrete value,
// the Key may be an unknown value, indicating that the step applies to
// *any* key of the given type.
//
// When indexing into a set, the Key is actually the element being accessed
// itself, since in sets elements are their own identity.
type IndexStep struct {
	pathStepImpl
	Key Value
}

// Apply returns the value resulting from indexing the given value with
// our key value.
func (s IndexStep) Apply(val Value) (Value, error) {
	switch s.Key.Type() {
	case Number:
		if !val.Type().IsListType() {
			return NilVal, errors.New("not a list type")
		}
	case String:
		if !val.Type().IsMapType() {
			return NilVal, errors.New("not a map type")
		}
	default:
		return NilVal, errors.New("key value not number or string")
	}

	has := val.HasIndex(s.Key)
	if !has.IsKnown() {
		return UnknownVal(val.Type().ElementType()), nil
	}
	if !has.True() {
		return NilVal, errors.New("value does not have given index key")
	}

	return val.Index(s.Key), nil
}

// GetAttrStep is a Step implementation representing retrieving an attribute
// from a value, which must be of an object type.
type GetAttrStep struct {
	pathStepImpl
	Name string
}

// Apply returns the value of our named attribute from the given value, which
// must be of an object type that has a value of that name.
func (s GetAttrStep) Apply(val Value) (Value, error) {
	if !val.Type().IsObjectType() {
		return NilVal, errors.New("not an object type")
	}

	if !val.Type().HasAttribute(s.Name) {
		return NilVal, fmt.Errorf("object has no attribute %q", s.Name)
	}

	return val.GetAttr(s.Name), nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_config_config_rule.go<|end_filename|>
package aws

import (
	"bytes"
	"fmt"
	"log"
	"time"

	"github.com/hashicorp/terraform/helper/hashcode"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/configservice"
)

func resourceAwsConfigConfigRule() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsConfigConfigRulePut,
		Read:   resourceAwsConfigConfigRuleRead,
		Update: resourceAwsConfigConfigRulePut,
		Delete: resourceAwsConfigConfigRuleDelete,

		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"name": {
				Type:         schema.TypeString,
				Required:     true,
				ValidateFunc: validateMaxLength(64),
			},
			"rule_id": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"arn": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"description": {
				Type:         schema.TypeString,
				Optional:     true,
				ValidateFunc: validateMaxLength(256),
			},
			"input_parameters": {
				Type:         schema.TypeString,
				Optional:     true,
				ValidateFunc: validateJsonString,
			},
			"maximum_execution_frequency": {
				Type:         schema.TypeString,
				Optional:     true,
				ValidateFunc: validateConfigExecutionFrequency,
			},
			"scope": {
				Type:     schema.TypeList,
				MaxItems: 1,
				Optional: true,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"compliance_resource_id": {
							Type:         schema.TypeString,
							Optional:     true,
							ValidateFunc: validateMaxLength(256),
						},
						"compliance_resource_types": {
							Type:     schema.TypeSet,
							Optional: true,
							MaxItems: 100,
							Elem: &schema.Schema{
								Type:         schema.TypeString,
								ValidateFunc: validateMaxLength(256),
							},
							Set: schema.HashString,
						},
						"tag_key": {
							Type:         schema.TypeString,
							Optional:     true,
							ValidateFunc: validateMaxLength(128),
						},
						"tag_value": {
							Type:         schema.TypeString,
							Optional:     true,
							ValidateFunc: validateMaxLength(256),
						},
					},
				},
			},
			"source": {
				Type:     schema.TypeList,
				MaxItems: 1,
				Required: true,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"owner": {
							Type:         schema.TypeString,
							Required:     true,
							ValidateFunc: validateConfigRuleSourceOwner,
						},
						"source_detail": {
							Type:     schema.TypeSet,
							Set:      configRuleSourceDetailsHash,
							Optional: true,
							MaxItems: 25,
							Elem: &schema.Resource{
								Schema: map[string]*schema.Schema{
									"event_source": {
										Type:     schema.TypeString,
										Optional: true,
										Default:  "aws.config",
									},
									"maximum_execution_frequency": {
										Type:         schema.TypeString,
										Optional:     true,
										ValidateFunc: validateConfigExecutionFrequency,
									},
									"message_type": {
										Type:     schema.TypeString,
										Optional: true,
									},
								},
							},
						},
						"source_identifier": {
							Type:         schema.TypeString,
							Required:     true,
							ValidateFunc: validateMaxLength(256),
						},
					},
				},
			},
		},
	}
}

func resourceAwsConfigConfigRulePut(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).configconn

	name := d.Get("name").(string)
	ruleInput := configservice.ConfigRule{
		ConfigRuleName: aws.String(name),
		Source:         expandConfigRuleSource(d.Get("source").([]interface{})),
	}

	scopes := d.Get("scope").([]interface{})
	if len(scopes) > 0 {
		ruleInput.Scope = expandConfigRuleScope(scopes[0].(map[string]interface{}))
	}

	if v, ok := d.GetOk("description"); ok {
		ruleInput.Description = aws.String(v.(string))
	}
	if v, ok := d.GetOk("input_parameters"); ok {
		ruleInput.InputParameters = aws.String(v.(string))
	}
	if v, ok := d.GetOk("maximum_execution_frequency"); ok {
		ruleInput.MaximumExecutionFrequency = aws.String(v.(string))
	}

	input := configservice.PutConfigRuleInput{
		ConfigRule: &ruleInput,
	}
	log.Printf("[DEBUG] Creating AWSConfig config rule: %s", input)
	err := resource.Retry(2*time.Minute, func() *resource.RetryError {
		_, err := conn.PutConfigRule(&input)
		if err != nil {
			if awsErr, ok := err.(awserr.Error); ok {
				if awsErr.Code() == "InsufficientPermissionsException" {
					// IAM is eventually consistent
					return resource.RetryableError(err)
				}
			}

			return resource.NonRetryableError(fmt.Errorf("Failed to create AWSConfig rule: %s", err))
		}

		return nil
	})
	if err != nil {
		return err
	}

	d.SetId(name)

	log.Printf("[DEBUG] AWSConfig config rule %q created", name)

	return resourceAwsConfigConfigRuleRead(d, meta)
}

func resourceAwsConfigConfigRuleRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).configconn

	out, err := conn.DescribeConfigRules(&configservice.DescribeConfigRulesInput{
		ConfigRuleNames: []*string{aws.String(d.Id())},
	})
	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoSuchConfigRuleException" {
			log.Printf("[WARN] Config Rule %q is gone (NoSuchConfigRuleException)", d.Id())
			d.SetId("")
			return nil
		}
		return err
	}

	numberOfRules := len(out.ConfigRules)
	if numberOfRules < 1 {
		log.Printf("[WARN] Config Rule %q is gone (no rules found)", d.Id())
		d.SetId("")
		return nil
	}

	if numberOfRules > 1 {
		return fmt.Errorf("Expected exactly 1 Config Rule, received %d: %#v",
			numberOfRules, out.ConfigRules)
	}

	log.Printf("[DEBUG] AWS Config config rule received: %s", out)

	rule := out.ConfigRules[0]
	d.Set("arn", rule.ConfigRuleArn)
	d.Set("rule_id", rule.ConfigRuleId)
	d.Set("name", rule.ConfigRuleName)
	d.Set("description", rule.Description)
	d.Set("input_parameters", rule.InputParameters)
	d.Set("maximum_execution_frequency", rule.MaximumExecutionFrequency)

	if rule.Scope != nil {
		d.Set("scope", flattenConfigRuleScope(rule.Scope))
	}

	d.Set("source", flattenConfigRuleSource(rule.Source))

	return nil
}

func resourceAwsConfigConfigRuleDelete(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).configconn

	name := d.Get("name").(string)

	log.Printf("[DEBUG] Deleting AWS Config config rule %q", name)
	err := resource.Retry(2*time.Minute, func() *resource.RetryError {
		_, err := conn.DeleteConfigRule(&configservice.DeleteConfigRuleInput{
			ConfigRuleName: aws.String(name),
		})
		if err != nil {
			if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "ResourceInUseException" {
				return resource.RetryableError(err)
			}
			return resource.NonRetryableError(err)
		}
		return nil
	})
	if err != nil {
		return fmt.Errorf("Deleting Config Rule failed: %s", err)
	}

	conf := resource.StateChangeConf{
		Pending: []string{
			configservice.ConfigRuleStateActive,
			configservice.ConfigRuleStateDeleting,
			configservice.ConfigRuleStateDeletingResults,
			configservice.ConfigRuleStateEvaluating,
		},
		Target:  []string{""},
		Timeout: 5 * time.Minute,
		Refresh: func() (interface{}, string, error) {
			out, err := conn.DescribeConfigRules(&configservice.DescribeConfigRulesInput{
				ConfigRuleNames: []*string{aws.String(d.Id())},
			})
			if err != nil {
				if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoSuchConfigRuleException" {
					return 42, "", nil
				}
				return 42, "", fmt.Errorf("Failed to describe config rule %q: %s", d.Id(), err)
			}
			if len(out.ConfigRules) < 1 {
				return 42, "", nil
			}
			rule := out.ConfigRules[0]
			return out, *rule.ConfigRuleState, nil
		},
	}
	_, err = conf.WaitForState()
	if err != nil {
		return err
	}

	log.Printf("[DEBUG] AWS Config config rule %q deleted", name)

	d.SetId("")
	return nil
}

func configRuleSourceDetailsHash(v interface{}) int {
	var buf bytes.Buffer
	m := v.(map[string]interface{})
	if v, ok := m["message_type"]; ok {
		buf.WriteString(fmt.Sprintf("%s-", v.(string)))
	}
	if v, ok := m["event_source"]; ok {
		buf.WriteString(fmt.Sprintf("%s-", v.(string)))
	}
	if v, ok := m["maximum_execution_frequency"]; ok {
		buf.WriteString(fmt.Sprintf("%s-", v.(string)))
	}
	return hashcode.String(buf.String())
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/hashicorp/go-getter/get_http.go<|end_filename|>
package getter

import (
	"encoding/xml"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"strings"
)

// HttpGetter is a Getter implementation that will download from an HTTP
// endpoint.
//
// For file downloads, HTTP is used directly.
//
// The protocol for downloading a directory from an HTTP endpoing is as follows:
//
// An HTTP GET request is made to the URL with the additional GET parameter
// "terraform-get=1". This lets you handle that scenario specially if you
// wish. The response must be a 2xx.
//
// First, a header is looked for "X-Terraform-Get" which should contain
// a source URL to download.
//
// If the header is not present, then a meta tag is searched for named
// "terraform-get" and the content should be a source URL.
//
// The source URL, whether from the header or meta tag, must be a fully
// formed URL. The shorthand syntax of "github.com/foo/bar" or relative
// paths are not allowed.
type HttpGetter struct {
	// Netrc, if true, will lookup and use auth information found
	// in the user's netrc file if available.
	Netrc bool

	// Client is the http.Client to use for Get requests.
	// This defaults to a cleanhttp.DefaultClient if left unset.
	Client *http.Client
}

func (g *HttpGetter) ClientMode(u *url.URL) (ClientMode, error) {
	if strings.HasSuffix(u.Path, "/") {
		return ClientModeDir, nil
	}
	return ClientModeFile, nil
}

func (g *HttpGetter) Get(dst string, u *url.URL) error {
	// Copy the URL so we can modify it
	var newU url.URL = *u
	u = &newU

	if g.Netrc {
		// Add auth from netrc if we can
		if err := addAuthFromNetrc(u); err != nil {
			return err
		}
	}

	if g.Client == nil {
		g.Client = httpClient
	}

	// Add terraform-get to the parameter.
	q := u.Query()
	q.Add("terraform-get", "1")
	u.RawQuery = q.Encode()

	// Get the URL
	resp, err := g.Client.Get(u.String())
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
		return fmt.Errorf("bad response code: %d", resp.StatusCode)
	}

	// Extract the source URL
	var source string
	if v := resp.Header.Get("X-Terraform-Get"); v != "" {
		source = v
	} else {
		source, err = g.parseMeta(resp.Body)
		if err != nil {
			return err
		}
	}
	if source == "" {
		return fmt.Errorf("no source URL was returned")
	}

	// If there is a subdir component, then we download the root separately
	// into a temporary directory, then copy over the proper subdir.
	source, subDir := SourceDirSubdir(source)
	if subDir == "" {
		return Get(dst, source)
	}

	// We have a subdir, time to jump some hoops
	return g.getSubdir(dst, source, subDir)
}

func (g *HttpGetter) GetFile(dst string, u *url.URL) error {
	if g.Netrc {
		// Add auth from netrc if we can
		if err := addAuthFromNetrc(u); err != nil {
			return err
		}
	}

	if g.Client == nil {
		g.Client = httpClient
	}

	resp, err := g.Client.Get(u.String())
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		return fmt.Errorf("bad response code: %d", resp.StatusCode)
	}

	// Create all the parent directories
	if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil {
		return err
	}

	f, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer f.Close()

	_, err = io.Copy(f, resp.Body)
	return err
}

// getSubdir downloads the source into the destination, but with
// the proper subdir.
func (g *HttpGetter) getSubdir(dst, source, subDir string) error {
	// Create a temporary directory to store the full source
	td, err := ioutil.TempDir("", "tf")
	if err != nil {
		return err
	}
	defer os.RemoveAll(td)

	// We have to create a subdirectory that doesn't exist for the file
	// getter to work.
	td = filepath.Join(td, "data")

	// Download that into the given directory
	if err := Get(td, source); err != nil {
		return err
	}

	// Process any globbing
	sourcePath, err := SubdirGlob(td, subDir)
	if err != nil {
		return err
	}

	// Make sure the subdir path actually exists
	if _, err := os.Stat(sourcePath); err != nil {
		return fmt.Errorf(
			"Error downloading %s: %s", source, err)
	}

	// Copy the subdirectory into our actual destination.
	if err := os.RemoveAll(dst); err != nil {
		return err
	}

	// Make the final destination
	if err := os.MkdirAll(dst, 0755); err != nil {
		return err
	}

	return copyDir(dst, sourcePath, false)
}

// parseMeta looks for the first meta tag in the given reader that
// will give us the source URL.
func (g *HttpGetter) parseMeta(r io.Reader) (string, error) {
	d := xml.NewDecoder(r)
	d.CharsetReader = charsetReader
	d.Strict = false
	var err error
	var t xml.Token
	for {
		t, err = d.Token()
		if err != nil {
			if err == io.EOF {
				err = nil
			}
			return "", err
		}
		if e, ok := t.(xml.StartElement); ok && strings.EqualFold(e.Name.Local, "body") {
			return "", nil
		}
		if e, ok := t.(xml.EndElement); ok && strings.EqualFold(e.Name.Local, "head") {
			return "", nil
		}
		e, ok := t.(xml.StartElement)
		if !ok || !strings.EqualFold(e.Name.Local, "meta") {
			continue
		}
		if attrValue(e.Attr, "name") != "terraform-get" {
			continue
		}
		if f := attrValue(e.Attr, "content"); f != "" {
			return f, nil
		}
	}
}

// attrValue returns the attribute value for the case-insensitive key
// `name', or the empty string if nothing is found.
func attrValue(attrs []xml.Attr, name string) string {
	for _, a := range attrs {
		if strings.EqualFold(a.Name.Local, name) {
			return a.Value
		}
	}
	return ""
}

// charsetReader returns a reader for the given charset. Currently
// it only supports UTF-8 and ASCII. Otherwise, it returns a meaningful
// error which is printed by go get, so the user can find why the package
// wasn't downloaded if the encoding is not supported. Note that, in
// order to reduce potential errors, ASCII is treated as UTF-8 (i.e. characters
// greater than 0x7f are not rejected).
func charsetReader(charset string, input io.Reader) (io.Reader, error) {
	switch strings.ToLower(charset) {
	case "ascii":
		return input, nil
	default:
		return nil, fmt.Errorf("can't decode XML document using charset %q", charset)
	}
}


<|start_filename|>vendor/github.com/mitchellh/packer/builder/lxc/command.go<|end_filename|>
package lxc

import (
	"os/exec"
)

// CommandWrapper is a type that given a command, will possibly modify that
// command in-flight. This might return an error.
type CommandWrapper func(string) (string, error)

// ShellCommand takes a command string and returns an *exec.Cmd to execute
// it within the context of a shell (/bin/sh).
func ShellCommand(command string) *exec.Cmd {
	return exec.Command("/bin/sh", "-c", command)
}


<|start_filename|>vendor/github.com/mitchellh/packer/vendor/github.com/joyent/triton-go/compute/snapshots.go<|end_filename|>
//
// Copyright (c) 2018, Joyent, Inc. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

package compute

import (
	"context"
	"encoding/json"
	"net/http"
	"path"
	"time"

	"github.com/joyent/triton-go/client"
	"github.com/pkg/errors"
)

type SnapshotsClient struct {
	client *client.Client
}

type Snapshot struct {
	Name    string
	State   string
	Created time.Time
	Updated time.Time
}

type ListSnapshotsInput struct {
	MachineID string
}

func (c *SnapshotsClient) List(ctx context.Context, input *ListSnapshotsInput) ([]*Snapshot, error) {
	fullPath := path.Join("/", c.client.AccountName, "machines", input.MachineID, "snapshots")
	reqInputs := client.RequestInput{
		Method: http.MethodGet,
		Path:   fullPath,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to list snapshots")
	}

	var result []*Snapshot
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode list snapshots response")
	}

	return result, nil
}

type GetSnapshotInput struct {
	MachineID string
	Name      string
}

func (c *SnapshotsClient) Get(ctx context.Context, input *GetSnapshotInput) (*Snapshot, error) {
	fullPath := path.Join("/", c.client.AccountName, "machines", input.MachineID, "snapshots", input.Name)
	reqInputs := client.RequestInput{
		Method: http.MethodGet,
		Path:   fullPath,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to get snapshot")
	}

	var result *Snapshot
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode get snapshot response")
	}

	return result, nil
}

type DeleteSnapshotInput struct {
	MachineID string
	Name      string
}

func (c *SnapshotsClient) Delete(ctx context.Context, input *DeleteSnapshotInput) error {
	fullPath := path.Join("/", c.client.AccountName, "machines", input.MachineID, "snapshots", input.Name)
	reqInputs := client.RequestInput{
		Method: http.MethodDelete,
		Path:   fullPath,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return errors.Wrap(err, "unable to delete snapshot")
	}

	return nil
}

type StartMachineFromSnapshotInput struct {
	MachineID string
	Name      string
}

func (c *SnapshotsClient) StartMachine(ctx context.Context, input *StartMachineFromSnapshotInput) error {
	fullPath := path.Join("/", c.client.AccountName, "machines", input.MachineID, "snapshots", input.Name)
	reqInputs := client.RequestInput{
		Method: http.MethodPost,
		Path:   fullPath,
	}
	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return errors.Wrap(err, "unable to start machine")
	}

	return nil
}

type CreateSnapshotInput struct {
	MachineID string
	Name      string
}

func (c *SnapshotsClient) Create(ctx context.Context, input *CreateSnapshotInput) (*Snapshot, error) {
	fullPath := path.Join("/", c.client.AccountName, "machines", input.MachineID, "snapshots")

	data := make(map[string]interface{})
	data["name"] = input.Name

	reqInputs := client.RequestInput{
		Method: http.MethodPost,
		Path:   fullPath,
		Body:   data,
	}

	respReader, err := c.client.ExecuteRequest(ctx, reqInputs)
	if respReader != nil {
		defer respReader.Close()
	}
	if err != nil {
		return nil, errors.Wrap(err, "unable to create snapshot")
	}

	var result *Snapshot
	decoder := json.NewDecoder(respReader)
	if err = decoder.Decode(&result); err != nil {
		return nil, errors.Wrap(err, "unable to decode create snapshot response")
	}

	return result, nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/aws/aws-sdk-go/service/elbv2/api.go<|end_filename|>
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.

package elbv2

import (
	"fmt"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awsutil"
	"github.com/aws/aws-sdk-go/aws/request"
)

const opAddListenerCertificates = "AddListenerCertificates"

// AddListenerCertificatesRequest generates a "aws/request.Request" representing the
// client's request for the AddListenerCertificates operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See AddListenerCertificates for more information on using the AddListenerCertificates
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the AddListenerCertificatesRequest method.
//    req, resp := client.AddListenerCertificatesRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/AddListenerCertificates
func (c *ELBV2) AddListenerCertificatesRequest(input *AddListenerCertificatesInput) (req *request.Request, output *AddListenerCertificatesOutput) {
	op := &request.Operation{
		Name:       opAddListenerCertificates,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &AddListenerCertificatesInput{}
	}

	output = &AddListenerCertificatesOutput{}
	req = c.newRequest(op, input, output)
	return
}

// AddListenerCertificates API operation for Elastic Load Balancing.
//
// Adds the specified certificate to the specified secure listener.
//
// If the certificate was already added, the call is successful but the certificate
// is not added again.
//
// To list the certificates for your listener, use DescribeListenerCertificates.
// To remove certificates from your listener, use RemoveListenerCertificates.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation AddListenerCertificates for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeListenerNotFoundException "ListenerNotFound"
//   The specified listener does not exist.
//
//   * ErrCodeTooManyCertificatesException "TooManyCertificates"
//   You've reached the limit on the number of certificates per load balancer.
//
//   * ErrCodeCertificateNotFoundException "CertificateNotFound"
//   The specified certificate does not exist.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/AddListenerCertificates
func (c *ELBV2) AddListenerCertificates(input *AddListenerCertificatesInput) (*AddListenerCertificatesOutput, error) {
	req, out := c.AddListenerCertificatesRequest(input)
	return out, req.Send()
}

// AddListenerCertificatesWithContext is the same as AddListenerCertificates with the addition of
// the ability to pass a context and additional request options.
//
// See AddListenerCertificates for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) AddListenerCertificatesWithContext(ctx aws.Context, input *AddListenerCertificatesInput, opts ...request.Option) (*AddListenerCertificatesOutput, error) {
	req, out := c.AddListenerCertificatesRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opAddTags = "AddTags"

// AddTagsRequest generates a "aws/request.Request" representing the
// client's request for the AddTags operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See AddTags for more information on using the AddTags
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the AddTagsRequest method.
//    req, resp := client.AddTagsRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/AddTags
func (c *ELBV2) AddTagsRequest(input *AddTagsInput) (req *request.Request, output *AddTagsOutput) {
	op := &request.Operation{
		Name:       opAddTags,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &AddTagsInput{}
	}

	output = &AddTagsOutput{}
	req = c.newRequest(op, input, output)
	return
}

// AddTags API operation for Elastic Load Balancing.
//
// Adds the specified tags to the specified Elastic Load Balancing resource.
// You can tag your Application Load Balancers, Network Load Balancers, and
// your target groups.
//
// Each tag consists of a key and an optional value. If a resource already has
// a tag with the same key, AddTags updates its value.
//
// To list the current tags for your resources, use DescribeTags. To remove
// tags from your resources, use RemoveTags.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation AddTags for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeDuplicateTagKeysException "DuplicateTagKeys"
//   A tag key was specified more than once.
//
//   * ErrCodeTooManyTagsException "TooManyTags"
//   You've reached the limit on the number of tags per load balancer.
//
//   * ErrCodeLoadBalancerNotFoundException "LoadBalancerNotFound"
//   The specified load balancer does not exist.
//
//   * ErrCodeTargetGroupNotFoundException "TargetGroupNotFound"
//   The specified target group does not exist.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/AddTags
func (c *ELBV2) AddTags(input *AddTagsInput) (*AddTagsOutput, error) {
	req, out := c.AddTagsRequest(input)
	return out, req.Send()
}

// AddTagsWithContext is the same as AddTags with the addition of
// the ability to pass a context and additional request options.
//
// See AddTags for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) AddTagsWithContext(ctx aws.Context, input *AddTagsInput, opts ...request.Option) (*AddTagsOutput, error) {
	req, out := c.AddTagsRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opCreateListener = "CreateListener"

// CreateListenerRequest generates a "aws/request.Request" representing the
// client's request for the CreateListener operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See CreateListener for more information on using the CreateListener
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the CreateListenerRequest method.
//    req, resp := client.CreateListenerRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/CreateListener
func (c *ELBV2) CreateListenerRequest(input *CreateListenerInput) (req *request.Request, output *CreateListenerOutput) {
	op := &request.Operation{
		Name:       opCreateListener,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &CreateListenerInput{}
	}

	output = &CreateListenerOutput{}
	req = c.newRequest(op, input, output)
	return
}

// CreateListener API operation for Elastic Load Balancing.
//
// Creates a listener for the specified Application Load Balancer or Network
// Load Balancer.
//
// To update a listener, use ModifyListener. When you are finished with a listener,
// you can delete it using DeleteListener. If you are finished with both the
// listener and the load balancer, you can delete them both using DeleteLoadBalancer.
//
// This operation is idempotent, which means that it completes at most one time.
// If you attempt to create multiple listeners with the same settings, each
// call succeeds.
//
// For more information, see Listeners for Your Application Load Balancers (http://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-listeners.html)
// in the Application Load Balancers Guide and Listeners for Your Network Load
// Balancers (http://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-listeners.html)
// in the Network Load Balancers Guide.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation CreateListener for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeDuplicateListenerException "DuplicateListener"
//   A listener with the specified port already exists.
//
//   * ErrCodeTooManyListenersException "TooManyListeners"
//   You've reached the limit on the number of listeners per load balancer.
//
//   * ErrCodeTooManyCertificatesException "TooManyCertificates"
//   You've reached the limit on the number of certificates per load balancer.
//
//   * ErrCodeLoadBalancerNotFoundException "LoadBalancerNotFound"
//   The specified load balancer does not exist.
//
//   * ErrCodeTargetGroupNotFoundException "TargetGroupNotFound"
//   The specified target group does not exist.
//
//   * ErrCodeTargetGroupAssociationLimitException "TargetGroupAssociationLimit"
//   You've reached the limit on the number of load balancers per target group.
//
//   * ErrCodeInvalidConfigurationRequestException "InvalidConfigurationRequest"
//   The requested configuration is not valid.
//
//   * ErrCodeIncompatibleProtocolsException "IncompatibleProtocols"
//   The specified configuration is not valid with this protocol.
//
//   * ErrCodeSSLPolicyNotFoundException "SSLPolicyNotFound"
//   The specified SSL policy does not exist.
//
//   * ErrCodeCertificateNotFoundException "CertificateNotFound"
//   The specified certificate does not exist.
//
//   * ErrCodeUnsupportedProtocolException "UnsupportedProtocol"
//   The specified protocol is not supported.
//
//   * ErrCodeTooManyRegistrationsForTargetIdException "TooManyRegistrationsForTargetId"
//   You've reached the limit on the number of times a target can be registered
//   with a load balancer.
//
//   * ErrCodeTooManyTargetsException "TooManyTargets"
//   You've reached the limit on the number of targets.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/CreateListener
func (c *ELBV2) CreateListener(input *CreateListenerInput) (*CreateListenerOutput, error) {
	req, out := c.CreateListenerRequest(input)
	return out, req.Send()
}

// CreateListenerWithContext is the same as CreateListener with the addition of
// the ability to pass a context and additional request options.
//
// See CreateListener for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) CreateListenerWithContext(ctx aws.Context, input *CreateListenerInput, opts ...request.Option) (*CreateListenerOutput, error) {
	req, out := c.CreateListenerRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opCreateLoadBalancer = "CreateLoadBalancer"

// CreateLoadBalancerRequest generates a "aws/request.Request" representing the
// client's request for the CreateLoadBalancer operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See CreateLoadBalancer for more information on using the CreateLoadBalancer
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the CreateLoadBalancerRequest method.
//    req, resp := client.CreateLoadBalancerRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/CreateLoadBalancer
func (c *ELBV2) CreateLoadBalancerRequest(input *CreateLoadBalancerInput) (req *request.Request, output *CreateLoadBalancerOutput) {
	op := &request.Operation{
		Name:       opCreateLoadBalancer,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &CreateLoadBalancerInput{}
	}

	output = &CreateLoadBalancerOutput{}
	req = c.newRequest(op, input, output)
	return
}

// CreateLoadBalancer API operation for Elastic Load Balancing.
//
// Creates an Application Load Balancer or a Network Load Balancer.
//
// When you create a load balancer, you can specify security groups, subnets,
// IP address type, and tags. Otherwise, you could do so later using SetSecurityGroups,
// SetSubnets, SetIpAddressType, and AddTags.
//
// To create listeners for your load balancer, use CreateListener. To describe
// your current load balancers, see DescribeLoadBalancers. When you are finished
// with a load balancer, you can delete it using DeleteLoadBalancer.
//
// For limit information, see Limits for Your Application Load Balancer (http://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-limits.html)
// in the Application Load Balancers Guide and Limits for Your Network Load
// Balancer (http://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-limits.html)
// in the Network Load Balancers Guide.
//
// This operation is idempotent, which means that it completes at most one time.
// If you attempt to create multiple load balancers with the same settings,
// each call succeeds.
//
// For more information, see Application Load Balancers (http://docs.aws.amazon.com/elasticloadbalancing/latest/application/application-load-balancers.html)
// in the Application Load Balancers Guide and Network Load Balancers (http://docs.aws.amazon.com/elasticloadbalancing/latest/network/network-load-balancers.html)
// in the Network Load Balancers Guide.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation CreateLoadBalancer for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeDuplicateLoadBalancerNameException "DuplicateLoadBalancerName"
//   A load balancer with the specified name already exists.
//
//   * ErrCodeTooManyLoadBalancersException "TooManyLoadBalancers"
//   You've reached the limit on the number of load balancers for your AWS account.
//
//   * ErrCodeInvalidConfigurationRequestException "InvalidConfigurationRequest"
//   The requested configuration is not valid.
//
//   * ErrCodeSubnetNotFoundException "SubnetNotFound"
//   The specified subnet does not exist.
//
//   * ErrCodeInvalidSubnetException "InvalidSubnet"
//   The specified subnet is out of available addresses.
//
//   * ErrCodeInvalidSecurityGroupException "InvalidSecurityGroup"
//   The specified security group does not exist.
//
//   * ErrCodeInvalidSchemeException "InvalidScheme"
//   The requested scheme is not valid.
//
//   * ErrCodeTooManyTagsException "TooManyTags"
//   You've reached the limit on the number of tags per load balancer.
//
//   * ErrCodeDuplicateTagKeysException "DuplicateTagKeys"
//   A tag key was specified more than once.
//
//   * ErrCodeResourceInUseException "ResourceInUse"
//   A specified resource is in use.
//
//   * ErrCodeAllocationIdNotFoundException "AllocationIdNotFound"
//   The specified allocation ID does not exist.
//
//   * ErrCodeAvailabilityZoneNotSupportedException "AvailabilityZoneNotSupported"
//   The specified Availability Zone is not supported.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/CreateLoadBalancer
func (c *ELBV2) CreateLoadBalancer(input *CreateLoadBalancerInput) (*CreateLoadBalancerOutput, error) {
	req, out := c.CreateLoadBalancerRequest(input)
	return out, req.Send()
}

// CreateLoadBalancerWithContext is the same as CreateLoadBalancer with the addition of
// the ability to pass a context and additional request options.
//
// See CreateLoadBalancer for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) CreateLoadBalancerWithContext(ctx aws.Context, input *CreateLoadBalancerInput, opts ...request.Option) (*CreateLoadBalancerOutput, error) {
	req, out := c.CreateLoadBalancerRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opCreateRule = "CreateRule"

// CreateRuleRequest generates a "aws/request.Request" representing the
// client's request for the CreateRule operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See CreateRule for more information on using the CreateRule
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the CreateRuleRequest method.
//    req, resp := client.CreateRuleRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/CreateRule
func (c *ELBV2) CreateRuleRequest(input *CreateRuleInput) (req *request.Request, output *CreateRuleOutput) {
	op := &request.Operation{
		Name:       opCreateRule,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &CreateRuleInput{}
	}

	output = &CreateRuleOutput{}
	req = c.newRequest(op, input, output)
	return
}

// CreateRule API operation for Elastic Load Balancing.
//
// Creates a rule for the specified listener. The listener must be associated
// with an Application Load Balancer.
//
// Rules are evaluated in priority order, from the lowest value to the highest
// value. When the condition for a rule is met, the specified action is taken.
// If no conditions are met, the action for the default rule is taken. For more
// information, see Listener Rules (http://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-listeners.html#listener-rules)
// in the Application Load Balancers Guide.
//
// To view your current rules, use DescribeRules. To update a rule, use ModifyRule.
// To set the priorities of your rules, use SetRulePriorities. To delete a rule,
// use DeleteRule.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation CreateRule for usage and error information.
//
// Returned Error Codes:
//   * ErrCodePriorityInUseException "PriorityInUse"
//   The specified priority is in use.
//
//   * ErrCodeTooManyTargetGroupsException "TooManyTargetGroups"
//   You've reached the limit on the number of target groups for your AWS account.
//
//   * ErrCodeTooManyRulesException "TooManyRules"
//   You've reached the limit on the number of rules per load balancer.
//
//   * ErrCodeTargetGroupAssociationLimitException "TargetGroupAssociationLimit"
//   You've reached the limit on the number of load balancers per target group.
//
//   * ErrCodeIncompatibleProtocolsException "IncompatibleProtocols"
//   The specified configuration is not valid with this protocol.
//
//   * ErrCodeListenerNotFoundException "ListenerNotFound"
//   The specified listener does not exist.
//
//   * ErrCodeTargetGroupNotFoundException "TargetGroupNotFound"
//   The specified target group does not exist.
//
//   * ErrCodeInvalidConfigurationRequestException "InvalidConfigurationRequest"
//   The requested configuration is not valid.
//
//   * ErrCodeTooManyRegistrationsForTargetIdException "TooManyRegistrationsForTargetId"
//   You've reached the limit on the number of times a target can be registered
//   with a load balancer.
//
//   * ErrCodeTooManyTargetsException "TooManyTargets"
//   You've reached the limit on the number of targets.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/CreateRule
func (c *ELBV2) CreateRule(input *CreateRuleInput) (*CreateRuleOutput, error) {
	req, out := c.CreateRuleRequest(input)
	return out, req.Send()
}

// CreateRuleWithContext is the same as CreateRule with the addition of
// the ability to pass a context and additional request options.
//
// See CreateRule for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) CreateRuleWithContext(ctx aws.Context, input *CreateRuleInput, opts ...request.Option) (*CreateRuleOutput, error) {
	req, out := c.CreateRuleRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opCreateTargetGroup = "CreateTargetGroup"

// CreateTargetGroupRequest generates a "aws/request.Request" representing the
// client's request for the CreateTargetGroup operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See CreateTargetGroup for more information on using the CreateTargetGroup
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the CreateTargetGroupRequest method.
//    req, resp := client.CreateTargetGroupRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/CreateTargetGroup
func (c *ELBV2) CreateTargetGroupRequest(input *CreateTargetGroupInput) (req *request.Request, output *CreateTargetGroupOutput) {
	op := &request.Operation{
		Name:       opCreateTargetGroup,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &CreateTargetGroupInput{}
	}

	output = &CreateTargetGroupOutput{}
	req = c.newRequest(op, input, output)
	return
}

// CreateTargetGroup API operation for Elastic Load Balancing.
//
// Creates a target group.
//
// To register targets with the target group, use RegisterTargets. To update
// the health check settings for the target group, use ModifyTargetGroup. To
// monitor the health of targets in the target group, use DescribeTargetHealth.
//
// To route traffic to the targets in a target group, specify the target group
// in an action using CreateListener or CreateRule.
//
// To delete a target group, use DeleteTargetGroup.
//
// This operation is idempotent, which means that it completes at most one time.
// If you attempt to create multiple target groups with the same settings, each
// call succeeds.
//
// For more information, see Target Groups for Your Application Load Balancers
// (http://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-target-groups.html)
// in the Application Load Balancers Guide or Target Groups for Your Network
// Load Balancers (http://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-target-groups.html)
// in the Network Load Balancers Guide.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation CreateTargetGroup for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeDuplicateTargetGroupNameException "DuplicateTargetGroupName"
//   A target group with the specified name already exists.
//
//   * ErrCodeTooManyTargetGroupsException "TooManyTargetGroups"
//   You've reached the limit on the number of target groups for your AWS account.
//
//   * ErrCodeInvalidConfigurationRequestException "InvalidConfigurationRequest"
//   The requested configuration is not valid.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/CreateTargetGroup
func (c *ELBV2) CreateTargetGroup(input *CreateTargetGroupInput) (*CreateTargetGroupOutput, error) {
	req, out := c.CreateTargetGroupRequest(input)
	return out, req.Send()
}

// CreateTargetGroupWithContext is the same as CreateTargetGroup with the addition of
// the ability to pass a context and additional request options.
//
// See CreateTargetGroup for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) CreateTargetGroupWithContext(ctx aws.Context, input *CreateTargetGroupInput, opts ...request.Option) (*CreateTargetGroupOutput, error) {
	req, out := c.CreateTargetGroupRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opDeleteListener = "DeleteListener"

// DeleteListenerRequest generates a "aws/request.Request" representing the
// client's request for the DeleteListener operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeleteListener for more information on using the DeleteListener
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the DeleteListenerRequest method.
//    req, resp := client.DeleteListenerRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeleteListener
func (c *ELBV2) DeleteListenerRequest(input *DeleteListenerInput) (req *request.Request, output *DeleteListenerOutput) {
	op := &request.Operation{
		Name:       opDeleteListener,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &DeleteListenerInput{}
	}

	output = &DeleteListenerOutput{}
	req = c.newRequest(op, input, output)
	return
}

// DeleteListener API operation for Elastic Load Balancing.
//
// Deletes the specified listener.
//
// Alternatively, your listener is deleted when you delete the load balancer
// it is attached to using DeleteLoadBalancer.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation DeleteListener for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeListenerNotFoundException "ListenerNotFound"
//   The specified listener does not exist.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeleteListener
func (c *ELBV2) DeleteListener(input *DeleteListenerInput) (*DeleteListenerOutput, error) {
	req, out := c.DeleteListenerRequest(input)
	return out, req.Send()
}

// DeleteListenerWithContext is the same as DeleteListener with the addition of
// the ability to pass a context and additional request options.
//
// See DeleteListener for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) DeleteListenerWithContext(ctx aws.Context, input *DeleteListenerInput, opts ...request.Option) (*DeleteListenerOutput, error) {
	req, out := c.DeleteListenerRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opDeleteLoadBalancer = "DeleteLoadBalancer"

// DeleteLoadBalancerRequest generates a "aws/request.Request" representing the
// client's request for the DeleteLoadBalancer operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeleteLoadBalancer for more information on using the DeleteLoadBalancer
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the DeleteLoadBalancerRequest method.
//    req, resp := client.DeleteLoadBalancerRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeleteLoadBalancer
func (c *ELBV2) DeleteLoadBalancerRequest(input *DeleteLoadBalancerInput) (req *request.Request, output *DeleteLoadBalancerOutput) {
	op := &request.Operation{
		Name:       opDeleteLoadBalancer,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &DeleteLoadBalancerInput{}
	}

	output = &DeleteLoadBalancerOutput{}
	req = c.newRequest(op, input, output)
	return
}

// DeleteLoadBalancer API operation for Elastic Load Balancing.
//
// Deletes the specified Application Load Balancer or Network Load Balancer
// and its attached listeners.
//
// You can't delete a load balancer if deletion protection is enabled. If the
// load balancer does not exist or has already been deleted, the call succeeds.
//
// Deleting a load balancer does not affect its registered targets. For example,
// your EC2 instances continue to run and are still registered to their target
// groups. If you no longer need these EC2 instances, you can stop or terminate
// them.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation DeleteLoadBalancer for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeLoadBalancerNotFoundException "LoadBalancerNotFound"
//   The specified load balancer does not exist.
//
//   * ErrCodeOperationNotPermittedException "OperationNotPermitted"
//   This operation is not allowed.
//
//   * ErrCodeResourceInUseException "ResourceInUse"
//   A specified resource is in use.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeleteLoadBalancer
func (c *ELBV2) DeleteLoadBalancer(input *DeleteLoadBalancerInput) (*DeleteLoadBalancerOutput, error) {
	req, out := c.DeleteLoadBalancerRequest(input)
	return out, req.Send()
}

// DeleteLoadBalancerWithContext is the same as DeleteLoadBalancer with the addition of
// the ability to pass a context and additional request options.
//
// See DeleteLoadBalancer for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) DeleteLoadBalancerWithContext(ctx aws.Context, input *DeleteLoadBalancerInput, opts ...request.Option) (*DeleteLoadBalancerOutput, error) {
	req, out := c.DeleteLoadBalancerRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opDeleteRule = "DeleteRule"

// DeleteRuleRequest generates a "aws/request.Request" representing the
// client's request for the DeleteRule operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeleteRule for more information on using the DeleteRule
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the DeleteRuleRequest method.
//    req, resp := client.DeleteRuleRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeleteRule
func (c *ELBV2) DeleteRuleRequest(input *DeleteRuleInput) (req *request.Request, output *DeleteRuleOutput) {
	op := &request.Operation{
		Name:       opDeleteRule,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &DeleteRuleInput{}
	}

	output = &DeleteRuleOutput{}
	req = c.newRequest(op, input, output)
	return
}

// DeleteRule API operation for Elastic Load Balancing.
//
// Deletes the specified rule.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation DeleteRule for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeRuleNotFoundException "RuleNotFound"
//   The specified rule does not exist.
//
//   * ErrCodeOperationNotPermittedException "OperationNotPermitted"
//   This operation is not allowed.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeleteRule
func (c *ELBV2) DeleteRule(input *DeleteRuleInput) (*DeleteRuleOutput, error) {
	req, out := c.DeleteRuleRequest(input)
	return out, req.Send()
}

// DeleteRuleWithContext is the same as DeleteRule with the addition of
// the ability to pass a context and additional request options.
//
// See DeleteRule for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) DeleteRuleWithContext(ctx aws.Context, input *DeleteRuleInput, opts ...request.Option) (*DeleteRuleOutput, error) {
	req, out := c.DeleteRuleRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opDeleteTargetGroup = "DeleteTargetGroup"

// DeleteTargetGroupRequest generates a "aws/request.Request" representing the
// client's request for the DeleteTargetGroup operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeleteTargetGroup for more information on using the DeleteTargetGroup
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the DeleteTargetGroupRequest method.
//    req, resp := client.DeleteTargetGroupRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeleteTargetGroup
func (c *ELBV2) DeleteTargetGroupRequest(input *DeleteTargetGroupInput) (req *request.Request, output *DeleteTargetGroupOutput) {
	op := &request.Operation{
		Name:       opDeleteTargetGroup,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &DeleteTargetGroupInput{}
	}

	output = &DeleteTargetGroupOutput{}
	req = c.newRequest(op, input, output)
	return
}

// DeleteTargetGroup API operation for Elastic Load Balancing.
//
// Deletes the specified target group.
//
// You can delete a target group if it is not referenced by any actions. Deleting
// a target group also deletes any associated health checks.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation DeleteTargetGroup for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeResourceInUseException "ResourceInUse"
//   A specified resource is in use.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeleteTargetGroup
func (c *ELBV2) DeleteTargetGroup(input *DeleteTargetGroupInput) (*DeleteTargetGroupOutput, error) {
	req, out := c.DeleteTargetGroupRequest(input)
	return out, req.Send()
}

// DeleteTargetGroupWithContext is the same as DeleteTargetGroup with the addition of
// the ability to pass a context and additional request options.
//
// See DeleteTargetGroup for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) DeleteTargetGroupWithContext(ctx aws.Context, input *DeleteTargetGroupInput, opts ...request.Option) (*DeleteTargetGroupOutput, error) {
	req, out := c.DeleteTargetGroupRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opDeregisterTargets = "DeregisterTargets"

// DeregisterTargetsRequest generates a "aws/request.Request" representing the
// client's request for the DeregisterTargets operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DeregisterTargets for more information on using the DeregisterTargets
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the DeregisterTargetsRequest method.
//    req, resp := client.DeregisterTargetsRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeregisterTargets
func (c *ELBV2) DeregisterTargetsRequest(input *DeregisterTargetsInput) (req *request.Request, output *DeregisterTargetsOutput) {
	op := &request.Operation{
		Name:       opDeregisterTargets,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &DeregisterTargetsInput{}
	}

	output = &DeregisterTargetsOutput{}
	req = c.newRequest(op, input, output)
	return
}

// DeregisterTargets API operation for Elastic Load Balancing.
//
// Deregisters the specified targets from the specified target group. After
// the targets are deregistered, they no longer receive traffic from the load
// balancer.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation DeregisterTargets for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeTargetGroupNotFoundException "TargetGroupNotFound"
//   The specified target group does not exist.
//
//   * ErrCodeInvalidTargetException "InvalidTarget"
//   The specified target does not exist, is not in the same VPC as the target
//   group, or has an unsupported instance type.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeregisterTargets
func (c *ELBV2) DeregisterTargets(input *DeregisterTargetsInput) (*DeregisterTargetsOutput, error) {
	req, out := c.DeregisterTargetsRequest(input)
	return out, req.Send()
}

// DeregisterTargetsWithContext is the same as DeregisterTargets with the addition of
// the ability to pass a context and additional request options.
//
// See DeregisterTargets for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) DeregisterTargetsWithContext(ctx aws.Context, input *DeregisterTargetsInput, opts ...request.Option) (*DeregisterTargetsOutput, error) {
	req, out := c.DeregisterTargetsRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opDescribeAccountLimits = "DescribeAccountLimits"

// DescribeAccountLimitsRequest generates a "aws/request.Request" representing the
// client's request for the DescribeAccountLimits operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DescribeAccountLimits for more information on using the DescribeAccountLimits
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the DescribeAccountLimitsRequest method.
//    req, resp := client.DescribeAccountLimitsRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeAccountLimits
func (c *ELBV2) DescribeAccountLimitsRequest(input *DescribeAccountLimitsInput) (req *request.Request, output *DescribeAccountLimitsOutput) {
	op := &request.Operation{
		Name:       opDescribeAccountLimits,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &DescribeAccountLimitsInput{}
	}

	output = &DescribeAccountLimitsOutput{}
	req = c.newRequest(op, input, output)
	return
}

// DescribeAccountLimits API operation for Elastic Load Balancing.
//
// Describes the current Elastic Load Balancing resource limits for your AWS
// account.
//
// For more information, see Limits for Your Application Load Balancers (http://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-limits.html)
// in the Application Load Balancer Guide or Limits for Your Network Load Balancers
// (http://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-limits.html)
// in the Network Load Balancers Guide.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation DescribeAccountLimits for usage and error information.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeAccountLimits
func (c *ELBV2) DescribeAccountLimits(input *DescribeAccountLimitsInput) (*DescribeAccountLimitsOutput, error) {
	req, out := c.DescribeAccountLimitsRequest(input)
	return out, req.Send()
}

// DescribeAccountLimitsWithContext is the same as DescribeAccountLimits with the addition of
// the ability to pass a context and additional request options.
//
// See DescribeAccountLimits for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) DescribeAccountLimitsWithContext(ctx aws.Context, input *DescribeAccountLimitsInput, opts ...request.Option) (*DescribeAccountLimitsOutput, error) {
	req, out := c.DescribeAccountLimitsRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opDescribeListenerCertificates = "DescribeListenerCertificates"

// DescribeListenerCertificatesRequest generates a "aws/request.Request" representing the
// client's request for the DescribeListenerCertificates operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DescribeListenerCertificates for more information on using the DescribeListenerCertificates
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the DescribeListenerCertificatesRequest method.
//    req, resp := client.DescribeListenerCertificatesRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeListenerCertificates
func (c *ELBV2) DescribeListenerCertificatesRequest(input *DescribeListenerCertificatesInput) (req *request.Request, output *DescribeListenerCertificatesOutput) {
	op := &request.Operation{
		Name:       opDescribeListenerCertificates,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &DescribeListenerCertificatesInput{}
	}

	output = &DescribeListenerCertificatesOutput{}
	req = c.newRequest(op, input, output)
	return
}

// DescribeListenerCertificates API operation for Elastic Load Balancing.
//
// Describes the certificates for the specified secure listener.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation DescribeListenerCertificates for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeListenerNotFoundException "ListenerNotFound"
//   The specified listener does not exist.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeListenerCertificates
func (c *ELBV2) DescribeListenerCertificates(input *DescribeListenerCertificatesInput) (*DescribeListenerCertificatesOutput, error) {
	req, out := c.DescribeListenerCertificatesRequest(input)
	return out, req.Send()
}

// DescribeListenerCertificatesWithContext is the same as DescribeListenerCertificates with the addition of
// the ability to pass a context and additional request options.
//
// See DescribeListenerCertificates for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) DescribeListenerCertificatesWithContext(ctx aws.Context, input *DescribeListenerCertificatesInput, opts ...request.Option) (*DescribeListenerCertificatesOutput, error) {
	req, out := c.DescribeListenerCertificatesRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opDescribeListeners = "DescribeListeners"

// DescribeListenersRequest generates a "aws/request.Request" representing the
// client's request for the DescribeListeners operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DescribeListeners for more information on using the DescribeListeners
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the DescribeListenersRequest method.
//    req, resp := client.DescribeListenersRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeListeners
func (c *ELBV2) DescribeListenersRequest(input *DescribeListenersInput) (req *request.Request, output *DescribeListenersOutput) {
	op := &request.Operation{
		Name:       opDescribeListeners,
		HTTPMethod: "POST",
		HTTPPath:   "/",
		Paginator: &request.Paginator{
			InputTokens:     []string{"Marker"},
			OutputTokens:    []string{"NextMarker"},
			LimitToken:      "",
			TruncationToken: "",
		},
	}

	if input == nil {
		input = &DescribeListenersInput{}
	}

	output = &DescribeListenersOutput{}
	req = c.newRequest(op, input, output)
	return
}

// DescribeListeners API operation for Elastic Load Balancing.
//
// Describes the specified listeners or the listeners for the specified Application
// Load Balancer or Network Load Balancer. You must specify either a load balancer
// or one or more listeners.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation DescribeListeners for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeListenerNotFoundException "ListenerNotFound"
//   The specified listener does not exist.
//
//   * ErrCodeLoadBalancerNotFoundException "LoadBalancerNotFound"
//   The specified load balancer does not exist.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeListeners
func (c *ELBV2) DescribeListeners(input *DescribeListenersInput) (*DescribeListenersOutput, error) {
	req, out := c.DescribeListenersRequest(input)
	return out, req.Send()
}

// DescribeListenersWithContext is the same as DescribeListeners with the addition of
// the ability to pass a context and additional request options.
//
// See DescribeListeners for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) DescribeListenersWithContext(ctx aws.Context, input *DescribeListenersInput, opts ...request.Option) (*DescribeListenersOutput, error) {
	req, out := c.DescribeListenersRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

// DescribeListenersPages iterates over the pages of a DescribeListeners operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See DescribeListeners method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
//    // Example iterating over at most 3 pages of a DescribeListeners operation.
//    pageNum := 0
//    err := client.DescribeListenersPages(params,
//        func(page *DescribeListenersOutput, lastPage bool) bool {
//            pageNum++
//            fmt.Println(page)
//            return pageNum <= 3
//        })
//
func (c *ELBV2) DescribeListenersPages(input *DescribeListenersInput, fn func(*DescribeListenersOutput, bool) bool) error {
	return c.DescribeListenersPagesWithContext(aws.BackgroundContext(), input, fn)
}

// DescribeListenersPagesWithContext same as DescribeListenersPages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) DescribeListenersPagesWithContext(ctx aws.Context, input *DescribeListenersInput, fn func(*DescribeListenersOutput, bool) bool, opts ...request.Option) error {
	p := request.Pagination{
		NewRequest: func() (*request.Request, error) {
			var inCpy *DescribeListenersInput
			if input != nil {
				tmp := *input
				inCpy = &tmp
			}
			req, _ := c.DescribeListenersRequest(inCpy)
			req.SetContext(ctx)
			req.ApplyOptions(opts...)
			return req, nil
		},
	}

	cont := true
	for p.Next() && cont {
		cont = fn(p.Page().(*DescribeListenersOutput), !p.HasNextPage())
	}
	return p.Err()
}

const opDescribeLoadBalancerAttributes = "DescribeLoadBalancerAttributes"

// DescribeLoadBalancerAttributesRequest generates a "aws/request.Request" representing the
// client's request for the DescribeLoadBalancerAttributes operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DescribeLoadBalancerAttributes for more information on using the DescribeLoadBalancerAttributes
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the DescribeLoadBalancerAttributesRequest method.
//    req, resp := client.DescribeLoadBalancerAttributesRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancerAttributes
func (c *ELBV2) DescribeLoadBalancerAttributesRequest(input *DescribeLoadBalancerAttributesInput) (req *request.Request, output *DescribeLoadBalancerAttributesOutput) {
	op := &request.Operation{
		Name:       opDescribeLoadBalancerAttributes,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &DescribeLoadBalancerAttributesInput{}
	}

	output = &DescribeLoadBalancerAttributesOutput{}
	req = c.newRequest(op, input, output)
	return
}

// DescribeLoadBalancerAttributes API operation for Elastic Load Balancing.
//
// Describes the attributes for the specified Application Load Balancer or Network
// Load Balancer.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation DescribeLoadBalancerAttributes for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeLoadBalancerNotFoundException "LoadBalancerNotFound"
//   The specified load balancer does not exist.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancerAttributes
func (c *ELBV2) DescribeLoadBalancerAttributes(input *DescribeLoadBalancerAttributesInput) (*DescribeLoadBalancerAttributesOutput, error) {
	req, out := c.DescribeLoadBalancerAttributesRequest(input)
	return out, req.Send()
}

// DescribeLoadBalancerAttributesWithContext is the same as DescribeLoadBalancerAttributes with the addition of
// the ability to pass a context and additional request options.
//
// See DescribeLoadBalancerAttributes for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) DescribeLoadBalancerAttributesWithContext(ctx aws.Context, input *DescribeLoadBalancerAttributesInput, opts ...request.Option) (*DescribeLoadBalancerAttributesOutput, error) {
	req, out := c.DescribeLoadBalancerAttributesRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opDescribeLoadBalancers = "DescribeLoadBalancers"

// DescribeLoadBalancersRequest generates a "aws/request.Request" representing the
// client's request for the DescribeLoadBalancers operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DescribeLoadBalancers for more information on using the DescribeLoadBalancers
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the DescribeLoadBalancersRequest method.
//    req, resp := client.DescribeLoadBalancersRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancers
func (c *ELBV2) DescribeLoadBalancersRequest(input *DescribeLoadBalancersInput) (req *request.Request, output *DescribeLoadBalancersOutput) {
	op := &request.Operation{
		Name:       opDescribeLoadBalancers,
		HTTPMethod: "POST",
		HTTPPath:   "/",
		Paginator: &request.Paginator{
			InputTokens:     []string{"Marker"},
			OutputTokens:    []string{"NextMarker"},
			LimitToken:      "",
			TruncationToken: "",
		},
	}

	if input == nil {
		input = &DescribeLoadBalancersInput{}
	}

	output = &DescribeLoadBalancersOutput{}
	req = c.newRequest(op, input, output)
	return
}

// DescribeLoadBalancers API operation for Elastic Load Balancing.
//
// Describes the specified load balancers or all of your load balancers.
//
// To describe the listeners for a load balancer, use DescribeListeners. To
// describe the attributes for a load balancer, use DescribeLoadBalancerAttributes.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation DescribeLoadBalancers for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeLoadBalancerNotFoundException "LoadBalancerNotFound"
//   The specified load balancer does not exist.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancers
func (c *ELBV2) DescribeLoadBalancers(input *DescribeLoadBalancersInput) (*DescribeLoadBalancersOutput, error) {
	req, out := c.DescribeLoadBalancersRequest(input)
	return out, req.Send()
}

// DescribeLoadBalancersWithContext is the same as DescribeLoadBalancers with the addition of
// the ability to pass a context and additional request options.
//
// See DescribeLoadBalancers for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) DescribeLoadBalancersWithContext(ctx aws.Context, input *DescribeLoadBalancersInput, opts ...request.Option) (*DescribeLoadBalancersOutput, error) {
	req, out := c.DescribeLoadBalancersRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

// DescribeLoadBalancersPages iterates over the pages of a DescribeLoadBalancers operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See DescribeLoadBalancers method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
//    // Example iterating over at most 3 pages of a DescribeLoadBalancers operation.
//    pageNum := 0
//    err := client.DescribeLoadBalancersPages(params,
//        func(page *DescribeLoadBalancersOutput, lastPage bool) bool {
//            pageNum++
//            fmt.Println(page)
//            return pageNum <= 3
//        })
//
func (c *ELBV2) DescribeLoadBalancersPages(input *DescribeLoadBalancersInput, fn func(*DescribeLoadBalancersOutput, bool) bool) error {
	return c.DescribeLoadBalancersPagesWithContext(aws.BackgroundContext(), input, fn)
}

// DescribeLoadBalancersPagesWithContext same as DescribeLoadBalancersPages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) DescribeLoadBalancersPagesWithContext(ctx aws.Context, input *DescribeLoadBalancersInput, fn func(*DescribeLoadBalancersOutput, bool) bool, opts ...request.Option) error {
	p := request.Pagination{
		NewRequest: func() (*request.Request, error) {
			var inCpy *DescribeLoadBalancersInput
			if input != nil {
				tmp := *input
				inCpy = &tmp
			}
			req, _ := c.DescribeLoadBalancersRequest(inCpy)
			req.SetContext(ctx)
			req.ApplyOptions(opts...)
			return req, nil
		},
	}

	cont := true
	for p.Next() && cont {
		cont = fn(p.Page().(*DescribeLoadBalancersOutput), !p.HasNextPage())
	}
	return p.Err()
}

const opDescribeRules = "DescribeRules"

// DescribeRulesRequest generates a "aws/request.Request" representing the
// client's request for the DescribeRules operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DescribeRules for more information on using the DescribeRules
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the DescribeRulesRequest method.
//    req, resp := client.DescribeRulesRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeRules
func (c *ELBV2) DescribeRulesRequest(input *DescribeRulesInput) (req *request.Request, output *DescribeRulesOutput) {
	op := &request.Operation{
		Name:       opDescribeRules,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &DescribeRulesInput{}
	}

	output = &DescribeRulesOutput{}
	req = c.newRequest(op, input, output)
	return
}

// DescribeRules API operation for Elastic Load Balancing.
//
// Describes the specified rules or the rules for the specified listener. You
// must specify either a listener or one or more rules.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation DescribeRules for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeListenerNotFoundException "ListenerNotFound"
//   The specified listener does not exist.
//
//   * ErrCodeRuleNotFoundException "RuleNotFound"
//   The specified rule does not exist.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeRules
func (c *ELBV2) DescribeRules(input *DescribeRulesInput) (*DescribeRulesOutput, error) {
	req, out := c.DescribeRulesRequest(input)
	return out, req.Send()
}

// DescribeRulesWithContext is the same as DescribeRules with the addition of
// the ability to pass a context and additional request options.
//
// See DescribeRules for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) DescribeRulesWithContext(ctx aws.Context, input *DescribeRulesInput, opts ...request.Option) (*DescribeRulesOutput, error) {
	req, out := c.DescribeRulesRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opDescribeSSLPolicies = "DescribeSSLPolicies"

// DescribeSSLPoliciesRequest generates a "aws/request.Request" representing the
// client's request for the DescribeSSLPolicies operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DescribeSSLPolicies for more information on using the DescribeSSLPolicies
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the DescribeSSLPoliciesRequest method.
//    req, resp := client.DescribeSSLPoliciesRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeSSLPolicies
func (c *ELBV2) DescribeSSLPoliciesRequest(input *DescribeSSLPoliciesInput) (req *request.Request, output *DescribeSSLPoliciesOutput) {
	op := &request.Operation{
		Name:       opDescribeSSLPolicies,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &DescribeSSLPoliciesInput{}
	}

	output = &DescribeSSLPoliciesOutput{}
	req = c.newRequest(op, input, output)
	return
}

// DescribeSSLPolicies API operation for Elastic Load Balancing.
//
// Describes the specified policies or all policies used for SSL negotiation.
//
// For more information, see Security Policies (http://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-https-listener.html#describe-ssl-policies)
// in the Application Load Balancers Guide.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation DescribeSSLPolicies for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeSSLPolicyNotFoundException "SSLPolicyNotFound"
//   The specified SSL policy does not exist.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeSSLPolicies
func (c *ELBV2) DescribeSSLPolicies(input *DescribeSSLPoliciesInput) (*DescribeSSLPoliciesOutput, error) {
	req, out := c.DescribeSSLPoliciesRequest(input)
	return out, req.Send()
}

// DescribeSSLPoliciesWithContext is the same as DescribeSSLPolicies with the addition of
// the ability to pass a context and additional request options.
//
// See DescribeSSLPolicies for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) DescribeSSLPoliciesWithContext(ctx aws.Context, input *DescribeSSLPoliciesInput, opts ...request.Option) (*DescribeSSLPoliciesOutput, error) {
	req, out := c.DescribeSSLPoliciesRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opDescribeTags = "DescribeTags"

// DescribeTagsRequest generates a "aws/request.Request" representing the
// client's request for the DescribeTags operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DescribeTags for more information on using the DescribeTags
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the DescribeTagsRequest method.
//    req, resp := client.DescribeTagsRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeTags
func (c *ELBV2) DescribeTagsRequest(input *DescribeTagsInput) (req *request.Request, output *DescribeTagsOutput) {
	op := &request.Operation{
		Name:       opDescribeTags,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &DescribeTagsInput{}
	}

	output = &DescribeTagsOutput{}
	req = c.newRequest(op, input, output)
	return
}

// DescribeTags API operation for Elastic Load Balancing.
//
// Describes the tags for the specified resources. You can describe the tags
// for one or more Application Load Balancers, Network Load Balancers, and target
// groups.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation DescribeTags for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeLoadBalancerNotFoundException "LoadBalancerNotFound"
//   The specified load balancer does not exist.
//
//   * ErrCodeTargetGroupNotFoundException "TargetGroupNotFound"
//   The specified target group does not exist.
//
//   * ErrCodeListenerNotFoundException "ListenerNotFound"
//   The specified listener does not exist.
//
//   * ErrCodeRuleNotFoundException "RuleNotFound"
//   The specified rule does not exist.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeTags
func (c *ELBV2) DescribeTags(input *DescribeTagsInput) (*DescribeTagsOutput, error) {
	req, out := c.DescribeTagsRequest(input)
	return out, req.Send()
}

// DescribeTagsWithContext is the same as DescribeTags with the addition of
// the ability to pass a context and additional request options.
//
// See DescribeTags for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) DescribeTagsWithContext(ctx aws.Context, input *DescribeTagsInput, opts ...request.Option) (*DescribeTagsOutput, error) {
	req, out := c.DescribeTagsRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opDescribeTargetGroupAttributes = "DescribeTargetGroupAttributes"

// DescribeTargetGroupAttributesRequest generates a "aws/request.Request" representing the
// client's request for the DescribeTargetGroupAttributes operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DescribeTargetGroupAttributes for more information on using the DescribeTargetGroupAttributes
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the DescribeTargetGroupAttributesRequest method.
//    req, resp := client.DescribeTargetGroupAttributesRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeTargetGroupAttributes
func (c *ELBV2) DescribeTargetGroupAttributesRequest(input *DescribeTargetGroupAttributesInput) (req *request.Request, output *DescribeTargetGroupAttributesOutput) {
	op := &request.Operation{
		Name:       opDescribeTargetGroupAttributes,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &DescribeTargetGroupAttributesInput{}
	}

	output = &DescribeTargetGroupAttributesOutput{}
	req = c.newRequest(op, input, output)
	return
}

// DescribeTargetGroupAttributes API operation for Elastic Load Balancing.
//
// Describes the attributes for the specified target group.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation DescribeTargetGroupAttributes for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeTargetGroupNotFoundException "TargetGroupNotFound"
//   The specified target group does not exist.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeTargetGroupAttributes
func (c *ELBV2) DescribeTargetGroupAttributes(input *DescribeTargetGroupAttributesInput) (*DescribeTargetGroupAttributesOutput, error) {
	req, out := c.DescribeTargetGroupAttributesRequest(input)
	return out, req.Send()
}

// DescribeTargetGroupAttributesWithContext is the same as DescribeTargetGroupAttributes with the addition of
// the ability to pass a context and additional request options.
//
// See DescribeTargetGroupAttributes for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) DescribeTargetGroupAttributesWithContext(ctx aws.Context, input *DescribeTargetGroupAttributesInput, opts ...request.Option) (*DescribeTargetGroupAttributesOutput, error) {
	req, out := c.DescribeTargetGroupAttributesRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opDescribeTargetGroups = "DescribeTargetGroups"

// DescribeTargetGroupsRequest generates a "aws/request.Request" representing the
// client's request for the DescribeTargetGroups operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DescribeTargetGroups for more information on using the DescribeTargetGroups
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the DescribeTargetGroupsRequest method.
//    req, resp := client.DescribeTargetGroupsRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeTargetGroups
func (c *ELBV2) DescribeTargetGroupsRequest(input *DescribeTargetGroupsInput) (req *request.Request, output *DescribeTargetGroupsOutput) {
	op := &request.Operation{
		Name:       opDescribeTargetGroups,
		HTTPMethod: "POST",
		HTTPPath:   "/",
		Paginator: &request.Paginator{
			InputTokens:     []string{"Marker"},
			OutputTokens:    []string{"NextMarker"},
			LimitToken:      "",
			TruncationToken: "",
		},
	}

	if input == nil {
		input = &DescribeTargetGroupsInput{}
	}

	output = &DescribeTargetGroupsOutput{}
	req = c.newRequest(op, input, output)
	return
}

// DescribeTargetGroups API operation for Elastic Load Balancing.
//
// Describes the specified target groups or all of your target groups. By default,
// all target groups are described. Alternatively, you can specify one of the
// following to filter the results: the ARN of the load balancer, the names
// of one or more target groups, or the ARNs of one or more target groups.
//
// To describe the targets for a target group, use DescribeTargetHealth. To
// describe the attributes of a target group, use DescribeTargetGroupAttributes.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation DescribeTargetGroups for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeLoadBalancerNotFoundException "LoadBalancerNotFound"
//   The specified load balancer does not exist.
//
//   * ErrCodeTargetGroupNotFoundException "TargetGroupNotFound"
//   The specified target group does not exist.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeTargetGroups
func (c *ELBV2) DescribeTargetGroups(input *DescribeTargetGroupsInput) (*DescribeTargetGroupsOutput, error) {
	req, out := c.DescribeTargetGroupsRequest(input)
	return out, req.Send()
}

// DescribeTargetGroupsWithContext is the same as DescribeTargetGroups with the addition of
// the ability to pass a context and additional request options.
//
// See DescribeTargetGroups for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) DescribeTargetGroupsWithContext(ctx aws.Context, input *DescribeTargetGroupsInput, opts ...request.Option) (*DescribeTargetGroupsOutput, error) {
	req, out := c.DescribeTargetGroupsRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

// DescribeTargetGroupsPages iterates over the pages of a DescribeTargetGroups operation,
// calling the "fn" function with the response data for each page. To stop
// iterating, return false from the fn function.
//
// See DescribeTargetGroups method for more information on how to use this operation.
//
// Note: This operation can generate multiple requests to a service.
//
//    // Example iterating over at most 3 pages of a DescribeTargetGroups operation.
//    pageNum := 0
//    err := client.DescribeTargetGroupsPages(params,
//        func(page *DescribeTargetGroupsOutput, lastPage bool) bool {
//            pageNum++
//            fmt.Println(page)
//            return pageNum <= 3
//        })
//
func (c *ELBV2) DescribeTargetGroupsPages(input *DescribeTargetGroupsInput, fn func(*DescribeTargetGroupsOutput, bool) bool) error {
	return c.DescribeTargetGroupsPagesWithContext(aws.BackgroundContext(), input, fn)
}

// DescribeTargetGroupsPagesWithContext same as DescribeTargetGroupsPages except
// it takes a Context and allows setting request options on the pages.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) DescribeTargetGroupsPagesWithContext(ctx aws.Context, input *DescribeTargetGroupsInput, fn func(*DescribeTargetGroupsOutput, bool) bool, opts ...request.Option) error {
	p := request.Pagination{
		NewRequest: func() (*request.Request, error) {
			var inCpy *DescribeTargetGroupsInput
			if input != nil {
				tmp := *input
				inCpy = &tmp
			}
			req, _ := c.DescribeTargetGroupsRequest(inCpy)
			req.SetContext(ctx)
			req.ApplyOptions(opts...)
			return req, nil
		},
	}

	cont := true
	for p.Next() && cont {
		cont = fn(p.Page().(*DescribeTargetGroupsOutput), !p.HasNextPage())
	}
	return p.Err()
}

const opDescribeTargetHealth = "DescribeTargetHealth"

// DescribeTargetHealthRequest generates a "aws/request.Request" representing the
// client's request for the DescribeTargetHealth operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See DescribeTargetHealth for more information on using the DescribeTargetHealth
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the DescribeTargetHealthRequest method.
//    req, resp := client.DescribeTargetHealthRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeTargetHealth
func (c *ELBV2) DescribeTargetHealthRequest(input *DescribeTargetHealthInput) (req *request.Request, output *DescribeTargetHealthOutput) {
	op := &request.Operation{
		Name:       opDescribeTargetHealth,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &DescribeTargetHealthInput{}
	}

	output = &DescribeTargetHealthOutput{}
	req = c.newRequest(op, input, output)
	return
}

// DescribeTargetHealth API operation for Elastic Load Balancing.
//
// Describes the health of the specified targets or all of your targets.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation DescribeTargetHealth for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeInvalidTargetException "InvalidTarget"
//   The specified target does not exist, is not in the same VPC as the target
//   group, or has an unsupported instance type.
//
//   * ErrCodeTargetGroupNotFoundException "TargetGroupNotFound"
//   The specified target group does not exist.
//
//   * ErrCodeHealthUnavailableException "HealthUnavailable"
//   The health of the specified targets could not be retrieved due to an internal
//   error.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeTargetHealth
func (c *ELBV2) DescribeTargetHealth(input *DescribeTargetHealthInput) (*DescribeTargetHealthOutput, error) {
	req, out := c.DescribeTargetHealthRequest(input)
	return out, req.Send()
}

// DescribeTargetHealthWithContext is the same as DescribeTargetHealth with the addition of
// the ability to pass a context and additional request options.
//
// See DescribeTargetHealth for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) DescribeTargetHealthWithContext(ctx aws.Context, input *DescribeTargetHealthInput, opts ...request.Option) (*DescribeTargetHealthOutput, error) {
	req, out := c.DescribeTargetHealthRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opModifyListener = "ModifyListener"

// ModifyListenerRequest generates a "aws/request.Request" representing the
// client's request for the ModifyListener operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ModifyListener for more information on using the ModifyListener
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the ModifyListenerRequest method.
//    req, resp := client.ModifyListenerRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyListener
func (c *ELBV2) ModifyListenerRequest(input *ModifyListenerInput) (req *request.Request, output *ModifyListenerOutput) {
	op := &request.Operation{
		Name:       opModifyListener,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &ModifyListenerInput{}
	}

	output = &ModifyListenerOutput{}
	req = c.newRequest(op, input, output)
	return
}

// ModifyListener API operation for Elastic Load Balancing.
//
// Modifies the specified properties of the specified listener.
//
// Any properties that you do not specify retain their current values. However,
// changing the protocol from HTTPS to HTTP removes the security policy and
// SSL certificate properties. If you change the protocol from HTTP to HTTPS,
// you must add the security policy and server certificate.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation ModifyListener for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeDuplicateListenerException "DuplicateListener"
//   A listener with the specified port already exists.
//
//   * ErrCodeTooManyListenersException "TooManyListeners"
//   You've reached the limit on the number of listeners per load balancer.
//
//   * ErrCodeTooManyCertificatesException "TooManyCertificates"
//   You've reached the limit on the number of certificates per load balancer.
//
//   * ErrCodeListenerNotFoundException "ListenerNotFound"
//   The specified listener does not exist.
//
//   * ErrCodeTargetGroupNotFoundException "TargetGroupNotFound"
//   The specified target group does not exist.
//
//   * ErrCodeTargetGroupAssociationLimitException "TargetGroupAssociationLimit"
//   You've reached the limit on the number of load balancers per target group.
//
//   * ErrCodeIncompatibleProtocolsException "IncompatibleProtocols"
//   The specified configuration is not valid with this protocol.
//
//   * ErrCodeSSLPolicyNotFoundException "SSLPolicyNotFound"
//   The specified SSL policy does not exist.
//
//   * ErrCodeCertificateNotFoundException "CertificateNotFound"
//   The specified certificate does not exist.
//
//   * ErrCodeInvalidConfigurationRequestException "InvalidConfigurationRequest"
//   The requested configuration is not valid.
//
//   * ErrCodeUnsupportedProtocolException "UnsupportedProtocol"
//   The specified protocol is not supported.
//
//   * ErrCodeTooManyRegistrationsForTargetIdException "TooManyRegistrationsForTargetId"
//   You've reached the limit on the number of times a target can be registered
//   with a load balancer.
//
//   * ErrCodeTooManyTargetsException "TooManyTargets"
//   You've reached the limit on the number of targets.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyListener
func (c *ELBV2) ModifyListener(input *ModifyListenerInput) (*ModifyListenerOutput, error) {
	req, out := c.ModifyListenerRequest(input)
	return out, req.Send()
}

// ModifyListenerWithContext is the same as ModifyListener with the addition of
// the ability to pass a context and additional request options.
//
// See ModifyListener for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) ModifyListenerWithContext(ctx aws.Context, input *ModifyListenerInput, opts ...request.Option) (*ModifyListenerOutput, error) {
	req, out := c.ModifyListenerRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opModifyLoadBalancerAttributes = "ModifyLoadBalancerAttributes"

// ModifyLoadBalancerAttributesRequest generates a "aws/request.Request" representing the
// client's request for the ModifyLoadBalancerAttributes operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ModifyLoadBalancerAttributes for more information on using the ModifyLoadBalancerAttributes
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the ModifyLoadBalancerAttributesRequest method.
//    req, resp := client.ModifyLoadBalancerAttributesRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyLoadBalancerAttributes
func (c *ELBV2) ModifyLoadBalancerAttributesRequest(input *ModifyLoadBalancerAttributesInput) (req *request.Request, output *ModifyLoadBalancerAttributesOutput) {
	op := &request.Operation{
		Name:       opModifyLoadBalancerAttributes,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &ModifyLoadBalancerAttributesInput{}
	}

	output = &ModifyLoadBalancerAttributesOutput{}
	req = c.newRequest(op, input, output)
	return
}

// ModifyLoadBalancerAttributes API operation for Elastic Load Balancing.
//
// Modifies the specified attributes of the specified Application Load Balancer
// or Network Load Balancer.
//
// If any of the specified attributes can't be modified as requested, the call
// fails. Any existing attributes that you do not modify retain their current
// values.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation ModifyLoadBalancerAttributes for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeLoadBalancerNotFoundException "LoadBalancerNotFound"
//   The specified load balancer does not exist.
//
//   * ErrCodeInvalidConfigurationRequestException "InvalidConfigurationRequest"
//   The requested configuration is not valid.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyLoadBalancerAttributes
func (c *ELBV2) ModifyLoadBalancerAttributes(input *ModifyLoadBalancerAttributesInput) (*ModifyLoadBalancerAttributesOutput, error) {
	req, out := c.ModifyLoadBalancerAttributesRequest(input)
	return out, req.Send()
}

// ModifyLoadBalancerAttributesWithContext is the same as ModifyLoadBalancerAttributes with the addition of
// the ability to pass a context and additional request options.
//
// See ModifyLoadBalancerAttributes for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) ModifyLoadBalancerAttributesWithContext(ctx aws.Context, input *ModifyLoadBalancerAttributesInput, opts ...request.Option) (*ModifyLoadBalancerAttributesOutput, error) {
	req, out := c.ModifyLoadBalancerAttributesRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opModifyRule = "ModifyRule"

// ModifyRuleRequest generates a "aws/request.Request" representing the
// client's request for the ModifyRule operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ModifyRule for more information on using the ModifyRule
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the ModifyRuleRequest method.
//    req, resp := client.ModifyRuleRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyRule
func (c *ELBV2) ModifyRuleRequest(input *ModifyRuleInput) (req *request.Request, output *ModifyRuleOutput) {
	op := &request.Operation{
		Name:       opModifyRule,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &ModifyRuleInput{}
	}

	output = &ModifyRuleOutput{}
	req = c.newRequest(op, input, output)
	return
}

// ModifyRule API operation for Elastic Load Balancing.
//
// Modifies the specified rule.
//
// Any existing properties that you do not modify retain their current values.
//
// To modify the default action, use ModifyListener.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation ModifyRule for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeTargetGroupAssociationLimitException "TargetGroupAssociationLimit"
//   You've reached the limit on the number of load balancers per target group.
//
//   * ErrCodeIncompatibleProtocolsException "IncompatibleProtocols"
//   The specified configuration is not valid with this protocol.
//
//   * ErrCodeRuleNotFoundException "RuleNotFound"
//   The specified rule does not exist.
//
//   * ErrCodeOperationNotPermittedException "OperationNotPermitted"
//   This operation is not allowed.
//
//   * ErrCodeTooManyRegistrationsForTargetIdException "TooManyRegistrationsForTargetId"
//   You've reached the limit on the number of times a target can be registered
//   with a load balancer.
//
//   * ErrCodeTooManyTargetsException "TooManyTargets"
//   You've reached the limit on the number of targets.
//
//   * ErrCodeTargetGroupNotFoundException "TargetGroupNotFound"
//   The specified target group does not exist.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyRule
func (c *ELBV2) ModifyRule(input *ModifyRuleInput) (*ModifyRuleOutput, error) {
	req, out := c.ModifyRuleRequest(input)
	return out, req.Send()
}

// ModifyRuleWithContext is the same as ModifyRule with the addition of
// the ability to pass a context and additional request options.
//
// See ModifyRule for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) ModifyRuleWithContext(ctx aws.Context, input *ModifyRuleInput, opts ...request.Option) (*ModifyRuleOutput, error) {
	req, out := c.ModifyRuleRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opModifyTargetGroup = "ModifyTargetGroup"

// ModifyTargetGroupRequest generates a "aws/request.Request" representing the
// client's request for the ModifyTargetGroup operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ModifyTargetGroup for more information on using the ModifyTargetGroup
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the ModifyTargetGroupRequest method.
//    req, resp := client.ModifyTargetGroupRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyTargetGroup
func (c *ELBV2) ModifyTargetGroupRequest(input *ModifyTargetGroupInput) (req *request.Request, output *ModifyTargetGroupOutput) {
	op := &request.Operation{
		Name:       opModifyTargetGroup,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &ModifyTargetGroupInput{}
	}

	output = &ModifyTargetGroupOutput{}
	req = c.newRequest(op, input, output)
	return
}

// ModifyTargetGroup API operation for Elastic Load Balancing.
//
// Modifies the health checks used when evaluating the health state of the targets
// in the specified target group.
//
// To monitor the health of the targets, use DescribeTargetHealth.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation ModifyTargetGroup for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeTargetGroupNotFoundException "TargetGroupNotFound"
//   The specified target group does not exist.
//
//   * ErrCodeInvalidConfigurationRequestException "InvalidConfigurationRequest"
//   The requested configuration is not valid.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyTargetGroup
func (c *ELBV2) ModifyTargetGroup(input *ModifyTargetGroupInput) (*ModifyTargetGroupOutput, error) {
	req, out := c.ModifyTargetGroupRequest(input)
	return out, req.Send()
}

// ModifyTargetGroupWithContext is the same as ModifyTargetGroup with the addition of
// the ability to pass a context and additional request options.
//
// See ModifyTargetGroup for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) ModifyTargetGroupWithContext(ctx aws.Context, input *ModifyTargetGroupInput, opts ...request.Option) (*ModifyTargetGroupOutput, error) {
	req, out := c.ModifyTargetGroupRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opModifyTargetGroupAttributes = "ModifyTargetGroupAttributes"

// ModifyTargetGroupAttributesRequest generates a "aws/request.Request" representing the
// client's request for the ModifyTargetGroupAttributes operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See ModifyTargetGroupAttributes for more information on using the ModifyTargetGroupAttributes
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the ModifyTargetGroupAttributesRequest method.
//    req, resp := client.ModifyTargetGroupAttributesRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyTargetGroupAttributes
func (c *ELBV2) ModifyTargetGroupAttributesRequest(input *ModifyTargetGroupAttributesInput) (req *request.Request, output *ModifyTargetGroupAttributesOutput) {
	op := &request.Operation{
		Name:       opModifyTargetGroupAttributes,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &ModifyTargetGroupAttributesInput{}
	}

	output = &ModifyTargetGroupAttributesOutput{}
	req = c.newRequest(op, input, output)
	return
}

// ModifyTargetGroupAttributes API operation for Elastic Load Balancing.
//
// Modifies the specified attributes of the specified target group.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation ModifyTargetGroupAttributes for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeTargetGroupNotFoundException "TargetGroupNotFound"
//   The specified target group does not exist.
//
//   * ErrCodeInvalidConfigurationRequestException "InvalidConfigurationRequest"
//   The requested configuration is not valid.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyTargetGroupAttributes
func (c *ELBV2) ModifyTargetGroupAttributes(input *ModifyTargetGroupAttributesInput) (*ModifyTargetGroupAttributesOutput, error) {
	req, out := c.ModifyTargetGroupAttributesRequest(input)
	return out, req.Send()
}

// ModifyTargetGroupAttributesWithContext is the same as ModifyTargetGroupAttributes with the addition of
// the ability to pass a context and additional request options.
//
// See ModifyTargetGroupAttributes for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) ModifyTargetGroupAttributesWithContext(ctx aws.Context, input *ModifyTargetGroupAttributesInput, opts ...request.Option) (*ModifyTargetGroupAttributesOutput, error) {
	req, out := c.ModifyTargetGroupAttributesRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opRegisterTargets = "RegisterTargets"

// RegisterTargetsRequest generates a "aws/request.Request" representing the
// client's request for the RegisterTargets operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See RegisterTargets for more information on using the RegisterTargets
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the RegisterTargetsRequest method.
//    req, resp := client.RegisterTargetsRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/RegisterTargets
func (c *ELBV2) RegisterTargetsRequest(input *RegisterTargetsInput) (req *request.Request, output *RegisterTargetsOutput) {
	op := &request.Operation{
		Name:       opRegisterTargets,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &RegisterTargetsInput{}
	}

	output = &RegisterTargetsOutput{}
	req = c.newRequest(op, input, output)
	return
}

// RegisterTargets API operation for Elastic Load Balancing.
//
// Registers the specified targets with the specified target group.
//
// You can register targets by instance ID or by IP address. If the target is
// an EC2 instance, it must be in the running state when you register it.
//
// By default, the load balancer routes requests to registered targets using
// the protocol and port for the target group. Alternatively, you can override
// the port for a target when you register it. You can register each EC2 instance
// or IP address with the same target group multiple times using different ports.
//
// With a Network Load Balancer, you cannot register instances by instance ID
// if they have the following instance types: C1, CC1, CC2, CG1, CG2, CR1, CS1,
// G1, G2, HI1, HS1, M1, M2, M3, and T1. You can register instances of these
// types by IP address.
//
// To remove a target from a target group, use DeregisterTargets.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation RegisterTargets for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeTargetGroupNotFoundException "TargetGroupNotFound"
//   The specified target group does not exist.
//
//   * ErrCodeTooManyTargetsException "TooManyTargets"
//   You've reached the limit on the number of targets.
//
//   * ErrCodeInvalidTargetException "InvalidTarget"
//   The specified target does not exist, is not in the same VPC as the target
//   group, or has an unsupported instance type.
//
//   * ErrCodeTooManyRegistrationsForTargetIdException "TooManyRegistrationsForTargetId"
//   You've reached the limit on the number of times a target can be registered
//   with a load balancer.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/RegisterTargets
func (c *ELBV2) RegisterTargets(input *RegisterTargetsInput) (*RegisterTargetsOutput, error) {
	req, out := c.RegisterTargetsRequest(input)
	return out, req.Send()
}

// RegisterTargetsWithContext is the same as RegisterTargets with the addition of
// the ability to pass a context and additional request options.
//
// See RegisterTargets for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) RegisterTargetsWithContext(ctx aws.Context, input *RegisterTargetsInput, opts ...request.Option) (*RegisterTargetsOutput, error) {
	req, out := c.RegisterTargetsRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opRemoveListenerCertificates = "RemoveListenerCertificates"

// RemoveListenerCertificatesRequest generates a "aws/request.Request" representing the
// client's request for the RemoveListenerCertificates operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See RemoveListenerCertificates for more information on using the RemoveListenerCertificates
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the RemoveListenerCertificatesRequest method.
//    req, resp := client.RemoveListenerCertificatesRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/RemoveListenerCertificates
func (c *ELBV2) RemoveListenerCertificatesRequest(input *RemoveListenerCertificatesInput) (req *request.Request, output *RemoveListenerCertificatesOutput) {
	op := &request.Operation{
		Name:       opRemoveListenerCertificates,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &RemoveListenerCertificatesInput{}
	}

	output = &RemoveListenerCertificatesOutput{}
	req = c.newRequest(op, input, output)
	return
}

// RemoveListenerCertificates API operation for Elastic Load Balancing.
//
// Removes the specified certificate from the specified secure listener.
//
// You can't remove the default certificate for a listener. To replace the default
// certificate, call ModifyListener.
//
// To list the certificates for your listener, use DescribeListenerCertificates.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation RemoveListenerCertificates for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeListenerNotFoundException "ListenerNotFound"
//   The specified listener does not exist.
//
//   * ErrCodeOperationNotPermittedException "OperationNotPermitted"
//   This operation is not allowed.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/RemoveListenerCertificates
func (c *ELBV2) RemoveListenerCertificates(input *RemoveListenerCertificatesInput) (*RemoveListenerCertificatesOutput, error) {
	req, out := c.RemoveListenerCertificatesRequest(input)
	return out, req.Send()
}

// RemoveListenerCertificatesWithContext is the same as RemoveListenerCertificates with the addition of
// the ability to pass a context and additional request options.
//
// See RemoveListenerCertificates for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) RemoveListenerCertificatesWithContext(ctx aws.Context, input *RemoveListenerCertificatesInput, opts ...request.Option) (*RemoveListenerCertificatesOutput, error) {
	req, out := c.RemoveListenerCertificatesRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opRemoveTags = "RemoveTags"

// RemoveTagsRequest generates a "aws/request.Request" representing the
// client's request for the RemoveTags operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See RemoveTags for more information on using the RemoveTags
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the RemoveTagsRequest method.
//    req, resp := client.RemoveTagsRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/RemoveTags
func (c *ELBV2) RemoveTagsRequest(input *RemoveTagsInput) (req *request.Request, output *RemoveTagsOutput) {
	op := &request.Operation{
		Name:       opRemoveTags,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &RemoveTagsInput{}
	}

	output = &RemoveTagsOutput{}
	req = c.newRequest(op, input, output)
	return
}

// RemoveTags API operation for Elastic Load Balancing.
//
// Removes the specified tags from the specified Elastic Load Balancing resource.
//
// To list the current tags for your resources, use DescribeTags.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation RemoveTags for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeLoadBalancerNotFoundException "LoadBalancerNotFound"
//   The specified load balancer does not exist.
//
//   * ErrCodeTargetGroupNotFoundException "TargetGroupNotFound"
//   The specified target group does not exist.
//
//   * ErrCodeListenerNotFoundException "ListenerNotFound"
//   The specified listener does not exist.
//
//   * ErrCodeRuleNotFoundException "RuleNotFound"
//   The specified rule does not exist.
//
//   * ErrCodeTooManyTagsException "TooManyTags"
//   You've reached the limit on the number of tags per load balancer.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/RemoveTags
func (c *ELBV2) RemoveTags(input *RemoveTagsInput) (*RemoveTagsOutput, error) {
	req, out := c.RemoveTagsRequest(input)
	return out, req.Send()
}

// RemoveTagsWithContext is the same as RemoveTags with the addition of
// the ability to pass a context and additional request options.
//
// See RemoveTags for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) RemoveTagsWithContext(ctx aws.Context, input *RemoveTagsInput, opts ...request.Option) (*RemoveTagsOutput, error) {
	req, out := c.RemoveTagsRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opSetIpAddressType = "SetIpAddressType"

// SetIpAddressTypeRequest generates a "aws/request.Request" representing the
// client's request for the SetIpAddressType operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See SetIpAddressType for more information on using the SetIpAddressType
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the SetIpAddressTypeRequest method.
//    req, resp := client.SetIpAddressTypeRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SetIpAddressType
func (c *ELBV2) SetIpAddressTypeRequest(input *SetIpAddressTypeInput) (req *request.Request, output *SetIpAddressTypeOutput) {
	op := &request.Operation{
		Name:       opSetIpAddressType,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &SetIpAddressTypeInput{}
	}

	output = &SetIpAddressTypeOutput{}
	req = c.newRequest(op, input, output)
	return
}

// SetIpAddressType API operation for Elastic Load Balancing.
//
// Sets the type of IP addresses used by the subnets of the specified Application
// Load Balancer or Network Load Balancer.
//
// Note that Network Load Balancers must use ipv4.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation SetIpAddressType for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeLoadBalancerNotFoundException "LoadBalancerNotFound"
//   The specified load balancer does not exist.
//
//   * ErrCodeInvalidConfigurationRequestException "InvalidConfigurationRequest"
//   The requested configuration is not valid.
//
//   * ErrCodeInvalidSubnetException "InvalidSubnet"
//   The specified subnet is out of available addresses.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SetIpAddressType
func (c *ELBV2) SetIpAddressType(input *SetIpAddressTypeInput) (*SetIpAddressTypeOutput, error) {
	req, out := c.SetIpAddressTypeRequest(input)
	return out, req.Send()
}

// SetIpAddressTypeWithContext is the same as SetIpAddressType with the addition of
// the ability to pass a context and additional request options.
//
// See SetIpAddressType for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) SetIpAddressTypeWithContext(ctx aws.Context, input *SetIpAddressTypeInput, opts ...request.Option) (*SetIpAddressTypeOutput, error) {
	req, out := c.SetIpAddressTypeRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opSetRulePriorities = "SetRulePriorities"

// SetRulePrioritiesRequest generates a "aws/request.Request" representing the
// client's request for the SetRulePriorities operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See SetRulePriorities for more information on using the SetRulePriorities
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the SetRulePrioritiesRequest method.
//    req, resp := client.SetRulePrioritiesRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SetRulePriorities
func (c *ELBV2) SetRulePrioritiesRequest(input *SetRulePrioritiesInput) (req *request.Request, output *SetRulePrioritiesOutput) {
	op := &request.Operation{
		Name:       opSetRulePriorities,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &SetRulePrioritiesInput{}
	}

	output = &SetRulePrioritiesOutput{}
	req = c.newRequest(op, input, output)
	return
}

// SetRulePriorities API operation for Elastic Load Balancing.
//
// Sets the priorities of the specified rules.
//
// You can reorder the rules as long as there are no priority conflicts in the
// new order. Any existing rules that you do not specify retain their current
// priority.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation SetRulePriorities for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeRuleNotFoundException "RuleNotFound"
//   The specified rule does not exist.
//
//   * ErrCodePriorityInUseException "PriorityInUse"
//   The specified priority is in use.
//
//   * ErrCodeOperationNotPermittedException "OperationNotPermitted"
//   This operation is not allowed.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SetRulePriorities
func (c *ELBV2) SetRulePriorities(input *SetRulePrioritiesInput) (*SetRulePrioritiesOutput, error) {
	req, out := c.SetRulePrioritiesRequest(input)
	return out, req.Send()
}

// SetRulePrioritiesWithContext is the same as SetRulePriorities with the addition of
// the ability to pass a context and additional request options.
//
// See SetRulePriorities for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) SetRulePrioritiesWithContext(ctx aws.Context, input *SetRulePrioritiesInput, opts ...request.Option) (*SetRulePrioritiesOutput, error) {
	req, out := c.SetRulePrioritiesRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opSetSecurityGroups = "SetSecurityGroups"

// SetSecurityGroupsRequest generates a "aws/request.Request" representing the
// client's request for the SetSecurityGroups operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See SetSecurityGroups for more information on using the SetSecurityGroups
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the SetSecurityGroupsRequest method.
//    req, resp := client.SetSecurityGroupsRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SetSecurityGroups
func (c *ELBV2) SetSecurityGroupsRequest(input *SetSecurityGroupsInput) (req *request.Request, output *SetSecurityGroupsOutput) {
	op := &request.Operation{
		Name:       opSetSecurityGroups,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &SetSecurityGroupsInput{}
	}

	output = &SetSecurityGroupsOutput{}
	req = c.newRequest(op, input, output)
	return
}

// SetSecurityGroups API operation for Elastic Load Balancing.
//
// Associates the specified security groups with the specified Application Load
// Balancer. The specified security groups override the previously associated
// security groups.
//
// Note that you can't specify a security group for a Network Load Balancer.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation SetSecurityGroups for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeLoadBalancerNotFoundException "LoadBalancerNotFound"
//   The specified load balancer does not exist.
//
//   * ErrCodeInvalidConfigurationRequestException "InvalidConfigurationRequest"
//   The requested configuration is not valid.
//
//   * ErrCodeInvalidSecurityGroupException "InvalidSecurityGroup"
//   The specified security group does not exist.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SetSecurityGroups
func (c *ELBV2) SetSecurityGroups(input *SetSecurityGroupsInput) (*SetSecurityGroupsOutput, error) {
	req, out := c.SetSecurityGroupsRequest(input)
	return out, req.Send()
}

// SetSecurityGroupsWithContext is the same as SetSecurityGroups with the addition of
// the ability to pass a context and additional request options.
//
// See SetSecurityGroups for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) SetSecurityGroupsWithContext(ctx aws.Context, input *SetSecurityGroupsInput, opts ...request.Option) (*SetSecurityGroupsOutput, error) {
	req, out := c.SetSecurityGroupsRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

const opSetSubnets = "SetSubnets"

// SetSubnetsRequest generates a "aws/request.Request" representing the
// client's request for the SetSubnets operation. The "output" return
// value will be populated with the request's response once the request complets
// successfuly.
//
// Use "Send" method on the returned Request to send the API call to the service.
// the "output" return value is not valid until after Send returns without error.
//
// See SetSubnets for more information on using the SetSubnets
// API call, and error handling.
//
// This method is useful when you want to inject custom logic or configuration
// into the SDK's request lifecycle. Such as custom headers, or retry logic.
//
//
//    // Example sending a request using the SetSubnetsRequest method.
//    req, resp := client.SetSubnetsRequest(params)
//
//    err := req.Send()
//    if err == nil { // resp is now filled
//        fmt.Println(resp)
//    }
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SetSubnets
func (c *ELBV2) SetSubnetsRequest(input *SetSubnetsInput) (req *request.Request, output *SetSubnetsOutput) {
	op := &request.Operation{
		Name:       opSetSubnets,
		HTTPMethod: "POST",
		HTTPPath:   "/",
	}

	if input == nil {
		input = &SetSubnetsInput{}
	}

	output = &SetSubnetsOutput{}
	req = c.newRequest(op, input, output)
	return
}

// SetSubnets API operation for Elastic Load Balancing.
//
// Enables the Availability Zone for the specified subnets for the specified
// Application Load Balancer. The specified subnets replace the previously enabled
// subnets.
//
// Note that you can't change the subnets for a Network Load Balancer.
//
// Returns awserr.Error for service API and SDK errors. Use runtime type assertions
// with awserr.Error's Code and Message methods to get detailed information about
// the error.
//
// See the AWS API reference guide for Elastic Load Balancing's
// API operation SetSubnets for usage and error information.
//
// Returned Error Codes:
//   * ErrCodeLoadBalancerNotFoundException "LoadBalancerNotFound"
//   The specified load balancer does not exist.
//
//   * ErrCodeInvalidConfigurationRequestException "InvalidConfigurationRequest"
//   The requested configuration is not valid.
//
//   * ErrCodeSubnetNotFoundException "SubnetNotFound"
//   The specified subnet does not exist.
//
//   * ErrCodeInvalidSubnetException "InvalidSubnet"
//   The specified subnet is out of available addresses.
//
//   * ErrCodeAllocationIdNotFoundException "AllocationIdNotFound"
//   The specified allocation ID does not exist.
//
//   * ErrCodeAvailabilityZoneNotSupportedException "AvailabilityZoneNotSupported"
//   The specified Availability Zone is not supported.
//
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SetSubnets
func (c *ELBV2) SetSubnets(input *SetSubnetsInput) (*SetSubnetsOutput, error) {
	req, out := c.SetSubnetsRequest(input)
	return out, req.Send()
}

// SetSubnetsWithContext is the same as SetSubnets with the addition of
// the ability to pass a context and additional request options.
//
// See SetSubnets for details on how to use this API operation.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *ELBV2) SetSubnetsWithContext(ctx aws.Context, input *SetSubnetsInput, opts ...request.Option) (*SetSubnetsOutput, error) {
	req, out := c.SetSubnetsRequest(input)
	req.SetContext(ctx)
	req.ApplyOptions(opts...)
	return out, req.Send()
}

// Information about an action.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/Action
type Action struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) of the target group.
	//
	// TargetGroupArn is a required field
	TargetGroupArn *string `type:"string" required:"true"`

	// The type of action.
	//
	// Type is a required field
	Type *string `type:"string" required:"true" enum:"ActionTypeEnum"`
}

// String returns the string representation
func (s Action) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s Action) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *Action) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "Action"}
	if s.TargetGroupArn == nil {
		invalidParams.Add(request.NewErrParamRequired("TargetGroupArn"))
	}
	if s.Type == nil {
		invalidParams.Add(request.NewErrParamRequired("Type"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetTargetGroupArn sets the TargetGroupArn field's value.
func (s *Action) SetTargetGroupArn(v string) *Action {
	s.TargetGroupArn = &v
	return s
}

// SetType sets the Type field's value.
func (s *Action) SetType(v string) *Action {
	s.Type = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/AddListenerCertificatesInput
type AddListenerCertificatesInput struct {
	_ struct{} `type:"structure"`

	// The certificate to add. You can specify one certificate per call.
	//
	// Certificates is a required field
	Certificates []*Certificate `type:"list" required:"true"`

	// The Amazon Resource Name (ARN) of the listener.
	//
	// ListenerArn is a required field
	ListenerArn *string `type:"string" required:"true"`
}

// String returns the string representation
func (s AddListenerCertificatesInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s AddListenerCertificatesInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *AddListenerCertificatesInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "AddListenerCertificatesInput"}
	if s.Certificates == nil {
		invalidParams.Add(request.NewErrParamRequired("Certificates"))
	}
	if s.ListenerArn == nil {
		invalidParams.Add(request.NewErrParamRequired("ListenerArn"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetCertificates sets the Certificates field's value.
func (s *AddListenerCertificatesInput) SetCertificates(v []*Certificate) *AddListenerCertificatesInput {
	s.Certificates = v
	return s
}

// SetListenerArn sets the ListenerArn field's value.
func (s *AddListenerCertificatesInput) SetListenerArn(v string) *AddListenerCertificatesInput {
	s.ListenerArn = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/AddListenerCertificatesOutput
type AddListenerCertificatesOutput struct {
	_ struct{} `type:"structure"`

	// Information about the certificates.
	Certificates []*Certificate `type:"list"`
}

// String returns the string representation
func (s AddListenerCertificatesOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s AddListenerCertificatesOutput) GoString() string {
	return s.String()
}

// SetCertificates sets the Certificates field's value.
func (s *AddListenerCertificatesOutput) SetCertificates(v []*Certificate) *AddListenerCertificatesOutput {
	s.Certificates = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/AddTagsInput
type AddTagsInput struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) of the resource.
	//
	// ResourceArns is a required field
	ResourceArns []*string `type:"list" required:"true"`

	// The tags. Each resource can have a maximum of 10 tags.
	//
	// Tags is a required field
	Tags []*Tag `min:"1" type:"list" required:"true"`
}

// String returns the string representation
func (s AddTagsInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s AddTagsInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *AddTagsInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "AddTagsInput"}
	if s.ResourceArns == nil {
		invalidParams.Add(request.NewErrParamRequired("ResourceArns"))
	}
	if s.Tags == nil {
		invalidParams.Add(request.NewErrParamRequired("Tags"))
	}
	if s.Tags != nil && len(s.Tags) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("Tags", 1))
	}
	if s.Tags != nil {
		for i, v := range s.Tags {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams))
			}
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetResourceArns sets the ResourceArns field's value.
func (s *AddTagsInput) SetResourceArns(v []*string) *AddTagsInput {
	s.ResourceArns = v
	return s
}

// SetTags sets the Tags field's value.
func (s *AddTagsInput) SetTags(v []*Tag) *AddTagsInput {
	s.Tags = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/AddTagsOutput
type AddTagsOutput struct {
	_ struct{} `type:"structure"`
}

// String returns the string representation
func (s AddTagsOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s AddTagsOutput) GoString() string {
	return s.String()
}

// Information about an Availability Zone.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/AvailabilityZone
type AvailabilityZone struct {
	_ struct{} `type:"structure"`

	// [Network Load Balancers] The static IP address.
	LoadBalancerAddresses []*LoadBalancerAddress `type:"list"`

	// The ID of the subnet.
	SubnetId *string `type:"string"`

	// The name of the Availability Zone.
	ZoneName *string `type:"string"`
}

// String returns the string representation
func (s AvailabilityZone) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s AvailabilityZone) GoString() string {
	return s.String()
}

// SetLoadBalancerAddresses sets the LoadBalancerAddresses field's value.
func (s *AvailabilityZone) SetLoadBalancerAddresses(v []*LoadBalancerAddress) *AvailabilityZone {
	s.LoadBalancerAddresses = v
	return s
}

// SetSubnetId sets the SubnetId field's value.
func (s *AvailabilityZone) SetSubnetId(v string) *AvailabilityZone {
	s.SubnetId = &v
	return s
}

// SetZoneName sets the ZoneName field's value.
func (s *AvailabilityZone) SetZoneName(v string) *AvailabilityZone {
	s.ZoneName = &v
	return s
}

// Information about an SSL server certificate.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/Certificate
type Certificate struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) of the certificate.
	CertificateArn *string `type:"string"`

	// Indicates whether the certificate is the default certificate.
	IsDefault *bool `type:"boolean"`
}

// String returns the string representation
func (s Certificate) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s Certificate) GoString() string {
	return s.String()
}

// SetCertificateArn sets the CertificateArn field's value.
func (s *Certificate) SetCertificateArn(v string) *Certificate {
	s.CertificateArn = &v
	return s
}

// SetIsDefault sets the IsDefault field's value.
func (s *Certificate) SetIsDefault(v bool) *Certificate {
	s.IsDefault = &v
	return s
}

// Information about a cipher used in a policy.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/Cipher
type Cipher struct {
	_ struct{} `type:"structure"`

	// The name of the cipher.
	Name *string `type:"string"`

	// The priority of the cipher.
	Priority *int64 `type:"integer"`
}

// String returns the string representation
func (s Cipher) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s Cipher) GoString() string {
	return s.String()
}

// SetName sets the Name field's value.
func (s *Cipher) SetName(v string) *Cipher {
	s.Name = &v
	return s
}

// SetPriority sets the Priority field's value.
func (s *Cipher) SetPriority(v int64) *Cipher {
	s.Priority = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/CreateListenerInput
type CreateListenerInput struct {
	_ struct{} `type:"structure"`

	// [HTTPS listeners] The SSL server certificate. You must provide exactly one
	// certificate.
	Certificates []*Certificate `type:"list"`

	// The default action for the listener. For Application Load Balancers, the
	// protocol of the specified target group must be HTTP or HTTPS. For Network
	// Load Balancers, the protocol of the specified target group must be TCP.
	//
	// DefaultActions is a required field
	DefaultActions []*Action `type:"list" required:"true"`

	// The Amazon Resource Name (ARN) of the load balancer.
	//
	// LoadBalancerArn is a required field
	LoadBalancerArn *string `type:"string" required:"true"`

	// The port on which the load balancer is listening.
	//
	// Port is a required field
	Port *int64 `min:"1" type:"integer" required:"true"`

	// The protocol for connections from clients to the load balancer. For Application
	// Load Balancers, the supported protocols are HTTP and HTTPS. For Network Load
	// Balancers, the supported protocol is TCP.
	//
	// Protocol is a required field
	Protocol *string `type:"string" required:"true" enum:"ProtocolEnum"`

	// [HTTPS listeners] The security policy that defines which ciphers and protocols
	// are supported. The default is the current predefined security policy.
	SslPolicy *string `type:"string"`
}

// String returns the string representation
func (s CreateListenerInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s CreateListenerInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *CreateListenerInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "CreateListenerInput"}
	if s.DefaultActions == nil {
		invalidParams.Add(request.NewErrParamRequired("DefaultActions"))
	}
	if s.LoadBalancerArn == nil {
		invalidParams.Add(request.NewErrParamRequired("LoadBalancerArn"))
	}
	if s.Port == nil {
		invalidParams.Add(request.NewErrParamRequired("Port"))
	}
	if s.Port != nil && *s.Port < 1 {
		invalidParams.Add(request.NewErrParamMinValue("Port", 1))
	}
	if s.Protocol == nil {
		invalidParams.Add(request.NewErrParamRequired("Protocol"))
	}
	if s.DefaultActions != nil {
		for i, v := range s.DefaultActions {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "DefaultActions", i), err.(request.ErrInvalidParams))
			}
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetCertificates sets the Certificates field's value.
func (s *CreateListenerInput) SetCertificates(v []*Certificate) *CreateListenerInput {
	s.Certificates = v
	return s
}

// SetDefaultActions sets the DefaultActions field's value.
func (s *CreateListenerInput) SetDefaultActions(v []*Action) *CreateListenerInput {
	s.DefaultActions = v
	return s
}

// SetLoadBalancerArn sets the LoadBalancerArn field's value.
func (s *CreateListenerInput) SetLoadBalancerArn(v string) *CreateListenerInput {
	s.LoadBalancerArn = &v
	return s
}

// SetPort sets the Port field's value.
func (s *CreateListenerInput) SetPort(v int64) *CreateListenerInput {
	s.Port = &v
	return s
}

// SetProtocol sets the Protocol field's value.
func (s *CreateListenerInput) SetProtocol(v string) *CreateListenerInput {
	s.Protocol = &v
	return s
}

// SetSslPolicy sets the SslPolicy field's value.
func (s *CreateListenerInput) SetSslPolicy(v string) *CreateListenerInput {
	s.SslPolicy = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/CreateListenerOutput
type CreateListenerOutput struct {
	_ struct{} `type:"structure"`

	// Information about the listener.
	Listeners []*Listener `type:"list"`
}

// String returns the string representation
func (s CreateListenerOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s CreateListenerOutput) GoString() string {
	return s.String()
}

// SetListeners sets the Listeners field's value.
func (s *CreateListenerOutput) SetListeners(v []*Listener) *CreateListenerOutput {
	s.Listeners = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/CreateLoadBalancerInput
type CreateLoadBalancerInput struct {
	_ struct{} `type:"structure"`

	// [Application Load Balancers] The type of IP addresses used by the subnets
	// for your load balancer. The possible values are ipv4 (for IPv4 addresses)
	// and dualstack (for IPv4 and IPv6 addresses). Internal load balancers must
	// use ipv4.
	IpAddressType *string `type:"string" enum:"IpAddressType"`

	// The name of the load balancer.
	//
	// This name must be unique per region per account, can have a maximum of 32
	// characters, must contain only alphanumeric characters or hyphens, and must
	// not begin or end with a hyphen.
	//
	// Name is a required field
	Name *string `type:"string" required:"true"`

	// The nodes of an Internet-facing load balancer have public IP addresses. The
	// DNS name of an Internet-facing load balancer is publicly resolvable to the
	// public IP addresses of the nodes. Therefore, Internet-facing load balancers
	// can route requests from clients over the Internet.
	//
	// The nodes of an internal load balancer have only private IP addresses. The
	// DNS name of an internal load balancer is publicly resolvable to the private
	// IP addresses of the nodes. Therefore, internal load balancers can only route
	// requests from clients with access to the VPC for the load balancer.
	//
	// The default is an Internet-facing load balancer.
	Scheme *string `type:"string" enum:"LoadBalancerSchemeEnum"`

	// [Application Load Balancers] The IDs of the security groups to assign to
	// the load balancer.
	SecurityGroups []*string `type:"list"`

	// The IDs of the subnets to attach to the load balancer. You can specify only
	// one subnet per Availability Zone. You must specify either subnets or subnet
	// mappings.
	//
	// [Application Load Balancers] You must specify subnets from at least two Availability
	// Zones. You cannot specify Elastic IP addresses for your subnets.
	//
	// [Network Load Balancers] You can specify subnets from one or more Availability
	// Zones. You can specify one Elastic IP address per subnet.
	SubnetMappings []*SubnetMapping `type:"list"`

	// The IDs of the subnets to attach to the load balancer. You can specify only
	// one subnet per Availability Zone. You must specify either subnets or subnet
	// mappings.
	//
	// [Application Load Balancers] You must specify subnets from at least two Availability
	// Zones.
	//
	// [Network Load Balancers] You can specify subnets from one or more Availability
	// Zones.
	Subnets []*string `type:"list"`

	// One or more tags to assign to the load balancer.
	Tags []*Tag `min:"1" type:"list"`

	// The type of load balancer to create. The default is application.
	Type *string `type:"string" enum:"LoadBalancerTypeEnum"`
}

// String returns the string representation
func (s CreateLoadBalancerInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s CreateLoadBalancerInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *CreateLoadBalancerInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "CreateLoadBalancerInput"}
	if s.Name == nil {
		invalidParams.Add(request.NewErrParamRequired("Name"))
	}
	if s.Tags != nil && len(s.Tags) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("Tags", 1))
	}
	if s.Tags != nil {
		for i, v := range s.Tags {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams))
			}
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetIpAddressType sets the IpAddressType field's value.
func (s *CreateLoadBalancerInput) SetIpAddressType(v string) *CreateLoadBalancerInput {
	s.IpAddressType = &v
	return s
}

// SetName sets the Name field's value.
func (s *CreateLoadBalancerInput) SetName(v string) *CreateLoadBalancerInput {
	s.Name = &v
	return s
}

// SetScheme sets the Scheme field's value.
func (s *CreateLoadBalancerInput) SetScheme(v string) *CreateLoadBalancerInput {
	s.Scheme = &v
	return s
}

// SetSecurityGroups sets the SecurityGroups field's value.
func (s *CreateLoadBalancerInput) SetSecurityGroups(v []*string) *CreateLoadBalancerInput {
	s.SecurityGroups = v
	return s
}

// SetSubnetMappings sets the SubnetMappings field's value.
func (s *CreateLoadBalancerInput) SetSubnetMappings(v []*SubnetMapping) *CreateLoadBalancerInput {
	s.SubnetMappings = v
	return s
}

// SetSubnets sets the Subnets field's value.
func (s *CreateLoadBalancerInput) SetSubnets(v []*string) *CreateLoadBalancerInput {
	s.Subnets = v
	return s
}

// SetTags sets the Tags field's value.
func (s *CreateLoadBalancerInput) SetTags(v []*Tag) *CreateLoadBalancerInput {
	s.Tags = v
	return s
}

// SetType sets the Type field's value.
func (s *CreateLoadBalancerInput) SetType(v string) *CreateLoadBalancerInput {
	s.Type = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/CreateLoadBalancerOutput
type CreateLoadBalancerOutput struct {
	_ struct{} `type:"structure"`

	// Information about the load balancer.
	LoadBalancers []*LoadBalancer `type:"list"`
}

// String returns the string representation
func (s CreateLoadBalancerOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s CreateLoadBalancerOutput) GoString() string {
	return s.String()
}

// SetLoadBalancers sets the LoadBalancers field's value.
func (s *CreateLoadBalancerOutput) SetLoadBalancers(v []*LoadBalancer) *CreateLoadBalancerOutput {
	s.LoadBalancers = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/CreateRuleInput
type CreateRuleInput struct {
	_ struct{} `type:"structure"`

	// An action. Each action has the type forward and specifies a target group.
	//
	// Actions is a required field
	Actions []*Action `type:"list" required:"true"`

	// The conditions. Each condition specifies a field name and a single value.
	//
	// If the field name is host-header, you can specify a single host name (for
	// example, my.example.com). A host name is case insensitive, can be up to 128
	// characters in length, and can contain any of the following characters. Note
	// that you can include up to three wildcard characters.
	//
	//    * A-Z, a-z, 0-9
	//
	//    * - .
	//
	//    * * (matches 0 or more characters)
	//
	//    * ? (matches exactly 1 character)
	//
	// If the field name is path-pattern, you can specify a single path pattern.
	// A path pattern is case sensitive, can be up to 128 characters in length,
	// and can contain any of the following characters. Note that you can include
	// up to three wildcard characters.
	//
	//    * A-Z, a-z, 0-9
	//
	//    * _ - . $ / ~ " ' @ : +
	//
	//    * & (using &)
	//
	//    * * (matches 0 or more characters)
	//
	//    * ? (matches exactly 1 character)
	//
	// Conditions is a required field
	Conditions []*RuleCondition `type:"list" required:"true"`

	// The Amazon Resource Name (ARN) of the listener.
	//
	// ListenerArn is a required field
	ListenerArn *string `type:"string" required:"true"`

	// The priority for the rule. A listener can't have multiple rules with the
	// same priority.
	//
	// Priority is a required field
	Priority *int64 `min:"1" type:"integer" required:"true"`
}

// String returns the string representation
func (s CreateRuleInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s CreateRuleInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *CreateRuleInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "CreateRuleInput"}
	if s.Actions == nil {
		invalidParams.Add(request.NewErrParamRequired("Actions"))
	}
	if s.Conditions == nil {
		invalidParams.Add(request.NewErrParamRequired("Conditions"))
	}
	if s.ListenerArn == nil {
		invalidParams.Add(request.NewErrParamRequired("ListenerArn"))
	}
	if s.Priority == nil {
		invalidParams.Add(request.NewErrParamRequired("Priority"))
	}
	if s.Priority != nil && *s.Priority < 1 {
		invalidParams.Add(request.NewErrParamMinValue("Priority", 1))
	}
	if s.Actions != nil {
		for i, v := range s.Actions {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Actions", i), err.(request.ErrInvalidParams))
			}
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetActions sets the Actions field's value.
func (s *CreateRuleInput) SetActions(v []*Action) *CreateRuleInput {
	s.Actions = v
	return s
}

// SetConditions sets the Conditions field's value.
func (s *CreateRuleInput) SetConditions(v []*RuleCondition) *CreateRuleInput {
	s.Conditions = v
	return s
}

// SetListenerArn sets the ListenerArn field's value.
func (s *CreateRuleInput) SetListenerArn(v string) *CreateRuleInput {
	s.ListenerArn = &v
	return s
}

// SetPriority sets the Priority field's value.
func (s *CreateRuleInput) SetPriority(v int64) *CreateRuleInput {
	s.Priority = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/CreateRuleOutput
type CreateRuleOutput struct {
	_ struct{} `type:"structure"`

	// Information about the rule.
	Rules []*Rule `type:"list"`
}

// String returns the string representation
func (s CreateRuleOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s CreateRuleOutput) GoString() string {
	return s.String()
}

// SetRules sets the Rules field's value.
func (s *CreateRuleOutput) SetRules(v []*Rule) *CreateRuleOutput {
	s.Rules = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/CreateTargetGroupInput
type CreateTargetGroupInput struct {
	_ struct{} `type:"structure"`

	// The approximate amount of time, in seconds, between health checks of an individual
	// target. For Application Load Balancers, the range is 5 to 300 seconds. For
	// Network Load Balancers, the supported values are 10 or 30 seconds. The default
	// is 30 seconds.
	HealthCheckIntervalSeconds *int64 `min:"5" type:"integer"`

	// [HTTP/HTTPS health checks] The ping path that is the destination on the targets
	// for health checks. The default is /.
	HealthCheckPath *string `min:"1" type:"string"`

	// The port the load balancer uses when performing health checks on targets.
	// The default is traffic-port, which is the port on which each target receives
	// traffic from the load balancer.
	HealthCheckPort *string `type:"string"`

	// The protocol the load balancer uses when performing health checks on targets.
	// The TCP protocol is supported only if the protocol of the target group is
	// TCP. For Application Load Balancers, the default is HTTP. For Network Load
	// Balancers, the default is TCP.
	HealthCheckProtocol *string `type:"string" enum:"ProtocolEnum"`

	// The amount of time, in seconds, during which no response from a target means
	// a failed health check. For Application Load Balancers, the range is 2 to
	// 60 seconds and the default is 5 seconds. For Network Load Balancers, this
	// is 10 seconds for TCP and HTTPS health checks and 6 seconds for HTTP health
	// checks.
	HealthCheckTimeoutSeconds *int64 `min:"2" type:"integer"`

	// The number of consecutive health checks successes required before considering
	// an unhealthy target healthy. For Application Load Balancers, the default
	// is 5. For Network Load Balancers, the default is 3.
	HealthyThresholdCount *int64 `min:"2" type:"integer"`

	// [HTTP/HTTPS health checks] The HTTP codes to use when checking for a successful
	// response from a target.
	Matcher *Matcher `type:"structure"`

	// The name of the target group.
	//
	// This name must be unique per region per account, can have a maximum of 32
	// characters, must contain only alphanumeric characters or hyphens, and must
	// not begin or end with a hyphen.
	//
	// Name is a required field
	Name *string `type:"string" required:"true"`

	// The port on which the targets receive traffic. This port is used unless you
	// specify a port override when registering the target.
	//
	// Port is a required field
	Port *int64 `min:"1" type:"integer" required:"true"`

	// The protocol to use for routing traffic to the targets. For Application Load
	// Balancers, the supported protocols are HTTP and HTTPS. For Network Load Balancers,
	// the supported protocol is TCP.
	//
	// Protocol is a required field
	Protocol *string `type:"string" required:"true" enum:"ProtocolEnum"`

	// The type of target that you must specify when registering targets with this
	// target group. The possible values are instance (targets are specified by
	// instance ID) or ip (targets are specified by IP address). The default is
	// instance. Note that you can't specify targets for a target group using both
	// instance IDs and IP addresses.
	//
	// If the target type is ip, specify IP addresses from the subnets of the virtual
	// private cloud (VPC) for the target group, the RFC 1918 range (10.0.0.0/8,
	// 172.16.0.0/12, and 192.168.0.0/16), and the RFC 6598 range (172.16.31.10/10).
	// You can't specify publicly routable IP addresses.
	TargetType *string `type:"string" enum:"TargetTypeEnum"`

	// The number of consecutive health check failures required before considering
	// a target unhealthy. For Application Load Balancers, the default is 2. For
	// Network Load Balancers, this value must be the same as the healthy threshold
	// count.
	UnhealthyThresholdCount *int64 `min:"2" type:"integer"`

	// The identifier of the virtual private cloud (VPC).
	//
	// VpcId is a required field
	VpcId *string `type:"string" required:"true"`
}

// String returns the string representation
func (s CreateTargetGroupInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s CreateTargetGroupInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *CreateTargetGroupInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "CreateTargetGroupInput"}
	if s.HealthCheckIntervalSeconds != nil && *s.HealthCheckIntervalSeconds < 5 {
		invalidParams.Add(request.NewErrParamMinValue("HealthCheckIntervalSeconds", 5))
	}
	if s.HealthCheckPath != nil && len(*s.HealthCheckPath) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("HealthCheckPath", 1))
	}
	if s.HealthCheckTimeoutSeconds != nil && *s.HealthCheckTimeoutSeconds < 2 {
		invalidParams.Add(request.NewErrParamMinValue("HealthCheckTimeoutSeconds", 2))
	}
	if s.HealthyThresholdCount != nil && *s.HealthyThresholdCount < 2 {
		invalidParams.Add(request.NewErrParamMinValue("HealthyThresholdCount", 2))
	}
	if s.Name == nil {
		invalidParams.Add(request.NewErrParamRequired("Name"))
	}
	if s.Port == nil {
		invalidParams.Add(request.NewErrParamRequired("Port"))
	}
	if s.Port != nil && *s.Port < 1 {
		invalidParams.Add(request.NewErrParamMinValue("Port", 1))
	}
	if s.Protocol == nil {
		invalidParams.Add(request.NewErrParamRequired("Protocol"))
	}
	if s.UnhealthyThresholdCount != nil && *s.UnhealthyThresholdCount < 2 {
		invalidParams.Add(request.NewErrParamMinValue("UnhealthyThresholdCount", 2))
	}
	if s.VpcId == nil {
		invalidParams.Add(request.NewErrParamRequired("VpcId"))
	}
	if s.Matcher != nil {
		if err := s.Matcher.Validate(); err != nil {
			invalidParams.AddNested("Matcher", err.(request.ErrInvalidParams))
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetHealthCheckIntervalSeconds sets the HealthCheckIntervalSeconds field's value.
func (s *CreateTargetGroupInput) SetHealthCheckIntervalSeconds(v int64) *CreateTargetGroupInput {
	s.HealthCheckIntervalSeconds = &v
	return s
}

// SetHealthCheckPath sets the HealthCheckPath field's value.
func (s *CreateTargetGroupInput) SetHealthCheckPath(v string) *CreateTargetGroupInput {
	s.HealthCheckPath = &v
	return s
}

// SetHealthCheckPort sets the HealthCheckPort field's value.
func (s *CreateTargetGroupInput) SetHealthCheckPort(v string) *CreateTargetGroupInput {
	s.HealthCheckPort = &v
	return s
}

// SetHealthCheckProtocol sets the HealthCheckProtocol field's value.
func (s *CreateTargetGroupInput) SetHealthCheckProtocol(v string) *CreateTargetGroupInput {
	s.HealthCheckProtocol = &v
	return s
}

// SetHealthCheckTimeoutSeconds sets the HealthCheckTimeoutSeconds field's value.
func (s *CreateTargetGroupInput) SetHealthCheckTimeoutSeconds(v int64) *CreateTargetGroupInput {
	s.HealthCheckTimeoutSeconds = &v
	return s
}

// SetHealthyThresholdCount sets the HealthyThresholdCount field's value.
func (s *CreateTargetGroupInput) SetHealthyThresholdCount(v int64) *CreateTargetGroupInput {
	s.HealthyThresholdCount = &v
	return s
}

// SetMatcher sets the Matcher field's value.
func (s *CreateTargetGroupInput) SetMatcher(v *Matcher) *CreateTargetGroupInput {
	s.Matcher = v
	return s
}

// SetName sets the Name field's value.
func (s *CreateTargetGroupInput) SetName(v string) *CreateTargetGroupInput {
	s.Name = &v
	return s
}

// SetPort sets the Port field's value.
func (s *CreateTargetGroupInput) SetPort(v int64) *CreateTargetGroupInput {
	s.Port = &v
	return s
}

// SetProtocol sets the Protocol field's value.
func (s *CreateTargetGroupInput) SetProtocol(v string) *CreateTargetGroupInput {
	s.Protocol = &v
	return s
}

// SetTargetType sets the TargetType field's value.
func (s *CreateTargetGroupInput) SetTargetType(v string) *CreateTargetGroupInput {
	s.TargetType = &v
	return s
}

// SetUnhealthyThresholdCount sets the UnhealthyThresholdCount field's value.
func (s *CreateTargetGroupInput) SetUnhealthyThresholdCount(v int64) *CreateTargetGroupInput {
	s.UnhealthyThresholdCount = &v
	return s
}

// SetVpcId sets the VpcId field's value.
func (s *CreateTargetGroupInput) SetVpcId(v string) *CreateTargetGroupInput {
	s.VpcId = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/CreateTargetGroupOutput
type CreateTargetGroupOutput struct {
	_ struct{} `type:"structure"`

	// Information about the target group.
	TargetGroups []*TargetGroup `type:"list"`
}

// String returns the string representation
func (s CreateTargetGroupOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s CreateTargetGroupOutput) GoString() string {
	return s.String()
}

// SetTargetGroups sets the TargetGroups field's value.
func (s *CreateTargetGroupOutput) SetTargetGroups(v []*TargetGroup) *CreateTargetGroupOutput {
	s.TargetGroups = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeleteListenerInput
type DeleteListenerInput struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) of the listener.
	//
	// ListenerArn is a required field
	ListenerArn *string `type:"string" required:"true"`
}

// String returns the string representation
func (s DeleteListenerInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DeleteListenerInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DeleteListenerInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DeleteListenerInput"}
	if s.ListenerArn == nil {
		invalidParams.Add(request.NewErrParamRequired("ListenerArn"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetListenerArn sets the ListenerArn field's value.
func (s *DeleteListenerInput) SetListenerArn(v string) *DeleteListenerInput {
	s.ListenerArn = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeleteListenerOutput
type DeleteListenerOutput struct {
	_ struct{} `type:"structure"`
}

// String returns the string representation
func (s DeleteListenerOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DeleteListenerOutput) GoString() string {
	return s.String()
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeleteLoadBalancerInput
type DeleteLoadBalancerInput struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) of the load balancer.
	//
	// LoadBalancerArn is a required field
	LoadBalancerArn *string `type:"string" required:"true"`
}

// String returns the string representation
func (s DeleteLoadBalancerInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DeleteLoadBalancerInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DeleteLoadBalancerInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DeleteLoadBalancerInput"}
	if s.LoadBalancerArn == nil {
		invalidParams.Add(request.NewErrParamRequired("LoadBalancerArn"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetLoadBalancerArn sets the LoadBalancerArn field's value.
func (s *DeleteLoadBalancerInput) SetLoadBalancerArn(v string) *DeleteLoadBalancerInput {
	s.LoadBalancerArn = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeleteLoadBalancerOutput
type DeleteLoadBalancerOutput struct {
	_ struct{} `type:"structure"`
}

// String returns the string representation
func (s DeleteLoadBalancerOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DeleteLoadBalancerOutput) GoString() string {
	return s.String()
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeleteRuleInput
type DeleteRuleInput struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) of the rule.
	//
	// RuleArn is a required field
	RuleArn *string `type:"string" required:"true"`
}

// String returns the string representation
func (s DeleteRuleInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DeleteRuleInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DeleteRuleInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DeleteRuleInput"}
	if s.RuleArn == nil {
		invalidParams.Add(request.NewErrParamRequired("RuleArn"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetRuleArn sets the RuleArn field's value.
func (s *DeleteRuleInput) SetRuleArn(v string) *DeleteRuleInput {
	s.RuleArn = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeleteRuleOutput
type DeleteRuleOutput struct {
	_ struct{} `type:"structure"`
}

// String returns the string representation
func (s DeleteRuleOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DeleteRuleOutput) GoString() string {
	return s.String()
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeleteTargetGroupInput
type DeleteTargetGroupInput struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) of the target group.
	//
	// TargetGroupArn is a required field
	TargetGroupArn *string `type:"string" required:"true"`
}

// String returns the string representation
func (s DeleteTargetGroupInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DeleteTargetGroupInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DeleteTargetGroupInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DeleteTargetGroupInput"}
	if s.TargetGroupArn == nil {
		invalidParams.Add(request.NewErrParamRequired("TargetGroupArn"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetTargetGroupArn sets the TargetGroupArn field's value.
func (s *DeleteTargetGroupInput) SetTargetGroupArn(v string) *DeleteTargetGroupInput {
	s.TargetGroupArn = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeleteTargetGroupOutput
type DeleteTargetGroupOutput struct {
	_ struct{} `type:"structure"`
}

// String returns the string representation
func (s DeleteTargetGroupOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DeleteTargetGroupOutput) GoString() string {
	return s.String()
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeregisterTargetsInput
type DeregisterTargetsInput struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) of the target group.
	//
	// TargetGroupArn is a required field
	TargetGroupArn *string `type:"string" required:"true"`

	// The targets. If you specified a port override when you registered a target,
	// you must specify both the target ID and the port when you deregister it.
	//
	// Targets is a required field
	Targets []*TargetDescription `type:"list" required:"true"`
}

// String returns the string representation
func (s DeregisterTargetsInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DeregisterTargetsInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DeregisterTargetsInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DeregisterTargetsInput"}
	if s.TargetGroupArn == nil {
		invalidParams.Add(request.NewErrParamRequired("TargetGroupArn"))
	}
	if s.Targets == nil {
		invalidParams.Add(request.NewErrParamRequired("Targets"))
	}
	if s.Targets != nil {
		for i, v := range s.Targets {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Targets", i), err.(request.ErrInvalidParams))
			}
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetTargetGroupArn sets the TargetGroupArn field's value.
func (s *DeregisterTargetsInput) SetTargetGroupArn(v string) *DeregisterTargetsInput {
	s.TargetGroupArn = &v
	return s
}

// SetTargets sets the Targets field's value.
func (s *DeregisterTargetsInput) SetTargets(v []*TargetDescription) *DeregisterTargetsInput {
	s.Targets = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DeregisterTargetsOutput
type DeregisterTargetsOutput struct {
	_ struct{} `type:"structure"`
}

// String returns the string representation
func (s DeregisterTargetsOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DeregisterTargetsOutput) GoString() string {
	return s.String()
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeAccountLimitsInput
type DescribeAccountLimitsInput struct {
	_ struct{} `type:"structure"`

	// The marker for the next set of results. (You received this marker from a
	// previous call.)
	Marker *string `type:"string"`

	// The maximum number of results to return with this call.
	PageSize *int64 `min:"1" type:"integer"`
}

// String returns the string representation
func (s DescribeAccountLimitsInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeAccountLimitsInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DescribeAccountLimitsInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DescribeAccountLimitsInput"}
	if s.PageSize != nil && *s.PageSize < 1 {
		invalidParams.Add(request.NewErrParamMinValue("PageSize", 1))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetMarker sets the Marker field's value.
func (s *DescribeAccountLimitsInput) SetMarker(v string) *DescribeAccountLimitsInput {
	s.Marker = &v
	return s
}

// SetPageSize sets the PageSize field's value.
func (s *DescribeAccountLimitsInput) SetPageSize(v int64) *DescribeAccountLimitsInput {
	s.PageSize = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeAccountLimitsOutput
type DescribeAccountLimitsOutput struct {
	_ struct{} `type:"structure"`

	// Information about the limits.
	Limits []*Limit `type:"list"`

	// The marker to use when requesting the next set of results. If there are no
	// additional results, the string is empty.
	NextMarker *string `type:"string"`
}

// String returns the string representation
func (s DescribeAccountLimitsOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeAccountLimitsOutput) GoString() string {
	return s.String()
}

// SetLimits sets the Limits field's value.
func (s *DescribeAccountLimitsOutput) SetLimits(v []*Limit) *DescribeAccountLimitsOutput {
	s.Limits = v
	return s
}

// SetNextMarker sets the NextMarker field's value.
func (s *DescribeAccountLimitsOutput) SetNextMarker(v string) *DescribeAccountLimitsOutput {
	s.NextMarker = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeListenerCertificatesInput
type DescribeListenerCertificatesInput struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Names (ARN) of the listener.
	//
	// ListenerArn is a required field
	ListenerArn *string `type:"string" required:"true"`

	// The marker for the next set of results. (You received this marker from a
	// previous call.)
	Marker *string `type:"string"`

	// The maximum number of results to return with this call.
	PageSize *int64 `min:"1" type:"integer"`
}

// String returns the string representation
func (s DescribeListenerCertificatesInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeListenerCertificatesInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DescribeListenerCertificatesInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DescribeListenerCertificatesInput"}
	if s.ListenerArn == nil {
		invalidParams.Add(request.NewErrParamRequired("ListenerArn"))
	}
	if s.PageSize != nil && *s.PageSize < 1 {
		invalidParams.Add(request.NewErrParamMinValue("PageSize", 1))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetListenerArn sets the ListenerArn field's value.
func (s *DescribeListenerCertificatesInput) SetListenerArn(v string) *DescribeListenerCertificatesInput {
	s.ListenerArn = &v
	return s
}

// SetMarker sets the Marker field's value.
func (s *DescribeListenerCertificatesInput) SetMarker(v string) *DescribeListenerCertificatesInput {
	s.Marker = &v
	return s
}

// SetPageSize sets the PageSize field's value.
func (s *DescribeListenerCertificatesInput) SetPageSize(v int64) *DescribeListenerCertificatesInput {
	s.PageSize = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeListenerCertificatesOutput
type DescribeListenerCertificatesOutput struct {
	_ struct{} `type:"structure"`

	// Information about the certificates.
	Certificates []*Certificate `type:"list"`

	// The marker to use when requesting the next set of results. If there are no
	// additional results, the string is empty.
	NextMarker *string `type:"string"`
}

// String returns the string representation
func (s DescribeListenerCertificatesOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeListenerCertificatesOutput) GoString() string {
	return s.String()
}

// SetCertificates sets the Certificates field's value.
func (s *DescribeListenerCertificatesOutput) SetCertificates(v []*Certificate) *DescribeListenerCertificatesOutput {
	s.Certificates = v
	return s
}

// SetNextMarker sets the NextMarker field's value.
func (s *DescribeListenerCertificatesOutput) SetNextMarker(v string) *DescribeListenerCertificatesOutput {
	s.NextMarker = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeListenersInput
type DescribeListenersInput struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Names (ARN) of the listeners.
	ListenerArns []*string `type:"list"`

	// The Amazon Resource Name (ARN) of the load balancer.
	LoadBalancerArn *string `type:"string"`

	// The marker for the next set of results. (You received this marker from a
	// previous call.)
	Marker *string `type:"string"`

	// The maximum number of results to return with this call.
	PageSize *int64 `min:"1" type:"integer"`
}

// String returns the string representation
func (s DescribeListenersInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeListenersInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DescribeListenersInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DescribeListenersInput"}
	if s.PageSize != nil && *s.PageSize < 1 {
		invalidParams.Add(request.NewErrParamMinValue("PageSize", 1))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetListenerArns sets the ListenerArns field's value.
func (s *DescribeListenersInput) SetListenerArns(v []*string) *DescribeListenersInput {
	s.ListenerArns = v
	return s
}

// SetLoadBalancerArn sets the LoadBalancerArn field's value.
func (s *DescribeListenersInput) SetLoadBalancerArn(v string) *DescribeListenersInput {
	s.LoadBalancerArn = &v
	return s
}

// SetMarker sets the Marker field's value.
func (s *DescribeListenersInput) SetMarker(v string) *DescribeListenersInput {
	s.Marker = &v
	return s
}

// SetPageSize sets the PageSize field's value.
func (s *DescribeListenersInput) SetPageSize(v int64) *DescribeListenersInput {
	s.PageSize = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeListenersOutput
type DescribeListenersOutput struct {
	_ struct{} `type:"structure"`

	// Information about the listeners.
	Listeners []*Listener `type:"list"`

	// The marker to use when requesting the next set of results. If there are no
	// additional results, the string is empty.
	NextMarker *string `type:"string"`
}

// String returns the string representation
func (s DescribeListenersOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeListenersOutput) GoString() string {
	return s.String()
}

// SetListeners sets the Listeners field's value.
func (s *DescribeListenersOutput) SetListeners(v []*Listener) *DescribeListenersOutput {
	s.Listeners = v
	return s
}

// SetNextMarker sets the NextMarker field's value.
func (s *DescribeListenersOutput) SetNextMarker(v string) *DescribeListenersOutput {
	s.NextMarker = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancerAttributesInput
type DescribeLoadBalancerAttributesInput struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) of the load balancer.
	//
	// LoadBalancerArn is a required field
	LoadBalancerArn *string `type:"string" required:"true"`
}

// String returns the string representation
func (s DescribeLoadBalancerAttributesInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeLoadBalancerAttributesInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DescribeLoadBalancerAttributesInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DescribeLoadBalancerAttributesInput"}
	if s.LoadBalancerArn == nil {
		invalidParams.Add(request.NewErrParamRequired("LoadBalancerArn"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetLoadBalancerArn sets the LoadBalancerArn field's value.
func (s *DescribeLoadBalancerAttributesInput) SetLoadBalancerArn(v string) *DescribeLoadBalancerAttributesInput {
	s.LoadBalancerArn = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancerAttributesOutput
type DescribeLoadBalancerAttributesOutput struct {
	_ struct{} `type:"structure"`

	// Information about the load balancer attributes.
	Attributes []*LoadBalancerAttribute `type:"list"`
}

// String returns the string representation
func (s DescribeLoadBalancerAttributesOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeLoadBalancerAttributesOutput) GoString() string {
	return s.String()
}

// SetAttributes sets the Attributes field's value.
func (s *DescribeLoadBalancerAttributesOutput) SetAttributes(v []*LoadBalancerAttribute) *DescribeLoadBalancerAttributesOutput {
	s.Attributes = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancersInput
type DescribeLoadBalancersInput struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Names (ARN) of the load balancers. You can specify up
	// to 20 load balancers in a single call.
	LoadBalancerArns []*string `type:"list"`

	// The marker for the next set of results. (You received this marker from a
	// previous call.)
	Marker *string `type:"string"`

	// The names of the load balancers.
	Names []*string `type:"list"`

	// The maximum number of results to return with this call.
	PageSize *int64 `min:"1" type:"integer"`
}

// String returns the string representation
func (s DescribeLoadBalancersInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeLoadBalancersInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DescribeLoadBalancersInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DescribeLoadBalancersInput"}
	if s.PageSize != nil && *s.PageSize < 1 {
		invalidParams.Add(request.NewErrParamMinValue("PageSize", 1))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetLoadBalancerArns sets the LoadBalancerArns field's value.
func (s *DescribeLoadBalancersInput) SetLoadBalancerArns(v []*string) *DescribeLoadBalancersInput {
	s.LoadBalancerArns = v
	return s
}

// SetMarker sets the Marker field's value.
func (s *DescribeLoadBalancersInput) SetMarker(v string) *DescribeLoadBalancersInput {
	s.Marker = &v
	return s
}

// SetNames sets the Names field's value.
func (s *DescribeLoadBalancersInput) SetNames(v []*string) *DescribeLoadBalancersInput {
	s.Names = v
	return s
}

// SetPageSize sets the PageSize field's value.
func (s *DescribeLoadBalancersInput) SetPageSize(v int64) *DescribeLoadBalancersInput {
	s.PageSize = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancersOutput
type DescribeLoadBalancersOutput struct {
	_ struct{} `type:"structure"`

	// Information about the load balancers.
	LoadBalancers []*LoadBalancer `type:"list"`

	// The marker to use when requesting the next set of results. If there are no
	// additional results, the string is empty.
	NextMarker *string `type:"string"`
}

// String returns the string representation
func (s DescribeLoadBalancersOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeLoadBalancersOutput) GoString() string {
	return s.String()
}

// SetLoadBalancers sets the LoadBalancers field's value.
func (s *DescribeLoadBalancersOutput) SetLoadBalancers(v []*LoadBalancer) *DescribeLoadBalancersOutput {
	s.LoadBalancers = v
	return s
}

// SetNextMarker sets the NextMarker field's value.
func (s *DescribeLoadBalancersOutput) SetNextMarker(v string) *DescribeLoadBalancersOutput {
	s.NextMarker = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeRulesInput
type DescribeRulesInput struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) of the listener.
	ListenerArn *string `type:"string"`

	// The marker for the next set of results. (You received this marker from a
	// previous call.)
	Marker *string `type:"string"`

	// The maximum number of results to return with this call.
	PageSize *int64 `min:"1" type:"integer"`

	// The Amazon Resource Names (ARN) of the rules.
	RuleArns []*string `type:"list"`
}

// String returns the string representation
func (s DescribeRulesInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeRulesInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DescribeRulesInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DescribeRulesInput"}
	if s.PageSize != nil && *s.PageSize < 1 {
		invalidParams.Add(request.NewErrParamMinValue("PageSize", 1))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetListenerArn sets the ListenerArn field's value.
func (s *DescribeRulesInput) SetListenerArn(v string) *DescribeRulesInput {
	s.ListenerArn = &v
	return s
}

// SetMarker sets the Marker field's value.
func (s *DescribeRulesInput) SetMarker(v string) *DescribeRulesInput {
	s.Marker = &v
	return s
}

// SetPageSize sets the PageSize field's value.
func (s *DescribeRulesInput) SetPageSize(v int64) *DescribeRulesInput {
	s.PageSize = &v
	return s
}

// SetRuleArns sets the RuleArns field's value.
func (s *DescribeRulesInput) SetRuleArns(v []*string) *DescribeRulesInput {
	s.RuleArns = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeRulesOutput
type DescribeRulesOutput struct {
	_ struct{} `type:"structure"`

	// The marker to use when requesting the next set of results. If there are no
	// additional results, the string is empty.
	NextMarker *string `type:"string"`

	// Information about the rules.
	Rules []*Rule `type:"list"`
}

// String returns the string representation
func (s DescribeRulesOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeRulesOutput) GoString() string {
	return s.String()
}

// SetNextMarker sets the NextMarker field's value.
func (s *DescribeRulesOutput) SetNextMarker(v string) *DescribeRulesOutput {
	s.NextMarker = &v
	return s
}

// SetRules sets the Rules field's value.
func (s *DescribeRulesOutput) SetRules(v []*Rule) *DescribeRulesOutput {
	s.Rules = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeSSLPoliciesInput
type DescribeSSLPoliciesInput struct {
	_ struct{} `type:"structure"`

	// The marker for the next set of results. (You received this marker from a
	// previous call.)
	Marker *string `type:"string"`

	// The names of the policies.
	Names []*string `type:"list"`

	// The maximum number of results to return with this call.
	PageSize *int64 `min:"1" type:"integer"`
}

// String returns the string representation
func (s DescribeSSLPoliciesInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeSSLPoliciesInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DescribeSSLPoliciesInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DescribeSSLPoliciesInput"}
	if s.PageSize != nil && *s.PageSize < 1 {
		invalidParams.Add(request.NewErrParamMinValue("PageSize", 1))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetMarker sets the Marker field's value.
func (s *DescribeSSLPoliciesInput) SetMarker(v string) *DescribeSSLPoliciesInput {
	s.Marker = &v
	return s
}

// SetNames sets the Names field's value.
func (s *DescribeSSLPoliciesInput) SetNames(v []*string) *DescribeSSLPoliciesInput {
	s.Names = v
	return s
}

// SetPageSize sets the PageSize field's value.
func (s *DescribeSSLPoliciesInput) SetPageSize(v int64) *DescribeSSLPoliciesInput {
	s.PageSize = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeSSLPoliciesOutput
type DescribeSSLPoliciesOutput struct {
	_ struct{} `type:"structure"`

	// The marker to use when requesting the next set of results. If there are no
	// additional results, the string is empty.
	NextMarker *string `type:"string"`

	// Information about the policies.
	SslPolicies []*SslPolicy `type:"list"`
}

// String returns the string representation
func (s DescribeSSLPoliciesOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeSSLPoliciesOutput) GoString() string {
	return s.String()
}

// SetNextMarker sets the NextMarker field's value.
func (s *DescribeSSLPoliciesOutput) SetNextMarker(v string) *DescribeSSLPoliciesOutput {
	s.NextMarker = &v
	return s
}

// SetSslPolicies sets the SslPolicies field's value.
func (s *DescribeSSLPoliciesOutput) SetSslPolicies(v []*SslPolicy) *DescribeSSLPoliciesOutput {
	s.SslPolicies = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeTagsInput
type DescribeTagsInput struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Names (ARN) of the resources.
	//
	// ResourceArns is a required field
	ResourceArns []*string `type:"list" required:"true"`
}

// String returns the string representation
func (s DescribeTagsInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeTagsInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DescribeTagsInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DescribeTagsInput"}
	if s.ResourceArns == nil {
		invalidParams.Add(request.NewErrParamRequired("ResourceArns"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetResourceArns sets the ResourceArns field's value.
func (s *DescribeTagsInput) SetResourceArns(v []*string) *DescribeTagsInput {
	s.ResourceArns = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeTagsOutput
type DescribeTagsOutput struct {
	_ struct{} `type:"structure"`

	// Information about the tags.
	TagDescriptions []*TagDescription `type:"list"`
}

// String returns the string representation
func (s DescribeTagsOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeTagsOutput) GoString() string {
	return s.String()
}

// SetTagDescriptions sets the TagDescriptions field's value.
func (s *DescribeTagsOutput) SetTagDescriptions(v []*TagDescription) *DescribeTagsOutput {
	s.TagDescriptions = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeTargetGroupAttributesInput
type DescribeTargetGroupAttributesInput struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) of the target group.
	//
	// TargetGroupArn is a required field
	TargetGroupArn *string `type:"string" required:"true"`
}

// String returns the string representation
func (s DescribeTargetGroupAttributesInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeTargetGroupAttributesInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DescribeTargetGroupAttributesInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DescribeTargetGroupAttributesInput"}
	if s.TargetGroupArn == nil {
		invalidParams.Add(request.NewErrParamRequired("TargetGroupArn"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetTargetGroupArn sets the TargetGroupArn field's value.
func (s *DescribeTargetGroupAttributesInput) SetTargetGroupArn(v string) *DescribeTargetGroupAttributesInput {
	s.TargetGroupArn = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeTargetGroupAttributesOutput
type DescribeTargetGroupAttributesOutput struct {
	_ struct{} `type:"structure"`

	// Information about the target group attributes
	Attributes []*TargetGroupAttribute `type:"list"`
}

// String returns the string representation
func (s DescribeTargetGroupAttributesOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeTargetGroupAttributesOutput) GoString() string {
	return s.String()
}

// SetAttributes sets the Attributes field's value.
func (s *DescribeTargetGroupAttributesOutput) SetAttributes(v []*TargetGroupAttribute) *DescribeTargetGroupAttributesOutput {
	s.Attributes = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeTargetGroupsInput
type DescribeTargetGroupsInput struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) of the load balancer.
	LoadBalancerArn *string `type:"string"`

	// The marker for the next set of results. (You received this marker from a
	// previous call.)
	Marker *string `type:"string"`

	// The names of the target groups.
	Names []*string `type:"list"`

	// The maximum number of results to return with this call.
	PageSize *int64 `min:"1" type:"integer"`

	// The Amazon Resource Names (ARN) of the target groups.
	TargetGroupArns []*string `type:"list"`
}

// String returns the string representation
func (s DescribeTargetGroupsInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeTargetGroupsInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DescribeTargetGroupsInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DescribeTargetGroupsInput"}
	if s.PageSize != nil && *s.PageSize < 1 {
		invalidParams.Add(request.NewErrParamMinValue("PageSize", 1))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetLoadBalancerArn sets the LoadBalancerArn field's value.
func (s *DescribeTargetGroupsInput) SetLoadBalancerArn(v string) *DescribeTargetGroupsInput {
	s.LoadBalancerArn = &v
	return s
}

// SetMarker sets the Marker field's value.
func (s *DescribeTargetGroupsInput) SetMarker(v string) *DescribeTargetGroupsInput {
	s.Marker = &v
	return s
}

// SetNames sets the Names field's value.
func (s *DescribeTargetGroupsInput) SetNames(v []*string) *DescribeTargetGroupsInput {
	s.Names = v
	return s
}

// SetPageSize sets the PageSize field's value.
func (s *DescribeTargetGroupsInput) SetPageSize(v int64) *DescribeTargetGroupsInput {
	s.PageSize = &v
	return s
}

// SetTargetGroupArns sets the TargetGroupArns field's value.
func (s *DescribeTargetGroupsInput) SetTargetGroupArns(v []*string) *DescribeTargetGroupsInput {
	s.TargetGroupArns = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeTargetGroupsOutput
type DescribeTargetGroupsOutput struct {
	_ struct{} `type:"structure"`

	// The marker to use when requesting the next set of results. If there are no
	// additional results, the string is empty.
	NextMarker *string `type:"string"`

	// Information about the target groups.
	TargetGroups []*TargetGroup `type:"list"`
}

// String returns the string representation
func (s DescribeTargetGroupsOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeTargetGroupsOutput) GoString() string {
	return s.String()
}

// SetNextMarker sets the NextMarker field's value.
func (s *DescribeTargetGroupsOutput) SetNextMarker(v string) *DescribeTargetGroupsOutput {
	s.NextMarker = &v
	return s
}

// SetTargetGroups sets the TargetGroups field's value.
func (s *DescribeTargetGroupsOutput) SetTargetGroups(v []*TargetGroup) *DescribeTargetGroupsOutput {
	s.TargetGroups = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeTargetHealthInput
type DescribeTargetHealthInput struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) of the target group.
	//
	// TargetGroupArn is a required field
	TargetGroupArn *string `type:"string" required:"true"`

	// The targets.
	Targets []*TargetDescription `type:"list"`
}

// String returns the string representation
func (s DescribeTargetHealthInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeTargetHealthInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *DescribeTargetHealthInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DescribeTargetHealthInput"}
	if s.TargetGroupArn == nil {
		invalidParams.Add(request.NewErrParamRequired("TargetGroupArn"))
	}
	if s.Targets != nil {
		for i, v := range s.Targets {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Targets", i), err.(request.ErrInvalidParams))
			}
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetTargetGroupArn sets the TargetGroupArn field's value.
func (s *DescribeTargetHealthInput) SetTargetGroupArn(v string) *DescribeTargetHealthInput {
	s.TargetGroupArn = &v
	return s
}

// SetTargets sets the Targets field's value.
func (s *DescribeTargetHealthInput) SetTargets(v []*TargetDescription) *DescribeTargetHealthInput {
	s.Targets = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/DescribeTargetHealthOutput
type DescribeTargetHealthOutput struct {
	_ struct{} `type:"structure"`

	// Information about the health of the targets.
	TargetHealthDescriptions []*TargetHealthDescription `type:"list"`
}

// String returns the string representation
func (s DescribeTargetHealthOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s DescribeTargetHealthOutput) GoString() string {
	return s.String()
}

// SetTargetHealthDescriptions sets the TargetHealthDescriptions field's value.
func (s *DescribeTargetHealthOutput) SetTargetHealthDescriptions(v []*TargetHealthDescription) *DescribeTargetHealthOutput {
	s.TargetHealthDescriptions = v
	return s
}

// Information about an Elastic Load Balancing resource limit for your AWS account.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/Limit
type Limit struct {
	_ struct{} `type:"structure"`

	// The maximum value of the limit.
	Max *string `type:"string"`

	// The name of the limit. The possible values are:
	//
	//    * application-load-balancers
	//
	//    * listeners-per-application-load-balancer
	//
	//    * listeners-per-network-load-balancer
	//
	//    * network-load-balancers
	//
	//    * rules-per-application-load-balancer
	//
	//    * target-groups
	//
	//    * targets-per-application-load-balancer
	//
	//    * targets-per-availability-zone-per-network-load-balancer
	//
	//    * targets-per-network-load-balancer
	Name *string `type:"string"`
}

// String returns the string representation
func (s Limit) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s Limit) GoString() string {
	return s.String()
}

// SetMax sets the Max field's value.
func (s *Limit) SetMax(v string) *Limit {
	s.Max = &v
	return s
}

// SetName sets the Name field's value.
func (s *Limit) SetName(v string) *Limit {
	s.Name = &v
	return s
}

// Information about a listener.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/Listener
type Listener struct {
	_ struct{} `type:"structure"`

	// The SSL server certificate. You must provide a certificate if the protocol
	// is HTTPS.
	Certificates []*Certificate `type:"list"`

	// The default actions for the listener.
	DefaultActions []*Action `type:"list"`

	// The Amazon Resource Name (ARN) of the listener.
	ListenerArn *string `type:"string"`

	// The Amazon Resource Name (ARN) of the load balancer.
	LoadBalancerArn *string `type:"string"`

	// The port on which the load balancer is listening.
	Port *int64 `min:"1" type:"integer"`

	// The protocol for connections from clients to the load balancer.
	Protocol *string `type:"string" enum:"ProtocolEnum"`

	// The security policy that defines which ciphers and protocols are supported.
	// The default is the current predefined security policy.
	SslPolicy *string `type:"string"`
}

// String returns the string representation
func (s Listener) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s Listener) GoString() string {
	return s.String()
}

// SetCertificates sets the Certificates field's value.
func (s *Listener) SetCertificates(v []*Certificate) *Listener {
	s.Certificates = v
	return s
}

// SetDefaultActions sets the DefaultActions field's value.
func (s *Listener) SetDefaultActions(v []*Action) *Listener {
	s.DefaultActions = v
	return s
}

// SetListenerArn sets the ListenerArn field's value.
func (s *Listener) SetListenerArn(v string) *Listener {
	s.ListenerArn = &v
	return s
}

// SetLoadBalancerArn sets the LoadBalancerArn field's value.
func (s *Listener) SetLoadBalancerArn(v string) *Listener {
	s.LoadBalancerArn = &v
	return s
}

// SetPort sets the Port field's value.
func (s *Listener) SetPort(v int64) *Listener {
	s.Port = &v
	return s
}

// SetProtocol sets the Protocol field's value.
func (s *Listener) SetProtocol(v string) *Listener {
	s.Protocol = &v
	return s
}

// SetSslPolicy sets the SslPolicy field's value.
func (s *Listener) SetSslPolicy(v string) *Listener {
	s.SslPolicy = &v
	return s
}

// Information about a load balancer.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/LoadBalancer
type LoadBalancer struct {
	_ struct{} `type:"structure"`

	// The Availability Zones for the load balancer.
	AvailabilityZones []*AvailabilityZone `type:"list"`

	// The ID of the Amazon Route 53 hosted zone associated with the load balancer.
	CanonicalHostedZoneId *string `type:"string"`

	// The date and time the load balancer was created.
	CreatedTime *time.Time `type:"timestamp" timestampFormat:"iso8601"`

	// The public DNS name of the load balancer.
	DNSName *string `type:"string"`

	// The type of IP addresses used by the subnets for your load balancer. The
	// possible values are ipv4 (for IPv4 addresses) and dualstack (for IPv4 and
	// IPv6 addresses).
	IpAddressType *string `type:"string" enum:"IpAddressType"`

	// The Amazon Resource Name (ARN) of the load balancer.
	LoadBalancerArn *string `type:"string"`

	// The name of the load balancer.
	LoadBalancerName *string `type:"string"`

	// The nodes of an Internet-facing load balancer have public IP addresses. The
	// DNS name of an Internet-facing load balancer is publicly resolvable to the
	// public IP addresses of the nodes. Therefore, Internet-facing load balancers
	// can route requests from clients over the Internet.
	//
	// The nodes of an internal load balancer have only private IP addresses. The
	// DNS name of an internal load balancer is publicly resolvable to the private
	// IP addresses of the nodes. Therefore, internal load balancers can only route
	// requests from clients with access to the VPC for the load balancer.
	Scheme *string `type:"string" enum:"LoadBalancerSchemeEnum"`

	// The IDs of the security groups for the load balancer.
	SecurityGroups []*string `type:"list"`

	// The state of the load balancer.
	State *LoadBalancerState `type:"structure"`

	// The type of load balancer.
	Type *string `type:"string" enum:"LoadBalancerTypeEnum"`

	// The ID of the VPC for the load balancer.
	VpcId *string `type:"string"`
}

// String returns the string representation
func (s LoadBalancer) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s LoadBalancer) GoString() string {
	return s.String()
}

// SetAvailabilityZones sets the AvailabilityZones field's value.
func (s *LoadBalancer) SetAvailabilityZones(v []*AvailabilityZone) *LoadBalancer {
	s.AvailabilityZones = v
	return s
}

// SetCanonicalHostedZoneId sets the CanonicalHostedZoneId field's value.
func (s *LoadBalancer) SetCanonicalHostedZoneId(v string) *LoadBalancer {
	s.CanonicalHostedZoneId = &v
	return s
}

// SetCreatedTime sets the CreatedTime field's value.
func (s *LoadBalancer) SetCreatedTime(v time.Time) *LoadBalancer {
	s.CreatedTime = &v
	return s
}

// SetDNSName sets the DNSName field's value.
func (s *LoadBalancer) SetDNSName(v string) *LoadBalancer {
	s.DNSName = &v
	return s
}

// SetIpAddressType sets the IpAddressType field's value.
func (s *LoadBalancer) SetIpAddressType(v string) *LoadBalancer {
	s.IpAddressType = &v
	return s
}

// SetLoadBalancerArn sets the LoadBalancerArn field's value.
func (s *LoadBalancer) SetLoadBalancerArn(v string) *LoadBalancer {
	s.LoadBalancerArn = &v
	return s
}

// SetLoadBalancerName sets the LoadBalancerName field's value.
func (s *LoadBalancer) SetLoadBalancerName(v string) *LoadBalancer {
	s.LoadBalancerName = &v
	return s
}

// SetScheme sets the Scheme field's value.
func (s *LoadBalancer) SetScheme(v string) *LoadBalancer {
	s.Scheme = &v
	return s
}

// SetSecurityGroups sets the SecurityGroups field's value.
func (s *LoadBalancer) SetSecurityGroups(v []*string) *LoadBalancer {
	s.SecurityGroups = v
	return s
}

// SetState sets the State field's value.
func (s *LoadBalancer) SetState(v *LoadBalancerState) *LoadBalancer {
	s.State = v
	return s
}

// SetType sets the Type field's value.
func (s *LoadBalancer) SetType(v string) *LoadBalancer {
	s.Type = &v
	return s
}

// SetVpcId sets the VpcId field's value.
func (s *LoadBalancer) SetVpcId(v string) *LoadBalancer {
	s.VpcId = &v
	return s
}

// Information about a static IP address for a load balancer.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/LoadBalancerAddress
type LoadBalancerAddress struct {
	_ struct{} `type:"structure"`

	// [Network Load Balancers] The allocation ID of the Elastic IP address.
	AllocationId *string `type:"string"`

	// The static IP address.
	IpAddress *string `type:"string"`
}

// String returns the string representation
func (s LoadBalancerAddress) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s LoadBalancerAddress) GoString() string {
	return s.String()
}

// SetAllocationId sets the AllocationId field's value.
func (s *LoadBalancerAddress) SetAllocationId(v string) *LoadBalancerAddress {
	s.AllocationId = &v
	return s
}

// SetIpAddress sets the IpAddress field's value.
func (s *LoadBalancerAddress) SetIpAddress(v string) *LoadBalancerAddress {
	s.IpAddress = &v
	return s
}

// Information about a load balancer attribute.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/LoadBalancerAttribute
type LoadBalancerAttribute struct {
	_ struct{} `type:"structure"`

	// The name of the attribute.
	//
	//    * access_logs.s3.enabled - [Application Load Balancers] Indicates whether
	//    access logs stored in Amazon S3 are enabled. The value is true or false.
	//
	//    * access_logs.s3.bucket - [Application Load Balancers] The name of the
	//    S3 bucket for the access logs. This attribute is required if access logs
	//    in Amazon S3 are enabled. The bucket must exist in the same region as
	//    the load balancer and have a bucket policy that grants Elastic Load Balancing
	//    permission to write to the bucket.
	//
	//    * access_logs.s3.prefix - [Application Load Balancers] The prefix for
	//    the location in the S3 bucket. If you don't specify a prefix, the access
	//    logs are stored in the root of the bucket.
	//
	//    * deletion_protection.enabled - Indicates whether deletion protection
	//    is enabled. The value is true or false.
	//
	//    * idle_timeout.timeout_seconds - [Application Load Balancers] The idle
	//    timeout value, in seconds. The valid range is 1-4000. The default is 60
	//    seconds.
	Key *string `type:"string"`

	// The value of the attribute.
	Value *string `type:"string"`
}

// String returns the string representation
func (s LoadBalancerAttribute) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s LoadBalancerAttribute) GoString() string {
	return s.String()
}

// SetKey sets the Key field's value.
func (s *LoadBalancerAttribute) SetKey(v string) *LoadBalancerAttribute {
	s.Key = &v
	return s
}

// SetValue sets the Value field's value.
func (s *LoadBalancerAttribute) SetValue(v string) *LoadBalancerAttribute {
	s.Value = &v
	return s
}

// Information about the state of the load balancer.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/LoadBalancerState
type LoadBalancerState struct {
	_ struct{} `type:"structure"`

	// The state code. The initial state of the load balancer is provisioning. After
	// the load balancer is fully set up and ready to route traffic, its state is
	// active. If the load balancer could not be set up, its state is failed.
	Code *string `type:"string" enum:"LoadBalancerStateEnum"`

	// A description of the state.
	Reason *string `type:"string"`
}

// String returns the string representation
func (s LoadBalancerState) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s LoadBalancerState) GoString() string {
	return s.String()
}

// SetCode sets the Code field's value.
func (s *LoadBalancerState) SetCode(v string) *LoadBalancerState {
	s.Code = &v
	return s
}

// SetReason sets the Reason field's value.
func (s *LoadBalancerState) SetReason(v string) *LoadBalancerState {
	s.Reason = &v
	return s
}

// Information to use when checking for a successful response from a target.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/Matcher
type Matcher struct {
	_ struct{} `type:"structure"`

	// The HTTP codes.
	//
	// For Application Load Balancers, you can specify values between 200 and 499,
	// and the default value is 200. You can specify multiple values (for example,
	// "200,202") or a range of values (for example, "200-299").
	//
	// For Network Load Balancers, this is 200 to 399.
	//
	// HttpCode is a required field
	HttpCode *string `type:"string" required:"true"`
}

// String returns the string representation
func (s Matcher) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s Matcher) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *Matcher) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "Matcher"}
	if s.HttpCode == nil {
		invalidParams.Add(request.NewErrParamRequired("HttpCode"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetHttpCode sets the HttpCode field's value.
func (s *Matcher) SetHttpCode(v string) *Matcher {
	s.HttpCode = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyListenerInput
type ModifyListenerInput struct {
	_ struct{} `type:"structure"`

	// The default SSL server certificate.
	Certificates []*Certificate `type:"list"`

	// The default action. For Application Load Balancers, the protocol of the specified
	// target group must be HTTP or HTTPS. For Network Load Balancers, the protocol
	// of the specified target group must be TCP.
	DefaultActions []*Action `type:"list"`

	// The Amazon Resource Name (ARN) of the listener.
	//
	// ListenerArn is a required field
	ListenerArn *string `type:"string" required:"true"`

	// The port for connections from clients to the load balancer.
	Port *int64 `min:"1" type:"integer"`

	// The protocol for connections from clients to the load balancer. Application
	// Load Balancers support HTTP and HTTPS and Network Load Balancers support
	// TCP.
	Protocol *string `type:"string" enum:"ProtocolEnum"`

	// The security policy that defines which protocols and ciphers are supported.
	// For more information, see Security Policies (http://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-https-listener.html#describe-ssl-policies)
	// in the Application Load Balancers Guide.
	SslPolicy *string `type:"string"`
}

// String returns the string representation
func (s ModifyListenerInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s ModifyListenerInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *ModifyListenerInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "ModifyListenerInput"}
	if s.ListenerArn == nil {
		invalidParams.Add(request.NewErrParamRequired("ListenerArn"))
	}
	if s.Port != nil && *s.Port < 1 {
		invalidParams.Add(request.NewErrParamMinValue("Port", 1))
	}
	if s.DefaultActions != nil {
		for i, v := range s.DefaultActions {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "DefaultActions", i), err.(request.ErrInvalidParams))
			}
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetCertificates sets the Certificates field's value.
func (s *ModifyListenerInput) SetCertificates(v []*Certificate) *ModifyListenerInput {
	s.Certificates = v
	return s
}

// SetDefaultActions sets the DefaultActions field's value.
func (s *ModifyListenerInput) SetDefaultActions(v []*Action) *ModifyListenerInput {
	s.DefaultActions = v
	return s
}

// SetListenerArn sets the ListenerArn field's value.
func (s *ModifyListenerInput) SetListenerArn(v string) *ModifyListenerInput {
	s.ListenerArn = &v
	return s
}

// SetPort sets the Port field's value.
func (s *ModifyListenerInput) SetPort(v int64) *ModifyListenerInput {
	s.Port = &v
	return s
}

// SetProtocol sets the Protocol field's value.
func (s *ModifyListenerInput) SetProtocol(v string) *ModifyListenerInput {
	s.Protocol = &v
	return s
}

// SetSslPolicy sets the SslPolicy field's value.
func (s *ModifyListenerInput) SetSslPolicy(v string) *ModifyListenerInput {
	s.SslPolicy = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyListenerOutput
type ModifyListenerOutput struct {
	_ struct{} `type:"structure"`

	// Information about the modified listeners.
	Listeners []*Listener `type:"list"`
}

// String returns the string representation
func (s ModifyListenerOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s ModifyListenerOutput) GoString() string {
	return s.String()
}

// SetListeners sets the Listeners field's value.
func (s *ModifyListenerOutput) SetListeners(v []*Listener) *ModifyListenerOutput {
	s.Listeners = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyLoadBalancerAttributesInput
type ModifyLoadBalancerAttributesInput struct {
	_ struct{} `type:"structure"`

	// The load balancer attributes.
	//
	// Attributes is a required field
	Attributes []*LoadBalancerAttribute `type:"list" required:"true"`

	// The Amazon Resource Name (ARN) of the load balancer.
	//
	// LoadBalancerArn is a required field
	LoadBalancerArn *string `type:"string" required:"true"`
}

// String returns the string representation
func (s ModifyLoadBalancerAttributesInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s ModifyLoadBalancerAttributesInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *ModifyLoadBalancerAttributesInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "ModifyLoadBalancerAttributesInput"}
	if s.Attributes == nil {
		invalidParams.Add(request.NewErrParamRequired("Attributes"))
	}
	if s.LoadBalancerArn == nil {
		invalidParams.Add(request.NewErrParamRequired("LoadBalancerArn"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetAttributes sets the Attributes field's value.
func (s *ModifyLoadBalancerAttributesInput) SetAttributes(v []*LoadBalancerAttribute) *ModifyLoadBalancerAttributesInput {
	s.Attributes = v
	return s
}

// SetLoadBalancerArn sets the LoadBalancerArn field's value.
func (s *ModifyLoadBalancerAttributesInput) SetLoadBalancerArn(v string) *ModifyLoadBalancerAttributesInput {
	s.LoadBalancerArn = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyLoadBalancerAttributesOutput
type ModifyLoadBalancerAttributesOutput struct {
	_ struct{} `type:"structure"`

	// Information about the load balancer attributes.
	Attributes []*LoadBalancerAttribute `type:"list"`
}

// String returns the string representation
func (s ModifyLoadBalancerAttributesOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s ModifyLoadBalancerAttributesOutput) GoString() string {
	return s.String()
}

// SetAttributes sets the Attributes field's value.
func (s *ModifyLoadBalancerAttributesOutput) SetAttributes(v []*LoadBalancerAttribute) *ModifyLoadBalancerAttributesOutput {
	s.Attributes = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyRuleInput
type ModifyRuleInput struct {
	_ struct{} `type:"structure"`

	// The actions. The target group must use the HTTP or HTTPS protocol.
	Actions []*Action `type:"list"`

	// The conditions.
	Conditions []*RuleCondition `type:"list"`

	// The Amazon Resource Name (ARN) of the rule.
	//
	// RuleArn is a required field
	RuleArn *string `type:"string" required:"true"`
}

// String returns the string representation
func (s ModifyRuleInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s ModifyRuleInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *ModifyRuleInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "ModifyRuleInput"}
	if s.RuleArn == nil {
		invalidParams.Add(request.NewErrParamRequired("RuleArn"))
	}
	if s.Actions != nil {
		for i, v := range s.Actions {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Actions", i), err.(request.ErrInvalidParams))
			}
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetActions sets the Actions field's value.
func (s *ModifyRuleInput) SetActions(v []*Action) *ModifyRuleInput {
	s.Actions = v
	return s
}

// SetConditions sets the Conditions field's value.
func (s *ModifyRuleInput) SetConditions(v []*RuleCondition) *ModifyRuleInput {
	s.Conditions = v
	return s
}

// SetRuleArn sets the RuleArn field's value.
func (s *ModifyRuleInput) SetRuleArn(v string) *ModifyRuleInput {
	s.RuleArn = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyRuleOutput
type ModifyRuleOutput struct {
	_ struct{} `type:"structure"`

	// Information about the rule.
	Rules []*Rule `type:"list"`
}

// String returns the string representation
func (s ModifyRuleOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s ModifyRuleOutput) GoString() string {
	return s.String()
}

// SetRules sets the Rules field's value.
func (s *ModifyRuleOutput) SetRules(v []*Rule) *ModifyRuleOutput {
	s.Rules = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyTargetGroupAttributesInput
type ModifyTargetGroupAttributesInput struct {
	_ struct{} `type:"structure"`

	// The attributes.
	//
	// Attributes is a required field
	Attributes []*TargetGroupAttribute `type:"list" required:"true"`

	// The Amazon Resource Name (ARN) of the target group.
	//
	// TargetGroupArn is a required field
	TargetGroupArn *string `type:"string" required:"true"`
}

// String returns the string representation
func (s ModifyTargetGroupAttributesInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s ModifyTargetGroupAttributesInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *ModifyTargetGroupAttributesInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "ModifyTargetGroupAttributesInput"}
	if s.Attributes == nil {
		invalidParams.Add(request.NewErrParamRequired("Attributes"))
	}
	if s.TargetGroupArn == nil {
		invalidParams.Add(request.NewErrParamRequired("TargetGroupArn"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetAttributes sets the Attributes field's value.
func (s *ModifyTargetGroupAttributesInput) SetAttributes(v []*TargetGroupAttribute) *ModifyTargetGroupAttributesInput {
	s.Attributes = v
	return s
}

// SetTargetGroupArn sets the TargetGroupArn field's value.
func (s *ModifyTargetGroupAttributesInput) SetTargetGroupArn(v string) *ModifyTargetGroupAttributesInput {
	s.TargetGroupArn = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyTargetGroupAttributesOutput
type ModifyTargetGroupAttributesOutput struct {
	_ struct{} `type:"structure"`

	// Information about the attributes.
	Attributes []*TargetGroupAttribute `type:"list"`
}

// String returns the string representation
func (s ModifyTargetGroupAttributesOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s ModifyTargetGroupAttributesOutput) GoString() string {
	return s.String()
}

// SetAttributes sets the Attributes field's value.
func (s *ModifyTargetGroupAttributesOutput) SetAttributes(v []*TargetGroupAttribute) *ModifyTargetGroupAttributesOutput {
	s.Attributes = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyTargetGroupInput
type ModifyTargetGroupInput struct {
	_ struct{} `type:"structure"`

	// The approximate amount of time, in seconds, between health checks of an individual
	// target. For Application Load Balancers, the range is 5 to 300 seconds. For
	// Network Load Balancers, the supported values are 10 or 30 seconds.
	HealthCheckIntervalSeconds *int64 `min:"5" type:"integer"`

	// [HTTP/HTTPS health checks] The ping path that is the destination for the
	// health check request.
	HealthCheckPath *string `min:"1" type:"string"`

	// The port the load balancer uses when performing health checks on targets.
	HealthCheckPort *string `type:"string"`

	// The protocol the load balancer uses when performing health checks on targets.
	// The TCP protocol is supported only if the protocol of the target group is
	// TCP.
	HealthCheckProtocol *string `type:"string" enum:"ProtocolEnum"`

	// [HTTP/HTTPS health checks] The amount of time, in seconds, during which no
	// response means a failed health check.
	HealthCheckTimeoutSeconds *int64 `min:"2" type:"integer"`

	// The number of consecutive health checks successes required before considering
	// an unhealthy target healthy.
	HealthyThresholdCount *int64 `min:"2" type:"integer"`

	// [HTTP/HTTPS health checks] The HTTP codes to use when checking for a successful
	// response from a target.
	Matcher *Matcher `type:"structure"`

	// The Amazon Resource Name (ARN) of the target group.
	//
	// TargetGroupArn is a required field
	TargetGroupArn *string `type:"string" required:"true"`

	// The number of consecutive health check failures required before considering
	// the target unhealthy. For Network Load Balancers, this value must be the
	// same as the healthy threshold count.
	UnhealthyThresholdCount *int64 `min:"2" type:"integer"`
}

// String returns the string representation
func (s ModifyTargetGroupInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s ModifyTargetGroupInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *ModifyTargetGroupInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "ModifyTargetGroupInput"}
	if s.HealthCheckIntervalSeconds != nil && *s.HealthCheckIntervalSeconds < 5 {
		invalidParams.Add(request.NewErrParamMinValue("HealthCheckIntervalSeconds", 5))
	}
	if s.HealthCheckPath != nil && len(*s.HealthCheckPath) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("HealthCheckPath", 1))
	}
	if s.HealthCheckTimeoutSeconds != nil && *s.HealthCheckTimeoutSeconds < 2 {
		invalidParams.Add(request.NewErrParamMinValue("HealthCheckTimeoutSeconds", 2))
	}
	if s.HealthyThresholdCount != nil && *s.HealthyThresholdCount < 2 {
		invalidParams.Add(request.NewErrParamMinValue("HealthyThresholdCount", 2))
	}
	if s.TargetGroupArn == nil {
		invalidParams.Add(request.NewErrParamRequired("TargetGroupArn"))
	}
	if s.UnhealthyThresholdCount != nil && *s.UnhealthyThresholdCount < 2 {
		invalidParams.Add(request.NewErrParamMinValue("UnhealthyThresholdCount", 2))
	}
	if s.Matcher != nil {
		if err := s.Matcher.Validate(); err != nil {
			invalidParams.AddNested("Matcher", err.(request.ErrInvalidParams))
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetHealthCheckIntervalSeconds sets the HealthCheckIntervalSeconds field's value.
func (s *ModifyTargetGroupInput) SetHealthCheckIntervalSeconds(v int64) *ModifyTargetGroupInput {
	s.HealthCheckIntervalSeconds = &v
	return s
}

// SetHealthCheckPath sets the HealthCheckPath field's value.
func (s *ModifyTargetGroupInput) SetHealthCheckPath(v string) *ModifyTargetGroupInput {
	s.HealthCheckPath = &v
	return s
}

// SetHealthCheckPort sets the HealthCheckPort field's value.
func (s *ModifyTargetGroupInput) SetHealthCheckPort(v string) *ModifyTargetGroupInput {
	s.HealthCheckPort = &v
	return s
}

// SetHealthCheckProtocol sets the HealthCheckProtocol field's value.
func (s *ModifyTargetGroupInput) SetHealthCheckProtocol(v string) *ModifyTargetGroupInput {
	s.HealthCheckProtocol = &v
	return s
}

// SetHealthCheckTimeoutSeconds sets the HealthCheckTimeoutSeconds field's value.
func (s *ModifyTargetGroupInput) SetHealthCheckTimeoutSeconds(v int64) *ModifyTargetGroupInput {
	s.HealthCheckTimeoutSeconds = &v
	return s
}

// SetHealthyThresholdCount sets the HealthyThresholdCount field's value.
func (s *ModifyTargetGroupInput) SetHealthyThresholdCount(v int64) *ModifyTargetGroupInput {
	s.HealthyThresholdCount = &v
	return s
}

// SetMatcher sets the Matcher field's value.
func (s *ModifyTargetGroupInput) SetMatcher(v *Matcher) *ModifyTargetGroupInput {
	s.Matcher = v
	return s
}

// SetTargetGroupArn sets the TargetGroupArn field's value.
func (s *ModifyTargetGroupInput) SetTargetGroupArn(v string) *ModifyTargetGroupInput {
	s.TargetGroupArn = &v
	return s
}

// SetUnhealthyThresholdCount sets the UnhealthyThresholdCount field's value.
func (s *ModifyTargetGroupInput) SetUnhealthyThresholdCount(v int64) *ModifyTargetGroupInput {
	s.UnhealthyThresholdCount = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/ModifyTargetGroupOutput
type ModifyTargetGroupOutput struct {
	_ struct{} `type:"structure"`

	// Information about the target group.
	TargetGroups []*TargetGroup `type:"list"`
}

// String returns the string representation
func (s ModifyTargetGroupOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s ModifyTargetGroupOutput) GoString() string {
	return s.String()
}

// SetTargetGroups sets the TargetGroups field's value.
func (s *ModifyTargetGroupOutput) SetTargetGroups(v []*TargetGroup) *ModifyTargetGroupOutput {
	s.TargetGroups = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/RegisterTargetsInput
type RegisterTargetsInput struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) of the target group.
	//
	// TargetGroupArn is a required field
	TargetGroupArn *string `type:"string" required:"true"`

	// The targets.
	//
	// Targets is a required field
	Targets []*TargetDescription `type:"list" required:"true"`
}

// String returns the string representation
func (s RegisterTargetsInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s RegisterTargetsInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *RegisterTargetsInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "RegisterTargetsInput"}
	if s.TargetGroupArn == nil {
		invalidParams.Add(request.NewErrParamRequired("TargetGroupArn"))
	}
	if s.Targets == nil {
		invalidParams.Add(request.NewErrParamRequired("Targets"))
	}
	if s.Targets != nil {
		for i, v := range s.Targets {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Targets", i), err.(request.ErrInvalidParams))
			}
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetTargetGroupArn sets the TargetGroupArn field's value.
func (s *RegisterTargetsInput) SetTargetGroupArn(v string) *RegisterTargetsInput {
	s.TargetGroupArn = &v
	return s
}

// SetTargets sets the Targets field's value.
func (s *RegisterTargetsInput) SetTargets(v []*TargetDescription) *RegisterTargetsInput {
	s.Targets = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/RegisterTargetsOutput
type RegisterTargetsOutput struct {
	_ struct{} `type:"structure"`
}

// String returns the string representation
func (s RegisterTargetsOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s RegisterTargetsOutput) GoString() string {
	return s.String()
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/RemoveListenerCertificatesInput
type RemoveListenerCertificatesInput struct {
	_ struct{} `type:"structure"`

	// The certificate to remove. You can specify one certificate per call.
	//
	// Certificates is a required field
	Certificates []*Certificate `type:"list" required:"true"`

	// The Amazon Resource Name (ARN) of the listener.
	//
	// ListenerArn is a required field
	ListenerArn *string `type:"string" required:"true"`
}

// String returns the string representation
func (s RemoveListenerCertificatesInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s RemoveListenerCertificatesInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *RemoveListenerCertificatesInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "RemoveListenerCertificatesInput"}
	if s.Certificates == nil {
		invalidParams.Add(request.NewErrParamRequired("Certificates"))
	}
	if s.ListenerArn == nil {
		invalidParams.Add(request.NewErrParamRequired("ListenerArn"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetCertificates sets the Certificates field's value.
func (s *RemoveListenerCertificatesInput) SetCertificates(v []*Certificate) *RemoveListenerCertificatesInput {
	s.Certificates = v
	return s
}

// SetListenerArn sets the ListenerArn field's value.
func (s *RemoveListenerCertificatesInput) SetListenerArn(v string) *RemoveListenerCertificatesInput {
	s.ListenerArn = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/RemoveListenerCertificatesOutput
type RemoveListenerCertificatesOutput struct {
	_ struct{} `type:"structure"`
}

// String returns the string representation
func (s RemoveListenerCertificatesOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s RemoveListenerCertificatesOutput) GoString() string {
	return s.String()
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/RemoveTagsInput
type RemoveTagsInput struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) of the resource.
	//
	// ResourceArns is a required field
	ResourceArns []*string `type:"list" required:"true"`

	// The tag keys for the tags to remove.
	//
	// TagKeys is a required field
	TagKeys []*string `type:"list" required:"true"`
}

// String returns the string representation
func (s RemoveTagsInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s RemoveTagsInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *RemoveTagsInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "RemoveTagsInput"}
	if s.ResourceArns == nil {
		invalidParams.Add(request.NewErrParamRequired("ResourceArns"))
	}
	if s.TagKeys == nil {
		invalidParams.Add(request.NewErrParamRequired("TagKeys"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetResourceArns sets the ResourceArns field's value.
func (s *RemoveTagsInput) SetResourceArns(v []*string) *RemoveTagsInput {
	s.ResourceArns = v
	return s
}

// SetTagKeys sets the TagKeys field's value.
func (s *RemoveTagsInput) SetTagKeys(v []*string) *RemoveTagsInput {
	s.TagKeys = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/RemoveTagsOutput
type RemoveTagsOutput struct {
	_ struct{} `type:"structure"`
}

// String returns the string representation
func (s RemoveTagsOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s RemoveTagsOutput) GoString() string {
	return s.String()
}

// Information about a rule.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/Rule
type Rule struct {
	_ struct{} `type:"structure"`

	// The actions.
	Actions []*Action `type:"list"`

	// The conditions.
	Conditions []*RuleCondition `type:"list"`

	// Indicates whether this is the default rule.
	IsDefault *bool `type:"boolean"`

	// The priority.
	Priority *string `type:"string"`

	// The Amazon Resource Name (ARN) of the rule.
	RuleArn *string `type:"string"`
}

// String returns the string representation
func (s Rule) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s Rule) GoString() string {
	return s.String()
}

// SetActions sets the Actions field's value.
func (s *Rule) SetActions(v []*Action) *Rule {
	s.Actions = v
	return s
}

// SetConditions sets the Conditions field's value.
func (s *Rule) SetConditions(v []*RuleCondition) *Rule {
	s.Conditions = v
	return s
}

// SetIsDefault sets the IsDefault field's value.
func (s *Rule) SetIsDefault(v bool) *Rule {
	s.IsDefault = &v
	return s
}

// SetPriority sets the Priority field's value.
func (s *Rule) SetPriority(v string) *Rule {
	s.Priority = &v
	return s
}

// SetRuleArn sets the RuleArn field's value.
func (s *Rule) SetRuleArn(v string) *Rule {
	s.RuleArn = &v
	return s
}

// Information about a condition for a rule.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/RuleCondition
type RuleCondition struct {
	_ struct{} `type:"structure"`

	// The name of the field. The possible values are host-header and path-pattern.
	Field *string `type:"string"`

	// The condition value.
	//
	// If the field name is host-header, you can specify a single host name (for
	// example, my.example.com). A host name is case insensitive, can be up to 128
	// characters in length, and can contain any of the following characters. Note
	// that you can include up to three wildcard characters.
	//
	//    * A-Z, a-z, 0-9
	//
	//    * - .
	//
	//    * * (matches 0 or more characters)
	//
	//    * ? (matches exactly 1 character)
	//
	// If the field name is path-pattern, you can specify a single path pattern
	// (for example, /img/*). A path pattern is case sensitive, can be up to 128
	// characters in length, and can contain any of the following characters. Note
	// that you can include up to three wildcard characters.
	//
	//    * A-Z, a-z, 0-9
	//
	//    * _ - . $ / ~ " ' @ : +
	//
	//    * & (using &)
	//
	//    * * (matches 0 or more characters)
	//
	//    * ? (matches exactly 1 character)
	Values []*string `type:"list"`
}

// String returns the string representation
func (s RuleCondition) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s RuleCondition) GoString() string {
	return s.String()
}

// SetField sets the Field field's value.
func (s *RuleCondition) SetField(v string) *RuleCondition {
	s.Field = &v
	return s
}

// SetValues sets the Values field's value.
func (s *RuleCondition) SetValues(v []*string) *RuleCondition {
	s.Values = v
	return s
}

// Information about the priorities for the rules for a listener.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/RulePriorityPair
type RulePriorityPair struct {
	_ struct{} `type:"structure"`

	// The rule priority.
	Priority *int64 `min:"1" type:"integer"`

	// The Amazon Resource Name (ARN) of the rule.
	RuleArn *string `type:"string"`
}

// String returns the string representation
func (s RulePriorityPair) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s RulePriorityPair) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *RulePriorityPair) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "RulePriorityPair"}
	if s.Priority != nil && *s.Priority < 1 {
		invalidParams.Add(request.NewErrParamMinValue("Priority", 1))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetPriority sets the Priority field's value.
func (s *RulePriorityPair) SetPriority(v int64) *RulePriorityPair {
	s.Priority = &v
	return s
}

// SetRuleArn sets the RuleArn field's value.
func (s *RulePriorityPair) SetRuleArn(v string) *RulePriorityPair {
	s.RuleArn = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SetIpAddressTypeInput
type SetIpAddressTypeInput struct {
	_ struct{} `type:"structure"`

	// The IP address type. The possible values are ipv4 (for IPv4 addresses) and
	// dualstack (for IPv4 and IPv6 addresses). Internal load balancers must use
	// ipv4.
	//
	// IpAddressType is a required field
	IpAddressType *string `type:"string" required:"true" enum:"IpAddressType"`

	// The Amazon Resource Name (ARN) of the load balancer.
	//
	// LoadBalancerArn is a required field
	LoadBalancerArn *string `type:"string" required:"true"`
}

// String returns the string representation
func (s SetIpAddressTypeInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s SetIpAddressTypeInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *SetIpAddressTypeInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "SetIpAddressTypeInput"}
	if s.IpAddressType == nil {
		invalidParams.Add(request.NewErrParamRequired("IpAddressType"))
	}
	if s.LoadBalancerArn == nil {
		invalidParams.Add(request.NewErrParamRequired("LoadBalancerArn"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetIpAddressType sets the IpAddressType field's value.
func (s *SetIpAddressTypeInput) SetIpAddressType(v string) *SetIpAddressTypeInput {
	s.IpAddressType = &v
	return s
}

// SetLoadBalancerArn sets the LoadBalancerArn field's value.
func (s *SetIpAddressTypeInput) SetLoadBalancerArn(v string) *SetIpAddressTypeInput {
	s.LoadBalancerArn = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SetIpAddressTypeOutput
type SetIpAddressTypeOutput struct {
	_ struct{} `type:"structure"`

	// The IP address type.
	IpAddressType *string `type:"string" enum:"IpAddressType"`
}

// String returns the string representation
func (s SetIpAddressTypeOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s SetIpAddressTypeOutput) GoString() string {
	return s.String()
}

// SetIpAddressType sets the IpAddressType field's value.
func (s *SetIpAddressTypeOutput) SetIpAddressType(v string) *SetIpAddressTypeOutput {
	s.IpAddressType = &v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SetRulePrioritiesInput
type SetRulePrioritiesInput struct {
	_ struct{} `type:"structure"`

	// The rule priorities.
	//
	// RulePriorities is a required field
	RulePriorities []*RulePriorityPair `type:"list" required:"true"`
}

// String returns the string representation
func (s SetRulePrioritiesInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s SetRulePrioritiesInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *SetRulePrioritiesInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "SetRulePrioritiesInput"}
	if s.RulePriorities == nil {
		invalidParams.Add(request.NewErrParamRequired("RulePriorities"))
	}
	if s.RulePriorities != nil {
		for i, v := range s.RulePriorities {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "RulePriorities", i), err.(request.ErrInvalidParams))
			}
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetRulePriorities sets the RulePriorities field's value.
func (s *SetRulePrioritiesInput) SetRulePriorities(v []*RulePriorityPair) *SetRulePrioritiesInput {
	s.RulePriorities = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SetRulePrioritiesOutput
type SetRulePrioritiesOutput struct {
	_ struct{} `type:"structure"`

	// Information about the rules.
	Rules []*Rule `type:"list"`
}

// String returns the string representation
func (s SetRulePrioritiesOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s SetRulePrioritiesOutput) GoString() string {
	return s.String()
}

// SetRules sets the Rules field's value.
func (s *SetRulePrioritiesOutput) SetRules(v []*Rule) *SetRulePrioritiesOutput {
	s.Rules = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SetSecurityGroupsInput
type SetSecurityGroupsInput struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) of the load balancer.
	//
	// LoadBalancerArn is a required field
	LoadBalancerArn *string `type:"string" required:"true"`

	// The IDs of the security groups.
	//
	// SecurityGroups is a required field
	SecurityGroups []*string `type:"list" required:"true"`
}

// String returns the string representation
func (s SetSecurityGroupsInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s SetSecurityGroupsInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *SetSecurityGroupsInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "SetSecurityGroupsInput"}
	if s.LoadBalancerArn == nil {
		invalidParams.Add(request.NewErrParamRequired("LoadBalancerArn"))
	}
	if s.SecurityGroups == nil {
		invalidParams.Add(request.NewErrParamRequired("SecurityGroups"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetLoadBalancerArn sets the LoadBalancerArn field's value.
func (s *SetSecurityGroupsInput) SetLoadBalancerArn(v string) *SetSecurityGroupsInput {
	s.LoadBalancerArn = &v
	return s
}

// SetSecurityGroups sets the SecurityGroups field's value.
func (s *SetSecurityGroupsInput) SetSecurityGroups(v []*string) *SetSecurityGroupsInput {
	s.SecurityGroups = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SetSecurityGroupsOutput
type SetSecurityGroupsOutput struct {
	_ struct{} `type:"structure"`

	// The IDs of the security groups associated with the load balancer.
	SecurityGroupIds []*string `type:"list"`
}

// String returns the string representation
func (s SetSecurityGroupsOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s SetSecurityGroupsOutput) GoString() string {
	return s.String()
}

// SetSecurityGroupIds sets the SecurityGroupIds field's value.
func (s *SetSecurityGroupsOutput) SetSecurityGroupIds(v []*string) *SetSecurityGroupsOutput {
	s.SecurityGroupIds = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SetSubnetsInput
type SetSubnetsInput struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) of the load balancer.
	//
	// LoadBalancerArn is a required field
	LoadBalancerArn *string `type:"string" required:"true"`

	// The IDs of the subnets. You must specify subnets from at least two Availability
	// Zones. You can specify only one subnet per Availability Zone. You must specify
	// either subnets or subnet mappings.
	//
	// You cannot specify Elastic IP addresses for your subnets.
	SubnetMappings []*SubnetMapping `type:"list"`

	// The IDs of the subnets. You must specify subnets from at least two Availability
	// Zones. You can specify only one subnet per Availability Zone. You must specify
	// either subnets or subnet mappings.
	//
	// Subnets is a required field
	Subnets []*string `type:"list" required:"true"`
}

// String returns the string representation
func (s SetSubnetsInput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s SetSubnetsInput) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *SetSubnetsInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "SetSubnetsInput"}
	if s.LoadBalancerArn == nil {
		invalidParams.Add(request.NewErrParamRequired("LoadBalancerArn"))
	}
	if s.Subnets == nil {
		invalidParams.Add(request.NewErrParamRequired("Subnets"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetLoadBalancerArn sets the LoadBalancerArn field's value.
func (s *SetSubnetsInput) SetLoadBalancerArn(v string) *SetSubnetsInput {
	s.LoadBalancerArn = &v
	return s
}

// SetSubnetMappings sets the SubnetMappings field's value.
func (s *SetSubnetsInput) SetSubnetMappings(v []*SubnetMapping) *SetSubnetsInput {
	s.SubnetMappings = v
	return s
}

// SetSubnets sets the Subnets field's value.
func (s *SetSubnetsInput) SetSubnets(v []*string) *SetSubnetsInput {
	s.Subnets = v
	return s
}

// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SetSubnetsOutput
type SetSubnetsOutput struct {
	_ struct{} `type:"structure"`

	// Information about the subnet and Availability Zone.
	AvailabilityZones []*AvailabilityZone `type:"list"`
}

// String returns the string representation
func (s SetSubnetsOutput) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s SetSubnetsOutput) GoString() string {
	return s.String()
}

// SetAvailabilityZones sets the AvailabilityZones field's value.
func (s *SetSubnetsOutput) SetAvailabilityZones(v []*AvailabilityZone) *SetSubnetsOutput {
	s.AvailabilityZones = v
	return s
}

// Information about a policy used for SSL negotiation.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SslPolicy
type SslPolicy struct {
	_ struct{} `type:"structure"`

	// The ciphers.
	Ciphers []*Cipher `type:"list"`

	// The name of the policy.
	Name *string `type:"string"`

	// The protocols.
	SslProtocols []*string `type:"list"`
}

// String returns the string representation
func (s SslPolicy) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s SslPolicy) GoString() string {
	return s.String()
}

// SetCiphers sets the Ciphers field's value.
func (s *SslPolicy) SetCiphers(v []*Cipher) *SslPolicy {
	s.Ciphers = v
	return s
}

// SetName sets the Name field's value.
func (s *SslPolicy) SetName(v string) *SslPolicy {
	s.Name = &v
	return s
}

// SetSslProtocols sets the SslProtocols field's value.
func (s *SslPolicy) SetSslProtocols(v []*string) *SslPolicy {
	s.SslProtocols = v
	return s
}

// Information about a subnet mapping.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SubnetMapping
type SubnetMapping struct {
	_ struct{} `type:"structure"`

	// [Network Load Balancers] The allocation ID of the Elastic IP address.
	AllocationId *string `type:"string"`

	// The ID of the subnet.
	SubnetId *string `type:"string"`
}

// String returns the string representation
func (s SubnetMapping) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s SubnetMapping) GoString() string {
	return s.String()
}

// SetAllocationId sets the AllocationId field's value.
func (s *SubnetMapping) SetAllocationId(v string) *SubnetMapping {
	s.AllocationId = &v
	return s
}

// SetSubnetId sets the SubnetId field's value.
func (s *SubnetMapping) SetSubnetId(v string) *SubnetMapping {
	s.SubnetId = &v
	return s
}

// Information about a tag.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/Tag
type Tag struct {
	_ struct{} `type:"structure"`

	// The key of the tag.
	//
	// Key is a required field
	Key *string `min:"1" type:"string" required:"true"`

	// The value of the tag.
	Value *string `type:"string"`
}

// String returns the string representation
func (s Tag) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s Tag) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *Tag) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "Tag"}
	if s.Key == nil {
		invalidParams.Add(request.NewErrParamRequired("Key"))
	}
	if s.Key != nil && len(*s.Key) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("Key", 1))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetKey sets the Key field's value.
func (s *Tag) SetKey(v string) *Tag {
	s.Key = &v
	return s
}

// SetValue sets the Value field's value.
func (s *Tag) SetValue(v string) *Tag {
	s.Value = &v
	return s
}

// The tags associated with a resource.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/TagDescription
type TagDescription struct {
	_ struct{} `type:"structure"`

	// The Amazon Resource Name (ARN) of the resource.
	ResourceArn *string `type:"string"`

	// Information about the tags.
	Tags []*Tag `min:"1" type:"list"`
}

// String returns the string representation
func (s TagDescription) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s TagDescription) GoString() string {
	return s.String()
}

// SetResourceArn sets the ResourceArn field's value.
func (s *TagDescription) SetResourceArn(v string) *TagDescription {
	s.ResourceArn = &v
	return s
}

// SetTags sets the Tags field's value.
func (s *TagDescription) SetTags(v []*Tag) *TagDescription {
	s.Tags = v
	return s
}

// Information about a target.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/TargetDescription
type TargetDescription struct {
	_ struct{} `type:"structure"`

	// An Availability Zone or all. This determines whether the target receives
	// traffic from the load balancer nodes in the specified Availability Zone or
	// from all enabled Availability Zones for the load balancer.
	//
	// This parameter is not supported if the target type of the target group is
	// instance. If the IP address is in a subnet of the VPC for the target group,
	// the Availability Zone is automatically detected and this parameter is optional.
	// If the IP address is outside the VPC, this parameter is required.
	//
	// With an Application Load Balancer, if the IP address is outside the VPC for
	// the target group, the only supported value is all.
	AvailabilityZone *string `type:"string"`

	// The ID of the target. If the target type of the target group is instance,
	// specify an instance ID. If the target type is ip, specify an IP address.
	//
	// Id is a required field
	Id *string `type:"string" required:"true"`

	// The port on which the target is listening.
	Port *int64 `min:"1" type:"integer"`
}

// String returns the string representation
func (s TargetDescription) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s TargetDescription) GoString() string {
	return s.String()
}

// Validate inspects the fields of the type to determine if they are valid.
func (s *TargetDescription) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "TargetDescription"}
	if s.Id == nil {
		invalidParams.Add(request.NewErrParamRequired("Id"))
	}
	if s.Port != nil && *s.Port < 1 {
		invalidParams.Add(request.NewErrParamMinValue("Port", 1))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

// SetAvailabilityZone sets the AvailabilityZone field's value.
func (s *TargetDescription) SetAvailabilityZone(v string) *TargetDescription {
	s.AvailabilityZone = &v
	return s
}

// SetId sets the Id field's value.
func (s *TargetDescription) SetId(v string) *TargetDescription {
	s.Id = &v
	return s
}

// SetPort sets the Port field's value.
func (s *TargetDescription) SetPort(v int64) *TargetDescription {
	s.Port = &v
	return s
}

// Information about a target group.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/TargetGroup
type TargetGroup struct {
	_ struct{} `type:"structure"`

	// The approximate amount of time, in seconds, between health checks of an individual
	// target.
	HealthCheckIntervalSeconds *int64 `min:"5" type:"integer"`

	// The destination for the health check request.
	HealthCheckPath *string `min:"1" type:"string"`

	// The port to use to connect with the target.
	HealthCheckPort *string `type:"string"`

	// The protocol to use to connect with the target.
	HealthCheckProtocol *string `type:"string" enum:"ProtocolEnum"`

	// The amount of time, in seconds, during which no response means a failed health
	// check.
	HealthCheckTimeoutSeconds *int64 `min:"2" type:"integer"`

	// The number of consecutive health checks successes required before considering
	// an unhealthy target healthy.
	HealthyThresholdCount *int64 `min:"2" type:"integer"`

	// The Amazon Resource Names (ARN) of the load balancers that route traffic
	// to this target group.
	LoadBalancerArns []*string `type:"list"`

	// The HTTP codes to use when checking for a successful response from a target.
	Matcher *Matcher `type:"structure"`

	// The port on which the targets are listening.
	Port *int64 `min:"1" type:"integer"`

	// The protocol to use for routing traffic to the targets.
	Protocol *string `type:"string" enum:"ProtocolEnum"`

	// The Amazon Resource Name (ARN) of the target group.
	TargetGroupArn *string `type:"string"`

	// The name of the target group.
	TargetGroupName *string `type:"string"`

	// The type of target that you must specify when registering targets with this
	// target group. The possible values are instance (targets are specified by
	// instance ID) or ip (targets are specified by IP address).
	TargetType *string `type:"string" enum:"TargetTypeEnum"`

	// The number of consecutive health check failures required before considering
	// the target unhealthy.
	UnhealthyThresholdCount *int64 `min:"2" type:"integer"`

	// The ID of the VPC for the targets.
	VpcId *string `type:"string"`
}

// String returns the string representation
func (s TargetGroup) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s TargetGroup) GoString() string {
	return s.String()
}

// SetHealthCheckIntervalSeconds sets the HealthCheckIntervalSeconds field's value.
func (s *TargetGroup) SetHealthCheckIntervalSeconds(v int64) *TargetGroup {
	s.HealthCheckIntervalSeconds = &v
	return s
}

// SetHealthCheckPath sets the HealthCheckPath field's value.
func (s *TargetGroup) SetHealthCheckPath(v string) *TargetGroup {
	s.HealthCheckPath = &v
	return s
}

// SetHealthCheckPort sets the HealthCheckPort field's value.
func (s *TargetGroup) SetHealthCheckPort(v string) *TargetGroup {
	s.HealthCheckPort = &v
	return s
}

// SetHealthCheckProtocol sets the HealthCheckProtocol field's value.
func (s *TargetGroup) SetHealthCheckProtocol(v string) *TargetGroup {
	s.HealthCheckProtocol = &v
	return s
}

// SetHealthCheckTimeoutSeconds sets the HealthCheckTimeoutSeconds field's value.
func (s *TargetGroup) SetHealthCheckTimeoutSeconds(v int64) *TargetGroup {
	s.HealthCheckTimeoutSeconds = &v
	return s
}

// SetHealthyThresholdCount sets the HealthyThresholdCount field's value.
func (s *TargetGroup) SetHealthyThresholdCount(v int64) *TargetGroup {
	s.HealthyThresholdCount = &v
	return s
}

// SetLoadBalancerArns sets the LoadBalancerArns field's value.
func (s *TargetGroup) SetLoadBalancerArns(v []*string) *TargetGroup {
	s.LoadBalancerArns = v
	return s
}

// SetMatcher sets the Matcher field's value.
func (s *TargetGroup) SetMatcher(v *Matcher) *TargetGroup {
	s.Matcher = v
	return s
}

// SetPort sets the Port field's value.
func (s *TargetGroup) SetPort(v int64) *TargetGroup {
	s.Port = &v
	return s
}

// SetProtocol sets the Protocol field's value.
func (s *TargetGroup) SetProtocol(v string) *TargetGroup {
	s.Protocol = &v
	return s
}

// SetTargetGroupArn sets the TargetGroupArn field's value.
func (s *TargetGroup) SetTargetGroupArn(v string) *TargetGroup {
	s.TargetGroupArn = &v
	return s
}

// SetTargetGroupName sets the TargetGroupName field's value.
func (s *TargetGroup) SetTargetGroupName(v string) *TargetGroup {
	s.TargetGroupName = &v
	return s
}

// SetTargetType sets the TargetType field's value.
func (s *TargetGroup) SetTargetType(v string) *TargetGroup {
	s.TargetType = &v
	return s
}

// SetUnhealthyThresholdCount sets the UnhealthyThresholdCount field's value.
func (s *TargetGroup) SetUnhealthyThresholdCount(v int64) *TargetGroup {
	s.UnhealthyThresholdCount = &v
	return s
}

// SetVpcId sets the VpcId field's value.
func (s *TargetGroup) SetVpcId(v string) *TargetGroup {
	s.VpcId = &v
	return s
}

// Information about a target group attribute.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/TargetGroupAttribute
type TargetGroupAttribute struct {
	_ struct{} `type:"structure"`

	// The name of the attribute.
	//
	//    * deregistration_delay.timeout_seconds - The amount time for Elastic Load
	//    Balancing to wait before changing the state of a deregistering target
	//    from draining to unused. The range is 0-3600 seconds. The default value
	//    is 300 seconds.
	//
	//    * proxy_protocol_v2.enabled - [Network Load Balancers] Indicates whether
	//    Proxy Protocol version 2 is enabled.
	//
	//    * stickiness.enabled - [Application Load Balancers] Indicates whether
	//    sticky sessions are enabled. The value is true or false.
	//
	//    * stickiness.type - [Application Load Balancers] The type of sticky sessions.
	//    The possible value is lb_cookie.
	//
	//    * stickiness.lb_cookie.duration_seconds - [Application Load Balancers]
	//    The time period, in seconds, during which requests from a client should
	//    be routed to the same target. After this time period expires, the load
	//    balancer-generated cookie is considered stale. The range is 1 second to
	//    1 week (604800 seconds). The default value is 1 day (86400 seconds).
	Key *string `type:"string"`

	// The value of the attribute.
	Value *string `type:"string"`
}

// String returns the string representation
func (s TargetGroupAttribute) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s TargetGroupAttribute) GoString() string {
	return s.String()
}

// SetKey sets the Key field's value.
func (s *TargetGroupAttribute) SetKey(v string) *TargetGroupAttribute {
	s.Key = &v
	return s
}

// SetValue sets the Value field's value.
func (s *TargetGroupAttribute) SetValue(v string) *TargetGroupAttribute {
	s.Value = &v
	return s
}

// Information about the current health of a target.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/TargetHealth
type TargetHealth struct {
	_ struct{} `type:"structure"`

	// A description of the target health that provides additional details. If the
	// state is healthy, a description is not provided.
	Description *string `type:"string"`

	// The reason code. If the target state is healthy, a reason code is not provided.
	//
	// If the target state is initial, the reason code can be one of the following
	// values:
	//
	//    * Elb.RegistrationInProgress - The target is in the process of being registered
	//    with the load balancer.
	//
	//    * Elb.InitialHealthChecking - The load balancer is still sending the target
	//    the minimum number of health checks required to determine its health status.
	//
	// If the target state is unhealthy, the reason code can be one of the following
	// values:
	//
	//    * Target.ResponseCodeMismatch - The health checks did not return an expected
	//    HTTP code.
	//
	//    * Target.Timeout - The health check requests timed out.
	//
	//    * Target.FailedHealthChecks - The health checks failed because the connection
	//    to the target timed out, the target response was malformed, or the target
	//    failed the health check for an unknown reason.
	//
	//    * Elb.InternalError - The health checks failed due to an internal error.
	//
	// If the target state is unused, the reason code can be one of the following
	// values:
	//
	//    * Target.NotRegistered - The target is not registered with the target
	//    group.
	//
	//    * Target.NotInUse - The target group is not used by any load balancer
	//    or the target is in an Availability Zone that is not enabled for its load
	//    balancer.
	//
	//    * Target.IpUnusable - The target IP address is reserved for use by a load
	//    balancer.
	//
	//    * Target.InvalidState - The target is in the stopped or terminated state.
	//
	// If the target state is draining, the reason code can be the following value:
	//
	//    * Target.DeregistrationInProgress - The target is in the process of being
	//    deregistered and the deregistration delay period has not expired.
	Reason *string `type:"string" enum:"TargetHealthReasonEnum"`

	// The state of the target.
	State *string `type:"string" enum:"TargetHealthStateEnum"`
}

// String returns the string representation
func (s TargetHealth) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s TargetHealth) GoString() string {
	return s.String()
}

// SetDescription sets the Description field's value.
func (s *TargetHealth) SetDescription(v string) *TargetHealth {
	s.Description = &v
	return s
}

// SetReason sets the Reason field's value.
func (s *TargetHealth) SetReason(v string) *TargetHealth {
	s.Reason = &v
	return s
}

// SetState sets the State field's value.
func (s *TargetHealth) SetState(v string) *TargetHealth {
	s.State = &v
	return s
}

// Information about the health of a target.
// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/TargetHealthDescription
type TargetHealthDescription struct {
	_ struct{} `type:"structure"`

	// The port to use to connect with the target.
	HealthCheckPort *string `type:"string"`

	// The description of the target.
	Target *TargetDescription `type:"structure"`

	// The health information for the target.
	TargetHealth *TargetHealth `type:"structure"`
}

// String returns the string representation
func (s TargetHealthDescription) String() string {
	return awsutil.Prettify(s)
}

// GoString returns the string representation
func (s TargetHealthDescription) GoString() string {
	return s.String()
}

// SetHealthCheckPort sets the HealthCheckPort field's value.
func (s *TargetHealthDescription) SetHealthCheckPort(v string) *TargetHealthDescription {
	s.HealthCheckPort = &v
	return s
}

// SetTarget sets the Target field's value.
func (s *TargetHealthDescription) SetTarget(v *TargetDescription) *TargetHealthDescription {
	s.Target = v
	return s
}

// SetTargetHealth sets the TargetHealth field's value.
func (s *TargetHealthDescription) SetTargetHealth(v *TargetHealth) *TargetHealthDescription {
	s.TargetHealth = v
	return s
}

const (
	// ActionTypeEnumForward is a ActionTypeEnum enum value
	ActionTypeEnumForward = "forward"
)

const (
	// IpAddressTypeIpv4 is a IpAddressType enum value
	IpAddressTypeIpv4 = "ipv4"

	// IpAddressTypeDualstack is a IpAddressType enum value
	IpAddressTypeDualstack = "dualstack"
)

const (
	// LoadBalancerSchemeEnumInternetFacing is a LoadBalancerSchemeEnum enum value
	LoadBalancerSchemeEnumInternetFacing = "internet-facing"

	// LoadBalancerSchemeEnumInternal is a LoadBalancerSchemeEnum enum value
	LoadBalancerSchemeEnumInternal = "internal"
)

const (
	// LoadBalancerStateEnumActive is a LoadBalancerStateEnum enum value
	LoadBalancerStateEnumActive = "active"

	// LoadBalancerStateEnumProvisioning is a LoadBalancerStateEnum enum value
	LoadBalancerStateEnumProvisioning = "provisioning"

	// LoadBalancerStateEnumActiveImpaired is a LoadBalancerStateEnum enum value
	LoadBalancerStateEnumActiveImpaired = "active_impaired"

	// LoadBalancerStateEnumFailed is a LoadBalancerStateEnum enum value
	LoadBalancerStateEnumFailed = "failed"
)

const (
	// LoadBalancerTypeEnumApplication is a LoadBalancerTypeEnum enum value
	LoadBalancerTypeEnumApplication = "application"

	// LoadBalancerTypeEnumNetwork is a LoadBalancerTypeEnum enum value
	LoadBalancerTypeEnumNetwork = "network"
)

const (
	// ProtocolEnumHttp is a ProtocolEnum enum value
	ProtocolEnumHttp = "HTTP"

	// ProtocolEnumHttps is a ProtocolEnum enum value
	ProtocolEnumHttps = "HTTPS"

	// ProtocolEnumTcp is a ProtocolEnum enum value
	ProtocolEnumTcp = "TCP"
)

const (
	// TargetHealthReasonEnumElbRegistrationInProgress is a TargetHealthReasonEnum enum value
	TargetHealthReasonEnumElbRegistrationInProgress = "Elb.RegistrationInProgress"

	// TargetHealthReasonEnumElbInitialHealthChecking is a TargetHealthReasonEnum enum value
	TargetHealthReasonEnumElbInitialHealthChecking = "Elb.InitialHealthChecking"

	// TargetHealthReasonEnumTargetResponseCodeMismatch is a TargetHealthReasonEnum enum value
	TargetHealthReasonEnumTargetResponseCodeMismatch = "Target.ResponseCodeMismatch"

	// TargetHealthReasonEnumTargetTimeout is a TargetHealthReasonEnum enum value
	TargetHealthReasonEnumTargetTimeout = "Target.Timeout"

	// TargetHealthReasonEnumTargetFailedHealthChecks is a TargetHealthReasonEnum enum value
	TargetHealthReasonEnumTargetFailedHealthChecks = "Target.FailedHealthChecks"

	// TargetHealthReasonEnumTargetNotRegistered is a TargetHealthReasonEnum enum value
	TargetHealthReasonEnumTargetNotRegistered = "Target.NotRegistered"

	// TargetHealthReasonEnumTargetNotInUse is a TargetHealthReasonEnum enum value
	TargetHealthReasonEnumTargetNotInUse = "Target.NotInUse"

	// TargetHealthReasonEnumTargetDeregistrationInProgress is a TargetHealthReasonEnum enum value
	TargetHealthReasonEnumTargetDeregistrationInProgress = "Target.DeregistrationInProgress"

	// TargetHealthReasonEnumTargetInvalidState is a TargetHealthReasonEnum enum value
	TargetHealthReasonEnumTargetInvalidState = "Target.InvalidState"

	// TargetHealthReasonEnumTargetIpUnusable is a TargetHealthReasonEnum enum value
	TargetHealthReasonEnumTargetIpUnusable = "Target.IpUnusable"

	// TargetHealthReasonEnumElbInternalError is a TargetHealthReasonEnum enum value
	TargetHealthReasonEnumElbInternalError = "Elb.InternalError"
)

const (
	// TargetHealthStateEnumInitial is a TargetHealthStateEnum enum value
	TargetHealthStateEnumInitial = "initial"

	// TargetHealthStateEnumHealthy is a TargetHealthStateEnum enum value
	TargetHealthStateEnumHealthy = "healthy"

	// TargetHealthStateEnumUnhealthy is a TargetHealthStateEnum enum value
	TargetHealthStateEnumUnhealthy = "unhealthy"

	// TargetHealthStateEnumUnused is a TargetHealthStateEnum enum value
	TargetHealthStateEnumUnused = "unused"

	// TargetHealthStateEnumDraining is a TargetHealthStateEnum enum value
	TargetHealthStateEnumDraining = "draining"

	// TargetHealthStateEnumUnavailable is a TargetHealthStateEnum enum value
	TargetHealthStateEnumUnavailable = "unavailable"
)

const (
	// TargetTypeEnumInstance is a TargetTypeEnum enum value
	TargetTypeEnumInstance = "instance"

	// TargetTypeEnumIp is a TargetTypeEnum enum value
	TargetTypeEnumIp = "ip"
)


<|start_filename|>vendor/github.com/hashicorp/terraform/svchost/auth/credentials.go<|end_filename|>
// Package auth contains types and functions to manage authentication
// credentials for service hosts.
package auth

import (
	"net/http"

	"github.com/hashicorp/terraform/svchost"
)

// Credentials is a list of CredentialsSource objects that can be tried in
// turn until one returns credentials for a host, or one returns an error.
//
// A Credentials is itself a CredentialsSource, wrapping its members.
// In principle one CredentialsSource can be nested inside another, though
// there is no good reason to do so.
type Credentials []CredentialsSource

// NoCredentials is an empty CredentialsSource that always returns nil
// when asked for credentials.
var NoCredentials CredentialsSource = Credentials{}

// A CredentialsSource is an object that may be able to provide credentials
// for a given host.
//
// Credentials lookups are not guaranteed to be concurrency-safe. Callers
// using these facilities in concurrent code must use external concurrency
// primitives to prevent race conditions.
type CredentialsSource interface {
	// ForHost returns a non-nil HostCredentials if the source has credentials
	// available for the host, and a nil HostCredentials if it does not.
	//
	// If an error is returned, progress through a list of CredentialsSources
	// is halted and the error is returned to the user.
	ForHost(host svchost.Hostname) (HostCredentials, error)
}

// HostCredentials represents a single set of credentials for a particular
// host.
type HostCredentials interface {
	// PrepareRequest modifies the given request in-place to apply the
	// receiving credentials. The usual behavior of this method is to
	// add some sort of Authorization header to the request.
	PrepareRequest(req *http.Request)
}

// ForHost iterates over the contained CredentialsSource objects and
// tries to obtain credentials for the given host from each one in turn.
//
// If any source returns either a non-nil HostCredentials or a non-nil error
// then this result is returned. Otherwise, the result is nil, nil.
func (c Credentials) ForHost(host svchost.Hostname) (HostCredentials, error) {
	for _, source := range c {
		creds, err := source.ForHost(host)
		if creds != nil || err != nil {
			return creds, err
		}
	}
	return nil, nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_vpc_endpoint_route_table_association.go<|end_filename|>
package aws

import (
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/hashicorp/terraform/helper/hashcode"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsVpcEndpointRouteTableAssociation() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsVPCEndpointRouteTableAssociationCreate,
		Read:   resourceAwsVPCEndpointRouteTableAssociationRead,
		Delete: resourceAwsVPCEndpointRouteTableAssociationDelete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"vpc_endpoint_id": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"route_table_id": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
		},
	}
}

func resourceAwsVPCEndpointRouteTableAssociationCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ec2conn
	endpointId := d.Get("vpc_endpoint_id").(string)
	rtId := d.Get("route_table_id").(string)

	_, err := findResourceVPCEndpoint(conn, endpointId)
	if err != nil {
		return err
	}

	log.Printf(
		"[INFO] Creating VPC Endpoint/Route Table association: %s => %s",
		endpointId, rtId)

	input := &ec2.ModifyVpcEndpointInput{
		VpcEndpointId:    aws.String(endpointId),
		AddRouteTableIds: aws.StringSlice([]string{rtId}),
	}

	_, err = conn.ModifyVpcEndpoint(input)
	if err != nil {
		return fmt.Errorf("Error creating VPC Endpoint/Route Table association: %s", err.Error())
	}
	id := vpcEndpointIdRouteTableIdHash(endpointId, rtId)
	log.Printf("[DEBUG] VPC Endpoint/Route Table association %q created.", id)

	d.SetId(id)

	return resourceAwsVPCEndpointRouteTableAssociationRead(d, meta)
}

func resourceAwsVPCEndpointRouteTableAssociationRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ec2conn
	endpointId := d.Get("vpc_endpoint_id").(string)
	rtId := d.Get("route_table_id").(string)

	vpce, err := findResourceVPCEndpoint(conn, endpointId)
	if err != nil {
		if err, ok := err.(awserr.Error); ok && err.Code() == "InvalidVpcEndpointId.NotFound" {
			d.SetId("")
			return nil
		}

		return err
	}

	found := false
	for _, id := range vpce.RouteTableIds {
		if id != nil && *id == rtId {
			found = true
			break
		}
	}
	if !found {
		// The association no longer exists.
		d.SetId("")
		return nil
	}

	id := vpcEndpointIdRouteTableIdHash(endpointId, rtId)
	log.Printf("[DEBUG] Computed VPC Endpoint/Route Table ID %s", id)
	d.SetId(id)

	return nil
}

func resourceAwsVPCEndpointRouteTableAssociationDelete(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ec2conn
	endpointId := d.Get("vpc_endpoint_id").(string)
	rtId := d.Get("route_table_id").(string)

	input := &ec2.ModifyVpcEndpointInput{
		VpcEndpointId:       aws.String(endpointId),
		RemoveRouteTableIds: aws.StringSlice([]string{rtId}),
	}

	_, err := conn.ModifyVpcEndpoint(input)
	if err != nil {
		ec2err, ok := err.(awserr.Error)
		if !ok {
			return fmt.Errorf("Error deleting VPC Endpoint/Route Table association: %s", err.Error())
		}

		switch ec2err.Code() {
		case "InvalidVpcEndpointId.NotFound":
			fallthrough
		case "InvalidRouteTableId.NotFound":
			fallthrough
		case "InvalidParameter":
			log.Printf("[DEBUG] VPC Endpoint/Route Table association is already gone")
		default:
			return fmt.Errorf("Error deleting VPC Endpoint/Route Table association: %s", err.Error())
		}
	}

	log.Printf("[DEBUG] VPC Endpoint/Route Table association %q deleted", d.Id())
	d.SetId("")

	return nil
}

func findResourceVPCEndpoint(conn *ec2.EC2, id string) (*ec2.VpcEndpoint, error) {
	input := &ec2.DescribeVpcEndpointsInput{
		VpcEndpointIds: aws.StringSlice([]string{id}),
	}

	log.Printf("[DEBUG] Reading VPC Endpoint: %q", id)
	output, err := conn.DescribeVpcEndpoints(input)
	if err != nil {
		return nil, err
	}

	if output.VpcEndpoints == nil {
		return nil, fmt.Errorf("No VPC Endpoints were found for %q", id)
	}

	return output.VpcEndpoints[0], nil
}

func vpcEndpointIdRouteTableIdHash(endpointId, rtId string) string {
	return fmt.Sprintf("a-%s%d", endpointId, hashcode.String(rtId))
}


<|start_filename|>vendor/github.com/hashicorp/terraform/backend/legacy/legacy_test.go<|end_filename|>
package legacy

import (
	"testing"

	"github.com/hashicorp/terraform/backend"
	"github.com/hashicorp/terraform/state/remote"
)

func TestInit(t *testing.T) {
	m := make(map[string]func() backend.Backend)
	Init(m)

	for k, _ := range remote.BuiltinClients {
		b, ok := m[k]
		if !ok {
			t.Fatalf("missing: %s", k)
		}

		if typ := b().(*Backend).Type; typ != k {
			t.Fatalf("bad type: %s", typ)
		}
	}
}

func TestInit_ignoreExisting(t *testing.T) {
	m := make(map[string]func() backend.Backend)
	m["local"] = nil
	Init(m)

	if v, ok := m["local"]; !ok || v != nil {
		t.Fatalf("bad: %#v", m)
	}
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/hashicorp/hcl2/hcl/json/navigation.go<|end_filename|>
package json

import (
	"strings"
)

type navigation struct {
	root *objectVal
}

// Implementation of zcled.ContextString
func (n navigation) ContextString(offset int) string {
	steps := navigationStepsRev(n.root, offset)
	if steps == nil {
		return ""
	}

	// We built our slice backwards, so we'll reverse it in-place now.
	half := len(steps) / 2 // integer division
	for i := 0; i < half; i++ {
		steps[i], steps[len(steps)-1-i] = steps[len(steps)-1-i], steps[i]
	}

	return strings.Join(steps, ".")
}

func navigationStepsRev(obj *objectVal, offset int) []string {
	// Do any of our properties have an object that contains the target
	// offset?
	for k, attr := range obj.Attrs {
		ov, ok := attr.Value.(*objectVal)
		if !ok {
			continue
		}

		if ov.SrcRange.ContainsOffset(offset) {
			return append(navigationStepsRev(ov, offset), k)
		}
	}
	return nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_autoscaling_lifecycle_hook.go<|end_filename|>
package aws

import (
	"log"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/autoscaling"
	"github.com/hashicorp/errwrap"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsAutoscalingLifecycleHook() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsAutoscalingLifecycleHookPut,
		Read:   resourceAwsAutoscalingLifecycleHookRead,
		Update: resourceAwsAutoscalingLifecycleHookPut,
		Delete: resourceAwsAutoscalingLifecycleHookDelete,

		Schema: map[string]*schema.Schema{
			"name": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"autoscaling_group_name": {
				Type:     schema.TypeString,
				Required: true,
			},
			"default_result": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},
			"heartbeat_timeout": {
				Type:     schema.TypeInt,
				Optional: true,
			},
			"lifecycle_transition": {
				Type:     schema.TypeString,
				Required: true,
			},
			"notification_metadata": {
				Type:     schema.TypeString,
				Optional: true,
			},
			"notification_target_arn": {
				Type:     schema.TypeString,
				Optional: true,
			},
			"role_arn": {
				Type:     schema.TypeString,
				Optional: true,
			},
		},
	}
}

func resourceAwsAutoscalingLifecycleHookPutOp(conn *autoscaling.AutoScaling, params *autoscaling.PutLifecycleHookInput) error {
	log.Printf("[DEBUG] AutoScaling PutLifecyleHook: %s", params)
	return resource.Retry(5*time.Minute, func() *resource.RetryError {
		_, err := conn.PutLifecycleHook(params)

		if err != nil {
			if awsErr, ok := err.(awserr.Error); ok {
				if strings.Contains(awsErr.Message(), "Unable to publish test message to notification target") {
					return resource.RetryableError(errwrap.Wrapf("[DEBUG] Retrying AWS AutoScaling Lifecycle Hook: {{err}}", awsErr))
				}
			}
			return resource.NonRetryableError(errwrap.Wrapf("Error putting lifecycle hook: {{err}}", err))
		}
		return nil
	})
}

func resourceAwsAutoscalingLifecycleHookPut(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).autoscalingconn
	params := getAwsAutoscalingPutLifecycleHookInput(d)

	if err := resourceAwsAutoscalingLifecycleHookPutOp(conn, &params); err != nil {
		return err
	}

	d.SetId(d.Get("name").(string))

	return resourceAwsAutoscalingLifecycleHookRead(d, meta)
}

func resourceAwsAutoscalingLifecycleHookRead(d *schema.ResourceData, meta interface{}) error {
	p, err := getAwsAutoscalingLifecycleHook(d, meta)
	if err != nil {
		return err
	}
	if p == nil {
		log.Printf("[WARN] Autoscaling Lifecycle Hook (%s) not found, removing from state", d.Id())
		d.SetId("")
		return nil
	}

	log.Printf("[DEBUG] Read Lifecycle Hook: ASG: %s, SH: %s, Obj: %#v", d.Get("autoscaling_group_name"), d.Get("name"), p)

	d.Set("default_result", p.DefaultResult)
	d.Set("heartbeat_timeout", p.HeartbeatTimeout)
	d.Set("lifecycle_transition", p.LifecycleTransition)
	d.Set("notification_metadata", p.NotificationMetadata)
	d.Set("notification_target_arn", p.NotificationTargetARN)
	d.Set("name", p.LifecycleHookName)
	d.Set("role_arn", p.RoleARN)

	return nil
}

func resourceAwsAutoscalingLifecycleHookDelete(d *schema.ResourceData, meta interface{}) error {
	autoscalingconn := meta.(*AWSClient).autoscalingconn
	p, err := getAwsAutoscalingLifecycleHook(d, meta)
	if err != nil {
		return err
	}
	if p == nil {
		return nil
	}

	params := autoscaling.DeleteLifecycleHookInput{
		AutoScalingGroupName: aws.String(d.Get("autoscaling_group_name").(string)),
		LifecycleHookName:    aws.String(d.Get("name").(string)),
	}
	if _, err := autoscalingconn.DeleteLifecycleHook(&params); err != nil {
		return errwrap.Wrapf("Autoscaling Lifecycle Hook: {{err}}", err)
	}

	d.SetId("")
	return nil
}

func getAwsAutoscalingPutLifecycleHookInput(d *schema.ResourceData) autoscaling.PutLifecycleHookInput {
	var params = autoscaling.PutLifecycleHookInput{
		AutoScalingGroupName: aws.String(d.Get("autoscaling_group_name").(string)),
		LifecycleHookName:    aws.String(d.Get("name").(string)),
	}

	if v, ok := d.GetOk("default_result"); ok {
		params.DefaultResult = aws.String(v.(string))
	}

	if v, ok := d.GetOk("heartbeat_timeout"); ok {
		params.HeartbeatTimeout = aws.Int64(int64(v.(int)))
	}

	if v, ok := d.GetOk("lifecycle_transition"); ok {
		params.LifecycleTransition = aws.String(v.(string))
	}

	if v, ok := d.GetOk("notification_metadata"); ok {
		params.NotificationMetadata = aws.String(v.(string))
	}

	if v, ok := d.GetOk("notification_target_arn"); ok {
		params.NotificationTargetARN = aws.String(v.(string))
	}

	if v, ok := d.GetOk("role_arn"); ok {
		params.RoleARN = aws.String(v.(string))
	}

	return params
}

func getAwsAutoscalingLifecycleHook(d *schema.ResourceData, meta interface{}) (*autoscaling.LifecycleHook, error) {
	autoscalingconn := meta.(*AWSClient).autoscalingconn

	params := autoscaling.DescribeLifecycleHooksInput{
		AutoScalingGroupName: aws.String(d.Get("autoscaling_group_name").(string)),
		LifecycleHookNames:   []*string{aws.String(d.Get("name").(string))},
	}

	log.Printf("[DEBUG] AutoScaling Lifecycle Hook Describe Params: %#v", params)
	resp, err := autoscalingconn.DescribeLifecycleHooks(&params)
	if err != nil {
		return nil, errwrap.Wrapf("Error retrieving lifecycle hooks: {{err}}", err)
	}

	// find lifecycle hooks
	name := d.Get("name")
	for idx, sp := range resp.LifecycleHooks {
		if *sp.LifecycleHookName == name {
			return resp.LifecycleHooks[idx], nil
		}
	}

	// lifecycle hook not found
	return nil, nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/data_source_aws_elb_service_account.go<|end_filename|>
package aws

import (
	"fmt"

	"github.com/hashicorp/terraform/helper/schema"
)

// See http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/enable-access-logs.html#attach-bucket-policy
var elbAccountIdPerRegionMap = map[string]string{
	"ap-northeast-1": "582318560864",
	"ap-northeast-2": "600734575887",
	"ap-south-1":     "718504428378",
	"ap-southeast-1": "114774131450",
	"ap-southeast-2": "783225319266",
	"ca-central-1":   "985666609251",
	"cn-north-1":     "638102146993",
	"eu-central-1":   "054676820928",
	"eu-west-1":      "156460612806",
	"eu-west-2":      "652711504416",
	"eu-west-3":      "009996457667",
	"sa-east-1":      "507241528517",
	"us-east-1":      "127311923021",
	"us-east-2":      "033677994240",
	"us-gov-west":    "048591011584",
	"us-west-1":      "027434742980",
	"us-west-2":      "797873946194",
}

func dataSourceAwsElbServiceAccount() *schema.Resource {
	return &schema.Resource{
		Read: dataSourceAwsElbServiceAccountRead,

		Schema: map[string]*schema.Schema{
			"region": {
				Type:     schema.TypeString,
				Optional: true,
			},
			"arn": {
				Type:     schema.TypeString,
				Computed: true,
			},
		},
	}
}

func dataSourceAwsElbServiceAccountRead(d *schema.ResourceData, meta interface{}) error {
	region := meta.(*AWSClient).region
	if v, ok := d.GetOk("region"); ok {
		region = v.(string)
	}

	if accid, ok := elbAccountIdPerRegionMap[region]; ok {
		d.SetId(accid)

		d.Set("arn", fmt.Sprintf("arn:%s:iam::%s:root", meta.(*AWSClient).partition, accid))

		return nil
	}

	return fmt.Errorf("Unknown region (%q)", region)
}


<|start_filename|>vendor/github.com/hashicorp/terraform/helper/schema/resource_diff_test.go<|end_filename|>
package schema

import (
	"reflect"
	"testing"

	"github.com/davecgh/go-spew/spew"
	"github.com/hashicorp/terraform/terraform"
)

// testSetFunc is a very simple function we use to test a foo/bar complex set.
// Both "foo" and "bar" are int values.
//
// This is not foolproof as since it performs sums, you can run into
// collisions. Spec tests accordingly. :P
func testSetFunc(v interface{}) int {
	m := v.(map[string]interface{})
	return m["foo"].(int) + m["bar"].(int)
}

// resourceDiffTestCase provides a test case struct for SetNew and SetDiff.
type resourceDiffTestCase struct {
	Name          string
	Schema        map[string]*Schema
	State         *terraform.InstanceState
	Config        *terraform.ResourceConfig
	Diff          *terraform.InstanceDiff
	Key           string
	OldValue      interface{}
	NewValue      interface{}
	Expected      *terraform.InstanceDiff
	ExpectedError bool
}

// testDiffCases produces a list of test cases for use with SetNew and SetDiff.
func testDiffCases(t *testing.T, oldPrefix string, oldOffset int, computed bool) []resourceDiffTestCase {
	return []resourceDiffTestCase{
		resourceDiffTestCase{
			Name: "basic primitive diff",
			Schema: map[string]*Schema{
				"foo": &Schema{
					Type:     TypeString,
					Optional: true,
					Computed: true,
				},
			},
			State: &terraform.InstanceState{
				Attributes: map[string]string{
					"foo": "bar",
				},
			},
			Config: testConfig(t, map[string]interface{}{
				"foo": "baz",
			}),
			Diff: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"foo": &terraform.ResourceAttrDiff{
						Old: "bar",
						New: "baz",
					},
				},
			},
			Key:      "foo",
			NewValue: "qux",
			Expected: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"foo": &terraform.ResourceAttrDiff{
						Old: "bar",
						New: func() string {
							if computed {
								return ""
							}
							return "qux"
						}(),
						NewComputed: computed,
					},
				},
			},
		},
		resourceDiffTestCase{
			Name: "basic set diff",
			Schema: map[string]*Schema{
				"foo": &Schema{
					Type:     TypeSet,
					Optional: true,
					Computed: true,
					Elem:     &Schema{Type: TypeString},
					Set:      HashString,
				},
			},
			State: &terraform.InstanceState{
				Attributes: map[string]string{
					"foo.#":          "1",
					"foo.1996459178": "bar",
				},
			},
			Config: testConfig(t, map[string]interface{}{
				"foo": []interface{}{"baz"},
			}),
			Diff: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"foo.1996459178": &terraform.ResourceAttrDiff{
						Old:        "bar",
						New:        "",
						NewRemoved: true,
					},
					"foo.2015626392": &terraform.ResourceAttrDiff{
						Old: "",
						New: "baz",
					},
				},
			},
			Key:      "foo",
			NewValue: []interface{}{"qux"},
			Expected: &terraform.InstanceDiff{
				Attributes: func() map[string]*terraform.ResourceAttrDiff {
					result := map[string]*terraform.ResourceAttrDiff{}
					if computed {
						result["foo.#"] = &terraform.ResourceAttrDiff{
							Old:         "1",
							New:         "",
							NewComputed: true,
						}
					} else {
						result["foo.2800005064"] = &terraform.ResourceAttrDiff{
							Old: "",
							New: "qux",
						}
						result["foo.1996459178"] = &terraform.ResourceAttrDiff{
							Old:        "bar",
							New:        "",
							NewRemoved: true,
						}
					}
					return result
				}(),
			},
		},
		resourceDiffTestCase{
			Name: "basic list diff",
			Schema: map[string]*Schema{
				"foo": &Schema{
					Type:     TypeList,
					Optional: true,
					Computed: true,
					Elem:     &Schema{Type: TypeString},
				},
			},
			State: &terraform.InstanceState{
				Attributes: map[string]string{
					"foo.#": "1",
					"foo.0": "bar",
				},
			},
			Config: testConfig(t, map[string]interface{}{
				"foo": []interface{}{"baz"},
			}),
			Diff: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"foo.0": &terraform.ResourceAttrDiff{
						Old: "bar",
						New: "baz",
					},
				},
			},
			Key:      "foo",
			NewValue: []interface{}{"qux"},
			Expected: &terraform.InstanceDiff{
				Attributes: func() map[string]*terraform.ResourceAttrDiff {
					result := make(map[string]*terraform.ResourceAttrDiff)
					if computed {
						result["foo.#"] = &terraform.ResourceAttrDiff{
							Old:         "1",
							New:         "",
							NewComputed: true,
						}
					} else {
						result["foo.0"] = &terraform.ResourceAttrDiff{
							Old: "bar",
							New: "qux",
						}
					}
					return result
				}(),
			},
		},
		resourceDiffTestCase{
			Name: "basic map diff",
			Schema: map[string]*Schema{
				"foo": &Schema{
					Type:     TypeMap,
					Optional: true,
					Computed: true,
				},
			},
			State: &terraform.InstanceState{
				Attributes: map[string]string{
					"foo.%":   "1",
					"foo.bar": "baz",
				},
			},
			Config: testConfig(t, map[string]interface{}{
				"foo": map[string]interface{}{"bar": "qux"},
			}),
			Diff: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"foo.bar": &terraform.ResourceAttrDiff{
						Old: "baz",
						New: "qux",
					},
				},
			},
			Key:      "foo",
			NewValue: map[string]interface{}{"bar": "quux"},
			Expected: &terraform.InstanceDiff{
				Attributes: func() map[string]*terraform.ResourceAttrDiff {
					result := make(map[string]*terraform.ResourceAttrDiff)
					if computed {
						result["foo.%"] = &terraform.ResourceAttrDiff{
							Old:         "",
							New:         "",
							NewComputed: true,
						}
						result["foo.bar"] = &terraform.ResourceAttrDiff{
							Old:        "baz",
							New:        "",
							NewRemoved: true,
						}
					} else {
						result["foo.bar"] = &terraform.ResourceAttrDiff{
							Old: "baz",
							New: "quux",
						}
					}
					return result
				}(),
			},
		},
		resourceDiffTestCase{
			Name: "additional diff with primitive",
			Schema: map[string]*Schema{
				"foo": &Schema{
					Type:     TypeString,
					Optional: true,
				},
				"one": &Schema{
					Type:     TypeString,
					Optional: true,
					Computed: true,
				},
			},
			State: &terraform.InstanceState{
				Attributes: map[string]string{
					"foo": "bar",
					"one": "two",
				},
			},
			Config: testConfig(t, map[string]interface{}{
				"foo": "baz",
			}),
			Diff: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"foo": &terraform.ResourceAttrDiff{
						Old: "bar",
						New: "baz",
					},
				},
			},
			Key:      "one",
			NewValue: "four",
			Expected: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"foo": &terraform.ResourceAttrDiff{
						Old: "bar",
						New: "baz",
					},
					"one": &terraform.ResourceAttrDiff{
						Old: "two",
						New: func() string {
							if computed {
								return ""
							}
							return "four"
						}(),
						NewComputed: computed,
					},
				},
			},
		},
		resourceDiffTestCase{
			Name: "additional diff with primitive computed only",
			Schema: map[string]*Schema{
				"foo": &Schema{
					Type:     TypeString,
					Optional: true,
				},
				"one": &Schema{
					Type:     TypeString,
					Computed: true,
				},
			},
			State: &terraform.InstanceState{
				Attributes: map[string]string{
					"foo": "bar",
					"one": "two",
				},
			},
			Config: testConfig(t, map[string]interface{}{
				"foo": "baz",
			}),
			Diff: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"foo": &terraform.ResourceAttrDiff{
						Old: "bar",
						New: "baz",
					},
				},
			},
			Key:      "one",
			NewValue: "three",
			Expected: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"foo": &terraform.ResourceAttrDiff{
						Old: "bar",
						New: "baz",
					},
					"one": &terraform.ResourceAttrDiff{
						Old: "two",
						New: func() string {
							if computed {
								return ""
							}
							return "three"
						}(),
						NewComputed: computed,
					},
				},
			},
		},
		resourceDiffTestCase{
			Name: "complex-ish set diff",
			Schema: map[string]*Schema{
				"top": &Schema{
					Type:     TypeSet,
					Optional: true,
					Computed: true,
					Elem: &Resource{
						Schema: map[string]*Schema{
							"foo": &Schema{
								Type:     TypeInt,
								Optional: true,
								Computed: true,
							},
							"bar": &Schema{
								Type:     TypeInt,
								Optional: true,
								Computed: true,
							},
						},
					},
					Set: testSetFunc,
				},
			},
			State: &terraform.InstanceState{
				Attributes: map[string]string{
					"top.#":      "2",
					"top.3.foo":  "1",
					"top.3.bar":  "2",
					"top.23.foo": "11",
					"top.23.bar": "12",
				},
			},
			Config: testConfig(t, map[string]interface{}{
				"top": []interface{}{
					map[string]interface{}{
						"foo": 1,
						"bar": 3,
					},
					map[string]interface{}{
						"foo": 12,
						"bar": 12,
					},
				},
			}),
			Diff: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"top.4.foo": &terraform.ResourceAttrDiff{
						Old: "",
						New: "1",
					},
					"top.4.bar": &terraform.ResourceAttrDiff{
						Old: "",
						New: "3",
					},
					"top.24.foo": &terraform.ResourceAttrDiff{
						Old: "",
						New: "12",
					},
					"top.24.bar": &terraform.ResourceAttrDiff{
						Old: "",
						New: "12",
					},
				},
			},
			Key: "top",
			NewValue: NewSet(testSetFunc, []interface{}{
				map[string]interface{}{
					"foo": 1,
					"bar": 4,
				},
				map[string]interface{}{
					"foo": 13,
					"bar": 12,
				},
				map[string]interface{}{
					"foo": 21,
					"bar": 22,
				},
			}),
			Expected: &terraform.InstanceDiff{
				Attributes: func() map[string]*terraform.ResourceAttrDiff {
					result := make(map[string]*terraform.ResourceAttrDiff)
					if computed {
						result["top.#"] = &terraform.ResourceAttrDiff{
							Old:         "2",
							New:         "",
							NewComputed: true,
						}
					} else {
						result["top.#"] = &terraform.ResourceAttrDiff{
							Old: "2",
							New: "3",
						}
						result["top.5.foo"] = &terraform.ResourceAttrDiff{
							Old: "",
							New: "1",
						}
						result["top.5.bar"] = &terraform.ResourceAttrDiff{
							Old: "",
							New: "4",
						}
						result["top.25.foo"] = &terraform.ResourceAttrDiff{
							Old: "",
							New: "13",
						}
						result["top.25.bar"] = &terraform.ResourceAttrDiff{
							Old: "",
							New: "12",
						}
						result["top.43.foo"] = &terraform.ResourceAttrDiff{
							Old: "",
							New: "21",
						}
						result["top.43.bar"] = &terraform.ResourceAttrDiff{
							Old: "",
							New: "22",
						}
					}
					return result
				}(),
			},
		},
		resourceDiffTestCase{
			Name: "primitive, no diff, no refresh",
			Schema: map[string]*Schema{
				"foo": &Schema{
					Type:     TypeString,
					Computed: true,
				},
			},
			State: &terraform.InstanceState{
				Attributes: map[string]string{
					"foo": "bar",
				},
			},
			Config:   testConfig(t, map[string]interface{}{}),
			Diff:     &terraform.InstanceDiff{Attributes: map[string]*terraform.ResourceAttrDiff{}},
			Key:      "foo",
			NewValue: "baz",
			Expected: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"foo": &terraform.ResourceAttrDiff{
						Old: "bar",
						New: func() string {
							if computed {
								return ""
							}
							return "baz"
						}(),
						NewComputed: computed,
					},
				},
			},
		},
		resourceDiffTestCase{
			Name: "non-computed key, should error",
			Schema: map[string]*Schema{
				"foo": &Schema{
					Type:     TypeString,
					Required: true,
				},
			},
			State: &terraform.InstanceState{
				Attributes: map[string]string{
					"foo": "bar",
				},
			},
			Config: testConfig(t, map[string]interface{}{
				"foo": "baz",
			}),
			Diff: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"foo": &terraform.ResourceAttrDiff{
						Old: "bar",
						New: "baz",
					},
				},
			},
			Key:           "foo",
			NewValue:      "qux",
			ExpectedError: true,
		},
		resourceDiffTestCase{
			Name: "bad key, should error",
			Schema: map[string]*Schema{
				"foo": &Schema{
					Type:     TypeString,
					Required: true,
				},
			},
			State: &terraform.InstanceState{
				Attributes: map[string]string{
					"foo": "bar",
				},
			},
			Config: testConfig(t, map[string]interface{}{
				"foo": "baz",
			}),
			Diff: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"foo": &terraform.ResourceAttrDiff{
						Old: "bar",
						New: "baz",
					},
				},
			},
			Key:           "bad",
			NewValue:      "qux",
			ExpectedError: true,
		},
	}
}

func TestSetNew(t *testing.T) {
	testCases := testDiffCases(t, "", 0, false)
	for _, tc := range testCases {
		t.Run(tc.Name, func(t *testing.T) {
			m := schemaMap(tc.Schema)
			d := newResourceDiff(tc.Schema, tc.Config, tc.State, tc.Diff)
			err := d.SetNew(tc.Key, tc.NewValue)
			switch {
			case err != nil && !tc.ExpectedError:
				t.Fatalf("bad: %s", err)
			case err == nil && tc.ExpectedError:
				t.Fatalf("Expected error, got none")
			case err != nil && tc.ExpectedError:
				return
			}
			for _, k := range d.UpdatedKeys() {
				if err := m.diff(k, m[k], tc.Diff, d, false); err != nil {
					t.Fatalf("bad: %s", err)
				}
			}
			if !reflect.DeepEqual(tc.Expected, tc.Diff) {
				t.Fatalf("Expected %s, got %s", spew.Sdump(tc.Expected), spew.Sdump(tc.Diff))
			}
		})
	}
}

func TestSetNewComputed(t *testing.T) {
	testCases := testDiffCases(t, "", 0, true)
	for _, tc := range testCases {
		t.Run(tc.Name, func(t *testing.T) {
			m := schemaMap(tc.Schema)
			d := newResourceDiff(tc.Schema, tc.Config, tc.State, tc.Diff)
			err := d.SetNewComputed(tc.Key)
			switch {
			case err != nil && !tc.ExpectedError:
				t.Fatalf("bad: %s", err)
			case err == nil && tc.ExpectedError:
				t.Fatalf("Expected error, got none")
			case err != nil && tc.ExpectedError:
				return
			}
			for _, k := range d.UpdatedKeys() {
				if err := m.diff(k, m[k], tc.Diff, d, false); err != nil {
					t.Fatalf("bad: %s", err)
				}
			}
			if !reflect.DeepEqual(tc.Expected, tc.Diff) {
				t.Fatalf("Expected %s, got %s", spew.Sdump(tc.Expected), spew.Sdump(tc.Diff))
			}
		})
	}
}

func TestForceNew(t *testing.T) {
	cases := []resourceDiffTestCase{
		resourceDiffTestCase{
			Name: "basic primitive diff",
			Schema: map[string]*Schema{
				"foo": &Schema{
					Type:     TypeString,
					Optional: true,
					Computed: true,
				},
			},
			State: &terraform.InstanceState{
				Attributes: map[string]string{
					"foo": "bar",
				},
			},
			Config: testConfig(t, map[string]interface{}{
				"foo": "baz",
			}),
			Diff: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"foo": &terraform.ResourceAttrDiff{
						Old: "bar",
						New: "baz",
					},
				},
			},
			Key: "foo",
			Expected: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"foo": &terraform.ResourceAttrDiff{
						Old:         "bar",
						New:         "baz",
						RequiresNew: true,
					},
				},
			},
		},
		resourceDiffTestCase{
			Name: "no change, should error",
			Schema: map[string]*Schema{
				"foo": &Schema{
					Type:     TypeString,
					Optional: true,
					Computed: true,
				},
			},
			State: &terraform.InstanceState{
				Attributes: map[string]string{
					"foo": "bar",
				},
			},
			Config: testConfig(t, map[string]interface{}{
				"foo": "bar",
			}),
			ExpectedError: true,
		},
		resourceDiffTestCase{
			Name: "basic primitive, non-computed key",
			Schema: map[string]*Schema{
				"foo": &Schema{
					Type:     TypeString,
					Required: true,
				},
			},
			State: &terraform.InstanceState{
				Attributes: map[string]string{
					"foo": "bar",
				},
			},
			Config: testConfig(t, map[string]interface{}{
				"foo": "baz",
			}),
			Diff: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"foo": &terraform.ResourceAttrDiff{
						Old: "bar",
						New: "baz",
					},
				},
			},
			Key: "foo",
			Expected: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"foo": &terraform.ResourceAttrDiff{
						Old:         "bar",
						New:         "baz",
						RequiresNew: true,
					},
				},
			},
		},
	}
	for _, tc := range cases {
		t.Run(tc.Name, func(t *testing.T) {
			m := schemaMap(tc.Schema)
			d := newResourceDiff(m, tc.Config, tc.State, tc.Diff)
			err := d.ForceNew(tc.Key)
			switch {
			case err != nil && !tc.ExpectedError:
				t.Fatalf("bad: %s", err)
			case err == nil && tc.ExpectedError:
				t.Fatalf("Expected error, got none")
			case err != nil && tc.ExpectedError:
				return
			}
			for _, k := range d.UpdatedKeys() {
				if err := m.diff(k, m[k], tc.Diff, d, false); err != nil {
					t.Fatalf("bad: %s", err)
				}
			}
			if !reflect.DeepEqual(tc.Expected, tc.Diff) {
				t.Fatalf("Expected %s, got %s", spew.Sdump(tc.Expected), spew.Sdump(tc.Diff))
			}
		})
	}
}

func TestClear(t *testing.T) {
	cases := []resourceDiffTestCase{
		resourceDiffTestCase{
			Name: "basic primitive diff",
			Schema: map[string]*Schema{
				"foo": &Schema{
					Type:     TypeString,
					Optional: true,
					Computed: true,
				},
			},
			State: &terraform.InstanceState{
				Attributes: map[string]string{
					"foo": "bar",
				},
			},
			Config: testConfig(t, map[string]interface{}{
				"foo": "baz",
			}),
			Diff: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"foo": &terraform.ResourceAttrDiff{
						Old: "bar",
						New: "baz",
					},
				},
			},
			Key:      "foo",
			Expected: &terraform.InstanceDiff{Attributes: map[string]*terraform.ResourceAttrDiff{}},
		},
		resourceDiffTestCase{
			Name: "non-computed key, should error",
			Schema: map[string]*Schema{
				"foo": &Schema{
					Type:     TypeString,
					Required: true,
				},
			},
			State: &terraform.InstanceState{
				Attributes: map[string]string{
					"foo": "bar",
				},
			},
			Config: testConfig(t, map[string]interface{}{
				"foo": "baz",
			}),
			Diff: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"foo": &terraform.ResourceAttrDiff{
						Old: "bar",
						New: "baz",
					},
				},
			},
			Key:           "foo",
			ExpectedError: true,
		},
		resourceDiffTestCase{
			Name: "multi-value, one removed",
			Schema: map[string]*Schema{
				"foo": &Schema{
					Type:     TypeString,
					Optional: true,
					Computed: true,
				},
				"one": &Schema{
					Type:     TypeString,
					Optional: true,
					Computed: true,
				},
			},
			State: &terraform.InstanceState{
				Attributes: map[string]string{
					"foo": "bar",
					"one": "two",
				},
			},
			Config: testConfig(t, map[string]interface{}{
				"foo": "baz",
				"one": "three",
			}),
			Diff: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"foo": &terraform.ResourceAttrDiff{
						Old: "bar",
						New: "baz",
					},
					"one": &terraform.ResourceAttrDiff{
						Old: "two",
						New: "three",
					},
				},
			},
			Key: "one",
			Expected: &terraform.InstanceDiff{
				Attributes: map[string]*terraform.ResourceAttrDiff{
					"foo": &terraform.ResourceAttrDiff{
						Old: "bar",
						New: "baz",
					},
				},
			},
		},
	}
	for _, tc := range cases {
		t.Run(tc.Name, func(t *testing.T) {
			m := schemaMap(tc.Schema)
			d := newResourceDiff(m, tc.Config, tc.State, tc.Diff)
			err := d.Clear(tc.Key)
			switch {
			case err != nil && !tc.ExpectedError:
				t.Fatalf("bad: %s", err)
			case err == nil && tc.ExpectedError:
				t.Fatalf("Expected error, got none")
			case err != nil && tc.ExpectedError:
				return
			}
			for _, k := range d.UpdatedKeys() {
				if err := m.diff(k, m[k], tc.Diff, d, false); err != nil {
					t.Fatalf("bad: %s", err)
				}
			}
			if !reflect.DeepEqual(tc.Expected, tc.Diff) {
				t.Fatalf("Expected %s, got %s", spew.Sdump(tc.Expected), spew.Sdump(tc.Diff))
			}
		})
	}
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_waf_size_constraint_set.go<|end_filename|>
package aws

import (
	"log"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/waf"
	"github.com/hashicorp/errwrap"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsWafSizeConstraintSet() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsWafSizeConstraintSetCreate,
		Read:   resourceAwsWafSizeConstraintSetRead,
		Update: resourceAwsWafSizeConstraintSetUpdate,
		Delete: resourceAwsWafSizeConstraintSetDelete,

		Schema: map[string]*schema.Schema{
			"name": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"size_constraints": &schema.Schema{
				Type:     schema.TypeSet,
				Optional: true,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"field_to_match": {
							Type:     schema.TypeSet,
							Required: true,
							MaxItems: 1,
							Elem: &schema.Resource{
								Schema: map[string]*schema.Schema{
									"data": {
										Type:     schema.TypeString,
										Optional: true,
									},
									"type": {
										Type:     schema.TypeString,
										Required: true,
									},
								},
							},
						},
						"comparison_operator": &schema.Schema{
							Type:     schema.TypeString,
							Required: true,
						},
						"size": &schema.Schema{
							Type:     schema.TypeInt,
							Required: true,
						},
						"text_transformation": &schema.Schema{
							Type:     schema.TypeString,
							Required: true,
						},
					},
				},
			},
		},
	}
}

func resourceAwsWafSizeConstraintSetCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).wafconn

	log.Printf("[INFO] Creating SizeConstraintSet: %s", d.Get("name").(string))

	wr := newWafRetryer(conn, "global")
	out, err := wr.RetryWithToken(func(token *string) (interface{}, error) {
		params := &waf.CreateSizeConstraintSetInput{
			ChangeToken: token,
			Name:        aws.String(d.Get("name").(string)),
		}

		return conn.CreateSizeConstraintSet(params)
	})
	if err != nil {
		return errwrap.Wrapf("[ERROR] Error creating SizeConstraintSet: {{err}}", err)
	}
	resp := out.(*waf.CreateSizeConstraintSetOutput)

	d.SetId(*resp.SizeConstraintSet.SizeConstraintSetId)

	return resourceAwsWafSizeConstraintSetUpdate(d, meta)
}

func resourceAwsWafSizeConstraintSetRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).wafconn
	log.Printf("[INFO] Reading SizeConstraintSet: %s", d.Get("name").(string))
	params := &waf.GetSizeConstraintSetInput{
		SizeConstraintSetId: aws.String(d.Id()),
	}

	resp, err := conn.GetSizeConstraintSet(params)
	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "WAFNonexistentItemException" {
			log.Printf("[WARN] WAF IPSet (%s) not found, removing from state", d.Id())
			d.SetId("")
			return nil
		}

		return err
	}

	d.Set("name", resp.SizeConstraintSet.Name)
	d.Set("size_constraints", flattenWafSizeConstraints(resp.SizeConstraintSet.SizeConstraints))

	return nil
}

func resourceAwsWafSizeConstraintSetUpdate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).wafconn

	if d.HasChange("size_constraints") {
		o, n := d.GetChange("size_constraints")
		oldS, newS := o.(*schema.Set).List(), n.(*schema.Set).List()

		err := updateSizeConstraintSetResource(d.Id(), oldS, newS, conn)
		if err != nil {
			return errwrap.Wrapf("[ERROR] Error updating SizeConstraintSet: {{err}}", err)
		}
	}

	return resourceAwsWafSizeConstraintSetRead(d, meta)
}

func resourceAwsWafSizeConstraintSetDelete(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).wafconn

	oldConstraints := d.Get("size_constraints").(*schema.Set).List()

	if len(oldConstraints) > 0 {
		noConstraints := []interface{}{}
		err := updateSizeConstraintSetResource(d.Id(), oldConstraints, noConstraints, conn)
		if err != nil {
			return errwrap.Wrapf("[ERROR] Error deleting SizeConstraintSet: {{err}}", err)
		}
	}

	wr := newWafRetryer(conn, "global")
	_, err := wr.RetryWithToken(func(token *string) (interface{}, error) {
		req := &waf.DeleteSizeConstraintSetInput{
			ChangeToken:         token,
			SizeConstraintSetId: aws.String(d.Id()),
		}
		return conn.DeleteSizeConstraintSet(req)
	})
	if err != nil {
		return errwrap.Wrapf("[ERROR] Error deleting SizeConstraintSet: {{err}}", err)
	}

	return nil
}

func updateSizeConstraintSetResource(id string, oldS, newS []interface{}, conn *waf.WAF) error {
	wr := newWafRetryer(conn, "global")
	_, err := wr.RetryWithToken(func(token *string) (interface{}, error) {
		req := &waf.UpdateSizeConstraintSetInput{
			ChangeToken:         token,
			SizeConstraintSetId: aws.String(id),
			Updates:             diffWafSizeConstraints(oldS, newS),
		}

		log.Printf("[INFO] Updating WAF Size Constraint constraints: %s", req)
		return conn.UpdateSizeConstraintSet(req)
	})
	if err != nil {
		return errwrap.Wrapf("[ERROR] Error updating SizeConstraintSet: {{err}}", err)
	}

	return nil
}

func flattenWafSizeConstraints(sc []*waf.SizeConstraint) []interface{} {
	out := make([]interface{}, len(sc), len(sc))
	for i, c := range sc {
		m := make(map[string]interface{})
		m["comparison_operator"] = *c.ComparisonOperator
		if c.FieldToMatch != nil {
			m["field_to_match"] = flattenFieldToMatch(c.FieldToMatch)
		}
		m["size"] = *c.Size
		m["text_transformation"] = *c.TextTransformation
		out[i] = m
	}
	return out
}

func diffWafSizeConstraints(oldS, newS []interface{}) []*waf.SizeConstraintSetUpdate {
	updates := make([]*waf.SizeConstraintSetUpdate, 0)

	for _, os := range oldS {
		constraint := os.(map[string]interface{})

		if idx, contains := sliceContainsMap(newS, constraint); contains {
			newS = append(newS[:idx], newS[idx+1:]...)
			continue
		}

		updates = append(updates, &waf.SizeConstraintSetUpdate{
			Action: aws.String(waf.ChangeActionDelete),
			SizeConstraint: &waf.SizeConstraint{
				FieldToMatch:       expandFieldToMatch(constraint["field_to_match"].(*schema.Set).List()[0].(map[string]interface{})),
				ComparisonOperator: aws.String(constraint["comparison_operator"].(string)),
				Size:               aws.Int64(int64(constraint["size"].(int))),
				TextTransformation: aws.String(constraint["text_transformation"].(string)),
			},
		})
	}

	for _, ns := range newS {
		constraint := ns.(map[string]interface{})

		updates = append(updates, &waf.SizeConstraintSetUpdate{
			Action: aws.String(waf.ChangeActionInsert),
			SizeConstraint: &waf.SizeConstraint{
				FieldToMatch:       expandFieldToMatch(constraint["field_to_match"].(*schema.Set).List()[0].(map[string]interface{})),
				ComparisonOperator: aws.String(constraint["comparison_operator"].(string)),
				Size:               aws.Int64(int64(constraint["size"].(int))),
				TextTransformation: aws.String(constraint["text_transformation"].(string)),
			},
		})
	}
	return updates
}


<|start_filename|>vendor/github.com/hashicorp/terraform/command/fmt_test.go<|end_filename|>
package command

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/mitchellh/cli"
)

func TestFmt_errorReporting(t *testing.T) {
	tempDir, err := fmtFixtureWriteDir()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.RemoveAll(tempDir)

	ui := new(cli.MockUi)
	c := &FmtCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(testProvider()),
			Ui:               ui,
		},
	}

	dummy_file := filepath.Join(tempDir, "doesnotexist")
	args := []string{dummy_file}
	if code := c.Run(args); code != 2 {
		t.Fatalf("wrong exit code. errors: \n%s", ui.ErrorWriter.String())
	}

	expected := fmt.Sprintf("Error running fmt: stat %s: no such file or directory", dummy_file)
	if actual := ui.ErrorWriter.String(); !strings.Contains(actual, expected) {
		t.Fatalf("expected:\n%s\n\nto include: %q", actual, expected)
	}
}

func TestFmt_tooManyArgs(t *testing.T) {
	ui := new(cli.MockUi)
	c := &FmtCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(testProvider()),
			Ui:               ui,
		},
	}

	args := []string{
		"one",
		"two",
	}
	if code := c.Run(args); code != 1 {
		t.Fatalf("wrong exit code. errors: \n%s", ui.ErrorWriter.String())
	}

	expected := "The fmt command expects at most one argument."
	if actual := ui.ErrorWriter.String(); !strings.Contains(actual, expected) {
		t.Fatalf("expected:\n%s\n\nto include: %q", actual, expected)
	}
}

func TestFmt_workingDirectory(t *testing.T) {
	tempDir, err := fmtFixtureWriteDir()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.RemoveAll(tempDir)

	cwd, err := os.Getwd()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	err = os.Chdir(tempDir)
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Chdir(cwd)

	ui := new(cli.MockUi)
	c := &FmtCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(testProvider()),
			Ui:               ui,
		},
	}

	args := []string{}
	if code := c.Run(args); code != 0 {
		t.Fatalf("wrong exit code. errors: \n%s", ui.ErrorWriter.String())
	}

	expected := fmt.Sprintf("%s\n", fmtFixture.filename)
	if actual := ui.OutputWriter.String(); actual != expected {
		t.Fatalf("got: %q\nexpected: %q", actual, expected)
	}
}

func TestFmt_directoryArg(t *testing.T) {
	tempDir, err := fmtFixtureWriteDir()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.RemoveAll(tempDir)

	ui := new(cli.MockUi)
	c := &FmtCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(testProvider()),
			Ui:               ui,
		},
	}

	args := []string{tempDir}
	if code := c.Run(args); code != 0 {
		t.Fatalf("wrong exit code. errors: \n%s", ui.ErrorWriter.String())
	}

	expected := fmt.Sprintf("%s\n", filepath.Join(tempDir, fmtFixture.filename))
	if actual := ui.OutputWriter.String(); actual != expected {
		t.Fatalf("got: %q\nexpected: %q", actual, expected)
	}
}

func TestFmt_stdinArg(t *testing.T) {
	input := new(bytes.Buffer)
	input.Write(fmtFixture.input)

	ui := new(cli.MockUi)
	c := &FmtCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(testProvider()),
			Ui:               ui,
		},
		input: input,
	}

	args := []string{"-"}
	if code := c.Run(args); code != 0 {
		t.Fatalf("wrong exit code. errors: \n%s", ui.ErrorWriter.String())
	}

	expected := fmtFixture.golden
	if actual := ui.OutputWriter.Bytes(); !bytes.Equal(actual, expected) {
		t.Fatalf("got: %q\nexpected: %q", actual, expected)
	}
}

func TestFmt_nonDefaultOptions(t *testing.T) {
	tempDir, err := fmtFixtureWriteDir()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.RemoveAll(tempDir)

	ui := new(cli.MockUi)
	c := &FmtCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(testProvider()),
			Ui:               ui,
		},
	}

	args := []string{
		"-list=false",
		"-write=false",
		"-diff",
		tempDir,
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("wrong exit code. errors: \n%s", ui.ErrorWriter.String())
	}

	expected := fmt.Sprintf("-%s+%s", fmtFixture.input, fmtFixture.golden)
	if actual := ui.OutputWriter.String(); !strings.Contains(actual, expected) {
		t.Fatalf("expected:\n%s\n\nto include: %q", actual, expected)
	}
}

func TestFmt_check(t *testing.T) {
	tempDir, err := fmtFixtureWriteDir()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.RemoveAll(tempDir)

	ui := new(cli.MockUi)
	c := &FmtCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(testProvider()),
			Ui:               ui,
		},
	}

	args := []string{
		"-check",
		tempDir,
	}
	if code := c.Run(args); code != 3 {
		t.Fatalf("wrong exit code. expected 3")
	}

	if actual := ui.OutputWriter.String(); !strings.Contains(actual, tempDir) {
		t.Fatalf("expected:\n%s\n\nto include: %q", actual, tempDir)
	}
}

func TestFmt_checkStdin(t *testing.T) {
	input := new(bytes.Buffer)
	input.Write(fmtFixture.input)

	ui := new(cli.MockUi)
	c := &FmtCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(testProvider()),
			Ui:               ui,
		},
		input: input,
	}

	args := []string{
		"-check",
		"-",
	}
	if code := c.Run(args); code != 3 {
		t.Fatalf("wrong exit code. expected 3, got %d", code)
	}

	if ui.OutputWriter != nil {
		t.Fatalf("expected no output, got: %q", ui.OutputWriter.String())
	}
}

var fmtFixture = struct {
	filename      string
	input, golden []byte
}{
	"main.tf",
	[]byte(`  foo  =  "bar"
`),
	[]byte(`foo = "bar"
`),
}

func fmtFixtureWriteDir() (string, error) {
	dir, err := ioutil.TempDir("", "tf")
	if err != nil {
		return "", err
	}

	err = ioutil.WriteFile(filepath.Join(dir, fmtFixture.filename), fmtFixture.input, 0644)
	if err != nil {
		os.RemoveAll(dir)
		return "", err
	}

	return dir, nil
}


<|start_filename|>vendor/github.com/mitchellh/packer/packer/hook_mock.go<|end_filename|>
package packer

// MockHook is an implementation of Hook that can be used for tests.
type MockHook struct {
	RunFunc func() error

	RunCalled    bool
	RunComm      Communicator
	RunData      interface{}
	RunName      string
	RunUi        Ui
	CancelCalled bool
}

func (t *MockHook) Run(name string, ui Ui, comm Communicator, data interface{}) error {
	t.RunCalled = true
	t.RunComm = comm
	t.RunData = data
	t.RunName = name
	t.RunUi = ui

	if t.RunFunc == nil {
		return nil
	}

	return t.RunFunc()
}

func (t *MockHook) Cancel() {
	t.CancelCalled = true
}


<|start_filename|>vendor/github.com/posener/complete/predict_test.go<|end_filename|>
package complete

import (
	"sort"
	"strings"
	"testing"
)

func TestPredicate(t *testing.T) {
	t.Parallel()
	initTests()

	tests := []struct {
		name    string
		p       Predictor
		argList []string
		want    []string
	}{
		{
			name: "set",
			p:    PredictSet("a", "b", "c"),
			want: []string{"a", "b", "c"},
		},
		{
			name:    "set with does",
			p:       PredictSet("./..", "./x"),
			argList: []string{"./.", "./.."},
			want:    []string{"./.."},
		},
		{
			name: "set/empty",
			p:    PredictSet(),
			want: []string{},
		},
		{
			name: "anything",
			p:    PredictAnything,
			want: []string{},
		},
		{
			name: "or: word with nil",
			p:    PredictOr(PredictSet("a"), nil),
			want: []string{"a"},
		},
		{
			name: "or: nil with word",
			p:    PredictOr(nil, PredictSet("a")),
			want: []string{"a"},
		},
		{
			name: "or: nil with nil",
			p:    PredictOr(PredictNothing, PredictNothing),
			want: []string{},
		},
		{
			name: "or: word with word with word",
			p:    PredictOr(PredictSet("a"), PredictSet("b"), PredictSet("c")),
			want: []string{"a", "b", "c"},
		},
		{
			name: "files/txt",
			p:    PredictFiles("*.txt"),
			want: []string{"./", "dir/", "outer/", "a.txt", "b.txt", "c.txt", ".dot.txt"},
		},
		{
			name:    "files/txt",
			p:       PredictFiles("*.txt"),
			argList: []string{"./dir/"},
			want:    []string{"./dir/"},
		},
		{
			name:    "complete files inside dir if it is the only match",
			p:       PredictFiles("foo"),
			argList: []string{"./dir/", "./d"},
			want:    []string{"./dir/", "./dir/foo"},
		},
		{
			name:    "complete files inside dir when argList includes file name",
			p:       PredictFiles("*"),
			argList: []string{"./dir/f", "./dir/foo"},
			want:    []string{"./dir/foo"},
		},
		{
			name:    "files/md",
			p:       PredictFiles("*.md"),
			argList: []string{""},
			want:    []string{"./", "dir/", "outer/", "readme.md"},
		},
		{
			name:    "files/md with ./ prefix",
			p:       PredictFiles("*.md"),
			argList: []string{".", "./"},
			want:    []string{"./", "./dir/", "./outer/", "./readme.md"},
		},
		{
			name:    "dirs",
			p:       PredictDirs("*"),
			argList: []string{"di", "dir", "dir/"},
			want:    []string{"dir/"},
		},
		{
			name:    "dirs with ./ prefix",
			p:       PredictDirs("*"),
			argList: []string{"./di", "./dir", "./dir/"},
			want:    []string{"./dir/"},
		},
		{
			name:    "predict anything in dir",
			p:       PredictFiles("*"),
			argList: []string{"dir", "dir/", "di"},
			want:    []string{"dir/", "dir/foo", "dir/bar"},
		},
		{
			name:    "predict anything in dir with ./ prefix",
			p:       PredictFiles("*"),
			argList: []string{"./dir", "./dir/", "./di"},
			want:    []string{"./dir/", "./dir/foo", "./dir/bar"},
		},
		{
			name:    "root directories",
			p:       PredictDirs("*"),
			argList: []string{""},
			want:    []string{"./", "dir/", "outer/"},
		},
		{
			name:    "root directories with ./ prefix",
			p:       PredictDirs("*"),
			argList: []string{".", "./"},
			want:    []string{"./", "./dir/", "./outer/"},
		},
		{
			name:    "nested directories",
			p:       PredictDirs("*.md"),
			argList: []string{"ou", "outer", "outer/"},
			want:    []string{"outer/", "outer/inner/"},
		},
		{
			name:    "nested directories with ./ prefix",
			p:       PredictDirs("*.md"),
			argList: []string{"./ou", "./outer", "./outer/"},
			want:    []string{"./outer/", "./outer/inner/"},
		},
		{
			name:    "nested inner directory",
			p:       PredictFiles("*.md"),
			argList: []string{"outer/i"},
			want:    []string{"outer/inner/", "outer/inner/readme.md"},
		},
	}

	for _, tt := range tests {

		// no args in argList, means an empty argument
		if len(tt.argList) == 0 {
			tt.argList = append(tt.argList, "")
		}

		for _, arg := range tt.argList {
			t.Run(tt.name+"/arg="+arg, func(t *testing.T) {

				matches := tt.p.Predict(newArgs(strings.Split(arg, " ")))

				sort.Strings(matches)
				sort.Strings(tt.want)

				got := strings.Join(matches, ",")
				want := strings.Join(tt.want, ",")

				if got != want {
					t.Errorf("failed %s\ngot = %s\nwant: %s", t.Name(), got, want)
				}
			})
		}
	}
}


<|start_filename|>vendor/github.com/hashicorp/terraform/svchost/disco/disco_test.go<|end_filename|>
package disco

import (
	"crypto/tls"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"strconv"
	"testing"

	"github.com/hashicorp/terraform/svchost"
	"github.com/hashicorp/terraform/svchost/auth"
)

func TestMain(m *testing.M) {
	// During all tests we override the HTTP transport we use for discovery
	// so it'll tolerate the locally-generated TLS certificates we use
	// for test URLs.
	httpTransport = &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}

	os.Exit(m.Run())
}

func TestDiscover(t *testing.T) {
	t.Run("happy path", func(t *testing.T) {
		portStr, close := testServer(func(w http.ResponseWriter, r *http.Request) {
			resp := []byte(`
{
"thingy.v1": "http://example.com/foo",
"wotsit.v2": "http://example.net/bar"
}
`)
			w.Header().Add("Content-Type", "application/json")
			w.Header().Add("Content-Length", strconv.Itoa(len(resp)))
			w.Write(resp)
		})
		defer close()

		givenHost := "localhost" + portStr
		host, err := svchost.ForComparison(givenHost)
		if err != nil {
			t.Fatalf("test server hostname is invalid: %s", err)
		}

		d := NewDisco()
		discovered := d.Discover(host)
		gotURL := discovered.ServiceURL("thingy.v1")
		if gotURL == nil {
			t.Fatalf("found no URL for thingy.v1")
		}
		if got, want := gotURL.String(), "http://example.com/foo"; got != want {
			t.Fatalf("wrong result %q; want %q", got, want)
		}
	})
	t.Run("chunked encoding", func(t *testing.T) {
		portStr, close := testServer(func(w http.ResponseWriter, r *http.Request) {
			resp := []byte(`
{
"thingy.v1": "http://example.com/foo",
"wotsit.v2": "http://example.net/bar"
}
`)
			w.Header().Add("Content-Type", "application/json")
			// We're going to force chunked encoding here -- and thus prevent
			// the server from predicting the length -- so we can make sure
			// our client is tolerant of servers using this encoding.
			w.Write(resp[:5])
			w.(http.Flusher).Flush()
			w.Write(resp[5:])
			w.(http.Flusher).Flush()
		})
		defer close()

		givenHost := "localhost" + portStr
		host, err := svchost.ForComparison(givenHost)
		if err != nil {
			t.Fatalf("test server hostname is invalid: %s", err)
		}

		d := NewDisco()
		discovered := d.Discover(host)
		gotURL := discovered.ServiceURL("wotsit.v2")
		if gotURL == nil {
			t.Fatalf("found no URL for wotsit.v2")
		}
		if got, want := gotURL.String(), "http://example.net/bar"; got != want {
			t.Fatalf("wrong result %q; want %q", got, want)
		}
	})
	t.Run("with credentials", func(t *testing.T) {
		var authHeaderText string
		portStr, close := testServer(func(w http.ResponseWriter, r *http.Request) {
			resp := []byte(`{}`)
			authHeaderText = r.Header.Get("Authorization")
			w.Header().Add("Content-Type", "application/json")
			w.Header().Add("Content-Length", strconv.Itoa(len(resp)))
			w.Write(resp)
		})
		defer close()

		givenHost := "localhost" + portStr
		host, err := svchost.ForComparison(givenHost)
		if err != nil {
			t.Fatalf("test server hostname is invalid: %s", err)
		}

		d := NewDisco()
		d.SetCredentialsSource(auth.StaticCredentialsSource(map[svchost.Hostname]map[string]interface{}{
			host: map[string]interface{}{
				"token": "<PASSWORD>",
			},
		}))
		d.Discover(host)
		if got, want := authHeaderText, "Bearer abc123"; got != want {
			t.Fatalf("wrong Authorization header\ngot:  %s\nwant: %s", got, want)
		}
	})
	t.Run("forced services override", func(t *testing.T) {
		forced := map[string]interface{}{
			"thingy.v1": "http://example.net/foo",
			"wotsit.v2": "/foo",
		}

		d := NewDisco()
		d.ForceHostServices(svchost.Hostname("example.com"), forced)

		givenHost := "example.com"
		host, err := svchost.ForComparison(givenHost)
		if err != nil {
			t.Fatalf("test server hostname is invalid: %s", err)
		}

		discovered := d.Discover(host)
		{
			gotURL := discovered.ServiceURL("thingy.v1")
			if gotURL == nil {
				t.Fatalf("found no URL for thingy.v1")
			}
			if got, want := gotURL.String(), "http://example.net/foo"; got != want {
				t.Fatalf("wrong result %q; want %q", got, want)
			}
		}
		{
			gotURL := discovered.ServiceURL("wotsit.v2")
			if gotURL == nil {
				t.Fatalf("found no URL for wotsit.v2")
			}
			if got, want := gotURL.String(), "https://example.com/foo"; got != want {
				t.Fatalf("wrong result %q; want %q", got, want)
			}
		}
	})
	t.Run("not JSON", func(t *testing.T) {
		portStr, close := testServer(func(w http.ResponseWriter, r *http.Request) {
			resp := []byte(`{"thingy.v1": "http://example.com/foo"}`)
			w.Header().Add("Content-Type", "application/octet-stream")
			w.Write(resp)
		})
		defer close()

		givenHost := "localhost" + portStr
		host, err := svchost.ForComparison(givenHost)
		if err != nil {
			t.Fatalf("test server hostname is invalid: %s", err)
		}

		d := NewDisco()
		discovered := d.Discover(host)

		// result should be empty, which we can verify only by reaching into
		// its internals.
		if discovered.services != nil {
			t.Errorf("response not empty; should be")
		}
	})
	t.Run("malformed JSON", func(t *testing.T) {
		portStr, close := testServer(func(w http.ResponseWriter, r *http.Request) {
			resp := []byte(`{"thingy.v1": "htt`) // truncated, for example...
			w.Header().Add("Content-Type", "application/json")
			w.Write(resp)
		})
		defer close()

		givenHost := "localhost" + portStr
		host, err := svchost.ForComparison(givenHost)
		if err != nil {
			t.Fatalf("test server hostname is invalid: %s", err)
		}

		d := NewDisco()
		discovered := d.Discover(host)

		// result should be empty, which we can verify only by reaching into
		// its internals.
		if discovered.services != nil {
			t.Errorf("response not empty; should be")
		}
	})
	t.Run("JSON with redundant charset", func(t *testing.T) {
		// The JSON RFC defines no parameters for the application/json
		// MIME type, but some servers have a weird tendency to just add
		// "charset" to everything, so we'll make sure we ignore it successfully.
		// (JSON uses content sniffing for encoding detection, not media type params.)
		portStr, close := testServer(func(w http.ResponseWriter, r *http.Request) {
			resp := []byte(`{"thingy.v1": "http://example.com/foo"}`)
			w.Header().Add("Content-Type", "application/json; charset=latin-1")
			w.Write(resp)
		})
		defer close()

		givenHost := "localhost" + portStr
		host, err := svchost.ForComparison(givenHost)
		if err != nil {
			t.Fatalf("test server hostname is invalid: %s", err)
		}

		d := NewDisco()
		discovered := d.Discover(host)

		if discovered.services == nil {
			t.Errorf("response is empty; shouldn't be")
		}
	})
	t.Run("no discovery doc", func(t *testing.T) {
		portStr, close := testServer(func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(404)
		})
		defer close()

		givenHost := "localhost" + portStr
		host, err := svchost.ForComparison(givenHost)
		if err != nil {
			t.Fatalf("test server hostname is invalid: %s", err)
		}

		d := NewDisco()
		discovered := d.Discover(host)

		// result should be empty, which we can verify only by reaching into
		// its internals.
		if discovered.services != nil {
			t.Errorf("response not empty; should be")
		}
	})
	t.Run("redirect", func(t *testing.T) {
		// For this test, we have two servers and one redirects to the other
		portStr1, close1 := testServer(func(w http.ResponseWriter, r *http.Request) {
			// This server is the one that returns a real response.
			resp := []byte(`{"thingy.v1": "http://example.com/foo"}`)
			w.Header().Add("Content-Type", "application/json")
			w.Header().Add("Content-Length", strconv.Itoa(len(resp)))
			w.Write(resp)
		})
		portStr2, close2 := testServer(func(w http.ResponseWriter, r *http.Request) {
			// This server is the one that redirects.
			http.Redirect(w, r, "https://127.0.0.1"+portStr1+"/.well-known/terraform.json", 302)
		})
		defer close1()
		defer close2()

		givenHost := "localhost" + portStr2
		host, err := svchost.ForComparison(givenHost)
		if err != nil {
			t.Fatalf("test server hostname is invalid: %s", err)
		}

		d := NewDisco()
		discovered := d.Discover(host)

		gotURL := discovered.ServiceURL("thingy.v1")
		if gotURL == nil {
			t.Fatalf("found no URL for thingy.v1")
		}
		if got, want := gotURL.String(), "http://example.com/foo"; got != want {
			t.Fatalf("wrong result %q; want %q", got, want)
		}

		// The base URL for the host object should be the URL we redirected to,
		// rather than the we redirected _from_.
		gotBaseURL := discovered.discoURL.String()
		wantBaseURL := "https://127.0.0.1" + portStr1 + "/.well-known/terraform.json"
		if gotBaseURL != wantBaseURL {
			t.Errorf("incorrect base url %s; want %s", gotBaseURL, wantBaseURL)
		}

	})
}

func testServer(h func(w http.ResponseWriter, r *http.Request)) (portStr string, close func()) {
	server := httptest.NewTLSServer(http.HandlerFunc(
		func(w http.ResponseWriter, r *http.Request) {
			// Test server always returns 404 if the URL isn't what we expect
			if r.URL.Path != "/.well-known/terraform.json" {
				w.WriteHeader(404)
				w.Write([]byte("not found"))
				return
			}

			// If the URL is correct then the given hander decides the response
			h(w, r)
		},
	))

	serverURL, _ := url.Parse(server.URL)

	portStr = serverURL.Port()
	if portStr != "" {
		portStr = ":" + portStr
	}

	close = func() {
		server.Close()
	}

	return
}


<|start_filename|>vendor/github.com/mitchellh/packer/builder/amazon/common/step_pre_validate.go<|end_filename|>
package common

import (
	"context"
	"fmt"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/hashicorp/packer/helper/multistep"
	"github.com/hashicorp/packer/packer"
)

// StepPreValidate provides an opportunity to pre-validate any configuration for
// the build before actually doing any time consuming work
//
type StepPreValidate struct {
	DestAmiName     string
	ForceDeregister bool
}

func (s *StepPreValidate) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
	ui := state.Get("ui").(packer.Ui)
	if s.ForceDeregister {
		ui.Say("Force Deregister flag found, skipping prevalidating AMI Name")
		return multistep.ActionContinue
	}

	ec2conn := state.Get("ec2").(*ec2.EC2)

	ui.Say(fmt.Sprintf("Prevalidating AMI Name: %s", s.DestAmiName))
	resp, err := ec2conn.DescribeImages(&ec2.DescribeImagesInput{
		Filters: []*ec2.Filter{{
			Name:   aws.String("name"),
			Values: []*string{aws.String(s.DestAmiName)},
		}}})

	if err != nil {
		err := fmt.Errorf("Error querying AMI: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	if len(resp.Images) > 0 {
		err := fmt.Errorf("Error: name conflicts with an existing AMI: %s", *resp.Images[0].ImageId)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	return multistep.ActionContinue
}

func (s *StepPreValidate) Cleanup(multistep.StateBag) {}


<|start_filename|>vendor/github.com/hashicorp/terraform/communicator/communicator_mock.go<|end_filename|>
package communicator

import (
	"bytes"
	"fmt"
	"io"
	"strings"
	"time"

	"github.com/hashicorp/terraform/communicator/remote"
	"github.com/hashicorp/terraform/terraform"
)

// MockCommunicator is an implementation of Communicator that can be used for tests.
type MockCommunicator struct {
	RemoteScriptPath string
	Commands         map[string]bool
	Uploads          map[string]string
	UploadScripts    map[string]string
	UploadDirs       map[string]string
}

// Connect implementation of communicator.Communicator interface
func (c *MockCommunicator) Connect(o terraform.UIOutput) error {
	return nil
}

// Disconnect implementation of communicator.Communicator interface
func (c *MockCommunicator) Disconnect() error {
	return nil
}

// Timeout implementation of communicator.Communicator interface
func (c *MockCommunicator) Timeout() time.Duration {
	return time.Duration(5 * time.Second)
}

// ScriptPath implementation of communicator.Communicator interface
func (c *MockCommunicator) ScriptPath() string {
	return c.RemoteScriptPath
}

// Start implementation of communicator.Communicator interface
func (c *MockCommunicator) Start(r *remote.Cmd) error {
	if !c.Commands[r.Command] {
		return fmt.Errorf("Command not found!")
	}

	r.SetExited(0)

	return nil
}

// Upload implementation of communicator.Communicator interface
func (c *MockCommunicator) Upload(path string, input io.Reader) error {
	f, ok := c.Uploads[path]
	if !ok {
		return fmt.Errorf("Path %q not found!", path)
	}

	var buf bytes.Buffer
	buf.ReadFrom(input)
	content := strings.TrimSpace(buf.String())

	f = strings.TrimSpace(f)
	if f != content {
		return fmt.Errorf("expected: %q\n\ngot: %q\n", f, content)
	}

	return nil
}

// UploadScript implementation of communicator.Communicator interface
func (c *MockCommunicator) UploadScript(path string, input io.Reader) error {
	c.Uploads = c.UploadScripts
	return c.Upload(path, input)
}

// UploadDir implementation of communicator.Communicator interface
func (c *MockCommunicator) UploadDir(dst string, src string) error {
	v, ok := c.UploadDirs[src]
	if !ok {
		return fmt.Errorf("Directory not found!")
	}

	if v != dst {
		return fmt.Errorf("expected: %q\n\ngot: %q\n", v, dst)
	}

	return nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/communicator/communicator.go<|end_filename|>
package communicator

import (
	"fmt"
	"io"
	"time"

	"github.com/hashicorp/terraform/communicator/remote"
	"github.com/hashicorp/terraform/communicator/ssh"
	"github.com/hashicorp/terraform/communicator/winrm"
	"github.com/hashicorp/terraform/terraform"
)

// Communicator is an interface that must be implemented by all communicators
// used for any of the provisioners
type Communicator interface {
	// Connect is used to setup the connection
	Connect(terraform.UIOutput) error

	// Disconnect is used to terminate the connection
	Disconnect() error

	// Timeout returns the configured connection timeout
	Timeout() time.Duration

	// ScriptPath returns the configured script path
	ScriptPath() string

	// Start executes a remote command in a new session
	Start(*remote.Cmd) error

	// Upload is used to upload a single file
	Upload(string, io.Reader) error

	// UploadScript is used to upload a file as a executable script
	UploadScript(string, io.Reader) error

	// UploadDir is used to upload a directory
	UploadDir(string, string) error
}

// New returns a configured Communicator or an error if the connection type is not supported
func New(s *terraform.InstanceState) (Communicator, error) {
	connType := s.Ephemeral.ConnInfo["type"]
	switch connType {
	case "ssh", "": // The default connection type is ssh, so if connType is empty use ssh
		return ssh.New(s)
	case "winrm":
		return winrm.New(s)
	default:
		return nil, fmt.Errorf("connection type '%s' not supported", connType)
	}
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/data_source_aws_iam_user.go<|end_filename|>
package aws

import (
	"log"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/iam"
	"github.com/hashicorp/errwrap"
	"github.com/hashicorp/terraform/helper/schema"
)

func dataSourceAwsIAMUser() *schema.Resource {
	return &schema.Resource{
		Read: dataSourceAwsIAMUserRead,

		Schema: map[string]*schema.Schema{
			"arn": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"path": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"user_id": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"user_name": {
				Type:     schema.TypeString,
				Required: true,
			},
		},
	}
}

func dataSourceAwsIAMUserRead(d *schema.ResourceData, meta interface{}) error {
	iamconn := meta.(*AWSClient).iamconn
	userName := d.Get("user_name").(string)
	req := &iam.GetUserInput{
		UserName: aws.String(userName),
	}

	log.Printf("[DEBUG] Reading IAM User: %s", req)
	resp, err := iamconn.GetUser(req)
	if err != nil {
		return errwrap.Wrapf("error getting user: {{err}}", err)
	}

	user := resp.User
	d.SetId(*user.UserId)
	d.Set("arn", user.Arn)
	d.Set("path", user.Path)
	d.Set("user_id", user.UserId)

	return nil
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/hashicorp/hcl2/hcltest/mock.go<|end_filename|>
package hcltest

import (
	"fmt"

	"github.com/hashicorp/hcl2/hcl"
	"github.com/zclconf/go-cty/cty"
)

// MockBody returns a hcl.Body implementation that works in terms of a
// caller-constructed hcl.BodyContent, thus avoiding the need to parse
// a "real" zcl config file to use as input to a test.
func MockBody(content *hcl.BodyContent) hcl.Body {
	return mockBody{content}
}

type mockBody struct {
	C *hcl.BodyContent
}

func (b mockBody) Content(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Diagnostics) {
	content, remainI, diags := b.PartialContent(schema)
	remain := remainI.(mockBody)
	for _, attr := range remain.C.Attributes {
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Extraneous attribute in mock body",
			Detail:   fmt.Sprintf("Mock body has extraneous attribute %q.", attr.Name),
			Subject:  &attr.NameRange,
		})
	}
	for _, block := range remain.C.Blocks {
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Extraneous block in mock body",
			Detail:   fmt.Sprintf("Mock body has extraneous block of type %q.", block.Type),
			Subject:  &block.DefRange,
		})
	}
	return content, diags
}

func (b mockBody) PartialContent(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Body, hcl.Diagnostics) {
	ret := &hcl.BodyContent{
		Attributes:       map[string]*hcl.Attribute{},
		Blocks:           []*hcl.Block{},
		MissingItemRange: b.C.MissingItemRange,
	}
	remain := &hcl.BodyContent{
		Attributes:       map[string]*hcl.Attribute{},
		Blocks:           []*hcl.Block{},
		MissingItemRange: b.C.MissingItemRange,
	}
	var diags hcl.Diagnostics

	if len(schema.Attributes) != 0 {
		for _, attrS := range schema.Attributes {
			name := attrS.Name
			attr, ok := b.C.Attributes[name]
			if !ok {
				if attrS.Required {
					diags = append(diags, &hcl.Diagnostic{
						Severity: hcl.DiagError,
						Summary:  "Missing required attribute",
						Detail:   fmt.Sprintf("Mock body doesn't have attribute %q", name),
						Subject:  b.C.MissingItemRange.Ptr(),
					})
				}
				continue
			}
			ret.Attributes[name] = attr
		}
	}

	for attrN, attr := range b.C.Attributes {
		if _, ok := ret.Attributes[attrN]; !ok {
			remain.Attributes[attrN] = attr
		}
	}

	wantedBlocks := map[string]hcl.BlockHeaderSchema{}
	for _, blockS := range schema.Blocks {
		wantedBlocks[blockS.Type] = blockS
	}

	for _, block := range b.C.Blocks {
		if blockS, ok := wantedBlocks[block.Type]; ok {
			if len(block.Labels) != len(blockS.LabelNames) {
				diags = append(diags, &hcl.Diagnostic{
					Severity: hcl.DiagError,
					Summary:  "Wrong number of block labels",
					Detail:   fmt.Sprintf("Block of type %q requires %d labels, but got %d", blockS.Type, len(blockS.LabelNames), len(block.Labels)),
					Subject:  b.C.MissingItemRange.Ptr(),
				})
			}

			ret.Blocks = append(ret.Blocks, block)
		} else {
			remain.Blocks = append(remain.Blocks, block)
		}
	}

	return ret, mockBody{remain}, diags
}

func (b mockBody) JustAttributes() (hcl.Attributes, hcl.Diagnostics) {
	var diags hcl.Diagnostics
	if len(b.C.Blocks) != 0 {
		diags = append(diags, &hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Mock body has blocks",
			Detail:   "Can't use JustAttributes on a mock body with blocks.",
			Subject:  b.C.MissingItemRange.Ptr(),
		})
	}

	return b.C.Attributes, diags
}

func (b mockBody) MissingItemRange() hcl.Range {
	return b.C.MissingItemRange
}

// MockExprLiteral returns a hcl.Expression that evaluates to the given literal
// value.
func MockExprLiteral(val cty.Value) hcl.Expression {
	return mockExprLiteral{val}
}

type mockExprLiteral struct {
	V cty.Value
}

func (e mockExprLiteral) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) {
	return e.V, nil
}

func (e mockExprLiteral) Variables() []hcl.Traversal {
	return nil
}

func (e mockExprLiteral) Range() hcl.Range {
	return hcl.Range{
		Filename: "MockExprLiteral",
	}
}

func (e mockExprLiteral) StartRange() hcl.Range {
	return e.Range()
}

// MockExprVariable returns a hcl.Expression that evaluates to the value of
// the variable with the given name.
func MockExprVariable(name string) hcl.Expression {
	return mockExprVariable(name)
}

type mockExprVariable string

func (e mockExprVariable) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) {
	name := string(e)
	for ctx != nil {
		if val, ok := ctx.Variables[name]; ok {
			return val, nil
		}
		ctx = ctx.Parent()
	}

	// If we fall out here then there is no variable with the given name
	return cty.DynamicVal, hcl.Diagnostics{
		{
			Severity: hcl.DiagError,
			Summary:  "Reference to undefined variable",
			Detail:   fmt.Sprintf("Variable %q is not defined.", name),
		},
	}
}

func (e mockExprVariable) Variables() []hcl.Traversal {
	return []hcl.Traversal{
		{
			hcl.TraverseRoot{
				Name:     string(e),
				SrcRange: e.Range(),
			},
		},
	}
}

func (e mockExprVariable) Range() hcl.Range {
	return hcl.Range{
		Filename: "MockExprVariable",
	}
}

func (e mockExprVariable) StartRange() hcl.Range {
	return e.Range()
}

// MockAttrs constructs and returns a hcl.Attributes map with attributes
// derived from the given expression map.
//
// Each entry in the map becomes an attribute whose name is the key and
// whose expression is the value.
func MockAttrs(exprs map[string]hcl.Expression) hcl.Attributes {
	ret := make(hcl.Attributes)
	for name, expr := range exprs {
		ret[name] = &hcl.Attribute{
			Name: name,
			Expr: expr,
			Range: hcl.Range{
				Filename: "MockAttrs",
			},
			NameRange: hcl.Range{
				Filename: "MockAttrs",
			},
		}
	}
	return ret
}


<|start_filename|>vendor/github.com/hashicorp/terraform/command/output_test.go<|end_filename|>
package command

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/hashicorp/terraform/terraform"
	"github.com/mitchellh/cli"
)

func TestOutput(t *testing.T) {
	originalState := &terraform.State{
		Modules: []*terraform.ModuleState{
			{
				Path: []string{"root"},
				Outputs: map[string]*terraform.OutputState{
					"foo": {
						Value: "bar",
						Type:  "string",
					},
				},
			},
		},
	}

	statePath := testStateFile(t, originalState)

	ui := new(cli.MockUi)
	c := &OutputCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(testProvider()),
			Ui:               ui,
		},
	}

	args := []string{
		"-state", statePath,
		"foo",
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: \n%s", ui.ErrorWriter.String())
	}

	actual := strings.TrimSpace(ui.OutputWriter.String())
	if actual != "bar" {
		t.Fatalf("bad: %#v", actual)
	}
}

func TestModuleOutput(t *testing.T) {
	originalState := &terraform.State{
		Modules: []*terraform.ModuleState{
			{
				Path: []string{"root"},
				Outputs: map[string]*terraform.OutputState{
					"foo": {
						Value: "bar",
						Type:  "string",
					},
				},
			},
			{
				Path: []string{"root", "my_module"},
				Outputs: map[string]*terraform.OutputState{
					"blah": {
						Value: "tastatur",
						Type:  "string",
					},
				},
			},
		},
	}

	statePath := testStateFile(t, originalState)

	ui := new(cli.MockUi)
	c := &OutputCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(testProvider()),
			Ui:               ui,
		},
	}

	args := []string{
		"-state", statePath,
		"-module", "my_module",
		"blah",
	}

	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: \n%s", ui.ErrorWriter.String())
	}

	actual := strings.TrimSpace(ui.OutputWriter.String())
	if actual != "tastatur" {
		t.Fatalf("bad: %#v", actual)
	}
}

func TestModuleOutputs(t *testing.T) {
	originalState := &terraform.State{
		Modules: []*terraform.ModuleState{
			{
				Path: []string{"root"},
				Outputs: map[string]*terraform.OutputState{
					"foo": {
						Value: "bar",
						Type:  "string",
					},
				},
			},
			{
				Path: []string{"root", "my_module"},
				Outputs: map[string]*terraform.OutputState{
					"blah": {
						Value: "tastatur",
						Type:  "string",
					},
				},
			},
		},
	}

	statePath := testStateFile(t, originalState)

	ui := new(cli.MockUi)
	c := &OutputCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(testProvider()),
			Ui:               ui,
		},
	}

	args := []string{
		"-state", statePath,
		"-module", "my_module",
	}

	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: \n%s", ui.ErrorWriter.String())
	}

	actual := strings.TrimSpace(ui.OutputWriter.String())
	if actual != "blah = tastatur" {
		t.Fatalf("bad: %#v", actual)
	}
}

func TestOutput_nestedListAndMap(t *testing.T) {
	originalState := &terraform.State{
		Modules: []*terraform.ModuleState{
			{
				Path: []string{"root"},
				Outputs: map[string]*terraform.OutputState{
					"foo": {
						Value: []interface{}{
							map[string]interface{}{
								"key":  "value",
								"key2": "value2",
							},
							map[string]interface{}{
								"key": "value",
							},
						},
						Type: "list",
					},
				},
			},
		},
	}

	statePath := testStateFile(t, originalState)

	ui := new(cli.MockUi)
	c := &OutputCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(testProvider()),
			Ui:               ui,
		},
	}

	args := []string{
		"-state", statePath,
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: \n%s", ui.ErrorWriter.String())
	}

	actual := strings.TrimSpace(ui.OutputWriter.String())
	expected := "foo = [\n    {\n        key = value,\n        key2 = value2\n    },\n    {\n        key = value\n    }\n]"
	if actual != expected {
		t.Fatalf("bad:\n%#v\n%#v", expected, actual)
	}
}

func TestOutput_json(t *testing.T) {
	originalState := &terraform.State{
		Modules: []*terraform.ModuleState{
			{
				Path: []string{"root"},
				Outputs: map[string]*terraform.OutputState{
					"foo": {
						Value: "bar",
						Type:  "string",
					},
				},
			},
		},
	}

	statePath := testStateFile(t, originalState)

	ui := new(cli.MockUi)
	c := &OutputCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(testProvider()),
			Ui:               ui,
		},
	}

	args := []string{
		"-state", statePath,
		"-json",
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: \n%s", ui.ErrorWriter.String())
	}

	actual := strings.TrimSpace(ui.OutputWriter.String())
	expected := "{\n    \"foo\": {\n        \"sensitive\": false,\n        \"type\": \"string\",\n        \"value\": \"bar\"\n    }\n}"
	if actual != expected {
		t.Fatalf("bad:\n%#v\n%#v", expected, actual)
	}
}

func TestMissingModuleOutput(t *testing.T) {
	originalState := &terraform.State{
		Modules: []*terraform.ModuleState{
			{
				Path: []string{"root"},
				Outputs: map[string]*terraform.OutputState{
					"foo": {
						Value: "bar",
						Type:  "string",
					},
				},
			},
		},
	}

	statePath := testStateFile(t, originalState)

	ui := new(cli.MockUi)
	c := &OutputCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(testProvider()),
			Ui:               ui,
		},
	}

	args := []string{
		"-state", statePath,
		"-module", "not_existing_module",
		"blah",
	}

	if code := c.Run(args); code != 1 {
		t.Fatalf("bad: \n%s", ui.ErrorWriter.String())
	}
}

func TestOutput_badVar(t *testing.T) {
	originalState := &terraform.State{
		Modules: []*terraform.ModuleState{
			{
				Path: []string{"root"},
				Outputs: map[string]*terraform.OutputState{
					"foo": {
						Value: "bar",
						Type:  "string",
					},
				},
			},
		},
	}

	statePath := testStateFile(t, originalState)

	ui := new(cli.MockUi)
	c := &OutputCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(testProvider()),
			Ui:               ui,
		},
	}

	args := []string{
		"-state", statePath,
		"bar",
	}
	if code := c.Run(args); code != 1 {
		t.Fatalf("bad: \n%s", ui.ErrorWriter.String())
	}
}

func TestOutput_blank(t *testing.T) {
	originalState := &terraform.State{
		Modules: []*terraform.ModuleState{
			{
				Path: []string{"root"},
				Outputs: map[string]*terraform.OutputState{
					"foo": {
						Value: "bar",
						Type:  "string",
					},
					"name": {
						Value: "john-doe",
						Type:  "string",
					},
				},
			},
		},
	}

	statePath := testStateFile(t, originalState)

	ui := new(cli.MockUi)
	c := &OutputCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(testProvider()),
			Ui:               ui,
		},
	}

	args := []string{
		"-state", statePath,
		"",
	}

	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: \n%s", ui.ErrorWriter.String())
	}

	expectedOutput := "foo = bar\nname = john-doe\n"
	output := ui.OutputWriter.String()
	if output != expectedOutput {
		t.Fatalf("Expected output: %#v\ngiven: %#v", expectedOutput, output)
	}
}

func TestOutput_manyArgs(t *testing.T) {
	ui := new(cli.MockUi)
	c := &OutputCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(testProvider()),
			Ui:               ui,
		},
	}

	args := []string{
		"bad",
		"bad",
	}
	if code := c.Run(args); code != 1 {
		t.Fatalf("bad: \n%s", ui.OutputWriter.String())
	}
}

func TestOutput_noArgs(t *testing.T) {
	ui := new(cli.MockUi)
	c := &OutputCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(testProvider()),
			Ui:               ui,
		},
	}

	args := []string{}
	if code := c.Run(args); code != 1 {
		t.Fatalf("bad: \n%s", ui.OutputWriter.String())
	}
}

func TestOutput_noState(t *testing.T) {
	originalState := &terraform.State{}
	statePath := testStateFile(t, originalState)

	ui := new(cli.MockUi)
	c := &OutputCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(testProvider()),
			Ui:               ui,
		},
	}

	args := []string{
		"-state", statePath,
		"foo",
	}
	if code := c.Run(args); code != 1 {
		t.Fatalf("bad: \n%s", ui.ErrorWriter.String())
	}
}

func TestOutput_noVars(t *testing.T) {
	originalState := &terraform.State{
		Modules: []*terraform.ModuleState{
			{
				Path:    []string{"root"},
				Outputs: map[string]*terraform.OutputState{},
			},
		},
	}

	statePath := testStateFile(t, originalState)

	ui := new(cli.MockUi)
	c := &OutputCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(testProvider()),
			Ui:               ui,
		},
	}

	args := []string{
		"-state", statePath,
		"bar",
	}
	if code := c.Run(args); code != 1 {
		t.Fatalf("bad: \n%s", ui.ErrorWriter.String())
	}
}

func TestOutput_stateDefault(t *testing.T) {
	originalState := &terraform.State{
		Modules: []*terraform.ModuleState{
			{
				Path: []string{"root"},
				Outputs: map[string]*terraform.OutputState{
					"foo": {
						Value: "bar",
						Type:  "string",
					},
				},
			},
		},
	}

	// Write the state file in a temporary directory with the
	// default filename.
	td, err := ioutil.TempDir("", "tf")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	statePath := filepath.Join(td, DefaultStateFilename)

	f, err := os.Create(statePath)
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	err = terraform.WriteState(originalState, f)
	f.Close()
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	// Change to that directory
	cwd, err := os.Getwd()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if err := os.Chdir(filepath.Dir(statePath)); err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Chdir(cwd)

	ui := new(cli.MockUi)
	c := &OutputCommand{
		Meta: Meta{
			testingOverrides: metaOverridesForProvider(testProvider()),
			Ui:               ui,
		},
	}

	args := []string{
		"foo",
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: \n%s", ui.ErrorWriter.String())
	}

	actual := strings.TrimSpace(ui.OutputWriter.String())
	if actual != "bar" {
		t.Fatalf("bad: %#v", actual)
	}
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_route.go<|end_filename|>
package aws

import (
	"errors"
	"fmt"
	"log"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/hashicorp/terraform/helper/hashcode"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"
)

// How long to sleep if a limit-exceeded event happens
var routeTargetValidationError = errors.New("Error: more than 1 target specified. Only 1 of gateway_id, " +
	"egress_only_gateway_id, nat_gateway_id, instance_id, network_interface_id or " +
	"vpc_peering_connection_id is allowed.")

// AWS Route resource Schema declaration
func resourceAwsRoute() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsRouteCreate,
		Read:   resourceAwsRouteRead,
		Update: resourceAwsRouteUpdate,
		Delete: resourceAwsRouteDelete,
		Exists: resourceAwsRouteExists,

		Schema: map[string]*schema.Schema{
			"destination_cidr_block": {
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
			},
			"destination_ipv6_cidr_block": {
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
			},

			"destination_prefix_list_id": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"gateway_id": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"egress_only_gateway_id": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"nat_gateway_id": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"instance_id": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"instance_owner_id": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"network_interface_id": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"origin": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"state": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"route_table_id": {
				Type:     schema.TypeString,
				Required: true,
			},

			"vpc_peering_connection_id": {
				Type:     schema.TypeString,
				Optional: true,
			},
		},
	}
}

func resourceAwsRouteCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ec2conn
	var numTargets int
	var setTarget string
	allowedTargets := []string{
		"egress_only_gateway_id",
		"gateway_id",
		"nat_gateway_id",
		"instance_id",
		"network_interface_id",
		"vpc_peering_connection_id",
	}

	// Check if more than 1 target is specified
	for _, target := range allowedTargets {
		if len(d.Get(target).(string)) > 0 {
			numTargets++
			setTarget = target
		}
	}

	if numTargets > 1 {
		return routeTargetValidationError
	}

	createOpts := &ec2.CreateRouteInput{}
	// Formulate CreateRouteInput based on the target type
	switch setTarget {
	case "gateway_id":
		createOpts = &ec2.CreateRouteInput{
			RouteTableId: aws.String(d.Get("route_table_id").(string)),
			GatewayId:    aws.String(d.Get("gateway_id").(string)),
		}

		if v, ok := d.GetOk("destination_cidr_block"); ok {
			createOpts.DestinationCidrBlock = aws.String(v.(string))
		}

		if v, ok := d.GetOk("destination_ipv6_cidr_block"); ok {
			createOpts.DestinationIpv6CidrBlock = aws.String(v.(string))
		}

	case "egress_only_gateway_id":
		createOpts = &ec2.CreateRouteInput{
			RouteTableId:                aws.String(d.Get("route_table_id").(string)),
			DestinationIpv6CidrBlock:    aws.String(d.Get("destination_ipv6_cidr_block").(string)),
			EgressOnlyInternetGatewayId: aws.String(d.Get("egress_only_gateway_id").(string)),
		}
	case "nat_gateway_id":
		createOpts = &ec2.CreateRouteInput{
			RouteTableId:         aws.String(d.Get("route_table_id").(string)),
			DestinationCidrBlock: aws.String(d.Get("destination_cidr_block").(string)),
			NatGatewayId:         aws.String(d.Get("nat_gateway_id").(string)),
		}
	case "instance_id":
		createOpts = &ec2.CreateRouteInput{
			RouteTableId: aws.String(d.Get("route_table_id").(string)),
			InstanceId:   aws.String(d.Get("instance_id").(string)),
		}

		if v, ok := d.GetOk("destination_cidr_block"); ok {
			createOpts.DestinationCidrBlock = aws.String(v.(string))
		}

		if v, ok := d.GetOk("destination_ipv6_cidr_block"); ok {
			createOpts.DestinationIpv6CidrBlock = aws.String(v.(string))
		}

	case "network_interface_id":
		createOpts = &ec2.CreateRouteInput{
			RouteTableId:       aws.String(d.Get("route_table_id").(string)),
			NetworkInterfaceId: aws.String(d.Get("network_interface_id").(string)),
		}

		if v, ok := d.GetOk("destination_cidr_block"); ok {
			createOpts.DestinationCidrBlock = aws.String(v.(string))
		}

		if v, ok := d.GetOk("destination_ipv6_cidr_block"); ok {
			createOpts.DestinationIpv6CidrBlock = aws.String(v.(string))
		}

	case "vpc_peering_connection_id":
		createOpts = &ec2.CreateRouteInput{
			RouteTableId:           aws.String(d.Get("route_table_id").(string)),
			VpcPeeringConnectionId: aws.String(d.Get("vpc_peering_connection_id").(string)),
		}

		if v, ok := d.GetOk("destination_cidr_block"); ok {
			createOpts.DestinationCidrBlock = aws.String(v.(string))
		}

		if v, ok := d.GetOk("destination_ipv6_cidr_block"); ok {
			createOpts.DestinationIpv6CidrBlock = aws.String(v.(string))
		}

	default:
		return fmt.Errorf("An invalid target type specified: %s", setTarget)
	}
	log.Printf("[DEBUG] Route create config: %s", createOpts)

	// Create the route
	var err error

	err = resource.Retry(2*time.Minute, func() *resource.RetryError {
		_, err = conn.CreateRoute(createOpts)

		if err != nil {
			ec2err, ok := err.(awserr.Error)
			if !ok {
				return resource.NonRetryableError(err)
			}
			if ec2err.Code() == "InvalidParameterException" {
				log.Printf("[DEBUG] Trying to create route again: %q", ec2err.Message())
				return resource.RetryableError(err)
			}

			return resource.NonRetryableError(err)
		}

		return nil
	})
	if err != nil {
		return fmt.Errorf("Error creating route: %s", err)
	}

	var route *ec2.Route

	if v, ok := d.GetOk("destination_cidr_block"); ok {
		err = resource.Retry(2*time.Minute, func() *resource.RetryError {
			route, err = findResourceRoute(conn, d.Get("route_table_id").(string), v.(string), "")
			return resource.RetryableError(err)
		})
		if err != nil {
			return fmt.Errorf("Error finding route after creating it: %s", err)
		}
	}

	if v, ok := d.GetOk("destination_ipv6_cidr_block"); ok {
		err = resource.Retry(2*time.Minute, func() *resource.RetryError {
			route, err = findResourceRoute(conn, d.Get("route_table_id").(string), "", v.(string))
			return resource.RetryableError(err)
		})
		if err != nil {
			return fmt.Errorf("Error finding route after creating it: %s", err)
		}
	}

	d.SetId(routeIDHash(d, route))
	resourceAwsRouteSetResourceData(d, route)
	return nil
}

func resourceAwsRouteRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ec2conn
	routeTableId := d.Get("route_table_id").(string)

	destinationCidrBlock := d.Get("destination_cidr_block").(string)
	destinationIpv6CidrBlock := d.Get("destination_ipv6_cidr_block").(string)

	route, err := findResourceRoute(conn, routeTableId, destinationCidrBlock, destinationIpv6CidrBlock)
	if err != nil {
		if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidRouteTableID.NotFound" {
			log.Printf("[WARN] Route Table %q could not be found. Removing Route from state.",
				routeTableId)
			d.SetId("")
			return nil
		}
		return err
	}
	resourceAwsRouteSetResourceData(d, route)
	return nil
}

func resourceAwsRouteSetResourceData(d *schema.ResourceData, route *ec2.Route) {
	d.Set("destination_prefix_list_id", route.DestinationPrefixListId)
	d.Set("gateway_id", route.GatewayId)
	d.Set("egress_only_gateway_id", route.EgressOnlyInternetGatewayId)
	d.Set("nat_gateway_id", route.NatGatewayId)
	d.Set("instance_id", route.InstanceId)
	d.Set("instance_owner_id", route.InstanceOwnerId)
	d.Set("network_interface_id", route.NetworkInterfaceId)
	d.Set("origin", route.Origin)
	d.Set("state", route.State)
	d.Set("vpc_peering_connection_id", route.VpcPeeringConnectionId)
}

func resourceAwsRouteUpdate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ec2conn
	var numTargets int
	var setTarget string

	allowedTargets := []string{
		"egress_only_gateway_id",
		"gateway_id",
		"nat_gateway_id",
		"network_interface_id",
		"instance_id",
		"vpc_peering_connection_id",
	}
	replaceOpts := &ec2.ReplaceRouteInput{}

	// Check if more than 1 target is specified
	for _, target := range allowedTargets {
		if len(d.Get(target).(string)) > 0 {
			numTargets++
			setTarget = target
		}
	}

	switch setTarget {
	//instance_id is a special case due to the fact that AWS will "discover" the network_interace_id
	//when it creates the route and return that data.  In the case of an update, we should ignore the
	//existing network_interface_id
	case "instance_id":
		if numTargets > 2 || (numTargets == 2 && len(d.Get("network_interface_id").(string)) == 0) {
			return routeTargetValidationError
		}
	default:
		if numTargets > 1 {
			return routeTargetValidationError
		}
	}

	// Formulate ReplaceRouteInput based on the target type
	switch setTarget {
	case "gateway_id":
		replaceOpts = &ec2.ReplaceRouteInput{
			RouteTableId:         aws.String(d.Get("route_table_id").(string)),
			DestinationCidrBlock: aws.String(d.Get("destination_cidr_block").(string)),
			GatewayId:            aws.String(d.Get("gateway_id").(string)),
		}
	case "egress_only_gateway_id":
		replaceOpts = &ec2.ReplaceRouteInput{
			RouteTableId:                aws.String(d.Get("route_table_id").(string)),
			DestinationIpv6CidrBlock:    aws.String(d.Get("destination_ipv6_cidr_block").(string)),
			EgressOnlyInternetGatewayId: aws.String(d.Get("egress_only_gateway_id").(string)),
		}
	case "nat_gateway_id":
		replaceOpts = &ec2.ReplaceRouteInput{
			RouteTableId:         aws.String(d.Get("route_table_id").(string)),
			DestinationCidrBlock: aws.String(d.Get("destination_cidr_block").(string)),
			NatGatewayId:         aws.String(d.Get("nat_gateway_id").(string)),
		}
	case "instance_id":
		replaceOpts = &ec2.ReplaceRouteInput{
			RouteTableId:         aws.String(d.Get("route_table_id").(string)),
			DestinationCidrBlock: aws.String(d.Get("destination_cidr_block").(string)),
			InstanceId:           aws.String(d.Get("instance_id").(string)),
		}
	case "network_interface_id":
		replaceOpts = &ec2.ReplaceRouteInput{
			RouteTableId:         aws.String(d.Get("route_table_id").(string)),
			DestinationCidrBlock: aws.String(d.Get("destination_cidr_block").(string)),
			NetworkInterfaceId:   aws.String(d.Get("network_interface_id").(string)),
		}
	case "vpc_peering_connection_id":
		replaceOpts = &ec2.ReplaceRouteInput{
			RouteTableId:           aws.String(d.Get("route_table_id").(string)),
			DestinationCidrBlock:   aws.String(d.Get("destination_cidr_block").(string)),
			VpcPeeringConnectionId: aws.String(d.Get("vpc_peering_connection_id").(string)),
		}
	default:
		return fmt.Errorf("An invalid target type specified: %s", setTarget)
	}
	log.Printf("[DEBUG] Route replace config: %s", replaceOpts)

	// Replace the route
	_, err := conn.ReplaceRoute(replaceOpts)
	if err != nil {
		return err
	}

	return nil
}

func resourceAwsRouteDelete(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ec2conn

	deleteOpts := &ec2.DeleteRouteInput{
		RouteTableId: aws.String(d.Get("route_table_id").(string)),
	}
	if v, ok := d.GetOk("destination_cidr_block"); ok {
		deleteOpts.DestinationCidrBlock = aws.String(v.(string))
	}
	if v, ok := d.GetOk("destination_ipv6_cidr_block"); ok {
		deleteOpts.DestinationIpv6CidrBlock = aws.String(v.(string))
	}
	log.Printf("[DEBUG] Route delete opts: %s", deleteOpts)

	var err error
	err = resource.Retry(5*time.Minute, func() *resource.RetryError {
		log.Printf("[DEBUG] Trying to delete route with opts %s", deleteOpts)
		resp, err := conn.DeleteRoute(deleteOpts)
		log.Printf("[DEBUG] Route delete result: %s", resp)

		if err == nil {
			return nil
		}

		ec2err, ok := err.(awserr.Error)
		if !ok {
			return resource.NonRetryableError(err)
		}
		if ec2err.Code() == "InvalidParameterException" {
			log.Printf("[DEBUG] Trying to delete route again: %q",
				ec2err.Message())
			return resource.RetryableError(err)
		}

		return resource.NonRetryableError(err)
	})

	if err != nil {
		return err
	}

	d.SetId("")
	return nil
}

func resourceAwsRouteExists(d *schema.ResourceData, meta interface{}) (bool, error) {
	conn := meta.(*AWSClient).ec2conn
	routeTableId := d.Get("route_table_id").(string)

	findOpts := &ec2.DescribeRouteTablesInput{
		RouteTableIds: []*string{&routeTableId},
	}

	res, err := conn.DescribeRouteTables(findOpts)
	if err != nil {
		if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidRouteTableID.NotFound" {
			log.Printf("[WARN] Route Table %q could not be found.", routeTableId)
			return false, nil
		}
		return false, fmt.Errorf("Error while checking if route exists: %s", err)
	}

	if len(res.RouteTables) < 1 || res.RouteTables[0] == nil {
		log.Printf("[WARN] Route Table %q is gone, or route does not exist.",
			routeTableId)
		return false, nil
	}

	if v, ok := d.GetOk("destination_cidr_block"); ok {
		for _, route := range (*res.RouteTables[0]).Routes {
			if route.DestinationCidrBlock != nil && *route.DestinationCidrBlock == v.(string) {
				return true, nil
			}
		}
	}

	if v, ok := d.GetOk("destination_ipv6_cidr_block"); ok {
		for _, route := range (*res.RouteTables[0]).Routes {
			if route.DestinationIpv6CidrBlock != nil && *route.DestinationIpv6CidrBlock == v.(string) {
				return true, nil
			}
		}
	}

	return false, nil
}

// Create an ID for a route
func routeIDHash(d *schema.ResourceData, r *ec2.Route) string {

	if r.DestinationIpv6CidrBlock != nil && *r.DestinationIpv6CidrBlock != "" {
		return fmt.Sprintf("r-%s%d", d.Get("route_table_id").(string), hashcode.String(*r.DestinationIpv6CidrBlock))
	}

	return fmt.Sprintf("r-%s%d", d.Get("route_table_id").(string), hashcode.String(*r.DestinationCidrBlock))
}

// Helper: retrieve a route
func findResourceRoute(conn *ec2.EC2, rtbid string, cidr string, ipv6cidr string) (*ec2.Route, error) {
	routeTableID := rtbid

	findOpts := &ec2.DescribeRouteTablesInput{
		RouteTableIds: []*string{&routeTableID},
	}

	resp, err := conn.DescribeRouteTables(findOpts)
	if err != nil {
		return nil, err
	}

	if len(resp.RouteTables) < 1 || resp.RouteTables[0] == nil {
		return nil, fmt.Errorf("Route Table %q is gone, or route does not exist.",
			routeTableID)
	}

	if cidr != "" {
		for _, route := range (*resp.RouteTables[0]).Routes {
			if route.DestinationCidrBlock != nil && *route.DestinationCidrBlock == cidr {
				return route, nil
			}
		}

		return nil, fmt.Errorf("Unable to find matching route for Route Table (%s) "+
			"and destination CIDR block (%s).", rtbid, cidr)
	}

	if ipv6cidr != "" {
		for _, route := range (*resp.RouteTables[0]).Routes {
			if route.DestinationIpv6CidrBlock != nil && *route.DestinationIpv6CidrBlock == ipv6cidr {
				return route, nil
			}
		}

		return nil, fmt.Errorf("Unable to find matching route for Route Table (%s) "+
			"and destination IPv6 CIDR block (%s).", rtbid, ipv6cidr)
	}

	return nil, fmt.Errorf("When trying to find a matching route for Route Table %q "+
		"you need to specify a CIDR block of IPv6 CIDR Block", rtbid)

}


<|start_filename|>vendor/github.com/mitchellh/packer/provisioner/shell/unix_reader.go<|end_filename|>
package shell

import (
	"bufio"
	"io"
	"sync"
)

// UnixReader is a Reader implementation that automatically converts
// Windows line endings to Unix line endings.
type UnixReader struct {
	Reader io.Reader

	buf     []byte
	once    sync.Once
	scanner *bufio.Scanner
}

func (r *UnixReader) Read(p []byte) (n int, err error) {
	// Create the buffered reader once
	r.once.Do(func() {
		r.scanner = bufio.NewScanner(r.Reader)
		r.scanner.Split(scanUnixLine)
	})

	// If we have no data in our buffer, scan to the next token
	if len(r.buf) == 0 {
		if !r.scanner.Scan() {
			err = r.scanner.Err()
			if err == nil {
				err = io.EOF
			}

			return 0, err
		}

		r.buf = r.scanner.Bytes()
	}

	// Write out as much data as we can to the buffer, storing the rest
	// for the next read.
	n = len(p)
	if n > len(r.buf) {
		n = len(r.buf)
	}
	copy(p, r.buf)
	r.buf = r.buf[n:]

	return
}

// scanUnixLine is a bufio.Scanner SplitFunc. It tokenizes on lines, but
// only returns unix-style lines. So even if the line is "one\r\n", the
// token returned will be "one\n".
func scanUnixLine(data []byte, atEOF bool) (advance int, token []byte, err error) {
	advance, token, err = bufio.ScanLines(data, atEOF)
	if advance == 0 {
		// If we reached the end of a line without a newline, then
		// just return as it is. Otherwise the Scanner will keep trying
		// to scan, blocking forever.
		return
	}

	return advance, append(token, '\n'), err
}


<|start_filename|>vendor/github.com/hashicorp/terraform/builtin/provisioners/remote-exec/resource_provisioner.go<|end_filename|>
package remoteexec

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"strings"
	"sync/atomic"
	"time"

	"github.com/hashicorp/terraform/communicator"
	"github.com/hashicorp/terraform/communicator/remote"
	"github.com/hashicorp/terraform/helper/schema"
	"github.com/hashicorp/terraform/terraform"
	"github.com/mitchellh/go-linereader"
)

// maxBackoffDealy is the maximum delay between retry attempts
var maxBackoffDelay = 10 * time.Second
var initialBackoffDelay = time.Second

func Provisioner() terraform.ResourceProvisioner {
	return &schema.Provisioner{
		Schema: map[string]*schema.Schema{
			"inline": {
				Type:          schema.TypeList,
				Elem:          &schema.Schema{Type: schema.TypeString},
				PromoteSingle: true,
				Optional:      true,
				ConflictsWith: []string{"script", "scripts"},
			},

			"script": {
				Type:          schema.TypeString,
				Optional:      true,
				ConflictsWith: []string{"inline", "scripts"},
			},

			"scripts": {
				Type:          schema.TypeList,
				Elem:          &schema.Schema{Type: schema.TypeString},
				Optional:      true,
				ConflictsWith: []string{"script", "inline"},
			},
		},

		ApplyFunc: applyFn,
	}
}

// Apply executes the remote exec provisioner
func applyFn(ctx context.Context) error {
	connState := ctx.Value(schema.ProvRawStateKey).(*terraform.InstanceState)
	data := ctx.Value(schema.ProvConfigDataKey).(*schema.ResourceData)
	o := ctx.Value(schema.ProvOutputKey).(terraform.UIOutput)

	// Get a new communicator
	comm, err := communicator.New(connState)
	if err != nil {
		return err
	}

	// Collect the scripts
	scripts, err := collectScripts(data)
	if err != nil {
		return err
	}
	for _, s := range scripts {
		defer s.Close()
	}

	// Copy and execute each script
	if err := runScripts(ctx, o, comm, scripts); err != nil {
		return err
	}

	return nil
}

// generateScripts takes the configuration and creates a script from each inline config
func generateScripts(d *schema.ResourceData) ([]string, error) {
	var lines []string
	for _, l := range d.Get("inline").([]interface{}) {
		line, ok := l.(string)
		if !ok {
			return nil, fmt.Errorf("Error parsing %v as a string", l)
		}
		lines = append(lines, line)
	}
	lines = append(lines, "")

	return []string{strings.Join(lines, "\n")}, nil
}

// collectScripts is used to collect all the scripts we need
// to execute in preparation for copying them.
func collectScripts(d *schema.ResourceData) ([]io.ReadCloser, error) {
	// Check if inline
	if _, ok := d.GetOk("inline"); ok {
		scripts, err := generateScripts(d)
		if err != nil {
			return nil, err
		}

		var r []io.ReadCloser
		for _, script := range scripts {
			r = append(r, ioutil.NopCloser(bytes.NewReader([]byte(script))))
		}

		return r, nil
	}

	// Collect scripts
	var scripts []string
	if script, ok := d.GetOk("script"); ok {
		scr, ok := script.(string)
		if !ok {
			return nil, fmt.Errorf("Error parsing script %v as string", script)
		}
		scripts = append(scripts, scr)
	}

	if scriptList, ok := d.GetOk("scripts"); ok {
		for _, script := range scriptList.([]interface{}) {
			scr, ok := script.(string)
			if !ok {
				return nil, fmt.Errorf("Error parsing script %v as string", script)
			}
			scripts = append(scripts, scr)
		}
	}

	// Open all the scripts
	var fhs []io.ReadCloser
	for _, s := range scripts {
		fh, err := os.Open(s)
		if err != nil {
			for _, fh := range fhs {
				fh.Close()
			}
			return nil, fmt.Errorf("Failed to open script '%s': %v", s, err)
		}
		fhs = append(fhs, fh)
	}

	// Done, return the file handles
	return fhs, nil
}

// runScripts is used to copy and execute a set of scripts
func runScripts(
	ctx context.Context,
	o terraform.UIOutput,
	comm communicator.Communicator,
	scripts []io.ReadCloser) error {
	// Wrap out context in a cancelation function that we use to
	// kill the connection.
	ctx, cancelFunc := context.WithCancel(ctx)
	defer cancelFunc()

	// Wait for the context to end and then disconnect
	go func() {
		<-ctx.Done()
		comm.Disconnect()
	}()

	// Wait and retry until we establish the connection
	err := retryFunc(ctx, comm.Timeout(), func() error {
		err := comm.Connect(o)
		return err
	})
	if err != nil {
		return err
	}

	for _, script := range scripts {
		var cmd *remote.Cmd
		outR, outW := io.Pipe()
		errR, errW := io.Pipe()
		outDoneCh := make(chan struct{})
		errDoneCh := make(chan struct{})
		go copyOutput(o, outR, outDoneCh)
		go copyOutput(o, errR, errDoneCh)

		remotePath := comm.ScriptPath()
		err = retryFunc(ctx, comm.Timeout(), func() error {
			if err := comm.UploadScript(remotePath, script); err != nil {
				return fmt.Errorf("Failed to upload script: %v", err)
			}

			cmd = &remote.Cmd{
				Command: remotePath,
				Stdout:  outW,
				Stderr:  errW,
			}
			if err := comm.Start(cmd); err != nil {
				return fmt.Errorf("Error starting script: %v", err)
			}

			return nil
		})
		if err == nil {
			cmd.Wait()
			if cmd.ExitStatus != 0 {
				err = fmt.Errorf("Script exited with non-zero exit status: %d", cmd.ExitStatus)
			}
		}

		// If we have an error, end our context so the disconnect happens.
		// This has to happen before the output cleanup below since during
		// an interrupt this will cause the outputs to end.
		if err != nil {
			cancelFunc()
		}

		// Wait for output to clean up
		outW.Close()
		errW.Close()
		<-outDoneCh
		<-errDoneCh

		// Upload a blank follow up file in the same path to prevent residual
		// script contents from remaining on remote machine
		empty := bytes.NewReader([]byte(""))
		if err := comm.Upload(remotePath, empty); err != nil {
			// This feature is best-effort.
			log.Printf("[WARN] Failed to upload empty follow up script: %v", err)
		}

		// If we have an error, return it out now that we've cleaned up
		if err != nil {
			return err
		}
	}

	return nil
}

func copyOutput(
	o terraform.UIOutput, r io.Reader, doneCh chan<- struct{}) {
	defer close(doneCh)
	lr := linereader.New(r)
	for line := range lr.Ch {
		o.Output(line)
	}
}

// retryFunc is used to retry a function for a given duration
func retryFunc(ctx context.Context, timeout time.Duration, f func() error) error {
	// Build a new context with the timeout
	ctx, done := context.WithTimeout(ctx, timeout)
	defer done()

	// container for atomic error value
	type errWrap struct {
		E error
	}

	// Try the function in a goroutine
	var errVal atomic.Value
	doneCh := make(chan struct{})
	go func() {
		defer close(doneCh)

		delay := time.Duration(0)
		for {
			// If our context ended, we want to exit right away.
			select {
			case <-ctx.Done():
				return
			case <-time.After(delay):
			}

			// Try the function call
			err := f()
			errVal.Store(&errWrap{err})

			if err == nil {
				return
			}

			log.Printf("[WARN] retryable error: %v", err)

			delay *= 2

			if delay == 0 {
				delay = initialBackoffDelay
			}

			if delay > maxBackoffDelay {
				delay = maxBackoffDelay
			}

			log.Printf("[INFO] sleeping for %s", delay)
		}
	}()

	// Wait for completion
	select {
	case <-ctx.Done():
	case <-doneCh:
	}

	// Check if we have a context error to check if we're interrupted or timeout
	switch ctx.Err() {
	case context.Canceled:
		return fmt.Errorf("interrupted")
	case context.DeadlineExceeded:
		return fmt.Errorf("timeout")
	}

	// Check if we got an error executing
	if ev, ok := errVal.Load().(errWrap); ok {
		return ev.E
	}

	return nil
}


<|start_filename|>vendor/github.com/mitchellh/packer/packer/provisioner_mock.go<|end_filename|>
package packer

// MockProvisioner is an implementation of Provisioner that can be
// used for tests.
type MockProvisioner struct {
	ProvFunc func() error

	PrepCalled       bool
	PrepConfigs      []interface{}
	ProvCalled       bool
	ProvCommunicator Communicator
	ProvUi           Ui
	CancelCalled     bool
}

func (t *MockProvisioner) Prepare(configs ...interface{}) error {
	t.PrepCalled = true
	t.PrepConfigs = configs
	return nil
}

func (t *MockProvisioner) Provision(ui Ui, comm Communicator) error {
	t.ProvCalled = true
	t.ProvCommunicator = comm
	t.ProvUi = ui

	if t.ProvFunc == nil {
		return nil
	}

	return t.ProvFunc()
}

func (t *MockProvisioner) Cancel() {
	t.CancelCalled = true
}


<|start_filename|>vendor/github.com/posener/complete/args_test.go<|end_filename|>
package complete

import (
	"fmt"
	"strings"
	"testing"
)

func TestArgs(t *testing.T) {
	t.Parallel()
	tests := []struct {
		line          string
		completed     string
		last          string
		lastCompleted string
	}{
		{
			line:          "a b c",
			completed:     "b",
			last:          "c",
			lastCompleted: "b",
		},
		{
			line:          "a b ",
			completed:     "b",
			last:          "",
			lastCompleted: "b",
		},
		{
			line:          "",
			completed:     "",
			last:          "",
			lastCompleted: "",
		},
		{
			line:          "a",
			completed:     "",
			last:          "a",
			lastCompleted: "",
		},
		{
			line:          "a ",
			completed:     "",
			last:          "",
			lastCompleted: "",
		},
	}

	for _, tt := range tests {
		t.Run(tt.line, func(t *testing.T) {

			a := newArgs(strings.Split(tt.line, " "))

			if got, want := strings.Join(a.Completed, " "), tt.completed; got != want {
				t.Errorf("%s failed: Completed = %q, want %q", t.Name(), got, want)
			}
			if got, want := a.Last, tt.last; got != want {
				t.Errorf("Last = %q, want %q", got, want)
			}
			if got, want := a.LastCompleted, tt.lastCompleted; got != want {
				t.Errorf("%s failed: LastCompleted = %q, want %q", t.Name(), got, want)
			}
		})
	}
}

func TestArgs_From(t *testing.T) {
	t.Parallel()
	tests := []struct {
		line         string
		from         int
		newLine      string
		newCompleted string
	}{
		{
			line:         "a b c",
			from:         0,
			newLine:      "b c",
			newCompleted: "b",
		},
		{
			line:         "a b c",
			from:         1,
			newLine:      "c",
			newCompleted: "",
		},
		{
			line:         "a b c",
			from:         2,
			newLine:      "",
			newCompleted: "",
		},
		{
			line:         "a b c",
			from:         3,
			newLine:      "",
			newCompleted: "",
		},
		{
			line:         "a b c ",
			from:         0,
			newLine:      "b c ",
			newCompleted: "b c",
		},
		{
			line:         "a b c ",
			from:         1,
			newLine:      "c ",
			newCompleted: "c",
		},
		{
			line:         "a b c ",
			from:         2,
			newLine:      "",
			newCompleted: "",
		},
		{
			line:         "",
			from:         0,
			newLine:      "",
			newCompleted: "",
		},
		{
			line:         "",
			from:         1,
			newLine:      "",
			newCompleted: "",
		},
	}

	for _, tt := range tests {
		t.Run(fmt.Sprintf("%s/%d", tt.line, tt.from), func(t *testing.T) {

			a := newArgs(strings.Split(tt.line, " "))
			n := a.from(tt.from)

			if got, want := strings.Join(n.All, " "), tt.newLine; got != want {
				t.Errorf("%s failed: all = %q, want %q", t.Name(), got, want)
			}
			if got, want := strings.Join(n.Completed, " "), tt.newCompleted; got != want {
				t.Errorf("%s failed: completed = %q, want %q", t.Name(), got, want)
			}
		})
	}
}

func TestArgs_Directory(t *testing.T) {
	t.Parallel()
	initTests()

	tests := []struct {
		line      string
		directory string
	}{
		{
			line:      "a b c",
			directory: "./",
		},
		{
			line:      "a b c /tm",
			directory: "/",
		},
		{
			line:      "a b c /tmp",
			directory: "/tmp/",
		},
		{
			line:      "a b c /tmp ",
			directory: "./",
		},
		{
			line:      "a b c ./",
			directory: "./",
		},
		{
			line:      "a b c ./dir",
			directory: "./dir/",
		},
		{
			line:      "a b c dir",
			directory: "dir/",
		},
		{
			line:      "a b c ./di",
			directory: "./",
		},
		{
			line:      "a b c ./dir ",
			directory: "./",
		},
		{
			line:      "a b c ./di",
			directory: "./",
		},
		{
			line:      "a b c ./a.txt",
			directory: "./",
		},
		{
			line:      "a b c ./a.txt/x",
			directory: "./",
		},
	}

	for _, tt := range tests {
		t.Run(tt.line, func(t *testing.T) {

			a := newArgs(strings.Split(tt.line, " "))

			if got, want := a.Directory(), tt.directory; got != want {
				t.Errorf("%s failed: directory = %q, want %q", t.Name(), got, want)
			}
		})
	}
}


<|start_filename|>vendor/github.com/hashicorp/terraform/vendor/github.com/terraform-providers/terraform-provider-aws/aws/data_source_aws_lb_listener.go<|end_filename|>
package aws

import "github.com/hashicorp/terraform/helper/schema"

func dataSourceAwsLbListener() *schema.Resource {
	return &schema.Resource{
		Read: dataSourceAwsLbListenerRead,

		Schema: map[string]*schema.Schema{
			"arn": {
				Type:     schema.TypeString,
				Required: true,
			},

			"load_balancer_arn": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"port": {
				Type:     schema.TypeInt,
				Computed: true,
			},

			"protocol": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"ssl_policy": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"certificate_arn": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"default_action": {
				Type:     schema.TypeList,
				Computed: true,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"target_group_arn": {
							Type:     schema.TypeString,
							Computed: true,
						},
						"type": {
							Type:     schema.TypeString,
							Computed: true,
						},
					},
				},
			},
		},
	}
}

func dataSourceAwsLbListenerRead(d *schema.ResourceData, meta interface{}) error {
	d.SetId(d.Get("arn").(string))
	return resourceAwsLbListenerRead(d, meta)
}


<|start_filename|>vendor/github.com/hashicorp/terraform/backend/remote-state/azure/backend_test.go<|end_filename|>
package azure

import (
	"fmt"
	"os"
	"testing"

	"github.com/Azure/azure-sdk-for-go/arm/resources/resources"
	armStorage "github.com/Azure/azure-sdk-for-go/arm/storage"
	"github.com/Azure/azure-sdk-for-go/storage"
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/adal"
	"github.com/Azure/go-autorest/autorest/azure"
	"github.com/hashicorp/terraform/backend"
	"github.com/hashicorp/terraform/helper/acctest"
)

// verify that we are doing ACC tests or the Azure tests specifically
func testACC(t *testing.T) {
	skip := os.Getenv("TF_ACC") == "" && os.Getenv("TF_AZURE_TEST") == ""
	if skip {
		t.Log("azure backend tests require setting TF_ACC or TF_AZURE_TEST")
		t.Skip()
	}
}

func TestBackend_impl(t *testing.T) {
	var _ backend.Backend = new(Backend)
}

func TestBackendConfig(t *testing.T) {
	// This test just instantiates the client. Shouldn't make any actual
	// requests nor incur any costs.

	config := map[string]interface{}{
		"storage_account_name": "tfaccount",
		"container_name":       "tfcontainer",
		"key":                  "state",
		// Access Key must be Base64
		"access_key": "<KEY>",
	}

	b := backend.TestBackendConfig(t, New(), config).(*Backend)

	if b.containerName != "tfcontainer" {
		t.Fatalf("Incorrect bucketName was populated")
	}
	if b.keyName != "state" {
		t.Fatalf("Incorrect keyName was populated")
	}
}

func TestBackend(t *testing.T) {
	testACC(t)

	keyName := "testState"
	res := setupResources(t, keyName)
	defer destroyResources(t, res.resourceGroupName)

	b := backend.TestBackendConfig(t, New(), map[string]interface{}{
		"storage_account_name": res.storageAccountName,
		"container_name":       res.containerName,
		"key":                  keyName,
		"access_key":           res.accessKey,
	}).(*Backend)

	backend.TestBackend(t, b, nil)
}

func TestBackendLocked(t *testing.T) {
	testACC(t)

	keyName := "testState"
	res := setupResources(t, keyName)
	defer destroyResources(t, res.resourceGroupName)

	b1 := backend.TestBackendConfig(t, New(), map[string]interface{}{
		"storage_account_name": res.storageAccountName,
		"container_name":       res.containerName,
		"key":                  keyName,
		"access_key":           res.accessKey,
	}).(*Backend)

	b2 := backend.TestBackendConfig(t, New(), map[string]interface{}{
		"storage_account_name": res.storageAccountName,
		"container_name":       res.containerName,
		"key":                  keyName,
		"access_key":           res.accessKey,
	}).(*Backend)

	backend.TestBackend(t, b1, b2)
}

type testResources struct {
	resourceGroupName  string
	storageAccountName string
	containerName      string
	keyName            string
	accessKey          string
}

func setupResources(t *testing.T, keyName string) testResources {
	clients := getTestClient(t)

	ri := acctest.RandInt()
	rs := acctest.RandString(4)
	res := testResources{
		resourceGroupName:  fmt.Sprintf("terraform-backend-testing-%d", ri),
		storageAccountName: fmt.Sprintf("tfbackendtesting%s", rs),
		containerName:      "terraform",
		keyName:            keyName,
	}

	location := os.Getenv("ARM_LOCATION")
	if location == "" {
		location = "westus"
	}

	t.Logf("creating resource group %s", res.resourceGroupName)
	_, err := clients.groupsClient.CreateOrUpdate(res.resourceGroupName, resources.Group{Location: &location})
	if err != nil {
		t.Fatalf("failed to create test resource group: %s", err)
	}

	t.Logf("creating storage account %s", res.storageAccountName)
	_, createError := clients.storageAccountsClient.Create(res.resourceGroupName, res.storageAccountName, armStorage.AccountCreateParameters{
		Sku: &armStorage.Sku{
			Name: armStorage.StandardLRS,
			Tier: armStorage.Standard,
		},
		Location: &location,
	}, make(chan struct{}))
	createErr := <-createError
	if createErr != nil {
		destroyResources(t, res.resourceGroupName)
		t.Fatalf("failed to create test storage account: %s", err)
	}

	t.Log("fetching access key for storage account")
	resp, err := clients.storageAccountsClient.ListKeys(res.resourceGroupName, res.storageAccountName)
	if err != nil {
		destroyResources(t, res.resourceGroupName)
		t.Fatalf("failed to list storage account keys %s:", err)
	}

	keys := *resp.Keys
	res.accessKey = *keys[0].Value

	storageClient, err := storage.NewClient(res.storageAccountName, res.accessKey,
		clients.environment.StorageEndpointSuffix, storage.DefaultAPIVersion, true)
	if err != nil {
		destroyResources(t, res.resourceGroupName)
		t.Fatalf("failed to list storage account keys %s:", err)
	}

	t.Logf("creating container %s", res.containerName)
	blobService := storageClient.GetBlobService()
	container := blobService.GetContainerReference(res.containerName)
	err = container.Create(&storage.CreateContainerOptions{})
	if err != nil {
		destroyResources(t, res.resourceGroupName)
		t.Fatalf("failed to create storage container: %s", err)
	}

	return res
}

func destroyResources(t *testing.T, resourceGroupName string) {
	warning := "WARNING: Failed to delete the test Azure resources. They may incur charges. (error was %s)"

	clients := getTestClient(t)

	t.Log("destroying created resources")

	// destroying is simple as deleting the resource group will destroy everything else
	_, deleteErr := clients.groupsClient.Delete(resourceGroupName, make(chan struct{}))
	err := <-deleteErr
	if err != nil {
		t.Logf(warning, err)
		return
	}

	t.Log("Azure resources destroyed")
}

type testClient struct {
	subscriptionID        string
	tenantID              string
	clientID              string
	clientSecret          string
	environment           azure.Environment
	groupsClient          resources.GroupsClient
	storageAccountsClient armStorage.AccountsClient
}

func getTestClient(t *testing.T) testClient {
	client := testClient{
		subscriptionID: os.Getenv("ARM_SUBSCRIPTION_ID"),
		tenantID:       os.Getenv("ARM_TENANT_ID"),
		clientID:       os.Getenv("ARM_CLIENT_ID"),
		clientSecret:   os.Getenv("ARM_CLIENT_SECRET"),
	}

	if client.subscriptionID == "" || client.tenantID == "" || client.clientID == "" || client.clientSecret == "" {
		t.Fatal("Azure credentials missing or incomplete")
	}

	env, err := getAzureEnvironment(os.Getenv("ARM_ENVIRONMENT"))
	if err != nil {
		t.Fatalf("Failed to detect Azure environment from ARM_ENVIRONMENT value: %s", os.Getenv("ARM_ENVIRONMENT"))
	}
	client.environment = env

	oauthConfig, err := adal.NewOAuthConfig(env.ActiveDirectoryEndpoint, client.tenantID)
	if err != nil {
		t.Fatalf("Failed to get OAuth config: %s", err)
	}

	spt, err := adal.NewServicePrincipalToken(*oauthConfig, client.clientID, client.clientSecret, env.ResourceManagerEndpoint)
	if err != nil {
		t.Fatalf("Failed to create Service Principal Token: %s", err)
	}

	client.groupsClient = resources.NewGroupsClientWithBaseURI(env.ResourceManagerEndpoint, client.subscriptionID)
	client.groupsClient.Authorizer = autorest.NewBearerAuthorizer(spt)

	client.storageAccountsClient = armStorage.NewAccountsClientWithBaseURI(env.ResourceManagerEndpoint, client.subscriptionID)
	client.storageAccountsClient.Authorizer = autorest.NewBearerAuthorizer(spt)

	return client
}
