diff --git a/builtin/providers/README b/builtin/providers/README
new file mode 100644
index 000000000..00ffa7145
--- /dev/null
+++ b/builtin/providers/README
@@ -0,0 +1 @@
+providers moved to github.com/terraform-providers
diff --git a/builtin/providers/alicloud/common.go b/builtin/providers/alicloud/common.go
deleted file mode 100644
index e9bb1a9f8..000000000
--- a/builtin/providers/alicloud/common.go
+++ /dev/null
@@ -1,93 +0,0 @@
-package alicloud
-
-import (
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-type InstanceNetWork string
-
-const (
- ClassicNet = InstanceNetWork("classic")
- VpcNet = InstanceNetWork("vpc")
-)
-
-// timeout for common product, ecs e.g.
-const defaultTimeout = 120
-
-// timeout for long time progerss product, rds e.g.
-const defaultLongTimeout = 1000
-
-func getRegion(d *schema.ResourceData, meta interface{}) common.Region {
- return meta.(*AliyunClient).Region
-}
-
-func notFoundError(err error) bool {
- if e, ok := err.(*common.Error); ok &&
- (e.StatusCode == 404 || e.ErrorResponse.Message == "Not found" || e.Code == InstanceNotfound) {
- return true
- }
-
- return false
-}
-
-// Protocol represents network protocol
-type Protocol string
-
-// Constants of protocol definition
-const (
- Http = Protocol("http")
- Https = Protocol("https")
- Tcp = Protocol("tcp")
- Udp = Protocol("udp")
-)
-
-// ValidProtocols network protocol list
-var ValidProtocols = []Protocol{Http, Https, Tcp, Udp}
-
-// simple array value check method, support string type only
-func isProtocolValid(value string) bool {
- res := false
- for _, v := range ValidProtocols {
- if string(v) == value {
- res = true
- }
- }
- return res
-}
-
-var DefaultBusinessInfo = ecs.BusinessInfo{
- Pack: "terraform",
-}
-
-// default region for all resource
-const DEFAULT_REGION = "cn-beijing"
-
-// default security ip for db
-const DEFAULT_DB_SECURITY_IP = "127.0.0.1"
-
-// we the count of create instance is only one
-const DEFAULT_INSTANCE_COUNT = 1
-
-// symbol of multiIZ
-const MULTI_IZ_SYMBOL = "MAZ"
-
-// default connect port of db
-const DB_DEFAULT_CONNECT_PORT = "3306"
-
-const COMMA_SEPARATED = ","
-
-const COLON_SEPARATED = ":"
-
-const LOCAL_HOST_IP = "127.0.0.1"
-
-// Takes the result of flatmap.Expand for an array of strings
-// and returns a []string
-func expandStringList(configured []interface{}) []string {
- vs := make([]string, 0, len(configured))
- for _, v := range configured {
- vs = append(vs, v.(string))
- }
- return vs
-}
diff --git a/builtin/providers/alicloud/config.go b/builtin/providers/alicloud/config.go
deleted file mode 100644
index f84c7e02a..000000000
--- a/builtin/providers/alicloud/config.go
+++ /dev/null
@@ -1,138 +0,0 @@
-package alicloud
-
-import (
- "fmt"
-
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/denverdino/aliyungo/ess"
- "github.com/denverdino/aliyungo/rds"
- "github.com/denverdino/aliyungo/slb"
-)
-
-// Config of aliyun
-type Config struct {
- AccessKey string
- SecretKey string
- Region common.Region
-}
-
-// AliyunClient of aliyun
-type AliyunClient struct {
- Region common.Region
- ecsconn *ecs.Client
- essconn *ess.Client
- rdsconn *rds.Client
- // use new version
- ecsNewconn *ecs.Client
- vpcconn *ecs.Client
- slbconn *slb.Client
-}
-
-// Client for AliyunClient
-func (c *Config) Client() (*AliyunClient, error) {
- err := c.loadAndValidate()
- if err != nil {
- return nil, err
- }
-
- ecsconn, err := c.ecsConn()
- if err != nil {
- return nil, err
- }
-
- ecsNewconn, err := c.ecsConn()
- if err != nil {
- return nil, err
- }
- ecsNewconn.SetVersion(EcsApiVersion20160314)
-
- rdsconn, err := c.rdsConn()
- if err != nil {
- return nil, err
- }
-
- slbconn, err := c.slbConn()
- if err != nil {
- return nil, err
- }
-
- vpcconn, err := c.vpcConn()
- if err != nil {
- return nil, err
- }
-
- essconn, err := c.essConn()
- if err != nil {
- return nil, err
- }
-
- return &AliyunClient{
- Region: c.Region,
- ecsconn: ecsconn,
- ecsNewconn: ecsNewconn,
- vpcconn: vpcconn,
- slbconn: slbconn,
- rdsconn: rdsconn,
- essconn: essconn,
- }, nil
-}
-
-const BusinessInfoKey = "Terraform"
-
-func (c *Config) loadAndValidate() error {
- err := c.validateRegion()
- if err != nil {
- return err
- }
-
- return nil
-}
-
-func (c *Config) validateRegion() error {
-
- for _, valid := range common.ValidRegions {
- if c.Region == valid {
- return nil
- }
- }
-
- return fmt.Errorf("Not a valid region: %s", c.Region)
-}
-
-func (c *Config) ecsConn() (*ecs.Client, error) {
- client := ecs.NewECSClient(c.AccessKey, c.SecretKey, c.Region)
- client.SetBusinessInfo(BusinessInfoKey)
-
- _, err := client.DescribeRegions()
-
- if err != nil {
- return nil, err
- }
-
- return client, nil
-}
-
-func (c *Config) rdsConn() (*rds.Client, error) {
- client := rds.NewRDSClient(c.AccessKey, c.SecretKey, c.Region)
- client.SetBusinessInfo(BusinessInfoKey)
- return client, nil
-}
-
-func (c *Config) slbConn() (*slb.Client, error) {
- client := slb.NewSLBClient(c.AccessKey, c.SecretKey, c.Region)
- client.SetBusinessInfo(BusinessInfoKey)
- return client, nil
-}
-
-func (c *Config) vpcConn() (*ecs.Client, error) {
- client := ecs.NewVPCClient(c.AccessKey, c.SecretKey, c.Region)
- client.SetBusinessInfo(BusinessInfoKey)
- return client, nil
-
-}
-func (c *Config) essConn() (*ess.Client, error) {
- client := ess.NewESSClient(c.AccessKey, c.SecretKey, c.Region)
- client.SetBusinessInfo(BusinessInfoKey)
- return client, nil
-}
diff --git a/builtin/providers/alicloud/data_source_alicloud_common.go b/builtin/providers/alicloud/data_source_alicloud_common.go
deleted file mode 100644
index 1da432cfc..000000000
--- a/builtin/providers/alicloud/data_source_alicloud_common.go
+++ /dev/null
@@ -1,18 +0,0 @@
-package alicloud
-
-import (
- "bytes"
- "fmt"
- "github.com/hashicorp/terraform/helper/hashcode"
-)
-
-// Generates a hash for the set hash function used by the ID
-func dataResourceIdHash(ids []string) string {
- var buf bytes.Buffer
-
- for _, id := range ids {
- buf.WriteString(fmt.Sprintf("%s-", id))
- }
-
- return fmt.Sprintf("%d", hashcode.String(buf.String()))
-}
diff --git a/builtin/providers/alicloud/data_source_alicloud_images.go b/builtin/providers/alicloud/data_source_alicloud_images.go
deleted file mode 100644
index d9a873782..000000000
--- a/builtin/providers/alicloud/data_source_alicloud_images.go
+++ /dev/null
@@ -1,337 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "log"
- "regexp"
- "sort"
- "time"
-
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAlicloudImages() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAlicloudImagesRead,
-
- Schema: map[string]*schema.Schema{
- "name_regex": {
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- ValidateFunc: validateNameRegex,
- },
- "most_recent": {
- Type: schema.TypeBool,
- Optional: true,
- Default: false,
- ForceNew: true,
- },
- "owners": {
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- ValidateFunc: validateImageOwners,
- },
- // Computed values.
- "images": {
- Type: schema.TypeList,
- Computed: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "id": {
- Type: schema.TypeString,
- Computed: true,
- },
- "image_id": {
- Type: schema.TypeString,
- Computed: true,
- },
- "architecture": {
- Type: schema.TypeString,
- Computed: true,
- },
- "creation_time": {
- Type: schema.TypeString,
- Computed: true,
- },
- "description": {
- Type: schema.TypeString,
- Computed: true,
- },
- "image_owner_alias": {
- Type: schema.TypeString,
- Computed: true,
- },
- "os_type": {
- Type: schema.TypeString,
- Computed: true,
- },
- "os_name": {
- Type: schema.TypeString,
- Computed: true,
- },
- "name": {
- Type: schema.TypeString,
- Computed: true,
- },
- "platform": {
- Type: schema.TypeString,
- Computed: true,
- },
- "status": {
- Type: schema.TypeString,
- Computed: true,
- },
- "state": {
- Type: schema.TypeString,
- Computed: true,
- },
- "size": {
- Type: schema.TypeInt,
- Computed: true,
- },
- // Complex computed values
- "disk_device_mappings": {
- Type: schema.TypeList,
- Computed: true,
- //Set: imageDiskDeviceMappingHash,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "device": {
- Type: schema.TypeString,
- Computed: true,
- },
- "size": {
- Type: schema.TypeString,
- Computed: true,
- },
- "snapshot_id": {
- Type: schema.TypeString,
- Computed: true,
- },
- },
- },
- },
- "product_code": {
- Type: schema.TypeString,
- Computed: true,
- },
- "is_self_shared": {
- Type: schema.TypeString,
- Computed: true,
- },
- "is_subscribed": {
- Type: schema.TypeBool,
- Computed: true,
- },
- "is_copied": {
- Type: schema.TypeBool,
- Computed: true,
- },
- "is_support_io_optimized": {
- Type: schema.TypeBool,
- Computed: true,
- },
- "image_version": {
- Type: schema.TypeString,
- Computed: true,
- },
- "progress": {
- Type: schema.TypeString,
- Computed: true,
- },
- "usage": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "tags": tagsSchema(),
- },
- },
- },
- },
- }
-}
-
-// dataSourceAlicloudImagesDescriptionRead performs the Alicloud Image lookup.
-func dataSourceAlicloudImagesRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).ecsconn
-
- nameRegex, nameRegexOk := d.GetOk("name_regex")
- owners, ownersOk := d.GetOk("owners")
- mostRecent, mostRecentOk := d.GetOk("most_recent")
-
- if nameRegexOk == false && ownersOk == false && mostRecentOk == false {
- return fmt.Errorf("One of name_regex, owners or most_recent must be assigned")
- }
-
- params := &ecs.DescribeImagesArgs{
- RegionId: getRegion(d, meta),
- }
-
- if ownersOk {
- params.ImageOwnerAlias = ecs.ImageOwnerAlias(owners.(string))
- }
-
- var allImages []ecs.ImageType
-
- for {
- images, paginationResult, err := conn.DescribeImages(params)
- if err != nil {
- break
- }
-
- allImages = append(allImages, images...)
-
- pagination := paginationResult.NextPage()
- if pagination == nil {
- break
- }
-
- params.Pagination = *pagination
- }
-
- var filteredImages []ecs.ImageType
- if nameRegexOk {
- r := regexp.MustCompile(nameRegex.(string))
- for _, image := range allImages {
- // Check for a very rare case where the response would include no
- // image name. No name means nothing to attempt a match against,
- // therefore we are skipping such image.
- if image.ImageName == "" {
- log.Printf("[WARN] Unable to find Image name to match against "+
- "for image ID %q, nothing to do.",
- image.ImageId)
- continue
- }
- if r.MatchString(image.ImageName) {
- filteredImages = append(filteredImages, image)
- }
- }
- } else {
- filteredImages = allImages[:]
- }
-
- var images []ecs.ImageType
- if len(filteredImages) < 1 {
- return fmt.Errorf("Your query returned no results. Please change your search criteria and try again.")
- }
-
- log.Printf("[DEBUG] alicloud_image - multiple results found and `most_recent` is set to: %t", mostRecent.(bool))
- if len(filteredImages) > 1 && mostRecent.(bool) {
- // Query returned single result.
- images = append(images, mostRecentImage(filteredImages))
- } else {
- images = filteredImages
- }
-
- log.Printf("[DEBUG] alicloud_image - Images found: %#v", images)
- return imagesDescriptionAttributes(d, images, meta)
-}
-
-// populate the numerous fields that the image description returns.
-func imagesDescriptionAttributes(d *schema.ResourceData, images []ecs.ImageType, meta interface{}) error {
- var ids []string
- var s []map[string]interface{}
- for _, image := range images {
- mapping := map[string]interface{}{
- "id": image.ImageId,
- "architecture": image.Architecture,
- "creation_time": image.CreationTime.String(),
- "description": image.Description,
- "image_id": image.ImageId,
- "image_owner_alias": image.ImageOwnerAlias,
- "os_name": image.OSName,
- "os_type": image.OSType,
- "name": image.ImageName,
- "platform": image.Platform,
- "status": image.Status,
- "state": image.Status,
- "size": image.Size,
- "is_self_shared": image.IsSelfShared,
- "is_subscribed": image.IsSubscribed,
- "is_copied": image.IsCopied,
- "is_support_io_optimized": image.IsSupportIoOptimized,
- "image_version": image.ImageVersion,
- "progress": image.Progress,
- "usage": image.Usage,
- "product_code": image.ProductCode,
-
- // Complex types get their own functions
- "disk_device_mappings": imageDiskDeviceMappings(image.DiskDeviceMappings.DiskDeviceMapping),
- "tags": imageTagsMappings(d, image.ImageId, meta),
- }
-
- log.Printf("[DEBUG] alicloud_image - adding image mapping: %v", mapping)
- ids = append(ids, image.ImageId)
- s = append(s, mapping)
- }
-
- d.SetId(dataResourceIdHash(ids))
- if err := d.Set("images", s); err != nil {
- return err
- }
- return nil
-}
-
-//Find most recent image
-type imageSort []ecs.ImageType
-
-func (a imageSort) Len() int {
- return len(a)
-}
-func (a imageSort) Swap(i, j int) {
- a[i], a[j] = a[j], a[i]
-}
-func (a imageSort) Less(i, j int) bool {
- itime, _ := time.Parse(time.RFC3339, a[i].CreationTime.String())
- jtime, _ := time.Parse(time.RFC3339, a[j].CreationTime.String())
- return itime.Unix() < jtime.Unix()
-}
-
-// Returns the most recent Image out of a slice of images.
-func mostRecentImage(images []ecs.ImageType) ecs.ImageType {
- sortedImages := images
- sort.Sort(imageSort(sortedImages))
- return sortedImages[len(sortedImages)-1]
-}
-
-// Returns a set of disk device mappings.
-func imageDiskDeviceMappings(m []ecs.DiskDeviceMapping) []map[string]interface{} {
- var s []map[string]interface{}
-
- for _, v := range m {
- mapping := map[string]interface{}{
- "device": v.Device,
- "size": v.Size,
- "snapshot_id": v.SnapshotId,
- }
-
- log.Printf("[DEBUG] alicloud_image - adding disk device mapping: %v", mapping)
- s = append(s, mapping)
- }
-
- return s
-}
-
-//Returns a mapping of image tags
-func imageTagsMappings(d *schema.ResourceData, imageId string, meta interface{}) map[string]string {
- client := meta.(*AliyunClient)
- conn := client.ecsconn
-
- tags, _, err := conn.DescribeTags(&ecs.DescribeTagsArgs{
- RegionId: getRegion(d, meta),
- ResourceType: ecs.TagResourceImage,
- ResourceId: imageId,
- })
-
- if err != nil {
- log.Printf("[ERROR] DescribeTags for image got error: %#v", err)
- return nil
- }
-
- log.Printf("[DEBUG] DescribeTags for image : %v", tags)
- return tagsToMap(tags)
-}
diff --git a/builtin/providers/alicloud/data_source_alicloud_images_test.go b/builtin/providers/alicloud/data_source_alicloud_images_test.go
deleted file mode 100644
index 9c6e225e4..000000000
--- a/builtin/providers/alicloud/data_source_alicloud_images_test.go
+++ /dev/null
@@ -1,155 +0,0 @@
-package alicloud
-
-import (
- "regexp"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAlicloudImagesDataSource_images(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAlicloudImagesDataSourceImagesConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAlicloudDataSourceID("data.alicloud_images.multi_image"),
-
- resource.TestCheckResourceAttr("data.alicloud_images.multi_image", "images.#", "2"),
-
- resource.TestCheckResourceAttr("data.alicloud_images.multi_image", "images.0.architecture", "x86_64"),
- resource.TestCheckResourceAttr("data.alicloud_images.multi_image", "images.0.disk_device_mappings.#", "0"),
- resource.TestMatchResourceAttr("data.alicloud_images.multi_image", "images.0.creation_time", regexp.MustCompile("^20[0-9]{2}-")),
- resource.TestMatchResourceAttr("data.alicloud_images.multi_image", "images.0.image_id", regexp.MustCompile("^centos_6\\w{1,5}[64]{1}.")),
- resource.TestCheckResourceAttr("data.alicloud_images.multi_image", "images.0.image_owner_alias", "system"),
- resource.TestCheckResourceAttr("data.alicloud_images.multi_image", "images.0.os_type", "linux"),
- resource.TestMatchResourceAttr("data.alicloud_images.multi_image", "images.0.name", regexp.MustCompile("^centos_6[a-zA-Z0-9_]{1,5}[64]{1}.")),
- resource.TestCheckResourceAttr("data.alicloud_images.multi_image", "images.0.progress", "100%"),
- resource.TestCheckResourceAttr("data.alicloud_images.multi_image", "images.0.state", "Available"),
- resource.TestCheckResourceAttr("data.alicloud_images.multi_image", "images.0.status", "Available"),
- resource.TestCheckResourceAttr("data.alicloud_images.multi_image", "images.0.usage", "instance"),
- resource.TestCheckResourceAttr("data.alicloud_images.multi_image", "images.0.tags.%", "0"),
-
- resource.TestCheckResourceAttr("data.alicloud_images.multi_image", "images.1.architecture", "i386"),
- resource.TestCheckResourceAttr("data.alicloud_images.multi_image", "images.1.disk_device_mappings.#", "0"),
- resource.TestMatchResourceAttr("data.alicloud_images.multi_image", "images.1.creation_time", regexp.MustCompile("^20[0-9]{2}-")),
- resource.TestMatchResourceAttr("data.alicloud_images.multi_image", "images.1.image_id", regexp.MustCompile("^centos_6[a-zA-Z0-9_]{1,5}[32]{1}.")),
- resource.TestCheckResourceAttr("data.alicloud_images.multi_image", "images.1.image_owner_alias", "system"),
- resource.TestCheckResourceAttr("data.alicloud_images.multi_image", "images.1.os_type", "linux"),
- resource.TestMatchResourceAttr("data.alicloud_images.multi_image", "images.1.name", regexp.MustCompile("^centos_6\\w{1,5}[32]{1}.")),
- resource.TestCheckResourceAttr("data.alicloud_images.multi_image", "images.1.progress", "100%"),
- resource.TestCheckResourceAttr("data.alicloud_images.multi_image", "images.1.state", "Available"),
- resource.TestCheckResourceAttr("data.alicloud_images.multi_image", "images.1.status", "Available"),
- resource.TestCheckResourceAttr("data.alicloud_images.multi_image", "images.1.usage", "instance"),
- resource.TestCheckResourceAttr("data.alicloud_images.multi_image", "images.1.tags.%", "0"),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudImagesDataSource_owners(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAlicloudImagesDataSourceOwnersConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAlicloudDataSourceID("data.alicloud_images.owners_filtered_image"),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudImagesDataSource_ownersEmpty(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAlicloudImagesDataSourceEmptyOwnersConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAlicloudDataSourceID("data.alicloud_images.empty_owners_filtered_image"),
- resource.TestCheckResourceAttr("data.alicloud_images.empty_owners_filtered_image", "most_recent", "true"),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudImagesDataSource_nameRegexFilter(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAlicloudImagesDataSourceNameRegexConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAlicloudDataSourceID("data.alicloud_images.name_regex_filtered_image"),
- resource.TestMatchResourceAttr("data.alicloud_images.name_regex_filtered_image", "images.0.image_id", regexp.MustCompile("^centos_")),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudImagesDataSource_imageNotInFirstPage(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAlicloudImagesDataSourceImageNotInFirstPageConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAlicloudDataSourceID("data.alicloud_images.name_regex_filtered_image"),
- resource.TestMatchResourceAttr("data.alicloud_images.name_regex_filtered_image", "images.0.image_id", regexp.MustCompile("^ubuntu_14")),
- ),
- },
- },
- })
-}
-
-// Instance store test - using centos images
-const testAccCheckAlicloudImagesDataSourceImagesConfig = `
-data "alicloud_images" "multi_image" {
- owners = "system"
- name_regex = "^centos_6"
-}
-`
-
-// Testing owner parameter
-const testAccCheckAlicloudImagesDataSourceOwnersConfig = `
-data "alicloud_images" "owners_filtered_image" {
- most_recent = true
- owners = "system"
-}
-`
-
-const testAccCheckAlicloudImagesDataSourceEmptyOwnersConfig = `
-data "alicloud_images" "empty_owners_filtered_image" {
- most_recent = true
- owners = ""
-}
-`
-
-// Testing name_regex parameter
-const testAccCheckAlicloudImagesDataSourceNameRegexConfig = `
-data "alicloud_images" "name_regex_filtered_image" {
- most_recent = true
- owners = "system"
- name_regex = "^centos_6\\w{1,5}[64]{1}.*"
-}
-`
-
-// Testing image not in first page response
-const testAccCheckAlicloudImagesDataSourceImageNotInFirstPageConfig = `
-data "alicloud_images" "name_regex_filtered_image" {
- most_recent = true
- owners = "system"
- name_regex = "^ubuntu_14.*_64"
-}
-`
diff --git a/builtin/providers/alicloud/data_source_alicloud_instance_types.go b/builtin/providers/alicloud/data_source_alicloud_instance_types.go
deleted file mode 100644
index 87d6bfc43..000000000
--- a/builtin/providers/alicloud/data_source_alicloud_instance_types.go
+++ /dev/null
@@ -1,127 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/schema"
- "log"
-)
-
-func dataSourceAlicloudInstanceTypes() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAlicloudInstanceTypesRead,
-
- Schema: map[string]*schema.Schema{
- "instance_type_family": {
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
- "cpu_core_count": {
- Type: schema.TypeInt,
- Optional: true,
- ForceNew: true,
- },
- "memory_size": {
- Type: schema.TypeFloat,
- Optional: true,
- ForceNew: true,
- },
- // Computed values.
- "instance_types": {
- Type: schema.TypeList,
- Computed: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "id": {
- Type: schema.TypeString,
- Computed: true,
- },
- "cpu_core_count": {
- Type: schema.TypeInt,
- Computed: true,
- },
- "memory_size": {
- Type: schema.TypeFloat,
- Computed: true,
- },
- "family": {
- Type: schema.TypeString,
- Computed: true,
- },
- },
- },
- },
- },
- }
-}
-
-func dataSourceAlicloudInstanceTypesRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).ecsconn
-
- cpu, _ := d.Get("cpu_core_count").(int)
- mem, _ := d.Get("memory_size").(float64)
-
- args, err := buildAliyunAlicloudInstanceTypesArgs(d, meta)
-
- if err != nil {
- return err
- }
-
- resp, err := conn.DescribeInstanceTypesNew(args)
- if err != nil {
- return err
- }
-
- var instanceTypes []ecs.InstanceTypeItemType
- for _, types := range resp {
- if cpu > 0 && types.CpuCoreCount != cpu {
- continue
- }
-
- if mem > 0 && types.MemorySize != mem {
- continue
- }
- instanceTypes = append(instanceTypes, types)
- }
-
- if len(instanceTypes) < 1 {
- return fmt.Errorf("Your query returned no results. Please change your search criteria and try again.")
- }
-
- log.Printf("[DEBUG] alicloud_instance_type - Types found: %#v", instanceTypes)
- return instanceTypesDescriptionAttributes(d, instanceTypes)
-}
-
-func instanceTypesDescriptionAttributes(d *schema.ResourceData, types []ecs.InstanceTypeItemType) error {
- var ids []string
- var s []map[string]interface{}
- for _, t := range types {
- mapping := map[string]interface{}{
- "id": t.InstanceTypeId,
- "cpu_core_count": t.CpuCoreCount,
- "memory_size": t.MemorySize,
- "family": t.InstanceTypeFamily,
- }
-
- log.Printf("[DEBUG] alicloud_instance_type - adding type mapping: %v", mapping)
- ids = append(ids, t.InstanceTypeId)
- s = append(s, mapping)
- }
-
- d.SetId(dataResourceIdHash(ids))
- if err := d.Set("instance_types", s); err != nil {
- return err
- }
- return nil
-}
-
-func buildAliyunAlicloudInstanceTypesArgs(d *schema.ResourceData, meta interface{}) (*ecs.DescribeInstanceTypesArgs, error) {
- args := &ecs.DescribeInstanceTypesArgs{}
-
- if v := d.Get("instance_type_family").(string); v != "" {
- args.InstanceTypeFamily = v
- }
-
- return args, nil
-}
diff --git a/builtin/providers/alicloud/data_source_alicloud_instance_types_test.go b/builtin/providers/alicloud/data_source_alicloud_instance_types_test.go
deleted file mode 100644
index 335da3fbd..000000000
--- a/builtin/providers/alicloud/data_source_alicloud_instance_types_test.go
+++ /dev/null
@@ -1,54 +0,0 @@
-package alicloud
-
-import (
- "github.com/hashicorp/terraform/helper/resource"
- "testing"
-)
-
-func TestAccAlicloudInstanceTypesDataSource_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAlicloudInstanceTypesDataSourceBasicConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAlicloudDataSourceID("data.alicloud_instance_types.4c8g"),
-
- resource.TestCheckResourceAttr("data.alicloud_instance_types.4c8g", "instance_types.0.cpu_core_count", "4"),
- resource.TestCheckResourceAttr("data.alicloud_instance_types.4c8g", "instance_types.0.memory_size", "8"),
- resource.TestCheckResourceAttr("data.alicloud_instance_types.4c8g", "instance_types.0.id", "ecs.s3.large"),
- ),
- },
-
- resource.TestStep{
- Config: testAccCheckAlicloudInstanceTypesDataSourceBasicConfigUpdate,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAlicloudDataSourceID("data.alicloud_instance_types.4c8g"),
-
- resource.TestCheckResourceAttr("data.alicloud_instance_types.4c8g", "instance_types.#", "1"),
-
- resource.TestCheckResourceAttr("data.alicloud_instance_types.4c8g", "instance_types.0.cpu_core_count", "4"),
- resource.TestCheckResourceAttr("data.alicloud_instance_types.4c8g", "instance_types.0.memory_size", "8"),
- ),
- },
- },
- })
-}
-
-const testAccCheckAlicloudInstanceTypesDataSourceBasicConfig = `
-data "alicloud_instance_types" "4c8g" {
- cpu_core_count = 4
- memory_size = 8
-}
-`
-
-const testAccCheckAlicloudInstanceTypesDataSourceBasicConfigUpdate = `
-data "alicloud_instance_types" "4c8g" {
- instance_type_family= "ecs.s3"
- cpu_core_count = 4
- memory_size = 8
-}
-`
diff --git a/builtin/providers/alicloud/data_source_alicloud_regions.go b/builtin/providers/alicloud/data_source_alicloud_regions.go
deleted file mode 100644
index 8bdee26b6..000000000
--- a/builtin/providers/alicloud/data_source_alicloud_regions.go
+++ /dev/null
@@ -1,114 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/schema"
- "log"
-)
-
-func dataSourceAlicloudRegions() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAlicloudRegionsRead,
-
- Schema: map[string]*schema.Schema{
- "name": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
-
- "current": &schema.Schema{
- Type: schema.TypeBool,
- Optional: true,
- Computed: true,
- },
-
- //Computed value
- "regions": &schema.Schema{
- Type: schema.TypeList,
- Computed: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "id": {
- Type: schema.TypeString,
- Computed: true,
- },
- "region_id": {
- Type: schema.TypeString,
- Computed: true,
- },
- "local_name": {
- Type: schema.TypeString,
- Computed: true,
- },
- },
- },
- },
- },
- }
-}
-
-func dataSourceAlicloudRegionsRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).ecsconn
- currentRegion := getRegion(d, meta)
-
- resp, err := conn.DescribeRegions()
- if err != nil {
- return err
- }
- if resp == nil || len(resp) == 0 {
- return fmt.Errorf("no matching regions found")
- }
- name, nameOk := d.GetOk("name")
- current := d.Get("current").(bool)
- var filterRegions []ecs.RegionType
- for _, region := range resp {
- if current {
- if nameOk && common.Region(name.(string)) != currentRegion {
- return fmt.Errorf("name doesn't match current region: %#v, please input again.", currentRegion)
- }
- if region.RegionId == currentRegion {
- filterRegions = append(filterRegions, region)
- break
- }
- continue
- }
- if nameOk {
- if common.Region(name.(string)) == region.RegionId {
- filterRegions = append(filterRegions, region)
- break
- }
- continue
- }
- filterRegions = append(filterRegions, region)
- }
- if len(filterRegions) < 1 {
- return fmt.Errorf("Your query region returned no results. Please change your search criteria and try again.")
- }
-
- return regionsDescriptionAttributes(d, filterRegions)
-}
-
-func regionsDescriptionAttributes(d *schema.ResourceData, regions []ecs.RegionType) error {
- var ids []string
- var s []map[string]interface{}
- for _, region := range regions {
- mapping := map[string]interface{}{
- "id": region.RegionId,
- "region_id": region.RegionId,
- "local_name": region.LocalName,
- }
-
- log.Printf("[DEBUG] alicloud_regions - adding region mapping: %v", mapping)
- ids = append(ids, string(region.RegionId))
- s = append(s, mapping)
- }
-
- d.SetId(dataResourceIdHash(ids))
- if err := d.Set("regions", s); err != nil {
- return err
- }
- return nil
-}
diff --git a/builtin/providers/alicloud/data_source_alicloud_regions_test.go b/builtin/providers/alicloud/data_source_alicloud_regions_test.go
deleted file mode 100644
index 9dafaba1e..000000000
--- a/builtin/providers/alicloud/data_source_alicloud_regions_test.go
+++ /dev/null
@@ -1,109 +0,0 @@
-package alicloud
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAlicloudRegionsDataSource_regions(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAlicloudRegionsDataSourceRegionsConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAlicloudDataSourceID("data.alicloud_regions.region"),
-
- resource.TestCheckResourceAttr("data.alicloud_regions.region", "name", "cn-beijing"),
- resource.TestCheckResourceAttr("data.alicloud_regions.region", "current", "true"),
-
- resource.TestCheckResourceAttr("data.alicloud_regions.region", "regions.#", "1"),
-
- resource.TestCheckResourceAttr("data.alicloud_regions.region", "regions.0.id", "cn-beijing"),
- resource.TestCheckResourceAttr("data.alicloud_regions.region", "regions.0.region_id", "cn-beijing"),
- resource.TestCheckResourceAttr("data.alicloud_regions.region", "regions.0.local_name", "华北 2"),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudRegionsDataSource_name(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAlicloudRegionsDataSourceNameConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAlicloudDataSourceID("data.alicloud_regions.name_filtered_region"),
- resource.TestCheckResourceAttr("data.alicloud_regions.name_filtered_region", "name", "cn-hangzhou")),
- },
- },
- })
-}
-
-func TestAccAlicloudRegionsDataSource_current(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAlicloudRegionsDataSourceCurrentConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAlicloudDataSourceID("data.alicloud_regions.current_filtered_region"),
- resource.TestCheckResourceAttr("data.alicloud_regions.current_filtered_region", "current", "true"),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudRegionsDataSource_empty(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAlicloudRegionsDataSourceEmptyConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAlicloudDataSourceID("data.alicloud_regions.empty_params_region"),
-
- resource.TestCheckResourceAttr("data.alicloud_regions.empty_params_region", "regions.0.id", "cn-shenzhen"),
- resource.TestCheckResourceAttr("data.alicloud_regions.empty_params_region", "regions.0.region_id", "cn-shenzhen"),
- resource.TestCheckResourceAttr("data.alicloud_regions.empty_params_region", "regions.0.local_name", "华南 1"),
- ),
- },
- },
- })
-}
-
-// Instance store test - using centos regions
-const testAccCheckAlicloudRegionsDataSourceRegionsConfig = `
-data "alicloud_regions" "region" {
- name = "cn-beijing"
- current = true
-}
-`
-
-// Testing name parameter
-const testAccCheckAlicloudRegionsDataSourceNameConfig = `
-data "alicloud_regions" "name_filtered_region" {
- name = "cn-hangzhou"
-}
-`
-
-// Testing current parameter
-const testAccCheckAlicloudRegionsDataSourceCurrentConfig = `
-data "alicloud_regions" "current_filtered_region" {
- current = true
-}
-`
-
-// Testing empty parmas
-const testAccCheckAlicloudRegionsDataSourceEmptyConfig = `
-data "alicloud_regions" "empty_params_region" {
-}
-`
diff --git a/builtin/providers/alicloud/data_source_alicloud_zones.go b/builtin/providers/alicloud/data_source_alicloud_zones.go
deleted file mode 100644
index 689e98a16..000000000
--- a/builtin/providers/alicloud/data_source_alicloud_zones.go
+++ /dev/null
@@ -1,137 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/schema"
- "log"
- "reflect"
-)
-
-func dataSourceAlicloudZones() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAlicloudZonesRead,
-
- Schema: map[string]*schema.Schema{
- "available_instance_type": {
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
- "available_resource_creation": {
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
- "available_disk_category": {
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
- // Computed values.
- "zones": {
- Type: schema.TypeList,
- Computed: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "id": {
- Type: schema.TypeString,
- Computed: true,
- },
- "local_name": {
- Type: schema.TypeString,
- Computed: true,
- },
- "available_instance_types": {
- Type: schema.TypeList,
- Computed: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
- "available_resource_creation": {
- Type: schema.TypeList,
- Computed: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
- "available_disk_categories": {
- Type: schema.TypeList,
- Computed: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
- },
- },
- },
- },
- }
-}
-
-func dataSourceAlicloudZonesRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).ecsconn
-
- insType, _ := d.Get("available_instance_type").(string)
- resType, _ := d.Get("available_resource_creation").(string)
- diskType, _ := d.Get("available_disk_category").(string)
-
- resp, err := conn.DescribeZones(getRegion(d, meta))
- if err != nil {
- return err
- }
-
- var zoneTypes []ecs.ZoneType
- for _, types := range resp {
- if insType != "" && !constraints(types.AvailableInstanceTypes.InstanceTypes, insType) {
- continue
- }
-
- if resType != "" && !constraints(types.AvailableResourceCreation.ResourceTypes, resType) {
- continue
- }
-
- if diskType != "" && !constraints(types.AvailableDiskCategories.DiskCategories, diskType) {
- continue
- }
- zoneTypes = append(zoneTypes, types)
- }
-
- if len(zoneTypes) < 1 {
- return fmt.Errorf("Your query returned no results. Please change your search criteria and try again.")
- }
-
- log.Printf("[DEBUG] alicloud_zones - Zones found: %#v", zoneTypes)
- return zonesDescriptionAttributes(d, zoneTypes)
-}
-
-// check array constraints str
-func constraints(arr interface{}, v string) bool {
- arrs := reflect.ValueOf(arr)
- len := arrs.Len()
- for i := 0; i < len; i++ {
- if arrs.Index(i).String() == v {
- return true
- }
- }
- return false
-}
-
-func zonesDescriptionAttributes(d *schema.ResourceData, types []ecs.ZoneType) error {
- var ids []string
- var s []map[string]interface{}
- for _, t := range types {
- mapping := map[string]interface{}{
- "id": t.ZoneId,
- "local_name": t.LocalName,
- "available_instance_types": t.AvailableInstanceTypes.InstanceTypes,
- "available_resource_creation": t.AvailableResourceCreation.ResourceTypes,
- "available_disk_categories": t.AvailableDiskCategories.DiskCategories,
- }
-
- log.Printf("[DEBUG] alicloud_zones - adding zone mapping: %v", mapping)
- ids = append(ids, t.ZoneId)
- s = append(s, mapping)
- }
-
- d.SetId(dataResourceIdHash(ids))
- if err := d.Set("zones", s); err != nil {
- return err
- }
- return nil
-}
diff --git a/builtin/providers/alicloud/data_source_alicloud_zones_test.go b/builtin/providers/alicloud/data_source_alicloud_zones_test.go
deleted file mode 100644
index 4757f495c..000000000
--- a/builtin/providers/alicloud/data_source_alicloud_zones_test.go
+++ /dev/null
@@ -1,132 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
- "strconv"
- "testing"
-)
-
-func TestAccAlicloudZonesDataSource_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAlicloudZonesDataSourceBasicConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAlicloudDataSourceID("data.alicloud_zones.foo"),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudZonesDataSource_filter(t *testing.T) {
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAlicloudZonesDataSourceFilter,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAlicloudDataSourceID("data.alicloud_zones.foo"),
- testCheckZoneLength("data.alicloud_zones.foo"),
- ),
- },
-
- resource.TestStep{
- Config: testAccCheckAlicloudZonesDataSourceFilterIoOptimized,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAlicloudDataSourceID("data.alicloud_zones.foo"),
- testCheckZoneLength("data.alicloud_zones.foo"),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudZonesDataSource_unitRegion(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAlicloudZonesDataSource_unitRegion,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAlicloudDataSourceID("data.alicloud_zones.foo"),
- ),
- },
- },
- })
-}
-
-// the zone length changed occasionally
-// check by range to avoid test case failure
-func testCheckZoneLength(name string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- ms := s.RootModule()
- rs, ok := ms.Resources[name]
- if !ok {
- return fmt.Errorf("Not found: %s", name)
- }
-
- is := rs.Primary
- if is == nil {
- return fmt.Errorf("No primary instance: %s", name)
- }
-
- i, err := strconv.Atoi(is.Attributes["zones.#"])
-
- if err != nil {
- return fmt.Errorf("convert zone length err: %#v", err)
- }
-
- if i <= 0 {
- return fmt.Errorf("zone length expected greater than 0 got err: %d", i)
- }
-
- return nil
- }
-}
-
-const testAccCheckAlicloudZonesDataSourceBasicConfig = `
-data "alicloud_zones" "foo" {
-}
-`
-
-const testAccCheckAlicloudZonesDataSourceFilter = `
-data "alicloud_zones" "foo" {
- available_instance_type= "ecs.c2.xlarge"
- available_resource_creation= "VSwitch"
- available_disk_category= "cloud_efficiency"
-}
-`
-
-const testAccCheckAlicloudZonesDataSourceFilterIoOptimized = `
-data "alicloud_zones" "foo" {
- available_instance_type= "ecs.c2.xlarge"
- available_resource_creation= "IoOptimized"
- available_disk_category= "cloud"
-}
-`
-
-const testAccCheckAlicloudZonesDataSource_unitRegion = `
-provider "alicloud" {
- alias = "northeast"
- region = "ap-northeast-1"
-}
-
-data "alicloud_zones" "foo" {
- provider = "alicloud.northeast"
- available_resource_creation= "VSwitch"
-}
-`
diff --git a/builtin/providers/alicloud/errors.go b/builtin/providers/alicloud/errors.go
deleted file mode 100644
index c159d5c65..000000000
--- a/builtin/providers/alicloud/errors.go
+++ /dev/null
@@ -1,52 +0,0 @@
-package alicloud
-
-import "github.com/denverdino/aliyungo/common"
-
-const (
- // common
- Notfound = "Not found"
- // ecs
- InstanceNotfound = "Instance.Notfound"
- // disk
- DiskIncorrectStatus = "IncorrectDiskStatus"
- DiskCreatingSnapshot = "DiskCreatingSnapshot"
- InstanceLockedForSecurity = "InstanceLockedForSecurity"
- SystemDiskNotFound = "SystemDiskNotFound"
- // eip
- EipIncorrectStatus = "IncorrectEipStatus"
- InstanceIncorrectStatus = "IncorrectInstanceStatus"
- HaVipIncorrectStatus = "IncorrectHaVipStatus"
- // slb
- LoadBalancerNotFound = "InvalidLoadBalancerId.NotFound"
-
- // security_group
- InvalidInstanceIdAlreadyExists = "InvalidInstanceId.AlreadyExists"
- InvalidSecurityGroupIdNotFound = "InvalidSecurityGroupId.NotFound"
- SgDependencyViolation = "DependencyViolation"
-
- //Nat gateway
- NatGatewayInvalidRegionId = "Invalid.RegionId"
- DependencyViolationBandwidthPackages = "DependencyViolation.BandwidthPackages"
- NotFindSnatEntryBySnatId = "NotFindSnatEntryBySnatId"
- NotFindForwardEntryByForwardId = "NotFindForwardEntryByForwardId"
-
- // vswitch
- VswitcInvalidRegionId = "InvalidRegionId.NotFound"
-
- // ess
- InvalidScalingGroupIdNotFound = "InvalidScalingGroupId.NotFound"
- IncorrectScalingConfigurationLifecycleState = "IncorrectScalingConfigurationLifecycleState"
-
- //unknown Error
- UnknownError = "UnknownError"
-)
-
-func GetNotFoundErrorFromString(str string) error {
- return &common.Error{
- ErrorResponse: common.ErrorResponse{
- Code: InstanceNotfound,
- Message: str,
- },
- StatusCode: -1,
- }
-}
diff --git a/builtin/providers/alicloud/extension_ecs.go b/builtin/providers/alicloud/extension_ecs.go
deleted file mode 100644
index df21138bf..000000000
--- a/builtin/providers/alicloud/extension_ecs.go
+++ /dev/null
@@ -1,37 +0,0 @@
-package alicloud
-
-type GroupRuleDirection string
-
-const (
- GroupRuleIngress = GroupRuleDirection("ingress")
- GroupRuleEgress = GroupRuleDirection("egress")
-)
-
-type GroupRuleIpProtocol string
-
-const (
- GroupRuleTcp = GroupRuleIpProtocol("tcp")
- GroupRuleUdp = GroupRuleIpProtocol("udp")
- GroupRuleIcmp = GroupRuleIpProtocol("icmp")
- GroupRuleGre = GroupRuleIpProtocol("gre")
- GroupRuleAll = GroupRuleIpProtocol("all")
-)
-
-type GroupRuleNicType string
-
-const (
- GroupRuleInternet = GroupRuleNicType("internet")
- GroupRuleIntranet = GroupRuleNicType("intranet")
-)
-
-type GroupRulePolicy string
-
-const (
- GroupRulePolicyAccept = GroupRulePolicy("accept")
- GroupRulePolicyDrop = GroupRulePolicy("drop")
-)
-
-const (
- EcsApiVersion20160314 = "2016-03-14"
- EcsApiVersion20140526 = "2014-05-26"
-)
diff --git a/builtin/providers/alicloud/extension_slb.go b/builtin/providers/alicloud/extension_slb.go
deleted file mode 100644
index 2c4cf787b..000000000
--- a/builtin/providers/alicloud/extension_slb.go
+++ /dev/null
@@ -1,164 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "strings"
-
- "github.com/denverdino/aliyungo/slb"
-)
-
-type Listener struct {
- slb.HTTPListenerType
-
- InstancePort int
- LoadBalancerPort int
- Protocol string
- //tcp & udp
- PersistenceTimeout int
-
- //https
- SSLCertificateId string
-
- //tcp
- HealthCheckType slb.HealthCheckType
-
- //api interface: http & https is HealthCheckTimeout, tcp & udp is HealthCheckConnectTimeout
- HealthCheckConnectTimeout int
-}
-
-type ListenerErr struct {
- ErrType string
- Err error
-}
-
-func (e *ListenerErr) Error() string {
- return e.ErrType + " " + e.Err.Error()
-
-}
-
-const (
- HealthCheckErrType = "healthCheckErrType"
- StickySessionErrType = "stickySessionErrType"
- CookieTimeOutErrType = "cookieTimeoutErrType"
- CookieErrType = "cookieErrType"
-)
-
-// Takes the result of flatmap.Expand for an array of listeners and
-// returns ELB API compatible objects
-func expandListeners(configured []interface{}) ([]*Listener, error) {
- listeners := make([]*Listener, 0, len(configured))
-
- // Loop over our configured listeners and create
- // an array of aws-sdk-go compatabile objects
- for _, lRaw := range configured {
- data := lRaw.(map[string]interface{})
-
- ip := data["instance_port"].(int)
- lp := data["lb_port"].(int)
- l := &Listener{
- InstancePort: ip,
- LoadBalancerPort: lp,
- Protocol: data["lb_protocol"].(string),
- }
-
- l.Bandwidth = data["bandwidth"].(int)
-
- if v, ok := data["scheduler"]; ok {
- l.Scheduler = slb.SchedulerType(v.(string))
- }
-
- if v, ok := data["ssl_certificate_id"]; ok {
- l.SSLCertificateId = v.(string)
- }
-
- if v, ok := data["sticky_session"]; ok {
- l.StickySession = slb.FlagType(v.(string))
- }
-
- if v, ok := data["sticky_session_type"]; ok {
- l.StickySessionType = slb.StickySessionType(v.(string))
- }
-
- if v, ok := data["cookie_timeout"]; ok {
- l.CookieTimeout = v.(int)
- }
-
- if v, ok := data["cookie"]; ok {
- l.Cookie = v.(string)
- }
-
- if v, ok := data["persistence_timeout"]; ok {
- l.PersistenceTimeout = v.(int)
- }
-
- if v, ok := data["health_check"]; ok {
- l.HealthCheck = slb.FlagType(v.(string))
- }
-
- if v, ok := data["health_check_type"]; ok {
- l.HealthCheckType = slb.HealthCheckType(v.(string))
- }
-
- if v, ok := data["health_check_domain"]; ok {
- l.HealthCheckDomain = v.(string)
- }
-
- if v, ok := data["health_check_uri"]; ok {
- l.HealthCheckURI = v.(string)
- }
-
- if v, ok := data["health_check_connect_port"]; ok {
- l.HealthCheckConnectPort = v.(int)
- }
-
- if v, ok := data["healthy_threshold"]; ok {
- l.HealthyThreshold = v.(int)
- }
-
- if v, ok := data["unhealthy_threshold"]; ok {
- l.UnhealthyThreshold = v.(int)
- }
-
- if v, ok := data["health_check_timeout"]; ok {
- l.HealthCheckTimeout = v.(int)
- }
-
- if v, ok := data["health_check_interval"]; ok {
- l.HealthCheckInterval = v.(int)
- }
-
- if v, ok := data["health_check_http_code"]; ok {
- l.HealthCheckHttpCode = slb.HealthCheckHttpCodeType(v.(string))
- }
-
- var valid bool
- if l.SSLCertificateId != "" {
- // validate the protocol is correct
- for _, p := range []string{"https", "ssl"} {
- if strings.ToLower(l.Protocol) == p {
- valid = true
- }
- }
- } else {
- valid = true
- }
-
- if valid {
- listeners = append(listeners, l)
- } else {
- return nil, fmt.Errorf("[ERR] SLB Listener: ssl_certificate_id may be set only when protocol is 'https' or 'ssl'")
- }
- }
-
- return listeners, nil
-}
-
-func expandBackendServers(list []interface{}) []slb.BackendServerType {
- result := make([]slb.BackendServerType, 0, len(list))
- for _, i := range list {
- if i.(string) != "" {
- result = append(result, slb.BackendServerType{ServerId: i.(string), Weight: 100})
- }
- }
- return result
-}
diff --git a/builtin/providers/alicloud/extension_tags.go b/builtin/providers/alicloud/extension_tags.go
deleted file mode 100644
index 5b86ebab7..000000000
--- a/builtin/providers/alicloud/extension_tags.go
+++ /dev/null
@@ -1,43 +0,0 @@
-package alicloud
-
-import (
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
-)
-
-type Tag struct {
- Key string
- Value string
-}
-
-type AddTagsArgs struct {
- ResourceId string
- ResourceType ecs.TagResourceType //image, instance, snapshot or disk
- RegionId common.Region
- Tag []Tag
-}
-
-type RemoveTagsArgs struct {
- ResourceId string
- ResourceType ecs.TagResourceType //image, instance, snapshot or disk
- RegionId common.Region
- Tag []Tag
-}
-
-func AddTags(client *ecs.Client, args *AddTagsArgs) error {
- response := ecs.AddTagsResponse{}
- err := client.Invoke("AddTags", args, &response)
- if err != nil {
- return err
- }
- return err
-}
-
-func RemoveTags(client *ecs.Client, args *RemoveTagsArgs) error {
- response := ecs.RemoveTagsResponse{}
- err := client.Invoke("RemoveTags", args, &response)
- if err != nil {
- return err
- }
- return err
-}
diff --git a/builtin/providers/alicloud/provider.go b/builtin/providers/alicloud/provider.go
deleted file mode 100644
index d7f92da64..000000000
--- a/builtin/providers/alicloud/provider.go
+++ /dev/null
@@ -1,112 +0,0 @@
-package alicloud
-
-import (
- "github.com/denverdino/aliyungo/common"
- "github.com/hashicorp/terraform/helper/mutexkv"
- "github.com/hashicorp/terraform/helper/schema"
- "github.com/hashicorp/terraform/terraform"
- "os"
-)
-
-// Provider returns a schema.Provider for alicloud
-func Provider() terraform.ResourceProvider {
- return &schema.Provider{
- Schema: map[string]*schema.Schema{
- "access_key": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- DefaultFunc: schema.EnvDefaultFunc("ALICLOUD_ACCESS_KEY", nil),
- Description: descriptions["access_key"],
- },
- "secret_key": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- DefaultFunc: schema.EnvDefaultFunc("ALICLOUD_SECRET_KEY", nil),
- Description: descriptions["secret_key"],
- },
- "region": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- DefaultFunc: schema.EnvDefaultFunc("ALICLOUD_REGION", DEFAULT_REGION),
- Description: descriptions["region"],
- },
- },
- DataSourcesMap: map[string]*schema.Resource{
-
- "alicloud_images": dataSourceAlicloudImages(),
- "alicloud_regions": dataSourceAlicloudRegions(),
- "alicloud_zones": dataSourceAlicloudZones(),
- "alicloud_instance_types": dataSourceAlicloudInstanceTypes(),
- },
- ResourcesMap: map[string]*schema.Resource{
- "alicloud_instance": resourceAliyunInstance(),
- "alicloud_disk": resourceAliyunDisk(),
- "alicloud_disk_attachment": resourceAliyunDiskAttachment(),
- "alicloud_security_group": resourceAliyunSecurityGroup(),
- "alicloud_security_group_rule": resourceAliyunSecurityGroupRule(),
- "alicloud_db_instance": resourceAlicloudDBInstance(),
- "alicloud_ess_scaling_group": resourceAlicloudEssScalingGroup(),
- "alicloud_ess_scaling_configuration": resourceAlicloudEssScalingConfiguration(),
- "alicloud_ess_scaling_rule": resourceAlicloudEssScalingRule(),
- "alicloud_ess_schedule": resourceAlicloudEssSchedule(),
- "alicloud_vpc": resourceAliyunVpc(),
- "alicloud_nat_gateway": resourceAliyunNatGateway(),
- //both subnet and vswith exists,cause compatible old version, and compatible aws habit.
- "alicloud_subnet": resourceAliyunSubnet(),
- "alicloud_vswitch": resourceAliyunSubnet(),
- "alicloud_route_entry": resourceAliyunRouteEntry(),
- "alicloud_snat_entry": resourceAliyunSnatEntry(),
- "alicloud_forward_entry": resourceAliyunForwardEntry(),
- "alicloud_eip": resourceAliyunEip(),
- "alicloud_eip_association": resourceAliyunEipAssociation(),
- "alicloud_slb": resourceAliyunSlb(),
- "alicloud_slb_attachment": resourceAliyunSlbAttachment(),
- },
-
- ConfigureFunc: providerConfigure,
- }
-}
-
-func providerConfigure(d *schema.ResourceData) (interface{}, error) {
- accesskey, ok := d.GetOk("access_key")
- if !ok {
- accesskey = os.Getenv("ALICLOUD_ACCESS_KEY")
- }
- secretkey, ok := d.GetOk("secret_key")
- if !ok {
- secretkey = os.Getenv("ALICLOUD_SECRET_KEY")
- }
- region, ok := d.GetOk("region")
- if !ok {
- region = os.Getenv("ALICLOUD_REGION")
- if region == "" {
- region = DEFAULT_REGION
- }
- }
-
- config := Config{
- AccessKey: accesskey.(string),
- SecretKey: secretkey.(string),
- Region: common.Region(region.(string)),
- }
-
- client, err := config.Client()
- if err != nil {
- return nil, err
- }
-
- return client, nil
-}
-
-// This is a global MutexKV for use within this plugin.
-var alicloudMutexKV = mutexkv.NewMutexKV()
-
-var descriptions map[string]string
-
-func init() {
- descriptions = map[string]string{
- "access_key": "Access key of alicloud",
- "secret_key": "Secret key of alicloud",
- "region": "Region of alicloud",
- }
-}
diff --git a/builtin/providers/alicloud/provider_test.go b/builtin/providers/alicloud/provider_test.go
deleted file mode 100644
index f0f5e9bec..000000000
--- a/builtin/providers/alicloud/provider_test.go
+++ /dev/null
@@ -1,59 +0,0 @@
-package alicloud
-
-import (
- "log"
- "os"
- "testing"
-
- "fmt"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
- "github.com/hashicorp/terraform/terraform"
-)
-
-var testAccProviders map[string]terraform.ResourceProvider
-var testAccProvider *schema.Provider
-
-func init() {
- testAccProvider = Provider().(*schema.Provider)
- testAccProviders = map[string]terraform.ResourceProvider{
- "alicloud": testAccProvider,
- }
-}
-
-func TestProvider(t *testing.T) {
- if err := Provider().(*schema.Provider).InternalValidate(); err != nil {
- t.Fatalf("err: %s", err)
- }
-}
-
-func TestProvider_impl(t *testing.T) {
- var _ terraform.ResourceProvider = Provider()
-}
-
-func testAccPreCheck(t *testing.T) {
- if v := os.Getenv("ALICLOUD_ACCESS_KEY"); v == "" {
- t.Fatal("ALICLOUD_ACCESS_KEY must be set for acceptance tests")
- }
- if v := os.Getenv("ALICLOUD_SECRET_KEY"); v == "" {
- t.Fatal("ALICLOUD_SECRET_KEY must be set for acceptance tests")
- }
- if v := os.Getenv("ALICLOUD_REGION"); v == "" {
- log.Println("[INFO] Test: Using cn-beijing as test region")
- os.Setenv("ALICLOUD_REGION", "cn-beijing")
- }
-}
-
-func testAccCheckAlicloudDataSourceID(n string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Can't find data source: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("data source ID not set")
- }
- return nil
- }
-}
diff --git a/builtin/providers/alicloud/resource_alicloud_db_instance.go b/builtin/providers/alicloud/resource_alicloud_db_instance.go
deleted file mode 100644
index 062b5d0e1..000000000
--- a/builtin/providers/alicloud/resource_alicloud_db_instance.go
+++ /dev/null
@@ -1,550 +0,0 @@
-package alicloud
-
-import (
- "bytes"
- "encoding/json"
- "fmt"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/rds"
- "github.com/hashicorp/terraform/helper/hashcode"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
- "log"
- "strconv"
- "strings"
- "time"
-)
-
-func resourceAlicloudDBInstance() *schema.Resource {
- return &schema.Resource{
- Create: resourceAlicloudDBInstanceCreate,
- Read: resourceAlicloudDBInstanceRead,
- Update: resourceAlicloudDBInstanceUpdate,
- Delete: resourceAlicloudDBInstanceDelete,
-
- Schema: map[string]*schema.Schema{
- "engine": &schema.Schema{
- Type: schema.TypeString,
- ValidateFunc: validateAllowedStringValue([]string{"MySQL", "SQLServer", "PostgreSQL", "PPAS"}),
- ForceNew: true,
- Required: true,
- },
- "engine_version": &schema.Schema{
- Type: schema.TypeString,
- ValidateFunc: validateAllowedStringValue([]string{"5.5", "5.6", "5.7", "2008r2", "2012", "9.4", "9.3"}),
- ForceNew: true,
- Required: true,
- },
- "db_instance_class": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
- "db_instance_storage": &schema.Schema{
- Type: schema.TypeInt,
- Required: true,
- },
-
- "instance_charge_type": &schema.Schema{
- Type: schema.TypeString,
- ValidateFunc: validateAllowedStringValue([]string{string(rds.Postpaid), string(rds.Prepaid)}),
- Optional: true,
- ForceNew: true,
- Default: rds.Postpaid,
- },
- "period": &schema.Schema{
- Type: schema.TypeInt,
- ValidateFunc: validateAllowedIntValue([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 24, 36}),
- Optional: true,
- ForceNew: true,
- Default: 1,
- },
-
- "zone_id": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "multi_az": &schema.Schema{
- Type: schema.TypeBool,
- Optional: true,
- ForceNew: true,
- },
- "db_instance_net_type": &schema.Schema{
- Type: schema.TypeString,
- ValidateFunc: validateAllowedStringValue([]string{string(common.Internet), string(common.Intranet)}),
- Optional: true,
- },
- "allocate_public_connection": &schema.Schema{
- Type: schema.TypeBool,
- Optional: true,
- Default: false,
- },
-
- "instance_network_type": &schema.Schema{
- Type: schema.TypeString,
- ValidateFunc: validateAllowedStringValue([]string{string(common.VPC), string(common.Classic)}),
- Optional: true,
- Computed: true,
- },
- "vswitch_id": &schema.Schema{
- Type: schema.TypeString,
- ForceNew: true,
- Optional: true,
- },
-
- "master_user_name": &schema.Schema{
- Type: schema.TypeString,
- ForceNew: true,
- Optional: true,
- },
- "master_user_password": &schema.Schema{
- Type: schema.TypeString,
- ForceNew: true,
- Optional: true,
- Sensitive: true,
- },
-
- "preferred_backup_period": &schema.Schema{
- Type: schema.TypeList,
- Elem: &schema.Schema{Type: schema.TypeString},
- // terraform does not support ValidateFunc of TypeList attr
- // ValidateFunc: validateAllowedStringValue([]string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}),
- Optional: true,
- },
- "preferred_backup_time": &schema.Schema{
- Type: schema.TypeString,
- ValidateFunc: validateAllowedStringValue(rds.BACKUP_TIME),
- Optional: true,
- },
- "backup_retention_period": &schema.Schema{
- Type: schema.TypeInt,
- ValidateFunc: validateIntegerInRange(7, 730),
- Optional: true,
- },
-
- "security_ips": &schema.Schema{
- Type: schema.TypeList,
- Elem: &schema.Schema{Type: schema.TypeString},
- Computed: true,
- Optional: true,
- },
-
- "port": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
-
- "connections": &schema.Schema{
- Type: schema.TypeList,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "connection_string": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
- "ip_type": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
- "ip_address": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- },
- },
- },
- Computed: true,
- },
-
- "db_mappings": &schema.Schema{
- Type: schema.TypeSet,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "db_name": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
- "character_set_name": &schema.Schema{
- Type: schema.TypeString,
- ValidateFunc: validateAllowedStringValue(rds.CHARACTER_SET_NAME),
- Required: true,
- },
- "db_description": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- },
- },
- },
- Optional: true,
- Set: resourceAlicloudDatabaseHash,
- },
- },
- }
-}
-
-func resourceAlicloudDatabaseHash(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%s-", m["db_name"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["character_set_name"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["db_description"].(string)))
-
- return hashcode.String(buf.String())
-}
-
-func resourceAlicloudDBInstanceCreate(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
- conn := client.rdsconn
-
- args, err := buildDBCreateOrderArgs(d, meta)
- if err != nil {
- return err
- }
-
- resp, err := conn.CreateOrder(args)
-
- if err != nil {
- return fmt.Errorf("Error creating Alicloud db instance: %#v", err)
- }
-
- instanceId := resp.DBInstanceId
- if instanceId == "" {
- return fmt.Errorf("Error get Alicloud db instance id")
- }
-
- d.SetId(instanceId)
- d.Set("instance_charge_type", d.Get("instance_charge_type"))
- d.Set("period", d.Get("period"))
- d.Set("period_type", d.Get("period_type"))
-
- // wait instance status change from Creating to running
- if err := conn.WaitForInstance(d.Id(), rds.Running, defaultLongTimeout); err != nil {
- return fmt.Errorf("WaitForInstance %s got error: %#v", rds.Running, err)
- }
-
- if err := modifySecurityIps(d.Id(), d.Get("security_ips"), meta); err != nil {
- return err
- }
-
- masterUserName := d.Get("master_user_name").(string)
- masterUserPwd := d.Get("master_user_password").(string)
- if masterUserName != "" && masterUserPwd != "" {
- if err := client.CreateAccountByInfo(d.Id(), masterUserName, masterUserPwd); err != nil {
- return fmt.Errorf("Create db account %s error: %v", masterUserName, err)
- }
- }
-
- if d.Get("allocate_public_connection").(bool) {
- if err := client.AllocateDBPublicConnection(d.Id(), DB_DEFAULT_CONNECT_PORT); err != nil {
- return fmt.Errorf("Allocate public connection error: %v", err)
- }
- }
-
- return resourceAlicloudDBInstanceUpdate(d, meta)
-}
-
-func modifySecurityIps(id string, ips interface{}, meta interface{}) error {
- client := meta.(*AliyunClient)
- ipList := expandStringList(ips.([]interface{}))
-
- ipstr := strings.Join(ipList[:], COMMA_SEPARATED)
- // default disable connect from outside
- if ipstr == "" {
- ipstr = LOCAL_HOST_IP
- }
-
- if err := client.ModifyDBSecurityIps(id, ipstr); err != nil {
- return fmt.Errorf("Error modify security ips %s: %#v", ipstr, err)
- }
- return nil
-}
-
-func resourceAlicloudDBInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
- conn := client.rdsconn
- d.Partial(true)
-
- if d.HasChange("db_mappings") {
- o, n := d.GetChange("db_mappings")
- os := o.(*schema.Set)
- ns := n.(*schema.Set)
-
- var allDbs []string
- remove := os.Difference(ns).List()
- add := ns.Difference(os).List()
-
- if len(remove) > 0 && len(add) > 0 {
- return fmt.Errorf("Failure modify database, we neither support create and delete database simultaneous nor modify database attributes.")
- }
-
- if len(remove) > 0 {
- for _, db := range remove {
- dbm, _ := db.(map[string]interface{})
- if err := conn.DeleteDatabase(d.Id(), dbm["db_name"].(string)); err != nil {
- return fmt.Errorf("Failure delete database %s: %#v", dbm["db_name"].(string), err)
- }
- }
- }
-
- if len(add) > 0 {
- for _, db := range add {
- dbm, _ := db.(map[string]interface{})
- dbName := dbm["db_name"].(string)
- allDbs = append(allDbs, dbName)
-
- if err := client.CreateDatabaseByInfo(d.Id(), dbName, dbm["character_set_name"].(string), dbm["db_description"].(string)); err != nil {
- return fmt.Errorf("Failure create database %s: %#v", dbName, err)
- }
-
- }
- }
-
- if err := conn.WaitForAllDatabase(d.Id(), allDbs, rds.Running, 600); err != nil {
- return fmt.Errorf("Failure create database %#v", err)
- }
-
- if user := d.Get("master_user_name").(string); user != "" {
- for _, dbName := range allDbs {
- if err := client.GrantDBPrivilege2Account(d.Id(), user, dbName); err != nil {
- return fmt.Errorf("Failed to grant database %s readwrite privilege to account %s: %#v", dbName, user, err)
- }
- }
- }
-
- d.SetPartial("db_mappings")
- }
-
- if d.HasChange("preferred_backup_period") || d.HasChange("preferred_backup_time") || d.HasChange("backup_retention_period") {
- period := d.Get("preferred_backup_period").([]interface{})
- periodList := expandStringList(period)
- time := d.Get("preferred_backup_time").(string)
- retention := d.Get("backup_retention_period").(int)
-
- if time == "" || retention == 0 || len(periodList) < 1 {
- return fmt.Errorf("Both backup_time, backup_period and retention_period are required to set backup policy.")
- }
-
- ps := strings.Join(periodList[:], COMMA_SEPARATED)
-
- if err := client.ConfigDBBackup(d.Id(), time, ps, retention); err != nil {
- return fmt.Errorf("Error set backup policy: %#v", err)
- }
- d.SetPartial("preferred_backup_period")
- d.SetPartial("preferred_backup_time")
- d.SetPartial("backup_retention_period")
- }
-
- if d.HasChange("security_ips") {
- if err := modifySecurityIps(d.Id(), d.Get("security_ips"), meta); err != nil {
- return err
- }
- d.SetPartial("security_ips")
- }
-
- if d.HasChange("db_instance_class") || d.HasChange("db_instance_storage") {
- co, cn := d.GetChange("db_instance_class")
- so, sn := d.GetChange("db_instance_storage")
- classOld := co.(string)
- classNew := cn.(string)
- storageOld := so.(int)
- storageNew := sn.(int)
-
- // update except the first time, because we will do it in create function
- if classOld != "" && storageOld != 0 {
- chargeType := d.Get("instance_charge_type").(string)
- if chargeType == string(rds.Prepaid) {
- return fmt.Errorf("Prepaid db instance does not support modify db_instance_class or db_instance_storage")
- }
-
- if err := client.ModifyDBClassStorage(d.Id(), classNew, strconv.Itoa(storageNew)); err != nil {
- return fmt.Errorf("Error modify db instance class or storage error: %#v", err)
- }
- }
- }
-
- d.Partial(false)
- return resourceAlicloudDBInstanceRead(d, meta)
-}
-
-func resourceAlicloudDBInstanceRead(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
- conn := client.rdsconn
-
- instance, err := client.DescribeDBInstanceById(d.Id())
- if err != nil {
- if notFoundError(err) {
- d.SetId("")
- return nil
- }
- return fmt.Errorf("Error Describe DB InstanceAttribute: %#v", err)
- }
-
- args := rds.DescribeDatabasesArgs{
- DBInstanceId: d.Id(),
- }
-
- resp, err := conn.DescribeDatabases(&args)
- if err != nil {
- return err
- }
- if resp.Databases.Database == nil {
- d.SetId("")
- return nil
- }
-
- d.Set("db_mappings", flattenDatabaseMappings(resp.Databases.Database))
-
- argn := rds.DescribeDBInstanceNetInfoArgs{
- DBInstanceId: d.Id(),
- }
-
- resn, err := conn.DescribeDBInstanceNetInfo(&argn)
- if err != nil {
- return err
- }
- d.Set("connections", flattenDBConnections(resn.DBInstanceNetInfos.DBInstanceNetInfo))
-
- ips, err := client.GetSecurityIps(d.Id())
- if err != nil {
- log.Printf("Describe DB security ips error: %#v", err)
- }
- d.Set("security_ips", ips)
-
- d.Set("engine", instance.Engine)
- d.Set("engine_version", instance.EngineVersion)
- d.Set("db_instance_class", instance.DBInstanceClass)
- d.Set("port", instance.Port)
- d.Set("db_instance_storage", instance.DBInstanceStorage)
- d.Set("zone_id", instance.ZoneId)
- d.Set("db_instance_net_type", instance.DBInstanceNetType)
- d.Set("instance_network_type", instance.InstanceNetworkType)
-
- return nil
-}
-
-func resourceAlicloudDBInstanceDelete(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).rdsconn
-
- return resource.Retry(5*time.Minute, func() *resource.RetryError {
- err := conn.DeleteInstance(d.Id())
-
- if err != nil {
- return resource.RetryableError(fmt.Errorf("DB Instance in use - trying again while it is deleted."))
- }
-
- args := &rds.DescribeDBInstancesArgs{
- DBInstanceId: d.Id(),
- }
- resp, err := conn.DescribeDBInstanceAttribute(args)
- if err != nil {
- return resource.NonRetryableError(err)
- } else if len(resp.Items.DBInstanceAttribute) < 1 {
- return nil
- }
-
- return resource.RetryableError(fmt.Errorf("DB in use - trying again while it is deleted."))
- })
-}
-
-func buildDBCreateOrderArgs(d *schema.ResourceData, meta interface{}) (*rds.CreateOrderArgs, error) {
- client := meta.(*AliyunClient)
- args := &rds.CreateOrderArgs{
- RegionId: getRegion(d, meta),
- // we does not expose this param to user,
- // because create prepaid instance progress will be stopped when set auto_pay to false,
- // then could not get instance info, cause timeout error
- AutoPay: "true",
- EngineVersion: d.Get("engine_version").(string),
- Engine: rds.Engine(d.Get("engine").(string)),
- DBInstanceStorage: d.Get("db_instance_storage").(int),
- DBInstanceClass: d.Get("db_instance_class").(string),
- Quantity: DEFAULT_INSTANCE_COUNT,
- Resource: rds.DefaultResource,
- }
-
- bussStr, err := json.Marshal(DefaultBusinessInfo)
- if err != nil {
- return nil, fmt.Errorf("Failed to translate bussiness info %#v from json to string", DefaultBusinessInfo)
- }
-
- args.BusinessInfo = string(bussStr)
-
- zoneId := d.Get("zone_id").(string)
- args.ZoneId = zoneId
-
- multiAZ := d.Get("multi_az").(bool)
- if multiAZ {
- if zoneId != "" {
- return nil, fmt.Errorf("You cannot set the ZoneId parameter when the MultiAZ parameter is set to true")
- }
- izs, err := client.DescribeMultiIZByRegion()
- if err != nil {
- return nil, fmt.Errorf("Get multiAZ id error")
- }
-
- if len(izs) < 1 {
- return nil, fmt.Errorf("Current region does not support MultiAZ.")
- }
-
- args.ZoneId = izs[0]
- }
-
- vswitchId := d.Get("vswitch_id").(string)
-
- networkType := d.Get("instance_network_type").(string)
- args.InstanceNetworkType = common.NetworkType(networkType)
-
- if vswitchId != "" {
- args.VSwitchId = vswitchId
-
- // check InstanceNetworkType with vswitchId
- if networkType == string(common.Classic) {
- return nil, fmt.Errorf("When fill vswitchId, you shold set instance_network_type to VPC")
- } else if networkType == "" {
- args.InstanceNetworkType = common.VPC
- }
-
- // get vpcId
- vpcId, err := client.GetVpcIdByVSwitchId(vswitchId)
-
- if err != nil {
- return nil, fmt.Errorf("VswitchId %s is not valid of current region", vswitchId)
- }
- // fill vpcId by vswitchId
- args.VPCId = vpcId
-
- // check vswitchId in zone
- vsw, err := client.QueryVswitchById(vpcId, vswitchId)
- if err != nil {
- return nil, fmt.Errorf("VswitchId %s is not valid of current region", vswitchId)
- }
-
- if zoneId == "" {
- args.ZoneId = vsw.ZoneId
- } else if vsw.ZoneId != zoneId {
- return nil, fmt.Errorf("VswitchId %s is not belong to the zone %s", vswitchId, zoneId)
- }
- }
-
- if v := d.Get("db_instance_net_type").(string); v != "" {
- args.DBInstanceNetType = common.NetType(v)
- }
-
- chargeType := d.Get("instance_charge_type").(string)
- if chargeType != "" {
- args.PayType = rds.DBPayType(chargeType)
- } else {
- args.PayType = rds.Postpaid
- }
-
- // if charge type is postpaid, the commodity code must set to bards
- if chargeType == string(rds.Postpaid) {
- args.CommodityCode = rds.Bards
- } else {
- args.CommodityCode = rds.Rds
- }
-
- period := d.Get("period").(int)
- args.UsedTime, args.TimeType = TransformPeriod2Time(period, chargeType)
-
- return args, nil
-}
diff --git a/builtin/providers/alicloud/resource_alicloud_db_instance_test.go b/builtin/providers/alicloud/resource_alicloud_db_instance_test.go
deleted file mode 100644
index 498cc3ae1..000000000
--- a/builtin/providers/alicloud/resource_alicloud_db_instance_test.go
+++ /dev/null
@@ -1,765 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/rds"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
- "log"
- "strings"
- "testing"
-)
-
-func TestAccAlicloudDBInstance_basic(t *testing.T) {
- var instance rds.DBInstanceAttribute
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_db_instance.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckDBInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDBInstanceConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckDBInstanceExists(
- "alicloud_db_instance.foo", &instance),
- resource.TestCheckResourceAttr(
- "alicloud_db_instance.foo",
- "port",
- "3306"),
- resource.TestCheckResourceAttr(
- "alicloud_db_instance.foo",
- "db_instance_storage",
- "10"),
- resource.TestCheckResourceAttr(
- "alicloud_db_instance.foo",
- "instance_network_type",
- "Classic"),
- resource.TestCheckResourceAttr(
- "alicloud_db_instance.foo",
- "db_instance_net_type",
- "Intranet"),
- resource.TestCheckResourceAttr(
- "alicloud_db_instance.foo",
- "engine_version",
- "5.6"),
- resource.TestCheckResourceAttr(
- "alicloud_db_instance.foo",
- "engine",
- "MySQL"),
- ),
- },
- },
- })
-
-}
-
-func TestAccAlicloudDBInstance_vpc(t *testing.T) {
- var instance rds.DBInstanceAttribute
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_db_instance.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckDBInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDBInstance_vpc,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckDBInstanceExists(
- "alicloud_db_instance.foo", &instance),
- resource.TestCheckResourceAttr(
- "alicloud_db_instance.foo",
- "port",
- "3306"),
- resource.TestCheckResourceAttr(
- "alicloud_db_instance.foo",
- "db_instance_storage",
- "10"),
- resource.TestCheckResourceAttr(
- "alicloud_db_instance.foo",
- "instance_network_type",
- "VPC"),
- resource.TestCheckResourceAttr(
- "alicloud_db_instance.foo",
- "db_instance_net_type",
- "Intranet"),
- resource.TestCheckResourceAttr(
- "alicloud_db_instance.foo",
- "engine_version",
- "5.6"),
- resource.TestCheckResourceAttr(
- "alicloud_db_instance.foo",
- "engine",
- "MySQL"),
- ),
- },
- },
- })
-
-}
-
-func TestC2CAlicloudDBInstance_prepaid_order(t *testing.T) {
- var instance rds.DBInstanceAttribute
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_db_instance.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckDBInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDBInstance_prepaid_order,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckDBInstanceExists(
- "alicloud_db_instance.foo", &instance),
- resource.TestCheckResourceAttr(
- "alicloud_db_instance.foo",
- "port",
- "3306"),
- resource.TestCheckResourceAttr(
- "alicloud_db_instance.foo",
- "db_instance_storage",
- "10"),
- resource.TestCheckResourceAttr(
- "alicloud_db_instance.foo",
- "instance_network_type",
- "VPC"),
- resource.TestCheckResourceAttr(
- "alicloud_db_instance.foo",
- "db_instance_net_type",
- "Intranet"),
- resource.TestCheckResourceAttr(
- "alicloud_db_instance.foo",
- "engine_version",
- "5.6"),
- resource.TestCheckResourceAttr(
- "alicloud_db_instance.foo",
- "engine",
- "MySQL"),
- ),
- },
- },
- })
-
-}
-
-func TestAccAlicloudDBInstance_multiIZ(t *testing.T) {
- var instance rds.DBInstanceAttribute
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_db_instance.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckDBInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDBInstance_multiIZ,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckDBInstanceExists(
- "alicloud_db_instance.foo", &instance),
- testAccCheckDBInstanceMultiIZ(&instance),
- ),
- },
- },
- })
-
-}
-
-func TestAccAlicloudDBInstance_database(t *testing.T) {
- var instance rds.DBInstanceAttribute
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_db_instance.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckDBInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDBInstance_database,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckDBInstanceExists(
- "alicloud_db_instance.foo", &instance),
- resource.TestCheckResourceAttr("alicloud_db_instance.foo", "db_mappings.#", "2"),
- ),
- },
-
- resource.TestStep{
- Config: testAccDBInstance_database_update,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckDBInstanceExists(
- "alicloud_db_instance.foo", &instance),
- resource.TestCheckResourceAttr("alicloud_db_instance.foo", "db_mappings.#", "3"),
- ),
- },
- },
- })
-
-}
-
-func TestAccAlicloudDBInstance_account(t *testing.T) {
- var instance rds.DBInstanceAttribute
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_db_instance.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckDBInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDBInstance_grantDatabasePrivilege2Account,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckDBInstanceExists(
- "alicloud_db_instance.foo", &instance),
- resource.TestCheckResourceAttr("alicloud_db_instance.foo", "db_mappings.#", "2"),
- testAccCheckAccountHasPrivilege2Database("alicloud_db_instance.foo", "tester", "foo", "ReadWrite"),
- ),
- },
- },
- })
-
-}
-
-func TestAccAlicloudDBInstance_allocatePublicConnection(t *testing.T) {
- var instance rds.DBInstanceAttribute
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_db_instance.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckDBInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDBInstance_allocatePublicConnection,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckDBInstanceExists(
- "alicloud_db_instance.foo", &instance),
- resource.TestCheckResourceAttr("alicloud_db_instance.foo", "connections.#", "2"),
- testAccCheckHasPublicConnection("alicloud_db_instance.foo"),
- ),
- },
- },
- })
-
-}
-
-func TestAccAlicloudDBInstance_backupPolicy(t *testing.T) {
- var policies []map[string]interface{}
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_db_instance.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckDBInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDBInstance_backup,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckBackupPolicyExists(
- "alicloud_db_instance.foo", policies),
- testAccCheckKeyValueInMaps(policies, "backup policy", "preferred_backup_period", "Wednesday,Thursday"),
- testAccCheckKeyValueInMaps(policies, "backup policy", "preferred_backup_time", "00:00Z-01:00Z"),
- ),
- },
- },
- })
-
-}
-
-func TestAccAlicloudDBInstance_securityIps(t *testing.T) {
- var ips []map[string]interface{}
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_db_instance.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckDBInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDBInstance_securityIps,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckSecurityIpExists(
- "alicloud_db_instance.foo", ips),
- testAccCheckKeyValueInMaps(ips, "security ip", "security_ips", "127.0.0.1"),
- ),
- },
-
- resource.TestStep{
- Config: testAccDBInstance_securityIpsConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckSecurityIpExists(
- "alicloud_db_instance.foo", ips),
- testAccCheckKeyValueInMaps(ips, "security ip", "security_ips", "10.168.1.12,100.69.7.112"),
- ),
- },
- },
- })
-
-}
-
-func TestAccAlicloudDBInstance_upgradeClass(t *testing.T) {
- var instance rds.DBInstanceAttribute
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_db_instance.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckDBInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDBInstance_class,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckDBInstanceExists(
- "alicloud_db_instance.foo", &instance),
- resource.TestCheckResourceAttr("alicloud_db_instance.foo", "db_instance_class", "rds.mysql.t1.small"),
- ),
- },
-
- resource.TestStep{
- Config: testAccDBInstance_classUpgrade,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckDBInstanceExists(
- "alicloud_db_instance.foo", &instance),
- resource.TestCheckResourceAttr("alicloud_db_instance.foo", "db_instance_class", "rds.mysql.s1.small"),
- ),
- },
- },
- })
-
-}
-
-func testAccCheckSecurityIpExists(n string, ips []map[string]interface{}) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No DB Instance ID is set")
- }
-
- conn := testAccProvider.Meta().(*AliyunClient).rdsconn
- args := rds.DescribeDBInstanceIPsArgs{
- DBInstanceId: rs.Primary.ID,
- }
-
- resp, err := conn.DescribeDBInstanceIPs(&args)
- log.Printf("[DEBUG] check instance %s security ip %#v", rs.Primary.ID, resp)
-
- if err != nil {
- return err
- }
-
- p := resp.Items.DBInstanceIPArray
-
- if len(p) < 1 {
- return fmt.Errorf("DB security ip not found")
- }
-
- ips = flattenDBSecurityIPs(p)
- return nil
- }
-}
-
-func testAccCheckDBInstanceMultiIZ(i *rds.DBInstanceAttribute) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- if !strings.Contains(i.ZoneId, MULTI_IZ_SYMBOL) {
- return fmt.Errorf("Current region does not support multiIZ.")
- }
- return nil
- }
-}
-
-func testAccCheckAccountHasPrivilege2Database(n, accountName, dbName, privilege string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No DB instance ID is set")
- }
-
- conn := testAccProvider.Meta().(*AliyunClient).rdsconn
- if err := conn.WaitForAccountPrivilege(rs.Primary.ID, accountName, dbName, rds.AccountPrivilege(privilege), 50); err != nil {
- return fmt.Errorf("Failed to grant database %s privilege to account %s: %v", dbName, accountName, err)
- }
- return nil
- }
-}
-
-func testAccCheckHasPublicConnection(n string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No DB instance ID is set")
- }
-
- conn := testAccProvider.Meta().(*AliyunClient).rdsconn
- if err := conn.WaitForPublicConnection(rs.Primary.ID, 50); err != nil {
- return fmt.Errorf("Failed to allocate public connection: %v", err)
- }
- return nil
- }
-}
-
-func testAccCheckDBInstanceExists(n string, d *rds.DBInstanceAttribute) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No DB Instance ID is set")
- }
-
- client := testAccProvider.Meta().(*AliyunClient)
- attr, err := client.DescribeDBInstanceById(rs.Primary.ID)
- log.Printf("[DEBUG] check instance %s attribute %#v", rs.Primary.ID, attr)
-
- if err != nil {
- return err
- }
-
- if attr == nil {
- return fmt.Errorf("DB Instance not found")
- }
-
- *d = *attr
- return nil
- }
-}
-
-func testAccCheckBackupPolicyExists(n string, ps []map[string]interface{}) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Backup policy not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No DB Instance ID is set")
- }
-
- conn := testAccProvider.Meta().(*AliyunClient).rdsconn
-
- args := rds.DescribeBackupPolicyArgs{
- DBInstanceId: rs.Primary.ID,
- }
- resp, err := conn.DescribeBackupPolicy(&args)
- log.Printf("[DEBUG] check instance %s backup policy %#v", rs.Primary.ID, resp)
-
- if err != nil {
- return err
- }
-
- var bs []rds.BackupPolicy
- bs = append(bs, resp.BackupPolicy)
- ps = flattenDBBackup(bs)
-
- return nil
- }
-}
-
-func testAccCheckKeyValueInMaps(ps []map[string]interface{}, propName, key, value string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- for _, policy := range ps {
- if policy[key].(string) != value {
- return fmt.Errorf("DB %s attribute '%s' expected %#v, got %#v", propName, key, value, policy[key])
- }
- }
- return nil
- }
-}
-
-func testAccCheckDBInstanceDestroy(s *terraform.State) error {
- client := testAccProvider.Meta().(*AliyunClient)
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "alicloud_db_instance" {
- continue
- }
-
- ins, err := client.DescribeDBInstanceById(rs.Primary.ID)
-
- if ins != nil {
- return fmt.Errorf("Error DB Instance still exist")
- }
-
- // Verify the error is what we want
- if err != nil {
- // Verify the error is what we want
- e, _ := err.(*common.Error)
- if e.ErrorResponse.Code == InstanceNotfound {
- continue
- }
- return err
- }
- }
-
- return nil
-}
-
-const testAccDBInstanceConfig = `
-resource "alicloud_db_instance" "foo" {
- engine = "MySQL"
- engine_version = "5.6"
- db_instance_class = "rds.mysql.t1.small"
- db_instance_storage = "10"
- instance_charge_type = "Postpaid"
- db_instance_net_type = "Intranet"
-}
-`
-
-const testAccDBInstance_vpc = `
-data "alicloud_zones" "default" {
- "available_resource_creation"= "VSwitch"
-}
-
-resource "alicloud_vpc" "foo" {
- name = "tf_test_foo"
- cidr_block = "172.16.0.0/12"
-}
-
-resource "alicloud_vswitch" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- cidr_block = "172.16.0.0/21"
- availability_zone = "${data.alicloud_zones.default.zones.0.id}"
-}
-
-resource "alicloud_db_instance" "foo" {
- engine = "MySQL"
- engine_version = "5.6"
- db_instance_class = "rds.mysql.t1.small"
- db_instance_storage = "10"
- instance_charge_type = "Postpaid"
- db_instance_net_type = "Intranet"
-
- vswitch_id = "${alicloud_vswitch.foo.id}"
-}
-`
-const testAccDBInstance_multiIZ = `
-resource "alicloud_db_instance" "foo" {
- engine = "MySQL"
- engine_version = "5.6"
- db_instance_class = "rds.mysql.t1.small"
- db_instance_storage = "10"
- db_instance_net_type = "Intranet"
- multi_az = true
-}
-`
-
-const testAccDBInstance_prepaid_order = `
-resource "alicloud_db_instance" "foo" {
- engine = "MySQL"
- engine_version = "5.6"
- db_instance_class = "rds.mysql.t1.small"
- db_instance_storage = "10"
- instance_charge_type = "Prepaid"
- db_instance_net_type = "Intranet"
-}
-`
-
-const testAccDBInstance_database = `
-resource "alicloud_db_instance" "foo" {
- engine = "MySQL"
- engine_version = "5.6"
- db_instance_class = "rds.mysql.t1.small"
- db_instance_storage = "10"
- instance_charge_type = "Postpaid"
- db_instance_net_type = "Intranet"
-
- db_mappings = [
- {
- "db_name" = "foo"
- "character_set_name" = "utf8"
- "db_description" = "tf"
- },{
- "db_name" = "bar"
- "character_set_name" = "utf8"
- "db_description" = "tf"
- }]
-}
-`
-const testAccDBInstance_database_update = `
-resource "alicloud_db_instance" "foo" {
- engine = "MySQL"
- engine_version = "5.6"
- db_instance_class = "rds.mysql.t1.small"
- db_instance_storage = "10"
- instance_charge_type = "Postpaid"
- db_instance_net_type = "Intranet"
-
- db_mappings = [
- {
- "db_name" = "foo"
- "character_set_name" = "utf8"
- "db_description" = "tf"
- },{
- "db_name" = "bar"
- "character_set_name" = "utf8"
- "db_description" = "tf"
- },{
- "db_name" = "zzz"
- "character_set_name" = "utf8"
- "db_description" = "tf"
- }]
-}
-`
-
-const testAccDBInstance_grantDatabasePrivilege2Account = `
-resource "alicloud_db_instance" "foo" {
- engine = "MySQL"
- engine_version = "5.6"
- db_instance_class = "rds.mysql.t1.small"
- db_instance_storage = "10"
- instance_charge_type = "Postpaid"
- db_instance_net_type = "Intranet"
-
- master_user_name = "tester"
- master_user_password = "Test12345"
-
- db_mappings = [
- {
- "db_name" = "foo"
- "character_set_name" = "utf8"
- "db_description" = "tf"
- },{
- "db_name" = "bar"
- "character_set_name" = "utf8"
- "db_description" = "tf"
- }]
-}
-`
-
-const testAccDBInstance_allocatePublicConnection = `
-resource "alicloud_db_instance" "foo" {
- engine = "MySQL"
- engine_version = "5.6"
- db_instance_class = "rds.mysql.t1.small"
- db_instance_storage = "10"
- instance_charge_type = "Postpaid"
- db_instance_net_type = "Intranet"
-
- master_user_name = "tester"
- master_user_password = "Test12345"
-
- allocate_public_connection = true
-}
-`
-
-const testAccDBInstance_backup = `
-resource "alicloud_db_instance" "foo" {
- engine = "MySQL"
- engine_version = "5.6"
- db_instance_class = "rds.mysql.t1.small"
- db_instance_storage = "10"
- instance_charge_type = "Postpaid"
- db_instance_net_type = "Intranet"
-
- preferred_backup_period = ["Wednesday","Thursday"]
- preferred_backup_time = "00:00Z-01:00Z"
- backup_retention_period = 9
-}
-`
-
-const testAccDBInstance_securityIps = `
-resource "alicloud_db_instance" "foo" {
- engine = "MySQL"
- engine_version = "5.6"
- db_instance_class = "rds.mysql.t1.small"
- db_instance_storage = "10"
- instance_charge_type = "Postpaid"
- db_instance_net_type = "Intranet"
-}
-`
-const testAccDBInstance_securityIpsConfig = `
-resource "alicloud_db_instance" "foo" {
- engine = "MySQL"
- engine_version = "5.6"
- db_instance_class = "rds.mysql.t1.small"
- db_instance_storage = "10"
- instance_charge_type = "Postpaid"
- db_instance_net_type = "Intranet"
-
- security_ips = ["10.168.1.12", "100.69.7.112"]
-}
-`
-
-const testAccDBInstance_class = `
-resource "alicloud_db_instance" "foo" {
- engine = "MySQL"
- engine_version = "5.6"
- db_instance_class = "rds.mysql.t1.small"
- db_instance_storage = "10"
- db_instance_net_type = "Intranet"
-}
-`
-const testAccDBInstance_classUpgrade = `
-resource "alicloud_db_instance" "foo" {
- engine = "MySQL"
- engine_version = "5.6"
- db_instance_class = "rds.mysql.s1.small"
- db_instance_storage = "10"
- db_instance_net_type = "Intranet"
-}
-`
diff --git a/builtin/providers/alicloud/resource_alicloud_disk.go b/builtin/providers/alicloud/resource_alicloud_disk.go
deleted file mode 100644
index b31c37d93..000000000
--- a/builtin/providers/alicloud/resource_alicloud_disk.go
+++ /dev/null
@@ -1,247 +0,0 @@
-package alicloud
-
-import (
- "fmt"
-
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
- "log"
- "time"
-)
-
-func resourceAliyunDisk() *schema.Resource {
- return &schema.Resource{
- Create: resourceAliyunDiskCreate,
- Read: resourceAliyunDiskRead,
- Update: resourceAliyunDiskUpdate,
- Delete: resourceAliyunDiskDelete,
-
- Schema: map[string]*schema.Schema{
- "availability_zone": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
- "name": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ValidateFunc: validateDiskName,
- },
-
- "description": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ValidateFunc: validateDiskDescription,
- },
-
- "category": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- ValidateFunc: validateDiskCategory,
- Default: "cloud",
- },
-
- "size": &schema.Schema{
- Type: schema.TypeInt,
- Optional: true,
- },
-
- "snapshot_id": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- },
-
- "status": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
-
- "tags": tagsSchema(),
- },
- }
-}
-
-func resourceAliyunDiskCreate(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
-
- conn := client.ecsconn
-
- availabilityZone, err := client.DescribeZone(d.Get("availability_zone").(string))
- if err != nil {
- return err
- }
-
- args := &ecs.CreateDiskArgs{
- RegionId: getRegion(d, meta),
- ZoneId: availabilityZone.ZoneId,
- }
-
- if v, ok := d.GetOk("category"); ok && v.(string) != "" {
- category := ecs.DiskCategory(v.(string))
- if err := client.DiskAvailable(availabilityZone, category); err != nil {
- return err
- }
- args.DiskCategory = category
- }
-
- if v, ok := d.GetOk("size"); ok {
- size := v.(int)
- if args.DiskCategory == ecs.DiskCategoryCloud && (size < 5 || size > 2000) {
- return fmt.Errorf("the size of cloud disk must between 5 to 2000")
- }
-
- if (args.DiskCategory == ecs.DiskCategoryCloudEfficiency ||
- args.DiskCategory == ecs.DiskCategoryCloudSSD) && (size < 20 || size > 32768) {
- return fmt.Errorf("the size of %s disk must between 20 to 32768", args.DiskCategory)
- }
- args.Size = size
-
- d.Set("size", args.Size)
- }
-
- if v, ok := d.GetOk("snapshot_id"); ok && v.(string) != "" {
- args.SnapshotId = v.(string)
- }
-
- if args.Size <= 0 && args.SnapshotId == "" {
- return fmt.Errorf("One of size or snapshot_id is required when specifying an ECS disk.")
- }
-
- if v, ok := d.GetOk("name"); ok && v.(string) != "" {
- args.DiskName = v.(string)
- }
-
- if v, ok := d.GetOk("description"); ok && v.(string) != "" {
- args.Description = v.(string)
- }
-
- diskID, err := conn.CreateDisk(args)
- if err != nil {
- return fmt.Errorf("CreateDisk got a error: %#v", err)
- }
-
- d.SetId(diskID)
-
- return resourceAliyunDiskUpdate(d, meta)
-}
-
-func resourceAliyunDiskRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).ecsconn
-
- disks, _, err := conn.DescribeDisks(&ecs.DescribeDisksArgs{
- RegionId: getRegion(d, meta),
- DiskIds: []string{d.Id()},
- })
-
- if err != nil {
- if notFoundError(err) {
- d.SetId("")
- return nil
- }
- return fmt.Errorf("Error DescribeDiskAttribute: %#v", err)
- }
-
- log.Printf("[DEBUG] DescribeDiskAttribute for instance: %#v", disks)
-
- if disks == nil || len(disks) <= 0 {
- return fmt.Errorf("No disks found.")
- }
-
- disk := disks[0]
- d.Set("availability_zone", disk.ZoneId)
- d.Set("category", disk.Category)
- d.Set("size", disk.Size)
- d.Set("status", disk.Status)
- d.Set("name", disk.DiskName)
- d.Set("description", disk.Description)
- d.Set("snapshot_id", disk.SourceSnapshotId)
-
- tags, _, err := conn.DescribeTags(&ecs.DescribeTagsArgs{
- RegionId: getRegion(d, meta),
- ResourceType: ecs.TagResourceDisk,
- ResourceId: d.Id(),
- })
-
- if err != nil {
- log.Printf("[DEBUG] DescribeTags for disk got error: %#v", err)
- }
-
- d.Set("tags", tagsToMap(tags))
-
- return nil
-}
-
-func resourceAliyunDiskUpdate(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
- conn := client.ecsconn
-
- d.Partial(true)
-
- if err := setTags(client, ecs.TagResourceDisk, d); err != nil {
- log.Printf("[DEBUG] Set tags for instance got error: %#v", err)
- return fmt.Errorf("Set tags for instance got error: %#v", err)
- } else {
- d.SetPartial("tags")
- }
- attributeUpdate := false
- args := &ecs.ModifyDiskAttributeArgs{
- DiskId: d.Id(),
- }
-
- if d.HasChange("name") {
- d.SetPartial("name")
- val := d.Get("name").(string)
- args.DiskName = val
-
- attributeUpdate = true
- }
-
- if d.HasChange("description") {
- d.SetPartial("description")
- val := d.Get("description").(string)
- args.Description = val
-
- attributeUpdate = true
- }
- if attributeUpdate {
- if err := conn.ModifyDiskAttribute(args); err != nil {
- return err
- }
- }
-
- d.Partial(false)
-
- return resourceAliyunDiskRead(d, meta)
-}
-
-func resourceAliyunDiskDelete(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).ecsconn
-
- return resource.Retry(5*time.Minute, func() *resource.RetryError {
- err := conn.DeleteDisk(d.Id())
- if err != nil {
- e, _ := err.(*common.Error)
- if e.ErrorResponse.Code == DiskIncorrectStatus || e.ErrorResponse.Code == DiskCreatingSnapshot {
- return resource.RetryableError(fmt.Errorf("Disk in use - trying again while it is deleted."))
- }
- }
-
- disks, _, descErr := conn.DescribeDisks(&ecs.DescribeDisksArgs{
- RegionId: getRegion(d, meta),
- DiskIds: []string{d.Id()},
- })
-
- if descErr != nil {
- log.Printf("[ERROR] Delete disk is failed.")
- return resource.NonRetryableError(descErr)
- }
- if disks == nil || len(disks) < 1 {
- return nil
- }
-
- return resource.RetryableError(fmt.Errorf("Disk in use - trying again while it is deleted."))
- })
-}
diff --git a/builtin/providers/alicloud/resource_alicloud_disk_attachment.go b/builtin/providers/alicloud/resource_alicloud_disk_attachment.go
deleted file mode 100644
index 48a2c2c5c..000000000
--- a/builtin/providers/alicloud/resource_alicloud_disk_attachment.go
+++ /dev/null
@@ -1,176 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "strings"
-
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
- "log"
- "time"
-)
-
-func resourceAliyunDiskAttachment() *schema.Resource {
- return &schema.Resource{
- Create: resourceAliyunDiskAttachmentCreate,
- Read: resourceAliyunDiskAttachmentRead,
- Delete: resourceAliyunDiskAttachmentDelete,
-
- Schema: map[string]*schema.Schema{
- "instance_id": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
- "disk_id": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
-
- "device_name": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- ForceNew: true,
- },
- },
- }
-}
-
-func resourceAliyunDiskAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
-
- err := diskAttachment(d, meta)
- if err != nil {
- return err
- }
-
- d.SetId(d.Get("disk_id").(string) + ":" + d.Get("instance_id").(string))
-
- return resourceAliyunDiskAttachmentRead(d, meta)
-}
-
-func resourceAliyunDiskAttachmentRead(d *schema.ResourceData, meta interface{}) error {
- diskId, instanceId, err := getDiskIDAndInstanceID(d, meta)
- if err != nil {
- return err
- }
-
- conn := meta.(*AliyunClient).ecsconn
- disks, _, err := conn.DescribeDisks(&ecs.DescribeDisksArgs{
- RegionId: getRegion(d, meta),
- InstanceId: instanceId,
- DiskIds: []string{diskId},
- })
-
- if err != nil {
- if notFoundError(err) {
- d.SetId("")
- return nil
- }
- return fmt.Errorf("Error DescribeDiskAttribute: %#v", err)
- }
-
- log.Printf("[DEBUG] DescribeDiskAttribute for instance: %#v", disks)
- if disks == nil || len(disks) <= 0 {
- return fmt.Errorf("No Disks Found.")
- }
-
- disk := disks[0]
- d.Set("instance_id", disk.InstanceId)
- d.Set("disk_id", disk.DiskId)
- d.Set("device_name", disk.Device)
-
- return nil
-}
-
-func resourceAliyunDiskAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).ecsconn
- diskID, instanceID, err := getDiskIDAndInstanceID(d, meta)
- if err != nil {
- return err
- }
-
- return resource.Retry(5*time.Minute, func() *resource.RetryError {
- err := conn.DetachDisk(instanceID, diskID)
- if err != nil {
- e, _ := err.(*common.Error)
- if e.ErrorResponse.Code == DiskIncorrectStatus || e.ErrorResponse.Code == InstanceLockedForSecurity {
- return resource.RetryableError(fmt.Errorf("Disk in use - trying again while it detaches"))
- }
- }
-
- disks, _, descErr := conn.DescribeDisks(&ecs.DescribeDisksArgs{
- RegionId: getRegion(d, meta),
- DiskIds: []string{diskID},
- })
-
- if descErr != nil {
- log.Printf("[ERROR] Disk %s is not detached.", diskID)
- return resource.NonRetryableError(err)
- }
-
- for _, disk := range disks {
- if disk.Status != ecs.DiskStatusAvailable {
- return resource.RetryableError(fmt.Errorf("Disk in use - trying again while it is deleted."))
- }
- }
- return nil
- })
-}
-
-func getDiskIDAndInstanceID(d *schema.ResourceData, meta interface{}) (string, string, error) {
- parts := strings.Split(d.Id(), ":")
-
- if len(parts) != 2 {
- return "", "", fmt.Errorf("invalid resource id")
- }
- return parts[0], parts[1], nil
-}
-func diskAttachment(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).ecsconn
-
- diskID := d.Get("disk_id").(string)
- instanceID := d.Get("instance_id").(string)
-
- deviceName := d.Get("device_name").(string)
-
- args := &ecs.AttachDiskArgs{
- InstanceId: instanceID,
- DiskId: diskID,
- Device: deviceName,
- }
-
- return resource.Retry(5*time.Minute, func() *resource.RetryError {
- err := conn.AttachDisk(args)
- log.Printf("error : %s", err)
-
- if err != nil {
- e, _ := err.(*common.Error)
- if e.ErrorResponse.Code == DiskIncorrectStatus || e.ErrorResponse.Code == InstanceIncorrectStatus {
- return resource.RetryableError(fmt.Errorf("Disk or Instance status is incorrect - trying again while it attaches"))
- }
- return resource.NonRetryableError(err)
- }
-
- disks, _, descErr := conn.DescribeDisks(&ecs.DescribeDisksArgs{
- RegionId: getRegion(d, meta),
- InstanceId: instanceID,
- DiskIds: []string{diskID},
- })
-
- if descErr != nil {
- log.Printf("[ERROR] Disk %s is not attached.", diskID)
- return resource.NonRetryableError(err)
- }
-
- if disks == nil || len(disks) <= 0 {
- return resource.RetryableError(fmt.Errorf("Disk in attaching - trying again while it is attached."))
- }
-
- return nil
-
- })
-}
diff --git a/builtin/providers/alicloud/resource_alicloud_disk_attachment_test.go b/builtin/providers/alicloud/resource_alicloud_disk_attachment_test.go
deleted file mode 100644
index 00239f5c5..000000000
--- a/builtin/providers/alicloud/resource_alicloud_disk_attachment_test.go
+++ /dev/null
@@ -1,155 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "testing"
-
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
- "time"
-)
-
-func TestAccAlicloudDiskAttachment(t *testing.T) {
- var i ecs.InstanceAttributesType
- var v ecs.DiskItemType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_disk_attachment.disk-att",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckDiskAttachmentDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDiskAttachmentConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckInstanceExists(
- "alicloud_instance.instance", &i),
- testAccCheckDiskExists(
- "alicloud_disk.disk", &v),
- testAccCheckDiskAttachmentExists(
- "alicloud_disk_attachment.disk-att", &i, &v),
- resource.TestCheckResourceAttr(
- "alicloud_disk_attachment.disk-att",
- "device_name",
- "/dev/xvdb"),
- ),
- },
- },
- })
-
-}
-
-func testAccCheckDiskAttachmentExists(n string, instance *ecs.InstanceAttributesType, disk *ecs.DiskItemType) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No Disk ID is set")
- }
-
- client := testAccProvider.Meta().(*AliyunClient)
- conn := client.ecsconn
-
- request := &ecs.DescribeDisksArgs{
- RegionId: client.Region,
- DiskIds: []string{rs.Primary.Attributes["disk_id"]},
- }
-
- return resource.Retry(3*time.Minute, func() *resource.RetryError {
- response, _, err := conn.DescribeDisks(request)
- if response != nil {
- for _, d := range response {
- if d.Status != ecs.DiskStatusInUse {
- return resource.RetryableError(fmt.Errorf("Disk is in attaching - trying again while it attaches"))
- } else if d.InstanceId == instance.InstanceId {
- // pass
- *disk = d
- return nil
- }
- }
- }
- if err != nil {
- return resource.NonRetryableError(err)
- }
-
- return resource.NonRetryableError(fmt.Errorf("Error finding instance/disk"))
- })
- }
-}
-
-func testAccCheckDiskAttachmentDestroy(s *terraform.State) error {
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "alicloud_disk_attachment" {
- continue
- }
- // Try to find the Disk
- client := testAccProvider.Meta().(*AliyunClient)
- conn := client.ecsconn
-
- request := &ecs.DescribeDisksArgs{
- RegionId: client.Region,
- DiskIds: []string{rs.Primary.ID},
- }
-
- response, _, err := conn.DescribeDisks(request)
-
- for _, disk := range response {
- if disk.Status != ecs.DiskStatusAvailable {
- return fmt.Errorf("Error ECS Disk Attachment still exist")
- }
- }
-
- if err != nil {
- // Verify the error is what we want
- return err
- }
- }
-
- return nil
-}
-
-const testAccDiskAttachmentConfig = `
-resource "alicloud_disk" "disk" {
- availability_zone = "cn-beijing-a"
- size = "50"
-
- tags {
- Name = "TerraformTest-disk"
- }
-}
-
-resource "alicloud_instance" "instance" {
- image_id = "ubuntu_140405_64_40G_cloudinit_20161115.vhd"
- instance_type = "ecs.s1.small"
- availability_zone = "cn-beijing-a"
- security_groups = ["${alicloud_security_group.group.id}"]
- instance_name = "hello"
- internet_charge_type = "PayByBandwidth"
- io_optimized = "none"
-
- tags {
- Name = "TerraformTest-instance"
- }
-}
-
-resource "alicloud_disk_attachment" "disk-att" {
- disk_id = "${alicloud_disk.disk.id}"
- instance_id = "${alicloud_instance.instance.id}"
- device_name = "/dev/xvdb"
-}
-
-resource "alicloud_security_group" "group" {
- name = "terraform-test-group"
- description = "New security group"
-}
-
-`
diff --git a/builtin/providers/alicloud/resource_alicloud_disk_test.go b/builtin/providers/alicloud/resource_alicloud_disk_test.go
deleted file mode 100644
index b8d73a662..000000000
--- a/builtin/providers/alicloud/resource_alicloud_disk_test.go
+++ /dev/null
@@ -1,166 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "testing"
-
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
- "log"
-)
-
-func TestAccAlicloudDisk_basic(t *testing.T) {
- var v ecs.DiskItemType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_disk.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckDiskDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDiskConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckDiskExists(
- "alicloud_disk.foo", &v),
- resource.TestCheckResourceAttr(
- "alicloud_disk.foo",
- "category",
- "cloud_efficiency"),
- resource.TestCheckResourceAttr(
- "alicloud_disk.foo",
- "size",
- "30"),
- ),
- },
- },
- })
-
-}
-
-func TestAccAlicloudDisk_withTags(t *testing.T) {
- var v ecs.DiskItemType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- //module name
- IDRefreshName: "alicloud_disk.bar",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckDiskDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDiskConfigWithTags,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckDiskExists("alicloud_disk.bar", &v),
- resource.TestCheckResourceAttr(
- "alicloud_disk.bar",
- "tags.Name",
- "TerraformTest"),
- ),
- },
- },
- })
-}
-
-func testAccCheckDiskExists(n string, disk *ecs.DiskItemType) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No Disk ID is set")
- }
-
- client := testAccProvider.Meta().(*AliyunClient)
- conn := client.ecsconn
-
- request := &ecs.DescribeDisksArgs{
- RegionId: client.Region,
- DiskIds: []string{rs.Primary.ID},
- }
-
- response, _, err := conn.DescribeDisks(request)
- log.Printf("[WARN] disk ids %#v", rs.Primary.ID)
-
- if err == nil {
- if response != nil && len(response) > 0 {
- *disk = response[0]
- return nil
- }
- }
- return fmt.Errorf("Error finding ECS Disk %#v", rs.Primary.ID)
- }
-}
-
-func testAccCheckDiskDestroy(s *terraform.State) error {
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "alicloud_disk" {
- continue
- }
-
- // Try to find the Disk
- client := testAccProvider.Meta().(*AliyunClient)
- conn := client.ecsconn
-
- request := &ecs.DescribeDisksArgs{
- RegionId: client.Region,
- DiskIds: []string{rs.Primary.ID},
- }
-
- response, _, err := conn.DescribeDisks(request)
-
- if response != nil && len(response) > 0 {
- return fmt.Errorf("Error ECS Disk still exist")
- }
-
- if err != nil {
- // Verify the error is what we want
- return err
- }
- }
-
- return nil
-}
-
-const testAccDiskConfig = `
-data "alicloud_zones" "default" {
- "available_disk_category"= "cloud_efficiency"
-}
-
-resource "alicloud_disk" "foo" {
- # cn-beijing
- availability_zone = "${data.alicloud_zones.default.zones.0.id}"
- name = "New-disk"
- description = "Hello ecs disk."
- category = "cloud_efficiency"
- size = "30"
-}
-`
-const testAccDiskConfigWithTags = `
-data "alicloud_zones" "default" {
- "available_disk_category"= "cloud_efficiency"
-}
-
-resource "alicloud_disk" "bar" {
- # cn-beijing
- availability_zone = "${data.alicloud_zones.default.zones.0.id}"
- category = "cloud_efficiency"
- size = "20"
- tags {
- Name = "TerraformTest"
- }
-}
-`
diff --git a/builtin/providers/alicloud/resource_alicloud_eip.go b/builtin/providers/alicloud/resource_alicloud_eip.go
deleted file mode 100644
index f1c9621a8..000000000
--- a/builtin/providers/alicloud/resource_alicloud_eip.go
+++ /dev/null
@@ -1,157 +0,0 @@
-package alicloud
-
-import (
- "strconv"
-
- "fmt"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
- "time"
-)
-
-func resourceAliyunEip() *schema.Resource {
- return &schema.Resource{
- Create: resourceAliyunEipCreate,
- Read: resourceAliyunEipRead,
- Update: resourceAliyunEipUpdate,
- Delete: resourceAliyunEipDelete,
-
- Schema: map[string]*schema.Schema{
- "bandwidth": &schema.Schema{
- Type: schema.TypeInt,
- Optional: true,
- Default: 5,
- },
- "internet_charge_type": &schema.Schema{
- Type: schema.TypeString,
- Default: "PayByBandwidth",
- Optional: true,
- ForceNew: true,
- ValidateFunc: validateInternetChargeType,
- },
-
- "ip_address": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
-
- "status": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
-
- "instance": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- },
- }
-}
-
-func resourceAliyunEipCreate(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).ecsconn
-
- args, err := buildAliyunEipArgs(d, meta)
- if err != nil {
- return err
- }
-
- _, allocationID, err := conn.AllocateEipAddress(args)
- if err != nil {
- return err
- }
-
- d.SetId(allocationID)
-
- return resourceAliyunEipRead(d, meta)
-}
-
-func resourceAliyunEipRead(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
-
- eip, err := client.DescribeEipAddress(d.Id())
- if err != nil {
- if notFoundError(err) {
- d.SetId("")
- return nil
- }
- return fmt.Errorf("Error Describe Eip Attribute: %#v", err)
- }
-
- if eip.InstanceId != "" {
- d.Set("instance", eip.InstanceId)
- } else {
- d.Set("instance", "")
- return nil
- }
-
- bandwidth, _ := strconv.Atoi(eip.Bandwidth)
- d.Set("bandwidth", bandwidth)
- d.Set("internet_charge_type", eip.InternetChargeType)
- d.Set("ip_address", eip.IpAddress)
- d.Set("status", eip.Status)
-
- return nil
-}
-
-func resourceAliyunEipUpdate(d *schema.ResourceData, meta interface{}) error {
-
- conn := meta.(*AliyunClient).ecsconn
-
- d.Partial(true)
-
- if d.HasChange("bandwidth") {
- err := conn.ModifyEipAddressAttribute(d.Id(), d.Get("bandwidth").(int))
- if err != nil {
- return err
- }
-
- d.SetPartial("bandwidth")
- }
-
- d.Partial(false)
-
- return nil
-}
-
-func resourceAliyunEipDelete(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).ecsconn
-
- return resource.Retry(5*time.Minute, func() *resource.RetryError {
- err := conn.ReleaseEipAddress(d.Id())
-
- if err != nil {
- e, _ := err.(*common.Error)
- if e.ErrorResponse.Code == EipIncorrectStatus {
- return resource.RetryableError(fmt.Errorf("EIP in use - trying again while it is deleted."))
- }
- }
-
- args := &ecs.DescribeEipAddressesArgs{
- RegionId: getRegion(d, meta),
- AllocationId: d.Id(),
- }
-
- eips, _, descErr := conn.DescribeEipAddresses(args)
- if descErr != nil {
- return resource.NonRetryableError(descErr)
- } else if eips == nil || len(eips) < 1 {
- return nil
- }
- return resource.RetryableError(fmt.Errorf("EIP in use - trying again while it is deleted."))
- })
-}
-
-func buildAliyunEipArgs(d *schema.ResourceData, meta interface{}) (*ecs.AllocateEipAddressArgs, error) {
-
- args := &ecs.AllocateEipAddressArgs{
- RegionId: getRegion(d, meta),
- Bandwidth: d.Get("bandwidth").(int),
- InternetChargeType: common.InternetChargeType(d.Get("internet_charge_type").(string)),
- }
-
- return args, nil
-}
diff --git a/builtin/providers/alicloud/resource_alicloud_eip_association.go b/builtin/providers/alicloud/resource_alicloud_eip_association.go
deleted file mode 100644
index 5f492b40b..000000000
--- a/builtin/providers/alicloud/resource_alicloud_eip_association.go
+++ /dev/null
@@ -1,131 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "strings"
-
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
- "time"
-)
-
-func resourceAliyunEipAssociation() *schema.Resource {
- return &schema.Resource{
- Create: resourceAliyunEipAssociationCreate,
- Read: resourceAliyunEipAssociationRead,
- Delete: resourceAliyunEipAssociationDelete,
-
- Schema: map[string]*schema.Schema{
- "allocation_id": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- ForceNew: true,
- },
-
- "instance_id": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- ForceNew: true,
- },
- },
- }
-}
-
-func resourceAliyunEipAssociationCreate(d *schema.ResourceData, meta interface{}) error {
-
- conn := meta.(*AliyunClient).ecsconn
-
- allocationId := d.Get("allocation_id").(string)
- instanceId := d.Get("instance_id").(string)
-
- if err := conn.AssociateEipAddress(allocationId, instanceId); err != nil {
- return err
- }
-
- d.SetId(allocationId + ":" + instanceId)
-
- return resourceAliyunEipAssociationRead(d, meta)
-}
-
-func resourceAliyunEipAssociationRead(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
-
- allocationId, instanceId, err := getAllocationIdAndInstanceId(d, meta)
- if err != nil {
- return err
- }
-
- eip, err := client.DescribeEipAddress(allocationId)
-
- if err != nil {
- if notFoundError(err) {
- d.SetId("")
- return nil
- }
- return fmt.Errorf("Error Describe Eip Attribute: %#v", err)
- }
-
- if eip.InstanceId != instanceId {
- d.SetId("")
- return nil
- }
-
- d.Set("instance_id", eip.InstanceId)
- d.Set("allocation_id", allocationId)
- return nil
-}
-
-func resourceAliyunEipAssociationDelete(d *schema.ResourceData, meta interface{}) error {
-
- conn := meta.(*AliyunClient).ecsconn
-
- allocationId, instanceId, err := getAllocationIdAndInstanceId(d, meta)
- if err != nil {
- return err
- }
-
- return resource.Retry(5*time.Minute, func() *resource.RetryError {
- err := conn.UnassociateEipAddress(allocationId, instanceId)
-
- if err != nil {
- e, _ := err.(*common.Error)
- errCode := e.ErrorResponse.Code
- if errCode == InstanceIncorrectStatus || errCode == HaVipIncorrectStatus {
- return resource.RetryableError(fmt.Errorf("Eip in use - trying again while make it unassociated."))
- }
- }
-
- args := &ecs.DescribeEipAddressesArgs{
- RegionId: getRegion(d, meta),
- AllocationId: allocationId,
- }
-
- eips, _, descErr := conn.DescribeEipAddresses(args)
-
- if descErr != nil {
- return resource.NonRetryableError(descErr)
- } else if eips == nil || len(eips) < 1 {
- return nil
- }
- for _, eip := range eips {
- if eip.Status != ecs.EipStatusAvailable {
- return resource.RetryableError(fmt.Errorf("Eip in use - trying again while make it unassociated."))
- }
- }
-
- return nil
- })
-}
-
-func getAllocationIdAndInstanceId(d *schema.ResourceData, meta interface{}) (string, string, error) {
- parts := strings.Split(d.Id(), ":")
-
- if len(parts) != 2 {
- return "", "", fmt.Errorf("invalid resource id")
- }
- return parts[0], parts[1], nil
-}
diff --git a/builtin/providers/alicloud/resource_alicloud_eip_association_test.go b/builtin/providers/alicloud/resource_alicloud_eip_association_test.go
deleted file mode 100644
index 37c79f005..000000000
--- a/builtin/providers/alicloud/resource_alicloud_eip_association_test.go
+++ /dev/null
@@ -1,158 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "testing"
-
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
- "time"
-)
-
-func TestAccAlicloudEIPAssociation(t *testing.T) {
- var asso ecs.EipAddressSetType
- var inst ecs.InstanceAttributesType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_eip_association.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckEIPAssociationDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccEIPAssociationConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckInstanceExists(
- "alicloud_instance.instance", &inst),
- testAccCheckEIPExists(
- "alicloud_eip.eip", &asso),
- testAccCheckEIPAssociationExists(
- "alicloud_eip_association.foo", &inst, &asso),
- ),
- },
- },
- })
-
-}
-
-func testAccCheckEIPAssociationExists(n string, instance *ecs.InstanceAttributesType, eip *ecs.EipAddressSetType) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No EIP Association ID is set")
- }
-
- client := testAccProvider.Meta().(*AliyunClient)
- return resource.Retry(3*time.Minute, func() *resource.RetryError {
- d, err := client.DescribeEipAddress(rs.Primary.Attributes["allocation_id"])
-
- if err != nil {
- return resource.NonRetryableError(err)
- }
-
- if d != nil {
- if d.Status != ecs.EipStatusInUse {
- return resource.RetryableError(fmt.Errorf("Eip is in associating - trying again while it associates"))
- } else if d.InstanceId == instance.InstanceId {
- *eip = *d
- return nil
- }
- }
-
- return resource.NonRetryableError(fmt.Errorf("EIP Association not found"))
- })
- }
-}
-
-func testAccCheckEIPAssociationDestroy(s *terraform.State) error {
- client := testAccProvider.Meta().(*AliyunClient)
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "alicloud_eip_association" {
- continue
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No EIP Association ID is set")
- }
-
- // Try to find the EIP
- eips, _, err := client.ecsconn.DescribeEipAddresses(&ecs.DescribeEipAddressesArgs{
- RegionId: client.Region,
- AllocationId: rs.Primary.Attributes["allocation_id"],
- })
-
- for _, eip := range eips {
- if eip.Status != ecs.EipStatusAvailable {
- return fmt.Errorf("Error EIP Association still exist")
- }
- }
-
- // Verify the error is what we want
- if err != nil {
- return err
- }
- }
-
- return nil
-}
-
-const testAccEIPAssociationConfig = `
-data "alicloud_zones" "default" {
- "available_resource_creation"= "VSwitch"
-}
-
-resource "alicloud_vpc" "main" {
- cidr_block = "10.1.0.0/21"
-}
-
-resource "alicloud_vswitch" "main" {
- vpc_id = "${alicloud_vpc.main.id}"
- cidr_block = "10.1.1.0/24"
- availability_zone = "${data.alicloud_zones.default.zones.0.id}"
- depends_on = [
- "alicloud_vpc.main"]
-}
-
-resource "alicloud_instance" "instance" {
- # cn-beijing
- vswitch_id = "${alicloud_vswitch.main.id}"
- image_id = "ubuntu_140405_32_40G_cloudinit_20161115.vhd"
-
- # series II
- instance_type = "ecs.n1.medium"
- io_optimized = "optimized"
- system_disk_category = "cloud_efficiency"
-
- security_groups = ["${alicloud_security_group.group.id}"]
- instance_name = "test_foo"
-
- tags {
- Name = "TerraformTest-instance"
- }
-}
-
-resource "alicloud_eip" "eip" {
-}
-
-resource "alicloud_eip_association" "foo" {
- allocation_id = "${alicloud_eip.eip.id}"
- instance_id = "${alicloud_instance.instance.id}"
-}
-
-resource "alicloud_security_group" "group" {
- name = "terraform-test-group"
- description = "New security group"
- vpc_id = "${alicloud_vpc.main.id}"
-}
-`
diff --git a/builtin/providers/alicloud/resource_alicloud_eip_test.go b/builtin/providers/alicloud/resource_alicloud_eip_test.go
deleted file mode 100644
index 560f426ba..000000000
--- a/builtin/providers/alicloud/resource_alicloud_eip_test.go
+++ /dev/null
@@ -1,131 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "testing"
-
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
- "log"
-)
-
-func TestAccAlicloudEIP_basic(t *testing.T) {
- var eip ecs.EipAddressSetType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_eip.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckEIPDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccEIPConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckEIPExists(
- "alicloud_eip.foo", &eip),
- testAccCheckEIPAttributes(&eip),
- ),
- },
- resource.TestStep{
- Config: testAccEIPConfigTwo,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckEIPExists(
- "alicloud_eip.foo", &eip),
- testAccCheckEIPAttributes(&eip),
- resource.TestCheckResourceAttr(
- "alicloud_eip.foo",
- "bandwidth",
- "10"),
- ),
- },
- },
- })
-
-}
-
-func testAccCheckEIPExists(n string, eip *ecs.EipAddressSetType) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No EIP ID is set")
- }
-
- client := testAccProvider.Meta().(*AliyunClient)
- d, err := client.DescribeEipAddress(rs.Primary.ID)
-
- log.Printf("[WARN] eip id %#v", rs.Primary.ID)
-
- if err != nil {
- return err
- }
-
- if d == nil || d.IpAddress == "" {
- return fmt.Errorf("EIP not found")
- }
-
- *eip = *d
- return nil
- }
-}
-
-func testAccCheckEIPAttributes(eip *ecs.EipAddressSetType) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- if eip.IpAddress == "" {
- return fmt.Errorf("Empty Ip address")
- }
-
- return nil
- }
-}
-
-func testAccCheckEIPDestroy(s *terraform.State) error {
- client := testAccProvider.Meta().(*AliyunClient)
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "alicloud_eip" {
- continue
- }
-
- // Try to find the EIP
- conn := client.ecsconn
-
- args := &ecs.DescribeEipAddressesArgs{
- RegionId: client.Region,
- AllocationId: rs.Primary.ID,
- }
- d, _, err := conn.DescribeEipAddresses(args)
-
- if d != nil && len(d) > 0 {
- return fmt.Errorf("Error EIP still exist")
- }
-
- // Verify the error is what we want
- if err != nil {
- return err
- }
- }
-
- return nil
-}
-
-const testAccEIPConfig = `
-resource "alicloud_eip" "foo" {
-}
-`
-
-const testAccEIPConfigTwo = `
-resource "alicloud_eip" "foo" {
- bandwidth = "10"
- internet_charge_type = "PayByBandwidth"
-}
-`
diff --git a/builtin/providers/alicloud/resource_alicloud_ess_scalingconfiguration.go b/builtin/providers/alicloud/resource_alicloud_ess_scalingconfiguration.go
deleted file mode 100644
index 3a8d94380..000000000
--- a/builtin/providers/alicloud/resource_alicloud_ess_scalingconfiguration.go
+++ /dev/null
@@ -1,320 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/denverdino/aliyungo/ess"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
- "strings"
- "time"
-)
-
-func resourceAlicloudEssScalingConfiguration() *schema.Resource {
- return &schema.Resource{
- Create: resourceAliyunEssScalingConfigurationCreate,
- Read: resourceAliyunEssScalingConfigurationRead,
- Update: resourceAliyunEssScalingConfigurationUpdate,
- Delete: resourceAliyunEssScalingConfigurationDelete,
-
- Schema: map[string]*schema.Schema{
- "active": &schema.Schema{
- Type: schema.TypeBool,
- Optional: true,
- Computed: true,
- },
- "enable": &schema.Schema{
- Type: schema.TypeBool,
- Optional: true,
- },
- "scaling_group_id": &schema.Schema{
- Type: schema.TypeString,
- ForceNew: true,
- Required: true,
- },
- "image_id": &schema.Schema{
- Type: schema.TypeString,
- ForceNew: true,
- Required: true,
- },
- "instance_type": &schema.Schema{
- Type: schema.TypeString,
- ForceNew: true,
- Required: true,
- },
- "io_optimized": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- ValidateFunc: validateIoOptimized,
- },
- "security_group_id": &schema.Schema{
- Type: schema.TypeString,
- ForceNew: true,
- Required: true,
- },
- "scaling_configuration_name": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "internet_charge_type": &schema.Schema{
- Type: schema.TypeString,
- ForceNew: true,
- Optional: true,
- Computed: true,
- ValidateFunc: validateInternetChargeType,
- },
- "internet_max_bandwidth_in": &schema.Schema{
- Type: schema.TypeInt,
- Optional: true,
- ForceNew: true,
- Computed: true,
- },
- "internet_max_bandwidth_out": &schema.Schema{
- Type: schema.TypeInt,
- Optional: true,
- ForceNew: true,
- ValidateFunc: validateInternetMaxBandWidthOut,
- },
- "system_disk_category": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- Computed: true,
- ValidateFunc: validateAllowedStringValue([]string{
- string(ecs.DiskCategoryCloud),
- string(ecs.DiskCategoryCloudSSD),
- string(ecs.DiskCategoryCloudEfficiency),
- string(ecs.DiskCategoryEphemeralSSD),
- }),
- },
- "data_disk": &schema.Schema{
- Optional: true,
- ForceNew: true,
- Type: schema.TypeList,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "size": &schema.Schema{
- Type: schema.TypeInt,
- Optional: true,
- },
- "category": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- },
- "snapshot_id": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- },
- "device": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- },
- },
- },
- },
- "instance_ids": &schema.Schema{
- Type: schema.TypeList,
- Elem: &schema.Schema{Type: schema.TypeString},
- Optional: true,
- MaxItems: 20,
- },
- },
- }
-}
-
-func resourceAliyunEssScalingConfigurationCreate(d *schema.ResourceData, meta interface{}) error {
-
- args, err := buildAlicloudEssScalingConfigurationArgs(d, meta)
- if err != nil {
- return err
- }
-
- essconn := meta.(*AliyunClient).essconn
-
- scaling, err := essconn.CreateScalingConfiguration(args)
- if err != nil {
- return err
- }
-
- d.SetId(d.Get("scaling_group_id").(string) + COLON_SEPARATED + scaling.ScalingConfigurationId)
-
- return resourceAliyunEssScalingConfigurationUpdate(d, meta)
-}
-
-func resourceAliyunEssScalingConfigurationUpdate(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
- if d.HasChange("active") {
- active := d.Get("active").(bool)
- if !active {
- return fmt.Errorf("Please active the scaling configuration directly.")
- }
- ids := strings.Split(d.Id(), COLON_SEPARATED)
- err := client.ActiveScalingConfigurationById(ids[0], ids[1])
-
- if err != nil {
- return fmt.Errorf("Active scaling configuration %s err: %#v", ids[1], err)
- }
- }
-
- if err := enableEssScalingConfiguration(d, meta); err != nil {
- return err
- }
-
- return resourceAliyunEssScalingConfigurationRead(d, meta)
-}
-
-func enableEssScalingConfiguration(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
- ids := strings.Split(d.Id(), COLON_SEPARATED)
-
- if d.HasChange("enable") {
- d.SetPartial("enable")
- enable := d.Get("enable").(bool)
- if !enable {
- err := client.DisableScalingConfigurationById(ids[0])
-
- if err != nil {
- return fmt.Errorf("Disable scaling group %s err: %#v", ids[0], err)
- }
- }
-
- instance_ids := []string{}
- if d.HasChange("instance_ids") {
- d.SetPartial("instance_ids")
- instances := d.Get("instance_ids").([]interface{})
- instance_ids = expandStringList(instances)
- }
- err := client.EnableScalingConfigurationById(ids[0], ids[1], instance_ids)
-
- if err != nil {
- return fmt.Errorf("Enable scaling configuration %s err: %#v", ids[1], err)
- }
- }
- return nil
-}
-
-func resourceAliyunEssScalingConfigurationRead(d *schema.ResourceData, meta interface{}) error {
-
- client := meta.(*AliyunClient)
- ids := strings.Split(d.Id(), COLON_SEPARATED)
- c, err := client.DescribeScalingConfigurationById(ids[0], ids[1])
- if err != nil {
- if e, ok := err.(*common.Error); ok && e.Code == InstanceNotfound {
- d.SetId("")
- return nil
- }
- return fmt.Errorf("Error Describe ESS scaling configuration Attribute: %#v", err)
- }
-
- d.Set("scaling_group_id", c.ScalingGroupId)
- d.Set("active", c.LifecycleState == ess.Active)
- d.Set("image_id", c.ImageId)
- d.Set("instance_type", c.InstanceType)
- d.Set("io_optimized", c.IoOptimized)
- d.Set("security_group_id", c.SecurityGroupId)
- d.Set("scaling_configuration_name", c.ScalingConfigurationName)
- d.Set("internet_charge_type", c.InternetChargeType)
- d.Set("internet_max_bandwidth_in", c.InternetMaxBandwidthIn)
- d.Set("internet_max_bandwidth_out", c.InternetMaxBandwidthOut)
- d.Set("system_disk_category", c.SystemDiskCategory)
- d.Set("data_disk", flattenDataDiskMappings(c.DataDisks.DataDisk))
-
- return nil
-}
-
-func resourceAliyunEssScalingConfigurationDelete(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
-
- return resource.Retry(5*time.Minute, func() *resource.RetryError {
- ids := strings.Split(d.Id(), COLON_SEPARATED)
- err := client.DeleteScalingConfigurationById(ids[0], ids[1])
-
- if err != nil {
- e, _ := err.(*common.Error)
- if e.ErrorResponse.Code == IncorrectScalingConfigurationLifecycleState {
- return resource.NonRetryableError(
- fmt.Errorf("Scaling configuration is active - please active another one and trying again."))
- }
- if e.ErrorResponse.Code != InvalidScalingGroupIdNotFound {
- return resource.RetryableError(
- fmt.Errorf("Scaling configuration in use - trying again while it is deleted."))
- }
- }
-
- _, err = client.DescribeScalingConfigurationById(ids[0], ids[1])
- if err != nil {
- if notFoundError(err) {
- return nil
- }
- return resource.NonRetryableError(err)
- }
-
- return resource.RetryableError(
- fmt.Errorf("Scaling configuration in use - trying again while it is deleted."))
- })
-}
-
-func buildAlicloudEssScalingConfigurationArgs(d *schema.ResourceData, meta interface{}) (*ess.CreateScalingConfigurationArgs, error) {
- args := &ess.CreateScalingConfigurationArgs{
- ScalingGroupId: d.Get("scaling_group_id").(string),
- ImageId: d.Get("image_id").(string),
- InstanceType: d.Get("instance_type").(string),
- IoOptimized: ecs.IoOptimized(d.Get("io_optimized").(string)),
- SecurityGroupId: d.Get("security_group_id").(string),
- }
-
- if v := d.Get("scaling_configuration_name").(string); v != "" {
- args.ScalingConfigurationName = v
- }
-
- if v := d.Get("internet_charge_type").(string); v != "" {
- args.InternetChargeType = common.InternetChargeType(v)
- }
-
- if v := d.Get("internet_max_bandwidth_in").(int); v != 0 {
- args.InternetMaxBandwidthIn = v
- }
-
- if v := d.Get("internet_max_bandwidth_out").(int); v != 0 {
- args.InternetMaxBandwidthOut = v
- }
-
- if v := d.Get("system_disk_category").(string); v != "" {
- args.SystemDisk_Category = common.UnderlineString(v)
- }
-
- dds, ok := d.GetOk("data_disk")
- if ok {
- disks := dds.([]interface{})
- diskTypes := []ess.DataDiskType{}
-
- for _, e := range disks {
- pack := e.(map[string]interface{})
- disk := ess.DataDiskType{
- Size: pack["size"].(int),
- Category: pack["category"].(string),
- SnapshotId: pack["snapshot_id"].(string),
- Device: pack["device"].(string),
- }
- if v := pack["size"].(int); v != 0 {
- disk.Size = v
- }
- if v := pack["category"].(string); v != "" {
- disk.Category = v
- }
- if v := pack["snapshot_id"].(string); v != "" {
- disk.SnapshotId = v
- }
- if v := pack["device"].(string); v != "" {
- disk.Device = v
- }
- diskTypes = append(diskTypes, disk)
- }
- args.DataDisk = diskTypes
- }
-
- return args, nil
-}
diff --git a/builtin/providers/alicloud/resource_alicloud_ess_scalingconfiguration_test.go b/builtin/providers/alicloud/resource_alicloud_ess_scalingconfiguration_test.go
deleted file mode 100644
index 4a2269b38..000000000
--- a/builtin/providers/alicloud/resource_alicloud_ess_scalingconfiguration_test.go
+++ /dev/null
@@ -1,495 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ess"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
- "log"
- "regexp"
- "strings"
- "testing"
-)
-
-func TestAccAlicloudEssScalingConfiguration_basic(t *testing.T) {
- var sc ess.ScalingConfigurationItemType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_ess_scaling_configuration.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckEssScalingConfigurationDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccEssScalingConfigurationConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckEssScalingConfigurationExists(
- "alicloud_ess_scaling_configuration.foo", &sc),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_configuration.foo",
- "instance_type",
- "ecs.s2.large"),
- resource.TestMatchResourceAttr(
- "alicloud_ess_scaling_configuration.foo",
- "image_id",
- regexp.MustCompile("^centos_6")),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudEssScalingConfiguration_multiConfig(t *testing.T) {
- var sc ess.ScalingConfigurationItemType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_ess_scaling_configuration.bar",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckEssScalingConfigurationDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccEssScalingConfiguration_multiConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckEssScalingConfigurationExists(
- "alicloud_ess_scaling_configuration.bar", &sc),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_configuration.bar",
- "active",
- "false"),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_configuration.bar",
- "instance_type",
- "ecs.s2.large"),
- resource.TestMatchResourceAttr(
- "alicloud_ess_scaling_configuration.bar",
- "image_id",
- regexp.MustCompile("^centos_6")),
- ),
- },
- },
- })
-}
-
-func SkipTestAccAlicloudEssScalingConfiguration_active(t *testing.T) {
- var sc ess.ScalingConfigurationItemType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_ess_scaling_configuration.bar",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckEssScalingConfigurationDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccEssScalingConfiguration_active,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckEssScalingConfigurationExists(
- "alicloud_ess_scaling_configuration.bar", &sc),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_configuration.bar",
- "active",
- "true"),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_configuration.bar",
- "instance_type",
- "ecs.s2.large"),
- resource.TestMatchResourceAttr(
- "alicloud_ess_scaling_configuration.bar",
- "image_id",
- regexp.MustCompile("^centos_6")),
- ),
- },
-
- resource.TestStep{
- Config: testAccEssScalingConfiguration_inActive,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckEssScalingConfigurationExists(
- "alicloud_ess_scaling_configuration.bar", &sc),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_configuration.bar",
- "active",
- "false"),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_configuration.bar",
- "instance_type",
- "ecs.s2.large"),
- resource.TestMatchResourceAttr(
- "alicloud_ess_scaling_configuration.bar",
- "image_id",
- regexp.MustCompile("^centos_6")),
- ),
- },
- },
- })
-}
-
-func SkipTestAccAlicloudEssScalingConfiguration_enable(t *testing.T) {
- var sc ess.ScalingConfigurationItemType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_ess_scaling_configuration.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckEssScalingConfigurationDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccEssScalingConfiguration_enable,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckEssScalingConfigurationExists(
- "alicloud_ess_scaling_configuration.foo", &sc),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_configuration.foo",
- "enable",
- "true"),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_configuration.foo",
- "instance_type",
- "ecs.s2.large"),
- resource.TestMatchResourceAttr(
- "alicloud_ess_scaling_configuration.foo",
- "image_id",
- regexp.MustCompile("^centos_6")),
- ),
- },
-
- resource.TestStep{
- Config: testAccEssScalingConfiguration_disable,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckEssScalingConfigurationExists(
- "alicloud_ess_scaling_configuration.foo", &sc),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_configuration.foo",
- "enable",
- "false"),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_configuration.foo",
- "instance_type",
- "ecs.s2.large"),
- resource.TestMatchResourceAttr(
- "alicloud_ess_scaling_configuration.foo",
- "image_id",
- regexp.MustCompile("^centos_6")),
- ),
- },
- },
- })
-}
-
-func testAccCheckEssScalingConfigurationExists(n string, d *ess.ScalingConfigurationItemType) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No ESS Scaling Configuration ID is set")
- }
-
- client := testAccProvider.Meta().(*AliyunClient)
- ids := strings.Split(rs.Primary.ID, COLON_SEPARATED)
- attr, err := client.DescribeScalingConfigurationById(ids[0], ids[1])
- log.Printf("[DEBUG] check scaling configuration %s attribute %#v", rs.Primary.ID, attr)
-
- if err != nil {
- return err
- }
-
- if attr == nil {
- return fmt.Errorf("Scaling Configuration not found")
- }
-
- *d = *attr
- return nil
- }
-}
-
-func testAccCheckEssScalingConfigurationDestroy(s *terraform.State) error {
- client := testAccProvider.Meta().(*AliyunClient)
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "alicloud_ess_scaling_configuration" {
- continue
- }
- ids := strings.Split(rs.Primary.ID, COLON_SEPARATED)
- ins, err := client.DescribeScalingConfigurationById(ids[0], ids[1])
-
- if ins != nil {
- return fmt.Errorf("Error ESS scaling configuration still exist")
- }
-
- // Verify the error is what we want
- if err != nil {
- // Verify the error is what we want
- e, _ := err.(*common.Error)
- if e.ErrorResponse.Code == InstanceNotfound {
- continue
- }
- return err
- }
- }
-
- return nil
-}
-
-const testAccEssScalingConfigurationConfig = `
-data "alicloud_images" "ecs_image" {
- most_recent = true
- name_regex = "^centos_6\\w{1,5}[64].*"
-}
-
-resource "alicloud_security_group" "tf_test_foo" {
- description = "foo"
-}
-
-resource "alicloud_security_group_rule" "ssh-in" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "internet"
- policy = "accept"
- port_range = "22/22"
- priority = 1
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
- cidr_ip = "0.0.0.0/0"
-}
-
-resource "alicloud_ess_scaling_group" "foo" {
- min_size = 1
- max_size = 1
- scaling_group_name = "foo"
- removal_policies = ["OldestInstance", "NewestInstance"]
-}
-
-resource "alicloud_ess_scaling_configuration" "foo" {
- scaling_group_id = "${alicloud_ess_scaling_group.foo.id}"
-
- image_id = "${data.alicloud_images.ecs_image.images.0.id}"
- instance_type = "ecs.s2.large"
- io_optimized = "optimized"
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
-}
-`
-
-const testAccEssScalingConfiguration_multiConfig = `
-data "alicloud_images" "ecs_image" {
- most_recent = true
- name_regex = "^centos_6\\w{1,5}[64].*"
-}
-
-resource "alicloud_security_group" "tf_test_foo" {
- description = "foo"
-}
-
-resource "alicloud_security_group_rule" "ssh-in" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "internet"
- policy = "accept"
- port_range = "22/22"
- priority = 1
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
- cidr_ip = "0.0.0.0/0"
-}
-
-resource "alicloud_ess_scaling_group" "foo" {
- min_size = 1
- max_size = 1
- scaling_group_name = "foo"
- removal_policies = ["OldestInstance", "NewestInstance"]
-}
-
-resource "alicloud_ess_scaling_configuration" "foo" {
- scaling_group_id = "${alicloud_ess_scaling_group.foo.id}"
-
- image_id = "${data.alicloud_images.ecs_image.images.0.id}"
- instance_type = "ecs.s2.large"
- io_optimized = "optimized"
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
-}
-
-resource "alicloud_ess_scaling_configuration" "bar" {
- scaling_group_id = "${alicloud_ess_scaling_group.foo.id}"
-
- image_id = "${data.alicloud_images.ecs_image.images.0.id}"
- instance_type = "ecs.s2.large"
- io_optimized = "optimized"
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
-}
-`
-
-const testAccEssScalingConfiguration_active = `
-data "alicloud_images" "ecs_image" {
- most_recent = true
- name_regex = "^centos_6\\w{1,5}[64].*"
-}
-
-resource "alicloud_security_group" "tf_test_foo" {
- description = "foo"
-}
-
-resource "alicloud_security_group_rule" "ssh-in" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "internet"
- policy = "accept"
- port_range = "22/22"
- priority = 1
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
- cidr_ip = "0.0.0.0/0"
-}
-
-resource "alicloud_ess_scaling_group" "foo" {
- min_size = 1
- max_size = 1
- scaling_group_name = "foo"
- removal_policies = ["OldestInstance", "NewestInstance"]
-}
-
-resource "alicloud_ess_scaling_configuration" "foo" {
- scaling_group_id = "${alicloud_ess_scaling_group.foo.id}"
- active = true
-
- image_id = "${data.alicloud_images.ecs_image.images.0.id}"
- instance_type = "ecs.s2.large"
- io_optimized = "optimized"
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
-}
-`
-
-const testAccEssScalingConfiguration_inActive = `
-data "alicloud_images" "ecs_image" {
- most_recent = true
- name_regex = "^centos_6\\w{1,5}[64].*"
-}
-
-resource "alicloud_security_group" "tf_test_foo" {
- description = "foo"
-}
-
-resource "alicloud_security_group_rule" "ssh-in" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "internet"
- policy = "accept"
- port_range = "22/22"
- priority = 1
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
- cidr_ip = "0.0.0.0/0"
-}
-
-resource "alicloud_ess_scaling_group" "foo" {
- min_size = 1
- max_size = 1
- scaling_group_name = "foo"
- removal_policies = ["OldestInstance", "NewestInstance"]
-}
-
-resource "alicloud_ess_scaling_configuration" "foo" {
- scaling_group_id = "${alicloud_ess_scaling_group.foo.id}"
- active = false
-
- image_id = "${data.alicloud_images.ecs_image.images.0.id}"
- instance_type = "ecs.s2.large"
- io_optimized = "optimized"
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
-}
-`
-
-const testAccEssScalingConfiguration_enable = `
-data "alicloud_images" "ecs_image" {
- most_recent = true
- name_regex = "^centos_6\\w{1,5}[64].*"
-}
-
-resource "alicloud_security_group" "tf_test_foo" {
- description = "foo"
-}
-
-resource "alicloud_security_group_rule" "ssh-in" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "internet"
- policy = "accept"
- port_range = "22/22"
- priority = 1
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
- cidr_ip = "0.0.0.0/0"
-}
-
-resource "alicloud_ess_scaling_group" "foo" {
- min_size = 1
- max_size = 1
- scaling_group_name = "foo"
- removal_policies = ["OldestInstance", "NewestInstance"]
-}
-
-resource "alicloud_ess_scaling_configuration" "foo" {
- scaling_group_id = "${alicloud_ess_scaling_group.foo.id}"
- enable = true
-
- image_id = "${data.alicloud_images.ecs_image.images.0.id}"
- instance_type = "ecs.s2.large"
- io_optimized = "optimized"
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
-}
-`
-
-const testAccEssScalingConfiguration_disable = `
-data "alicloud_images" "ecs_image" {
- most_recent = true
- name_regex = "^centos_6\\w{1,5}[64].*"
-}
-
-resource "alicloud_security_group" "tf_test_foo" {
- description = "foo"
-}
-
-resource "alicloud_security_group_rule" "ssh-in" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "internet"
- policy = "accept"
- port_range = "22/22"
- priority = 1
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
- cidr_ip = "0.0.0.0/0"
-}
-
-resource "alicloud_ess_scaling_group" "foo" {
- min_size = 1
- max_size = 1
- scaling_group_name = "foo"
- removal_policies = ["OldestInstance", "NewestInstance"]
-}
-
-resource "alicloud_ess_scaling_configuration" "foo" {
- scaling_group_id = "${alicloud_ess_scaling_group.foo.id}"
- enable = false
-
- image_id = "${data.alicloud_images.ecs_image.images.0.id}"
- instance_type = "ecs.s2.large"
- io_optimized = "optimized"
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
-}
-`
diff --git a/builtin/providers/alicloud/resource_alicloud_ess_scalinggroup.go b/builtin/providers/alicloud/resource_alicloud_ess_scalinggroup.go
deleted file mode 100644
index 89f4154db..000000000
--- a/builtin/providers/alicloud/resource_alicloud_ess_scalinggroup.go
+++ /dev/null
@@ -1,209 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ess"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
- "strings"
- "time"
-)
-
-func resourceAlicloudEssScalingGroup() *schema.Resource {
- return &schema.Resource{
- Create: resourceAliyunEssScalingGroupCreate,
- Read: resourceAliyunEssScalingGroupRead,
- Update: resourceAliyunEssScalingGroupUpdate,
- Delete: resourceAliyunEssScalingGroupDelete,
-
- Schema: map[string]*schema.Schema{
- "min_size": &schema.Schema{
- Type: schema.TypeInt,
- Required: true,
- ValidateFunc: validateIntegerInRange(0, 100),
- },
- "max_size": &schema.Schema{
- Type: schema.TypeInt,
- Required: true,
- ValidateFunc: validateIntegerInRange(0, 100),
- },
- "scaling_group_name": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- },
- "default_cooldown": &schema.Schema{
- Type: schema.TypeInt,
- Default: 300,
- Optional: true,
- ValidateFunc: validateIntegerInRange(0, 86400),
- },
- "vswitch_id": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- },
- "removal_policies": &schema.Schema{
- Type: schema.TypeList,
- Elem: &schema.Schema{Type: schema.TypeString},
- Optional: true,
- MaxItems: 2,
- },
- "db_instance_ids": &schema.Schema{
- Type: schema.TypeList,
- Elem: &schema.Schema{Type: schema.TypeString},
- Optional: true,
- MaxItems: 3,
- },
- "loadbalancer_ids": &schema.Schema{
- Type: schema.TypeList,
- Elem: &schema.Schema{Type: schema.TypeString},
- Optional: true,
- },
- },
- }
-}
-
-func resourceAliyunEssScalingGroupCreate(d *schema.ResourceData, meta interface{}) error {
-
- args, err := buildAlicloudEssScalingGroupArgs(d, meta)
- if err != nil {
- return err
- }
-
- essconn := meta.(*AliyunClient).essconn
-
- scaling, err := essconn.CreateScalingGroup(args)
- if err != nil {
- return err
- }
-
- d.SetId(scaling.ScalingGroupId)
-
- return resourceAliyunEssScalingGroupUpdate(d, meta)
-}
-
-func resourceAliyunEssScalingGroupRead(d *schema.ResourceData, meta interface{}) error {
-
- client := meta.(*AliyunClient)
-
- scaling, err := client.DescribeScalingGroupById(d.Id())
- if err != nil {
- if e, ok := err.(*common.Error); ok && e.Code == InstanceNotfound {
- d.SetId("")
- return nil
- }
- return fmt.Errorf("Error Describe ESS scaling group Attribute: %#v", err)
- }
-
- d.Set("min_size", scaling.MinSize)
- d.Set("max_size", scaling.MaxSize)
- d.Set("scaling_group_name", scaling.ScalingGroupName)
- d.Set("default_cooldown", scaling.DefaultCooldown)
- d.Set("removal_policies", scaling.RemovalPolicies)
- d.Set("db_instance_ids", scaling.DBInstanceIds)
- d.Set("loadbalancer_ids", scaling.LoadBalancerId)
-
- return nil
-}
-
-func resourceAliyunEssScalingGroupUpdate(d *schema.ResourceData, meta interface{}) error {
-
- conn := meta.(*AliyunClient).essconn
- args := &ess.ModifyScalingGroupArgs{
- ScalingGroupId: d.Id(),
- }
-
- if d.HasChange("scaling_group_name") {
- args.ScalingGroupName = d.Get("scaling_group_name").(string)
- }
-
- if d.HasChange("min_size") {
- args.MinSize = d.Get("min_size").(int)
- }
-
- if d.HasChange("max_size") {
- args.MaxSize = d.Get("max_size").(int)
- }
-
- if d.HasChange("default_cooldown") {
- args.DefaultCooldown = d.Get("default_cooldown").(int)
- }
-
- if d.HasChange("removal_policies") {
- policyStrings := d.Get("removal_policies").([]interface{})
- args.RemovalPolicy = expandStringList(policyStrings)
- }
-
- if _, err := conn.ModifyScalingGroup(args); err != nil {
- return err
- }
-
- return resourceAliyunEssScalingGroupRead(d, meta)
-}
-
-func resourceAliyunEssScalingGroupDelete(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
-
- return resource.Retry(2*time.Minute, func() *resource.RetryError {
- err := client.DeleteScalingGroupById(d.Id())
-
- if err != nil {
- e, _ := err.(*common.Error)
- if e.ErrorResponse.Code != InvalidScalingGroupIdNotFound {
- return resource.RetryableError(fmt.Errorf("Scaling group in use - trying again while it is deleted."))
- }
- }
-
- _, err = client.DescribeScalingGroupById(d.Id())
- if err != nil {
- if notFoundError(err) {
- return nil
- }
- return resource.NonRetryableError(err)
- }
-
- return resource.RetryableError(fmt.Errorf("Scaling group in use - trying again while it is deleted."))
- })
-}
-
-func buildAlicloudEssScalingGroupArgs(d *schema.ResourceData, meta interface{}) (*ess.CreateScalingGroupArgs, error) {
- client := meta.(*AliyunClient)
- args := &ess.CreateScalingGroupArgs{
- RegionId: getRegion(d, meta),
- MinSize: d.Get("min_size").(int),
- MaxSize: d.Get("max_size").(int),
- DefaultCooldown: d.Get("default_cooldown").(int),
- }
-
- if v := d.Get("scaling_group_name").(string); v != "" {
- args.ScalingGroupName = v
- }
-
- if v := d.Get("vswitch_id").(string); v != "" {
- args.VSwitchId = v
-
- // get vpcId
- vpcId, err := client.GetVpcIdByVSwitchId(v)
-
- if err != nil {
- return nil, fmt.Errorf("VswitchId %s is not valid of current region", v)
- }
- // fill vpcId by vswitchId
- args.VpcId = vpcId
-
- }
-
- dbs, ok := d.GetOk("db_instance_ids")
- if ok {
- dbsStrings := dbs.([]interface{})
- args.DBInstanceId = expandStringList(dbsStrings)
- }
-
- lbs, ok := d.GetOk("loadbalancer_ids")
- if ok {
- lbsStrings := lbs.([]interface{})
- args.LoadBalancerId = strings.Join(expandStringList(lbsStrings), COMMA_SEPARATED)
- }
-
- return args, nil
-}
diff --git a/builtin/providers/alicloud/resource_alicloud_ess_scalinggroup_test.go b/builtin/providers/alicloud/resource_alicloud_ess_scalinggroup_test.go
deleted file mode 100644
index e707035b1..000000000
--- a/builtin/providers/alicloud/resource_alicloud_ess_scalinggroup_test.go
+++ /dev/null
@@ -1,297 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ess"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
- "log"
- "testing"
-)
-
-func TestAccAlicloudEssScalingGroup_basic(t *testing.T) {
- var sg ess.ScalingGroupItemType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_ess_scaling_group.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckEssScalingGroupDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccEssScalingGroupConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckEssScalingGroupExists(
- "alicloud_ess_scaling_group.foo", &sg),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_group.foo",
- "min_size",
- "1"),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_group.foo",
- "max_size",
- "1"),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_group.foo",
- "scaling_group_name",
- "foo"),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_group.foo",
- "removal_policies.#",
- "2",
- ),
- ),
- },
- },
- })
-
-}
-
-func TestAccAlicloudEssScalingGroup_update(t *testing.T) {
- var sg ess.ScalingGroupItemType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_ess_scaling_group.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckEssScalingGroupDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccEssScalingGroup,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckEssScalingGroupExists(
- "alicloud_ess_scaling_group.foo", &sg),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_group.foo",
- "min_size",
- "1"),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_group.foo",
- "max_size",
- "1"),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_group.foo",
- "scaling_group_name",
- "foo"),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_group.foo",
- "removal_policies.#",
- "2",
- ),
- ),
- },
-
- resource.TestStep{
- Config: testAccEssScalingGroup_update,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckEssScalingGroupExists(
- "alicloud_ess_scaling_group.foo", &sg),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_group.foo",
- "min_size",
- "2"),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_group.foo",
- "max_size",
- "2"),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_group.foo",
- "scaling_group_name",
- "update"),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_group.foo",
- "removal_policies.#",
- "1",
- ),
- ),
- },
- },
- })
-
-}
-
-func SkipTestAccAlicloudEssScalingGroup_vpc(t *testing.T) {
- var sg ess.ScalingGroupItemType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_ess_scaling_group.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckEssScalingGroupDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccEssScalingGroup_vpc,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckEssScalingGroupExists(
- "alicloud_ess_scaling_group.foo", &sg),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_group.foo",
- "min_size",
- "1"),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_group.foo",
- "max_size",
- "1"),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_group.foo",
- "scaling_group_name",
- "foo"),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_group.foo",
- "removal_policies.#",
- "2",
- ),
- ),
- },
- },
- })
-
-}
-
-func testAccCheckEssScalingGroupExists(n string, d *ess.ScalingGroupItemType) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No ESS Scaling Group ID is set")
- }
-
- client := testAccProvider.Meta().(*AliyunClient)
- attr, err := client.DescribeScalingGroupById(rs.Primary.ID)
- log.Printf("[DEBUG] check scaling group %s attribute %#v", rs.Primary.ID, attr)
-
- if err != nil {
- return err
- }
-
- if attr == nil {
- return fmt.Errorf("Scaling Group not found")
- }
-
- *d = *attr
- return nil
- }
-}
-
-func testAccCheckEssScalingGroupDestroy(s *terraform.State) error {
- client := testAccProvider.Meta().(*AliyunClient)
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "alicloud_ess_scaling_group" {
- continue
- }
-
- ins, err := client.DescribeScalingGroupById(rs.Primary.ID)
-
- if ins != nil {
- return fmt.Errorf("Error ESS scaling group still exist")
- }
-
- // Verify the error is what we want
- if err != nil {
- // Verify the error is what we want
- e, _ := err.(*common.Error)
- if e.ErrorResponse.Code == InstanceNotfound {
- continue
- }
- return err
- }
- }
-
- return nil
-}
-
-const testAccEssScalingGroupConfig = `
-resource "alicloud_ess_scaling_group" "foo" {
- min_size = 1
- max_size = 1
- scaling_group_name = "foo"
- removal_policies = ["OldestInstance", "NewestInstance"]
-}
-`
-
-const testAccEssScalingGroup = `
-resource "alicloud_ess_scaling_group" "foo" {
- min_size = 1
- max_size = 1
- scaling_group_name = "foo"
- removal_policies = ["OldestInstance", "NewestInstance"]
-}
-`
-
-const testAccEssScalingGroup_update = `
-resource "alicloud_ess_scaling_group" "foo" {
- min_size = 2
- max_size = 2
- scaling_group_name = "update"
- removal_policies = ["OldestInstance"]
-}
-`
-const testAccEssScalingGroup_vpc = `
-data "alicloud_images" "ecs_image" {
- most_recent = true
- name_regex = "^centos_6\\w{1,5}[64].*"
-}
-
-data "alicloud_zones" "default" {
- "available_disk_category"= "cloud_efficiency"
- "available_resource_creation"= "VSwitch"
-}
-
-resource "alicloud_vpc" "foo" {
- name = "tf_test_foo"
- cidr_block = "172.16.0.0/12"
-}
-
-resource "alicloud_vswitch" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- cidr_block = "172.16.0.0/21"
- availability_zone = "${data.alicloud_zones.default.zones.0.id}"
-}
-
-resource "alicloud_security_group" "tf_test_foo" {
- description = "foo"
- vpc_id = "${alicloud_vpc.foo.id}"
-}
-
-resource "alicloud_ess_scaling_group" "foo" {
- min_size = 1
- max_size = 1
- scaling_group_name = "foo"
- default_cooldown = 20
- vswitch_id = "${alicloud_vswitch.foo.id}"
- removal_policies = ["OldestInstance", "NewestInstance"]
-}
-
-resource "alicloud_ess_scaling_configuration" "foo" {
- scaling_group_id = "${alicloud_ess_scaling_group.foo.id}"
- enable = true
-
- image_id = "${data.alicloud_images.ecs_image.images.0.id}"
- instance_type = "ecs.n1.medium"
- io_optimized = "optimized"
- system_disk_category = "cloud_efficiency"
- internet_charge_type = "PayByTraffic"
- internet_max_bandwidth_out = 10
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
-}
-`
diff --git a/builtin/providers/alicloud/resource_alicloud_ess_scalingrule.go b/builtin/providers/alicloud/resource_alicloud_ess_scalingrule.go
deleted file mode 100644
index bfa1f904f..000000000
--- a/builtin/providers/alicloud/resource_alicloud_ess_scalingrule.go
+++ /dev/null
@@ -1,168 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ess"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
- "strings"
- "time"
-)
-
-func resourceAlicloudEssScalingRule() *schema.Resource {
- return &schema.Resource{
- Create: resourceAliyunEssScalingRuleCreate,
- Read: resourceAliyunEssScalingRuleRead,
- Update: resourceAliyunEssScalingRuleUpdate,
- Delete: resourceAliyunEssScalingRuleDelete,
-
- Schema: map[string]*schema.Schema{
- "scaling_group_id": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
- "adjustment_type": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ValidateFunc: validateAllowedStringValue([]string{string(ess.QuantityChangeInCapacity),
- string(ess.PercentChangeInCapacity), string(ess.TotalCapacity)}),
- },
- "adjustment_value": &schema.Schema{
- Type: schema.TypeInt,
- Required: true,
- },
- "scaling_rule_name": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- Optional: true,
- },
- "ari": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- "cooldown": &schema.Schema{
- Type: schema.TypeInt,
- Optional: true,
- ValidateFunc: validateIntegerInRange(0, 86400),
- },
- },
- }
-}
-
-func resourceAliyunEssScalingRuleCreate(d *schema.ResourceData, meta interface{}) error {
-
- args, err := buildAlicloudEssScalingRuleArgs(d, meta)
- if err != nil {
- return err
- }
-
- essconn := meta.(*AliyunClient).essconn
-
- rule, err := essconn.CreateScalingRule(args)
- if err != nil {
- return err
- }
-
- d.SetId(d.Get("scaling_group_id").(string) + COLON_SEPARATED + rule.ScalingRuleId)
-
- return resourceAliyunEssScalingRuleUpdate(d, meta)
-}
-
-func resourceAliyunEssScalingRuleRead(d *schema.ResourceData, meta interface{}) error {
-
- client := meta.(*AliyunClient)
- ids := strings.Split(d.Id(), COLON_SEPARATED)
-
- rule, err := client.DescribeScalingRuleById(ids[0], ids[1])
- if err != nil {
- if e, ok := err.(*common.Error); ok && e.Code == InstanceNotfound {
- d.SetId("")
- return nil
- }
- return fmt.Errorf("Error Describe ESS scaling rule Attribute: %#v", err)
- }
-
- d.Set("scaling_group_id", rule.ScalingGroupId)
- d.Set("ari", rule.ScalingRuleAri)
- d.Set("adjustment_type", rule.AdjustmentType)
- d.Set("adjustment_value", rule.AdjustmentValue)
- d.Set("scaling_rule_name", rule.ScalingRuleName)
- d.Set("cooldown", rule.Cooldown)
-
- return nil
-}
-
-func resourceAliyunEssScalingRuleDelete(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
- ids := strings.Split(d.Id(), COLON_SEPARATED)
-
- return resource.Retry(2*time.Minute, func() *resource.RetryError {
- err := client.DeleteScalingRuleById(ids[1])
-
- if err != nil {
- return resource.RetryableError(fmt.Errorf("Scaling rule in use - trying again while it is deleted."))
- }
-
- _, err = client.DescribeScalingRuleById(ids[0], ids[1])
- if err != nil {
- if notFoundError(err) {
- return nil
- }
- return resource.NonRetryableError(err)
- }
-
- return resource.RetryableError(fmt.Errorf("Scaling rule in use - trying again while it is deleted."))
- })
-}
-
-func resourceAliyunEssScalingRuleUpdate(d *schema.ResourceData, meta interface{}) error {
-
- conn := meta.(*AliyunClient).essconn
- ids := strings.Split(d.Id(), COLON_SEPARATED)
-
- args := &ess.ModifyScalingRuleArgs{
- ScalingRuleId: ids[1],
- }
-
- if d.HasChange("adjustment_type") {
- args.AdjustmentType = ess.AdjustmentType(d.Get("adjustment_type").(string))
- }
-
- if d.HasChange("adjustment_value") {
- args.AdjustmentValue = d.Get("adjustment_value").(int)
- }
-
- if d.HasChange("scaling_rule_name") {
- args.ScalingRuleName = d.Get("scaling_rule_name").(string)
- }
-
- if d.HasChange("cooldown") {
- args.Cooldown = d.Get("cooldown").(int)
- }
-
- if _, err := conn.ModifyScalingRule(args); err != nil {
- return err
- }
-
- return resourceAliyunEssScalingRuleRead(d, meta)
-}
-
-func buildAlicloudEssScalingRuleArgs(d *schema.ResourceData, meta interface{}) (*ess.CreateScalingRuleArgs, error) {
- args := &ess.CreateScalingRuleArgs{
- RegionId: getRegion(d, meta),
- ScalingGroupId: d.Get("scaling_group_id").(string),
- AdjustmentType: ess.AdjustmentType(d.Get("adjustment_type").(string)),
- AdjustmentValue: d.Get("adjustment_value").(int),
- }
-
- if v := d.Get("scaling_rule_name").(string); v != "" {
- args.ScalingRuleName = v
- }
-
- if v := d.Get("cooldown").(int); v != 0 {
- args.Cooldown = v
- }
-
- return args, nil
-}
diff --git a/builtin/providers/alicloud/resource_alicloud_ess_scalingrule_test.go b/builtin/providers/alicloud/resource_alicloud_ess_scalingrule_test.go
deleted file mode 100644
index 81020a747..000000000
--- a/builtin/providers/alicloud/resource_alicloud_ess_scalingrule_test.go
+++ /dev/null
@@ -1,290 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ess"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
- "log"
- "strings"
- "testing"
-)
-
-func TestAccAlicloudEssScalingRule_basic(t *testing.T) {
- var sc ess.ScalingRuleItemType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_ess_scaling_rule.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckEssScalingRuleDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccEssScalingRuleConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckEssScalingRuleExists(
- "alicloud_ess_scaling_rule.foo", &sc),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_rule.foo",
- "adjustment_type",
- "TotalCapacity"),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_rule.foo",
- "adjustment_value",
- "1"),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudEssScalingRule_update(t *testing.T) {
- var sc ess.ScalingRuleItemType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_ess_scaling_rule.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckEssScalingRuleDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccEssScalingRule,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckEssScalingRuleExists(
- "alicloud_ess_scaling_rule.foo", &sc),
- testAccCheckEssScalingRuleExists(
- "alicloud_ess_scaling_rule.foo", &sc),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_rule.foo",
- "adjustment_type",
- "TotalCapacity"),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_rule.foo",
- "adjustment_value",
- "1"),
- ),
- },
-
- resource.TestStep{
- Config: testAccEssScalingRule_update,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckEssScalingRuleExists(
- "alicloud_ess_scaling_rule.foo", &sc),
- testAccCheckEssScalingRuleExists(
- "alicloud_ess_scaling_rule.foo", &sc),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_rule.foo",
- "adjustment_type",
- "TotalCapacity"),
- resource.TestCheckResourceAttr(
- "alicloud_ess_scaling_rule.foo",
- "adjustment_value",
- "2"),
- ),
- },
- },
- })
-}
-
-func testAccCheckEssScalingRuleExists(n string, d *ess.ScalingRuleItemType) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No ESS Scaling Rule ID is set")
- }
-
- client := testAccProvider.Meta().(*AliyunClient)
- ids := strings.Split(rs.Primary.ID, COLON_SEPARATED)
- attr, err := client.DescribeScalingRuleById(ids[0], ids[1])
- log.Printf("[DEBUG] check scaling rule %s attribute %#v", rs.Primary.ID, attr)
-
- if err != nil {
- return err
- }
-
- if attr == nil {
- return fmt.Errorf("Scaling rule not found")
- }
-
- *d = *attr
- return nil
- }
-}
-
-func testAccCheckEssScalingRuleDestroy(s *terraform.State) error {
- client := testAccProvider.Meta().(*AliyunClient)
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "alicloud_ess_scaling_rule" {
- continue
- }
- ids := strings.Split(rs.Primary.ID, COLON_SEPARATED)
- ins, err := client.DescribeScalingRuleById(ids[0], ids[1])
-
- if ins != nil {
- return fmt.Errorf("Error ESS scaling rule still exist")
- }
-
- // Verify the error is what we want
- if err != nil {
- // Verify the error is what we want
- e, _ := err.(*common.Error)
- if e.ErrorResponse.Code == InstanceNotfound {
- continue
- }
- return err
- }
- }
-
- return nil
-}
-
-const testAccEssScalingRuleConfig = `
-data "alicloud_images" "ecs_image" {
- most_recent = true
- name_regex = "^centos_6\\w{1,5}[64].*"
-}
-
-resource "alicloud_security_group" "tf_test_foo" {
- description = "foo"
-}
-
-resource "alicloud_security_group_rule" "ssh-in" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "internet"
- policy = "accept"
- port_range = "22/22"
- priority = 1
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
- cidr_ip = "0.0.0.0/0"
-}
-
-resource "alicloud_ess_scaling_group" "bar" {
- min_size = 1
- max_size = 1
- scaling_group_name = "bar"
- removal_policies = ["OldestInstance", "NewestInstance"]
-}
-
-resource "alicloud_ess_scaling_configuration" "foo" {
- scaling_group_id = "${alicloud_ess_scaling_group.bar.id}"
-
- image_id = "${data.alicloud_images.ecs_image.images.0.id}"
- instance_type = "ecs.s2.large"
- io_optimized = "optimized"
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
-}
-
-resource "alicloud_ess_scaling_rule" "foo" {
- scaling_group_id = "${alicloud_ess_scaling_group.bar.id}"
- adjustment_type = "TotalCapacity"
- adjustment_value = 1
- cooldown = 120
-}
-`
-
-const testAccEssScalingRule = `
-data "alicloud_images" "ecs_image" {
- most_recent = true
- name_regex = "^centos_6\\w{1,5}[64].*"
-}
-
-resource "alicloud_security_group" "tf_test_foo" {
- description = "foo"
-}
-
-resource "alicloud_security_group_rule" "ssh-in" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "internet"
- policy = "accept"
- port_range = "22/22"
- priority = 1
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
- cidr_ip = "0.0.0.0/0"
-}
-
-resource "alicloud_ess_scaling_group" "bar" {
- min_size = 1
- max_size = 1
- scaling_group_name = "bar"
- removal_policies = ["OldestInstance", "NewestInstance"]
-}
-
-resource "alicloud_ess_scaling_configuration" "foo" {
- scaling_group_id = "${alicloud_ess_scaling_group.bar.id}"
-
- image_id = "${data.alicloud_images.ecs_image.images.0.id}"
- instance_type = "ecs.s2.large"
- io_optimized = "optimized"
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
-}
-
-resource "alicloud_ess_scaling_rule" "foo" {
- scaling_group_id = "${alicloud_ess_scaling_group.bar.id}"
- adjustment_type = "TotalCapacity"
- adjustment_value = 1
- cooldown = 120
-}
-`
-
-const testAccEssScalingRule_update = `
-data "alicloud_images" "ecs_image" {
- most_recent = true
- name_regex = "^centos_6\\w{1,5}[64].*"
-}
-
-resource "alicloud_security_group" "tf_test_foo" {
- description = "foo"
-}
-
-resource "alicloud_security_group_rule" "ssh-in" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "internet"
- policy = "accept"
- port_range = "22/22"
- priority = 1
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
- cidr_ip = "0.0.0.0/0"
-}
-
-resource "alicloud_ess_scaling_group" "bar" {
- min_size = 1
- max_size = 1
- scaling_group_name = "bar"
- removal_policies = ["OldestInstance", "NewestInstance"]
-}
-
-resource "alicloud_ess_scaling_configuration" "foo" {
- scaling_group_id = "${alicloud_ess_scaling_group.bar.id}"
-
- image_id = "${data.alicloud_images.ecs_image.images.0.id}"
- instance_type = "ecs.s2.large"
- io_optimized = "optimized"
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
-}
-
-resource "alicloud_ess_scaling_rule" "foo" {
- scaling_group_id = "${alicloud_ess_scaling_group.bar.id}"
- adjustment_type = "TotalCapacity"
- adjustment_value = 2
- cooldown = 60
-}
-`
diff --git a/builtin/providers/alicloud/resource_alicloud_ess_schedule.go b/builtin/providers/alicloud/resource_alicloud_ess_schedule.go
deleted file mode 100644
index 4e5660a50..000000000
--- a/builtin/providers/alicloud/resource_alicloud_ess_schedule.go
+++ /dev/null
@@ -1,220 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ess"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
- "time"
-)
-
-func resourceAlicloudEssSchedule() *schema.Resource {
- return &schema.Resource{
- Create: resourceAliyunEssScheduleCreate,
- Read: resourceAliyunEssScheduleRead,
- Update: resourceAliyunEssScheduleUpdate,
- Delete: resourceAliyunEssScheduleDelete,
-
- Schema: map[string]*schema.Schema{
- "scheduled_action": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
- "launch_time": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
- "scheduled_task_name": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- },
- "description": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- Optional: true,
- },
- "launch_expiration_time": &schema.Schema{
- Type: schema.TypeInt,
- Default: 600,
- Optional: true,
- ValidateFunc: validateIntegerInRange(0, 21600),
- },
- "recurrence_type": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- Optional: true,
- ValidateFunc: validateAllowedStringValue([]string{string(ess.Daily),
- string(ess.Weekly), string(ess.Monthly)}),
- },
- "recurrence_value": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- Optional: true,
- },
- "recurrence_end_time": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- Optional: true,
- },
- "task_enabled": &schema.Schema{
- Type: schema.TypeBool,
- Default: true,
- Optional: true,
- },
- },
- }
-}
-
-func resourceAliyunEssScheduleCreate(d *schema.ResourceData, meta interface{}) error {
-
- args, err := buildAlicloudEssScheduleArgs(d, meta)
- if err != nil {
- return err
- }
-
- essconn := meta.(*AliyunClient).essconn
-
- rule, err := essconn.CreateScheduledTask(args)
- if err != nil {
- return err
- }
-
- d.SetId(rule.ScheduledTaskId)
-
- return resourceAliyunEssScheduleUpdate(d, meta)
-}
-
-func resourceAliyunEssScheduleRead(d *schema.ResourceData, meta interface{}) error {
-
- client := meta.(*AliyunClient)
-
- rule, err := client.DescribeScheduleById(d.Id())
- if err != nil {
- if e, ok := err.(*common.Error); ok && e.Code == InstanceNotfound {
- d.SetId("")
- return nil
- }
- return fmt.Errorf("Error Describe ESS schedule Attribute: %#v", err)
- }
-
- d.Set("scheduled_action", rule.ScheduledAction)
- d.Set("launch_time", rule.LaunchTime)
- d.Set("scheduled_task_name", rule.ScheduledTaskName)
- d.Set("description", rule.Description)
- d.Set("launch_expiration_time", rule.LaunchExpirationTime)
- d.Set("recurrence_type", rule.RecurrenceType)
- d.Set("recurrence_value", rule.RecurrenceValue)
- d.Set("recurrence_end_time", rule.RecurrenceEndTime)
- d.Set("task_enabled", rule.TaskEnabled)
-
- return nil
-}
-
-func resourceAliyunEssScheduleUpdate(d *schema.ResourceData, meta interface{}) error {
-
- conn := meta.(*AliyunClient).essconn
-
- args := &ess.ModifyScheduledTaskArgs{
- ScheduledTaskId: d.Id(),
- }
-
- if d.HasChange("scheduled_task_name") {
- args.ScheduledTaskName = d.Get("scheduled_task_name").(string)
- }
-
- if d.HasChange("description") {
- args.Description = d.Get("description").(string)
- }
-
- if d.HasChange("scheduled_action") {
- args.ScheduledAction = d.Get("scheduled_action").(string)
- }
-
- if d.HasChange("launch_time") {
- args.LaunchTime = d.Get("launch_time").(string)
- }
-
- if d.HasChange("launch_expiration_time") {
- args.LaunchExpirationTime = d.Get("launch_expiration_time").(int)
- }
-
- if d.HasChange("recurrence_type") {
- args.RecurrenceType = ess.RecurrenceType(d.Get("recurrence_type").(string))
- }
-
- if d.HasChange("recurrence_value") {
- args.RecurrenceValue = d.Get("recurrence_value").(string)
- }
-
- if d.HasChange("recurrence_end_time") {
- args.RecurrenceEndTime = d.Get("recurrence_end_time").(string)
- }
-
- if d.HasChange("task_enabled") {
- args.TaskEnabled = d.Get("task_enabled").(bool)
- }
-
- if _, err := conn.ModifyScheduledTask(args); err != nil {
- return err
- }
-
- return resourceAliyunEssScheduleRead(d, meta)
-}
-
-func resourceAliyunEssScheduleDelete(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
-
- return resource.Retry(2*time.Minute, func() *resource.RetryError {
- err := client.DeleteScheduleById(d.Id())
-
- if err != nil {
- return resource.RetryableError(fmt.Errorf("Scaling schedule in use - trying again while it is deleted."))
- }
-
- _, err = client.DescribeScheduleById(d.Id())
- if err != nil {
- if notFoundError(err) {
- return nil
- }
- return resource.NonRetryableError(err)
- }
-
- return resource.RetryableError(fmt.Errorf("Scaling schedule in use - trying again while it is deleted."))
- })
-}
-
-func buildAlicloudEssScheduleArgs(d *schema.ResourceData, meta interface{}) (*ess.CreateScheduledTaskArgs, error) {
- args := &ess.CreateScheduledTaskArgs{
- RegionId: getRegion(d, meta),
- ScheduledAction: d.Get("scheduled_action").(string),
- LaunchTime: d.Get("launch_time").(string),
- TaskEnabled: d.Get("task_enabled").(bool),
- }
-
- if v := d.Get("scheduled_task_name").(string); v != "" {
- args.ScheduledTaskName = v
- }
-
- if v := d.Get("description").(string); v != "" {
- args.Description = v
- }
-
- if v := d.Get("recurrence_type").(string); v != "" {
- args.RecurrenceType = ess.RecurrenceType(v)
- }
-
- if v := d.Get("recurrence_value").(string); v != "" {
- args.RecurrenceValue = v
- }
-
- if v := d.Get("recurrence_end_time").(string); v != "" {
- args.RecurrenceEndTime = v
- }
-
- if v := d.Get("launch_expiration_time").(int); v != 0 {
- args.LaunchExpirationTime = v
- }
-
- return args, nil
-}
diff --git a/builtin/providers/alicloud/resource_alicloud_ess_schedule_test.go b/builtin/providers/alicloud/resource_alicloud_ess_schedule_test.go
deleted file mode 100644
index cb8044cc4..000000000
--- a/builtin/providers/alicloud/resource_alicloud_ess_schedule_test.go
+++ /dev/null
@@ -1,151 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ess"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
- "log"
- "testing"
-)
-
-func TestAccAlicloudEssSchedule_basic(t *testing.T) {
- var sc ess.ScheduledTaskItemType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_ess_schedule.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckEssScheduleDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccEssScheduleConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckEssScheduleExists(
- "alicloud_ess_schedule.foo", &sc),
- resource.TestCheckResourceAttr(
- "alicloud_ess_schedule.foo",
- "launch_time",
- "2017-04-29T07:30Z"),
- resource.TestCheckResourceAttr(
- "alicloud_ess_schedule.foo",
- "task_enabled",
- "true"),
- ),
- },
- },
- })
-}
-
-func testAccCheckEssScheduleExists(n string, d *ess.ScheduledTaskItemType) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No ESS Schedule ID is set")
- }
-
- client := testAccProvider.Meta().(*AliyunClient)
- attr, err := client.DescribeScheduleById(rs.Primary.ID)
- log.Printf("[DEBUG] check schedule %s attribute %#v", rs.Primary.ID, attr)
-
- if err != nil {
- return err
- }
-
- if attr == nil {
- return fmt.Errorf("Ess schedule not found")
- }
-
- *d = *attr
- return nil
- }
-}
-
-func testAccCheckEssScheduleDestroy(s *terraform.State) error {
- client := testAccProvider.Meta().(*AliyunClient)
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "alicloud_ess_schedule" {
- continue
- }
- ins, err := client.DescribeScheduleById(rs.Primary.ID)
-
- if ins != nil {
- return fmt.Errorf("Error ESS schedule still exist")
- }
-
- // Verify the error is what we want
- if err != nil {
- // Verify the error is what we want
- e, _ := err.(*common.Error)
- if e.ErrorResponse.Code == InstanceNotfound {
- continue
- }
- return err
- }
- }
-
- return nil
-}
-
-const testAccEssScheduleConfig = `
-data "alicloud_images" "ecs_image" {
- most_recent = true
- name_regex = "^centos_6\\w{1,5}[64].*"
-}
-
-resource "alicloud_security_group" "tf_test_foo" {
- name = "tf_test_foo"
- description = "foo"
-}
-
-resource "alicloud_security_group_rule" "ssh-in" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "internet"
- policy = "accept"
- port_range = "22/22"
- priority = 1
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
- cidr_ip = "0.0.0.0/0"
-}
-
-resource "alicloud_ess_scaling_group" "bar" {
- min_size = 1
- max_size = 1
- scaling_group_name = "bar"
- removal_policies = ["OldestInstance", "NewestInstance"]
-}
-
-resource "alicloud_ess_scaling_configuration" "foo" {
- scaling_group_id = "${alicloud_ess_scaling_group.bar.id}"
-
- image_id = "${data.alicloud_images.ecs_image.images.0.id}"
- instance_type = "ecs.s2.large"
- io_optimized = "optimized"
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
-}
-
-resource "alicloud_ess_scaling_rule" "foo" {
- scaling_group_id = "${alicloud_ess_scaling_group.bar.id}"
- adjustment_type = "TotalCapacity"
- adjustment_value = 2
- cooldown = 60
-}
-
-resource "alicloud_ess_schedule" "foo" {
- scheduled_action = "${alicloud_ess_scaling_rule.foo.ari}"
- launch_time = "2017-04-29T07:30Z"
- scheduled_task_name = "tf-foo"
-}
-`
diff --git a/builtin/providers/alicloud/resource_alicloud_forward.go b/builtin/providers/alicloud/resource_alicloud_forward.go
deleted file mode 100644
index 8f75c54d0..000000000
--- a/builtin/providers/alicloud/resource_alicloud_forward.go
+++ /dev/null
@@ -1,165 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func resourceAliyunForwardEntry() *schema.Resource {
- return &schema.Resource{
- Create: resourceAliyunForwardEntryCreate,
- Read: resourceAliyunForwardEntryRead,
- Update: resourceAliyunForwardEntryUpdate,
- Delete: resourceAliyunForwardEntryDelete,
-
- Schema: map[string]*schema.Schema{
- "forward_table_id": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
- "external_ip": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
- "external_port": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ValidateFunc: validateForwardPort,
- },
- "ip_protocol": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ValidateFunc: validateAllowedStringValue([]string{"tcp", "udp", "any"}),
- },
- "internal_ip": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
- "internal_port": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ValidateFunc: validateForwardPort,
- },
- },
- }
-}
-
-func resourceAliyunForwardEntryCreate(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).vpcconn
-
- args := &ecs.CreateForwardEntryArgs{
- RegionId: getRegion(d, meta),
- ForwardTableId: d.Get("forward_table_id").(string),
- ExternalIp: d.Get("external_ip").(string),
- ExternalPort: d.Get("external_port").(string),
- IpProtocol: d.Get("ip_protocol").(string),
- InternalIp: d.Get("internal_ip").(string),
- InternalPort: d.Get("internal_port").(string),
- }
-
- resp, err := conn.CreateForwardEntry(args)
- if err != nil {
- return fmt.Errorf("CreateForwardEntry got error: %#v", err)
- }
-
- d.SetId(resp.ForwardEntryId)
- d.Set("forward_table_id", d.Get("forward_table_id").(string))
-
- return resourceAliyunForwardEntryRead(d, meta)
-}
-
-func resourceAliyunForwardEntryRead(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
-
- forwardEntry, err := client.DescribeForwardEntry(d.Get("forward_table_id").(string), d.Id())
-
- if err != nil {
- if notFoundError(err) {
- return nil
- }
- return err
- }
-
- d.Set("forward_table_id", forwardEntry.ForwardTableId)
- d.Set("external_ip", forwardEntry.ExternalIp)
- d.Set("external_port", forwardEntry.ExternalPort)
- d.Set("ip_protocol", forwardEntry.IpProtocol)
- d.Set("internal_ip", forwardEntry.InternalIp)
- d.Set("internal_port", forwardEntry.InternalPort)
-
- return nil
-}
-
-func resourceAliyunForwardEntryUpdate(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
- conn := client.vpcconn
-
- forwardEntry, err := client.DescribeForwardEntry(d.Get("forward_table_id").(string), d.Id())
- if err != nil {
- return err
- }
-
- d.Partial(true)
- attributeUpdate := false
- args := &ecs.ModifyForwardEntryArgs{
- RegionId: getRegion(d, meta),
- ForwardTableId: forwardEntry.ForwardTableId,
- ForwardEntryId: forwardEntry.ForwardEntryId,
- ExternalIp: forwardEntry.ExternalIp,
- IpProtocol: forwardEntry.IpProtocol,
- ExternalPort: forwardEntry.ExternalPort,
- InternalIp: forwardEntry.InternalIp,
- InternalPort: forwardEntry.InternalPort,
- }
-
- if d.HasChange("external_port") {
- d.SetPartial("external_port")
- args.ExternalPort = d.Get("external_port").(string)
- attributeUpdate = true
- }
-
- if d.HasChange("ip_protocol") {
- d.SetPartial("ip_protocol")
- args.IpProtocol = d.Get("ip_protocol").(string)
- attributeUpdate = true
- }
-
- if d.HasChange("internal_port") {
- d.SetPartial("internal_port")
- args.InternalPort = d.Get("internal_port").(string)
- attributeUpdate = true
- }
-
- if attributeUpdate {
- if err := conn.ModifyForwardEntry(args); err != nil {
- return err
- }
- }
-
- d.Partial(false)
-
- return resourceAliyunForwardEntryRead(d, meta)
-}
-
-func resourceAliyunForwardEntryDelete(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
- conn := client.vpcconn
-
- forwardEntryId := d.Id()
- forwardTableId := d.Get("forward_table_id").(string)
-
- args := &ecs.DeleteForwardEntryArgs{
- RegionId: getRegion(d, meta),
- ForwardTableId: forwardTableId,
- ForwardEntryId: forwardEntryId,
- }
-
- if err := conn.DeleteForwardEntry(args); err != nil {
- return err
- }
-
- return nil
-}
diff --git a/builtin/providers/alicloud/resource_alicloud_forward_test.go b/builtin/providers/alicloud/resource_alicloud_forward_test.go
deleted file mode 100644
index 60a67f322..000000000
--- a/builtin/providers/alicloud/resource_alicloud_forward_test.go
+++ /dev/null
@@ -1,216 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
- "testing"
-)
-
-func TestAccAlicloudForward_basic(t *testing.T) {
- var forward ecs.ForwardTableEntrySetType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_forward_entry.foo",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckForwardEntryDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccForwardEntryConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckForwardEntryExists(
- "alicloud_forward_entry.foo", &forward),
- ),
- },
-
- resource.TestStep{
- Config: testAccForwardEntryUpdate,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckForwardEntryExists(
- "alicloud_forward_entry.foo", &forward),
- ),
- },
- },
- })
-
-}
-
-func testAccCheckForwardEntryDestroy(s *terraform.State) error {
- client := testAccProvider.Meta().(*AliyunClient)
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "alicloud_snat_entry" {
- continue
- }
-
- // Try to find the Snat entry
- instance, err := client.DescribeForwardEntry(rs.Primary.Attributes["forward_table_id"], rs.Primary.ID)
-
- //this special deal cause the DescribeSnatEntry can't find the records would be throw "cant find the snatTable error"
- if instance.ForwardEntryId == "" {
- return nil
- }
-
- if instance.ForwardEntryId != "" {
- return fmt.Errorf("Forward entry still exist")
- }
-
- if err != nil {
- // Verify the error is what we want
- e, _ := err.(*common.Error)
-
- if !notFoundError(e) {
- return err
- }
- }
-
- }
-
- return nil
-}
-
-func testAccCheckForwardEntryExists(n string, snat *ecs.ForwardTableEntrySetType) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No ForwardEntry ID is set")
- }
-
- client := testAccProvider.Meta().(*AliyunClient)
- instance, err := client.DescribeForwardEntry(rs.Primary.Attributes["forward_table_id"], rs.Primary.ID)
-
- if err != nil {
- return err
- }
- if instance.ForwardEntryId == "" {
- return fmt.Errorf("ForwardEntry not found")
- }
-
- *snat = instance
- return nil
- }
-}
-
-const testAccForwardEntryConfig = `
-provider "alicloud"{
- region = "cn-hangzhou"
-}
-
-data "alicloud_zones" "default" {
- "available_resource_creation"= "VSwitch"
-}
-
-resource "alicloud_vpc" "foo" {
- name = "tf_test_foo"
- cidr_block = "172.16.0.0/12"
-}
-
-resource "alicloud_vswitch" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- cidr_block = "172.16.0.0/21"
- availability_zone = "${data.alicloud_zones.default.zones.0.id}"
-}
-
-resource "alicloud_nat_gateway" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- spec = "Small"
- name = "test_foo"
- bandwidth_packages = [{
- ip_count = 1
- bandwidth = 5
- zone = "${data.alicloud_zones.default.zones.0.id}"
- },{
- ip_count = 1
- bandwidth = 6
- zone = "${data.alicloud_zones.default.zones.0.id}"
- }]
- depends_on = [
- "alicloud_vswitch.foo"]
-}
-
-resource "alicloud_forward_entry" "foo"{
- forward_table_id = "${alicloud_nat_gateway.foo.forward_table_ids}"
- external_ip = "${alicloud_nat_gateway.foo.bandwidth_packages.0.public_ip_addresses}"
- external_port = "80"
- ip_protocol = "tcp"
- internal_ip = "172.16.0.3"
- internal_port = "8080"
-}
-
-resource "alicloud_forward_entry" "foo1"{
- forward_table_id = "${alicloud_nat_gateway.foo.forward_table_ids}"
- external_ip = "${alicloud_nat_gateway.foo.bandwidth_packages.0.public_ip_addresses}"
- external_port = "443"
- ip_protocol = "udp"
- internal_ip = "172.16.0.4"
- internal_port = "8080"
-}
-`
-
-const testAccForwardEntryUpdate = `
-provider "alicloud"{
- region = "cn-hangzhou"
-}
-
-data "alicloud_zones" "default" {
- "available_resource_creation"= "VSwitch"
-}
-
-resource "alicloud_vpc" "foo" {
- name = "tf_test_foo"
- cidr_block = "172.16.0.0/12"
-}
-
-resource "alicloud_vswitch" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- cidr_block = "172.16.0.0/21"
- availability_zone = "${data.alicloud_zones.default.zones.0.id}"
-}
-
-resource "alicloud_nat_gateway" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- spec = "Small"
- name = "test_foo"
- bandwidth_packages = [{
- ip_count = 1
- bandwidth = 5
- zone = "${data.alicloud_zones.default.zones.0.id}"
- },{
- ip_count = 1
- bandwidth = 6
- zone = "${data.alicloud_zones.default.zones.0.id}"
- }]
- depends_on = [
- "alicloud_vswitch.foo"]
-}
-
-resource "alicloud_forward_entry" "foo"{
- forward_table_id = "${alicloud_nat_gateway.foo.forward_table_ids}"
- external_ip = "${alicloud_nat_gateway.foo.bandwidth_packages.0.public_ip_addresses}"
- external_port = "80"
- ip_protocol = "tcp"
- internal_ip = "172.16.0.3"
- internal_port = "8081"
-}
-
-
-resource "alicloud_forward_entry" "foo1"{
- forward_table_id = "${alicloud_nat_gateway.foo.forward_table_ids}"
- external_ip = "${alicloud_nat_gateway.foo.bandwidth_packages.0.public_ip_addresses}"
- external_port = "22"
- ip_protocol = "udp"
- internal_ip = "172.16.0.4"
- internal_port = "8080"
-}
-`
diff --git a/builtin/providers/alicloud/resource_alicloud_instance.go b/builtin/providers/alicloud/resource_alicloud_instance.go
deleted file mode 100644
index f6884ea83..000000000
--- a/builtin/providers/alicloud/resource_alicloud_instance.go
+++ /dev/null
@@ -1,700 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "log"
-
- "encoding/base64"
- "encoding/json"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
- "strings"
- "time"
-)
-
-func resourceAliyunInstance() *schema.Resource {
- return &schema.Resource{
- Create: resourceAliyunInstanceCreate,
- Read: resourceAliyunInstanceRead,
- Update: resourceAliyunInstanceUpdate,
- Delete: resourceAliyunInstanceDelete,
-
- Schema: map[string]*schema.Schema{
- "availability_zone": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- Computed: true,
- },
-
- "image_id": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
-
- "instance_type": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
-
- "security_groups": &schema.Schema{
- Type: schema.TypeSet,
- Elem: &schema.Schema{Type: schema.TypeString},
- Required: true,
- },
-
- "allocate_public_ip": &schema.Schema{
- Type: schema.TypeBool,
- Optional: true,
- Default: false,
- },
-
- "instance_name": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Default: "ECS-Instance",
- ValidateFunc: validateInstanceName,
- },
-
- "description": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ValidateFunc: validateInstanceDescription,
- },
-
- "internet_charge_type": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- ValidateFunc: validateInternetChargeType,
- },
- "internet_max_bandwidth_in": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
- "internet_max_bandwidth_out": &schema.Schema{
- Type: schema.TypeInt,
- Optional: true,
- ForceNew: true,
- ValidateFunc: validateInternetMaxBandWidthOut,
- },
- "host_name": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "password": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Sensitive: true,
- },
- "io_optimized": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- ValidateFunc: validateIoOptimized,
- },
-
- "system_disk_category": &schema.Schema{
- Type: schema.TypeString,
- Default: "cloud",
- Optional: true,
- ForceNew: true,
- ValidateFunc: validateAllowedStringValue([]string{
- string(ecs.DiskCategoryCloud),
- string(ecs.DiskCategoryCloudSSD),
- string(ecs.DiskCategoryCloudEfficiency),
- string(ecs.DiskCategoryEphemeralSSD),
- }),
- },
- "system_disk_size": &schema.Schema{
- Type: schema.TypeInt,
- Optional: true,
- Computed: true,
- ValidateFunc: validateIntegerInRange(40, 500),
- },
-
- //subnet_id and vswitch_id both exists, cause compatible old version, and aws habit.
- "subnet_id": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- Computed: true, //add this schema cause subnet_id not used enter parameter, will different, so will be ForceNew
- },
-
- "vswitch_id": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
-
- "instance_charge_type": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- ValidateFunc: validateInstanceChargeType,
- },
- "period": &schema.Schema{
- Type: schema.TypeInt,
- Optional: true,
- ForceNew: true,
- },
-
- "public_ip": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
-
- "private_ip": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
-
- "status": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
-
- "user_data": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
-
- "tags": tagsSchema(),
- },
- }
-}
-
-func resourceAliyunInstanceCreate(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).ecsconn
-
- // create postpaid instance by runInstances API
- if v := d.Get("instance_charge_type").(string); v != string(common.PrePaid) {
- return resourceAliyunRunInstance(d, meta)
- }
-
- args, err := buildAliyunInstanceArgs(d, meta)
- if err != nil {
- return err
- }
-
- instanceID, err := conn.CreateInstance(args)
- if err != nil {
- return fmt.Errorf("Error creating Aliyun ecs instance: %#v", err)
- }
-
- d.SetId(instanceID)
-
- d.Set("password", d.Get("password"))
-
- // after instance created, its status is pending,
- // so we need to wait it become to stopped and then start it
- if err := conn.WaitForInstanceAsyn(d.Id(), ecs.Stopped, defaultTimeout); err != nil {
- return fmt.Errorf("[DEBUG] WaitForInstance %s got error: %#v", ecs.Stopped, err)
- }
-
- if err := allocateIpAndBandWidthRelative(d, meta); err != nil {
- return fmt.Errorf("allocateIpAndBandWidthRelative err: %#v", err)
- }
-
- if err := conn.StartInstance(d.Id()); err != nil {
- return fmt.Errorf("Start instance got error: %#v", err)
- }
-
- if err := conn.WaitForInstanceAsyn(d.Id(), ecs.Running, defaultTimeout); err != nil {
- return fmt.Errorf("[DEBUG] WaitForInstance %s got error: %#v", ecs.Running, err)
- }
-
- return resourceAliyunInstanceUpdate(d, meta)
-}
-
-func resourceAliyunRunInstance(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).ecsconn
- newConn := meta.(*AliyunClient).ecsNewconn
-
- args, err := buildAliyunInstanceArgs(d, meta)
- if err != nil {
- return err
- }
-
- if args.IoOptimized == "optimized" {
- args.IoOptimized = ecs.IoOptimized("true")
- } else {
- args.IoOptimized = ecs.IoOptimized("false")
- }
-
- runArgs, err := buildAliyunRunInstancesArgs(d, meta)
- if err != nil {
- return err
- }
-
- runArgs.CreateInstanceArgs = *args
-
- // runInstances is support in version 2016-03-14
- instanceIds, err := newConn.RunInstances(runArgs)
-
- if err != nil {
- return fmt.Errorf("Error creating Aliyun ecs instance: %#v", err)
- }
-
- d.SetId(instanceIds[0])
-
- d.Set("password", d.Get("password"))
- d.Set("system_disk_category", d.Get("system_disk_category"))
- d.Set("system_disk_size", d.Get("system_disk_size"))
-
- // after instance created, its status change from pending, starting to running
- if err := conn.WaitForInstanceAsyn(d.Id(), ecs.Running, defaultTimeout); err != nil {
- return fmt.Errorf("[DEBUG] WaitForInstance %s got error: %#v", ecs.Running, err)
- }
-
- if err := allocateIpAndBandWidthRelative(d, meta); err != nil {
- return fmt.Errorf("allocateIpAndBandWidthRelative err: %#v", err)
- }
-
- if err := conn.WaitForInstanceAsyn(d.Id(), ecs.Running, defaultTimeout); err != nil {
- return fmt.Errorf("[DEBUG] WaitForInstance %s got error: %#v", ecs.Running, err)
- }
-
- return resourceAliyunInstanceUpdate(d, meta)
-}
-
-func resourceAliyunInstanceRead(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
- conn := client.ecsconn
-
- instance, err := client.QueryInstancesById(d.Id())
-
- if err != nil {
- if notFoundError(err) {
- d.SetId("")
- return nil
- }
- return fmt.Errorf("Error DescribeInstanceAttribute: %#v", err)
- }
-
- disk, diskErr := client.QueryInstanceSystemDisk(d.Id())
-
- if diskErr != nil {
- if notFoundError(diskErr) {
- d.SetId("")
- return nil
- }
- return fmt.Errorf("Error DescribeSystemDisk: %#v", err)
- }
-
- d.Set("instance_name", instance.InstanceName)
- d.Set("description", instance.Description)
- d.Set("status", instance.Status)
- d.Set("availability_zone", instance.ZoneId)
- d.Set("host_name", instance.HostName)
- d.Set("image_id", instance.ImageId)
- d.Set("instance_type", instance.InstanceType)
- d.Set("system_disk_category", disk.Category)
- d.Set("system_disk_size", disk.Size)
-
- // In Classic network, internet_charge_type is valid in any case, and its default value is 'PayByBanwidth'.
- // In VPC network, internet_charge_type is valid when instance has public ip, and its default value is 'PayByBanwidth'.
- d.Set("internet_charge_type", instance.InternetChargeType)
-
- if d.Get("allocate_public_ip").(bool) {
- d.Set("public_ip", instance.PublicIpAddress.IpAddress[0])
- }
-
- if ecs.StringOrBool(instance.IoOptimized).Value {
- d.Set("io_optimized", "optimized")
- } else {
- d.Set("io_optimized", "none")
- }
-
- if d.Get("subnet_id").(string) != "" || d.Get("vswitch_id").(string) != "" {
- ipAddress := instance.VpcAttributes.PrivateIpAddress.IpAddress[0]
- d.Set("private_ip", ipAddress)
- d.Set("subnet_id", instance.VpcAttributes.VSwitchId)
- d.Set("vswitch_id", instance.VpcAttributes.VSwitchId)
- } else {
- ipAddress := strings.Join(ecs.IpAddressSetType(instance.InnerIpAddress).IpAddress, ",")
- d.Set("private_ip", ipAddress)
- }
-
- if d.Get("user_data").(string) != "" {
- ud, err := conn.DescribeUserdata(&ecs.DescribeUserdataArgs{
- RegionId: getRegion(d, meta),
- InstanceId: d.Id(),
- })
-
- if err != nil {
- log.Printf("[ERROR] DescribeUserData for instance got error: %#v", err)
- }
- d.Set("user_data", userDataHashSum(ud.UserData))
- }
-
- tags, _, err := conn.DescribeTags(&ecs.DescribeTagsArgs{
- RegionId: getRegion(d, meta),
- ResourceType: ecs.TagResourceInstance,
- ResourceId: d.Id(),
- })
-
- if err != nil {
- log.Printf("[ERROR] DescribeTags for instance got error: %#v", err)
- }
- d.Set("tags", tagsToMap(tags))
-
- return nil
-}
-
-func resourceAliyunInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
-
- client := meta.(*AliyunClient)
- conn := client.ecsconn
-
- d.Partial(true)
-
- if err := setTags(client, ecs.TagResourceInstance, d); err != nil {
- log.Printf("[DEBUG] Set tags for instance got error: %#v", err)
- return fmt.Errorf("Set tags for instance got error: %#v", err)
- } else {
- d.SetPartial("tags")
- }
-
- imageUpdate := false
- if d.HasChange("image_id") && !d.IsNewResource() {
- log.Printf("[DEBUG] Replace instance system disk via changing image_id")
- replaceSystemArgs := &ecs.ReplaceSystemDiskArgs{
- InstanceId: d.Id(),
- ImageId: d.Get("image_id").(string),
- SystemDisk: ecs.SystemDiskType{
- Size: d.Get("system_disk_size").(int),
- },
- }
- if v, ok := d.GetOk("status"); ok && v.(string) != "" {
- if ecs.InstanceStatus(d.Get("status").(string)) == ecs.Running {
- log.Printf("[DEBUG] StopInstance before change system disk")
- if err := conn.StopInstance(d.Id(), true); err != nil {
- return fmt.Errorf("Force Stop Instance got an error: %#v", err)
- }
- if err := conn.WaitForInstance(d.Id(), ecs.Stopped, 60); err != nil {
- return fmt.Errorf("WaitForInstance got error: %#v", err)
- }
- }
- }
- _, err := conn.ReplaceSystemDisk(replaceSystemArgs)
- if err != nil {
- return fmt.Errorf("Replace system disk got an error: %#v", err)
- }
- // Ensure instance's image has been replaced successfully.
- timeout := ecs.InstanceDefaultTimeout
- for {
- instance, errDesc := conn.DescribeInstanceAttribute(d.Id())
- if errDesc != nil {
- return fmt.Errorf("Describe instance got an error: %#v", errDesc)
- }
- if instance.ImageId == d.Get("image_id") {
- break
- }
- time.Sleep(ecs.DefaultWaitForInterval * time.Second)
- timeout = timeout - ecs.DefaultWaitForInterval
- if timeout <= 0 {
- return common.GetClientErrorFromString("Timeout")
- }
- }
- imageUpdate = true
- d.SetPartial("system_disk_size")
- d.SetPartial("image_id")
- }
- // Provider doesn't support change 'system_disk_size'separately.
- if d.HasChange("system_disk_size") && !d.HasChange("image_id") {
- return fmt.Errorf("Update resource failed. 'system_disk_size' isn't allowed to change separately. You can update it via renewing instance or replacing system disk.")
- }
-
- attributeUpdate := false
- args := &ecs.ModifyInstanceAttributeArgs{
- InstanceId: d.Id(),
- }
-
- if d.HasChange("instance_name") && !d.IsNewResource() {
- log.Printf("[DEBUG] ModifyInstanceAttribute instance_name")
- d.SetPartial("instance_name")
- args.InstanceName = d.Get("instance_name").(string)
-
- attributeUpdate = true
- }
-
- if d.HasChange("description") && !d.IsNewResource() {
- log.Printf("[DEBUG] ModifyInstanceAttribute description")
- d.SetPartial("description")
- args.Description = d.Get("description").(string)
-
- attributeUpdate = true
- }
-
- if d.HasChange("host_name") && !d.IsNewResource() {
- log.Printf("[DEBUG] ModifyInstanceAttribute host_name")
- d.SetPartial("host_name")
- args.HostName = d.Get("host_name").(string)
-
- attributeUpdate = true
- }
-
- passwordUpdate := false
- if d.HasChange("password") && !d.IsNewResource() {
- log.Printf("[DEBUG] ModifyInstanceAttribute password")
- d.SetPartial("password")
- args.Password = d.Get("password").(string)
-
- attributeUpdate = true
- passwordUpdate = true
- }
-
- if attributeUpdate {
- if err := conn.ModifyInstanceAttribute(args); err != nil {
- return fmt.Errorf("Modify instance attribute got error: %#v", err)
- }
- }
-
- if imageUpdate || passwordUpdate {
- instance, errDesc := conn.DescribeInstanceAttribute(d.Id())
- if errDesc != nil {
- return fmt.Errorf("Describe instance got an error: %#v", errDesc)
- }
- if instance.Status != ecs.Running && instance.Status != ecs.Stopped {
- return fmt.Errorf("ECS instance's status doesn't support to start or reboot operation after replace image_id or update password. The current instance's status is %#v", instance.Status)
- } else if instance.Status == ecs.Running {
- log.Printf("[DEBUG] Reboot instance after change image or password")
- if err := conn.RebootInstance(d.Id(), false); err != nil {
- return fmt.Errorf("RebootInstance got error: %#v", err)
- }
- } else {
- log.Printf("[DEBUG] Start instance after change image or password")
- if err := conn.StartInstance(d.Id()); err != nil {
- return fmt.Errorf("StartInstance got error: %#v", err)
- }
- }
- // Start instance sometimes costs more than 6 minutes when os type is centos.
- if err := conn.WaitForInstance(d.Id(), ecs.Running, 400); err != nil {
- return fmt.Errorf("WaitForInstance got error: %#v", err)
- }
- }
-
- if d.HasChange("security_groups") {
- o, n := d.GetChange("security_groups")
- os := o.(*schema.Set)
- ns := n.(*schema.Set)
-
- rl := expandStringList(os.Difference(ns).List())
- al := expandStringList(ns.Difference(os).List())
-
- if len(al) > 0 {
- err := client.JoinSecurityGroups(d.Id(), al)
- if err != nil {
- return err
- }
- }
- if len(rl) > 0 {
- err := client.LeaveSecurityGroups(d.Id(), rl)
- if err != nil {
- return err
- }
- }
-
- d.SetPartial("security_groups")
- }
-
- d.Partial(false)
- return resourceAliyunInstanceRead(d, meta)
-}
-
-func resourceAliyunInstanceDelete(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
- conn := client.ecsconn
-
- return resource.Retry(5*time.Minute, func() *resource.RetryError {
- instance, err := client.QueryInstancesById(d.Id())
- if err != nil {
- if notFoundError(err) {
- return nil
- }
- }
-
- if instance.Status != ecs.Stopped {
- if err := conn.StopInstance(d.Id(), true); err != nil {
- return resource.RetryableError(fmt.Errorf("ECS stop error - trying again."))
- }
-
- if err := conn.WaitForInstance(d.Id(), ecs.Stopped, defaultTimeout); err != nil {
- return resource.RetryableError(fmt.Errorf("Waiting for ecs stopped timeout - trying again."))
- }
- }
-
- if err := conn.DeleteInstance(d.Id()); err != nil {
- return resource.RetryableError(fmt.Errorf("ECS Instance in use - trying again while it is deleted."))
- }
-
- return nil
- })
-
-}
-
-func allocateIpAndBandWidthRelative(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).ecsconn
- if d.Get("allocate_public_ip").(bool) {
- if d.Get("internet_max_bandwidth_out") == 0 {
- return fmt.Errorf("Error: if allocate_public_ip is true than the internet_max_bandwidth_out cannot equal zero.")
- }
- _, err := conn.AllocatePublicIpAddress(d.Id())
- if err != nil {
- return fmt.Errorf("[DEBUG] AllocatePublicIpAddress for instance got error: %#v", err)
- }
- }
- return nil
-}
-
-func buildAliyunRunInstancesArgs(d *schema.ResourceData, meta interface{}) (*ecs.RunInstanceArgs, error) {
- args := &ecs.RunInstanceArgs{
- MaxAmount: DEFAULT_INSTANCE_COUNT,
- MinAmount: DEFAULT_INSTANCE_COUNT,
- }
-
- bussStr, err := json.Marshal(DefaultBusinessInfo)
- if err != nil {
- log.Printf("Failed to translate bussiness info %#v from json to string", DefaultBusinessInfo)
- }
-
- args.BusinessInfo = string(bussStr)
-
- subnetValue := d.Get("subnet_id").(string)
- vswitchValue := d.Get("vswitch_id").(string)
- //networkValue := d.Get("instance_network_type").(string)
-
- // because runInstance is not compatible with createInstance, force NetworkType value to classic
- if subnetValue == "" && vswitchValue == "" {
- args.NetworkType = string(ClassicNet)
- }
-
- return args, nil
-}
-
-func buildAliyunInstanceArgs(d *schema.ResourceData, meta interface{}) (*ecs.CreateInstanceArgs, error) {
- client := meta.(*AliyunClient)
-
- args := &ecs.CreateInstanceArgs{
- RegionId: getRegion(d, meta),
- InstanceType: d.Get("instance_type").(string),
- }
-
- imageID := d.Get("image_id").(string)
-
- args.ImageId = imageID
-
- systemDiskCategory := ecs.DiskCategory(d.Get("system_disk_category").(string))
- systemDiskSize := d.Get("system_disk_size").(int)
-
- zoneID := d.Get("availability_zone").(string)
- // check instanceType and systemDiskCategory, when zoneID is not empty
- if zoneID != "" {
- zone, err := client.DescribeZone(zoneID)
- if err != nil {
- return nil, err
- }
-
- if err := client.ResourceAvailable(zone, ecs.ResourceTypeInstance); err != nil {
- return nil, err
- }
-
- if err := client.DiskAvailable(zone, systemDiskCategory); err != nil {
- return nil, err
- }
-
- args.ZoneId = zoneID
-
- }
-
- args.SystemDisk = ecs.SystemDiskType{
- Category: systemDiskCategory,
- Size: systemDiskSize,
- }
-
- sgs, ok := d.GetOk("security_groups")
-
- if ok {
- sgList := expandStringList(sgs.(*schema.Set).List())
- sg0 := sgList[0]
- // check security group instance exist
- _, err := client.DescribeSecurity(sg0)
- if err == nil {
- args.SecurityGroupId = sg0
- }
- }
-
- if v := d.Get("instance_name").(string); v != "" {
- args.InstanceName = v
- }
-
- if v := d.Get("description").(string); v != "" {
- args.Description = v
- }
-
- if v := d.Get("internet_charge_type").(string); v != "" {
- args.InternetChargeType = common.InternetChargeType(v)
- }
-
- if v := d.Get("internet_max_bandwidth_out").(int); v != 0 {
- args.InternetMaxBandwidthOut = v
- }
-
- if v := d.Get("host_name").(string); v != "" {
- args.HostName = v
- }
-
- if v := d.Get("password").(string); v != "" {
- args.Password = v
- }
-
- if v := d.Get("io_optimized").(string); v != "" {
- args.IoOptimized = ecs.IoOptimized(v)
- }
-
- vswitchValue := d.Get("subnet_id").(string)
- if vswitchValue == "" {
- vswitchValue = d.Get("vswitch_id").(string)
- }
- if vswitchValue != "" {
- args.VSwitchId = vswitchValue
- if d.Get("allocate_public_ip").(bool) && args.InternetMaxBandwidthOut <= 0 {
- return nil, fmt.Errorf("Invalid internet_max_bandwidth_out result in allocation public ip failed in the VPC.")
- }
- }
-
- if v := d.Get("instance_charge_type").(string); v != "" {
- args.InstanceChargeType = common.InstanceChargeType(v)
- }
-
- log.Printf("[DEBUG] period is %d", d.Get("period").(int))
- if v := d.Get("period").(int); v != 0 {
- args.Period = v
- } else if args.InstanceChargeType == common.PrePaid {
- return nil, fmt.Errorf("period is required for instance_charge_type is PrePaid")
- }
-
- if v := d.Get("user_data").(string); v != "" {
- args.UserData = v
- }
-
- return args, nil
-}
-
-func userDataHashSum(user_data string) string {
- // Check whether the user_data is not Base64 encoded.
- // Always calculate hash of base64 decoded value since we
- // check against double-encoding when setting it
- v, base64DecodeError := base64.StdEncoding.DecodeString(user_data)
- if base64DecodeError != nil {
- v = []byte(user_data)
- }
- return string(v)
-}
diff --git a/builtin/providers/alicloud/resource_alicloud_instance_test.go b/builtin/providers/alicloud/resource_alicloud_instance_test.go
deleted file mode 100644
index 18bb33b9c..000000000
--- a/builtin/providers/alicloud/resource_alicloud_instance_test.go
+++ /dev/null
@@ -1,1333 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "testing"
-
- "log"
-
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAlicloudInstance_basic(t *testing.T) {
- var instance ecs.InstanceAttributesType
-
- testCheck := func(*terraform.State) error {
- log.Printf("[WARN] instances: %#v", instance)
- if instance.ZoneId == "" {
- return fmt.Errorf("bad availability zone")
- }
- if len(instance.SecurityGroupIds.SecurityGroupId) == 0 {
- return fmt.Errorf("no security group: %#v", instance.SecurityGroupIds.SecurityGroupId)
- }
-
- return nil
- }
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_instance.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccInstanceConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckInstanceExists(
- "alicloud_instance.foo", &instance),
- testCheck,
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "image_id",
- "ubuntu_140405_32_40G_cloudinit_20161115.vhd"),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "instance_name",
- "test_foo"),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "internet_charge_type",
- "PayByBandwidth"),
- testAccCheckSystemDiskSize("alicloud_instance.foo", 80),
- ),
- },
-
- // test for multi steps
- resource.TestStep{
- Config: testAccInstanceConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckInstanceExists(
- "alicloud_instance.foo", &instance),
- testCheck,
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "image_id",
- "ubuntu_140405_32_40G_cloudinit_20161115.vhd"),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "instance_name",
- "test_foo"),
- ),
- },
- },
- })
-
-}
-
-func TestAccAlicloudInstance_vpc(t *testing.T) {
- var instance ecs.InstanceAttributesType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
- IDRefreshName: "alicloud_instance.foo",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccInstanceConfigVPC,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckInstanceExists(
- "alicloud_instance.foo", &instance),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "system_disk_category",
- "cloud_efficiency"),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "internet_charge_type",
- "PayByTraffic"),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudInstance_userData(t *testing.T) {
- var instance ecs.InstanceAttributesType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
- IDRefreshName: "alicloud_instance.foo",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccInstanceConfigUserData,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckInstanceExists(
- "alicloud_instance.foo", &instance),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "system_disk_category",
- "cloud_efficiency"),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "internet_charge_type",
- "PayByTraffic"),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "user_data",
- "echo 'net.ipv4.ip_forward=1'>> /etc/sysctl.conf"),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudInstance_multipleRegions(t *testing.T) {
- var instance ecs.InstanceAttributesType
-
- // multi provideris
- var providers []*schema.Provider
- providerFactories := map[string]terraform.ResourceProviderFactory{
- "alicloud": func() (terraform.ResourceProvider, error) {
- p := Provider()
- providers = append(providers, p.(*schema.Provider))
- return p, nil
- },
- }
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
- ProviderFactories: providerFactories,
- CheckDestroy: testAccCheckInstanceDestroyWithProviders(&providers),
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccInstanceConfigMultipleRegions,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckInstanceExistsWithProviders(
- "alicloud_instance.foo", &instance, &providers),
- testAccCheckInstanceExistsWithProviders(
- "alicloud_instance.bar", &instance, &providers),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudInstance_multiSecurityGroup(t *testing.T) {
- var instance ecs.InstanceAttributesType
-
- testCheck := func(sgCount int) resource.TestCheckFunc {
- return func(*terraform.State) error {
- if len(instance.SecurityGroupIds.SecurityGroupId) < 0 {
- return fmt.Errorf("no security group: %#v", instance.SecurityGroupIds.SecurityGroupId)
- }
-
- if len(instance.SecurityGroupIds.SecurityGroupId) < sgCount {
- return fmt.Errorf("less security group: %#v", instance.SecurityGroupIds.SecurityGroupId)
- }
-
- return nil
- }
- }
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_instance.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccInstanceConfig_multiSecurityGroup,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckInstanceExists(
- "alicloud_instance.foo", &instance),
- testCheck(2),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "image_id",
- "ubuntu_140405_32_40G_cloudinit_20161115.vhd"),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "instance_name",
- "test_foo"),
- ),
- },
- resource.TestStep{
- Config: testAccInstanceConfig_multiSecurityGroup_add,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckInstanceExists(
- "alicloud_instance.foo", &instance),
- testCheck(3),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "image_id",
- "ubuntu_140405_32_40G_cloudinit_20161115.vhd"),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "instance_name",
- "test_foo"),
- ),
- },
- resource.TestStep{
- Config: testAccInstanceConfig_multiSecurityGroup_remove,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckInstanceExists(
- "alicloud_instance.foo", &instance),
- testCheck(1),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "image_id",
- "ubuntu_140405_32_40G_cloudinit_20161115.vhd"),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "instance_name",
- "test_foo"),
- ),
- },
- },
- })
-
-}
-
-func TestAccAlicloudInstance_multiSecurityGroupByCount(t *testing.T) {
- var instance ecs.InstanceAttributesType
-
- testCheck := func(sgCount int) resource.TestCheckFunc {
- return func(*terraform.State) error {
- if len(instance.SecurityGroupIds.SecurityGroupId) < 0 {
- return fmt.Errorf("no security group: %#v", instance.SecurityGroupIds.SecurityGroupId)
- }
-
- if len(instance.SecurityGroupIds.SecurityGroupId) < sgCount {
- return fmt.Errorf("less security group: %#v", instance.SecurityGroupIds.SecurityGroupId)
- }
-
- return nil
- }
- }
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_instance.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccInstanceConfig_multiSecurityGroupByCount,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckInstanceExists(
- "alicloud_instance.foo", &instance),
- testCheck(2),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "image_id",
- "ubuntu_140405_32_40G_cloudinit_20161115.vhd"),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "instance_name",
- "test_foo"),
- ),
- },
- },
- })
-
-}
-
-func TestAccAlicloudInstance_NetworkInstanceSecurityGroups(t *testing.T) {
- var instance ecs.InstanceAttributesType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
- IDRefreshName: "alicloud_instance.foo",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccInstanceNetworkInstanceSecurityGroups,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckInstanceExists(
- "alicloud_instance.foo", &instance),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudInstance_tags(t *testing.T) {
- var instance ecs.InstanceAttributesType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccCheckInstanceConfigTags,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckInstanceExists("alicloud_instance.foo", &instance),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "tags.foo",
- "bar"),
- ),
- },
-
- resource.TestStep{
- Config: testAccCheckInstanceConfigTagsUpdate,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckInstanceExists("alicloud_instance.foo", &instance),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "tags.bar",
- "zzz"),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudInstance_update(t *testing.T) {
- var instance ecs.InstanceAttributesType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccCheckInstanceConfigOrigin,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckInstanceExists("alicloud_instance.foo", &instance),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "instance_name",
- "instance_foo"),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "host_name",
- "host-foo"),
- ),
- },
-
- resource.TestStep{
- Config: testAccCheckInstanceConfigOriginUpdate,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckInstanceExists("alicloud_instance.foo", &instance),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "instance_name",
- "instance_bar"),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "host_name",
- "host-bar"),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudInstanceImage_update(t *testing.T) {
- var instance ecs.InstanceAttributesType
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccCheckInstanceImageOrigin,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckInstanceExists("alicloud_instance.update_image", &instance),
- resource.TestCheckResourceAttr(
- "alicloud_instance.update_image",
- "system_disk_size",
- "50"),
- ),
- },
- resource.TestStep{
- Config: testAccCheckInstanceImageUpdate,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckInstanceExists("alicloud_instance.update_image", &instance),
- resource.TestCheckResourceAttr(
- "alicloud_instance.update_image",
- "system_disk_size",
- "60"),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudInstance_privateIP(t *testing.T) {
- var instance ecs.InstanceAttributesType
-
- testCheckPrivateIP := func() resource.TestCheckFunc {
- return func(*terraform.State) error {
- privateIP := instance.VpcAttributes.PrivateIpAddress.IpAddress[0]
- if privateIP == "" {
- return fmt.Errorf("can't get private IP")
- }
-
- return nil
- }
- }
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
- IDRefreshName: "alicloud_instance.foo",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccInstanceConfigPrivateIP,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckInstanceExists("alicloud_instance.foo", &instance),
- testCheckPrivateIP(),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudInstance_associatePublicIP(t *testing.T) {
- var instance ecs.InstanceAttributesType
-
- testCheckPrivateIP := func() resource.TestCheckFunc {
- return func(*terraform.State) error {
- privateIP := instance.VpcAttributes.PrivateIpAddress.IpAddress[0]
- if privateIP == "" {
- return fmt.Errorf("can't get private IP")
- }
-
- return nil
- }
- }
-
- testCheckPublicIP := func() resource.TestCheckFunc {
- return func(*terraform.State) error {
- publicIP := instance.PublicIpAddress.IpAddress[0]
- if publicIP == "" {
- return fmt.Errorf("can't get public IP")
- }
-
- return nil
- }
- }
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
- IDRefreshName: "alicloud_instance.foo",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccInstanceConfigAssociatePublicIP,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckInstanceExists("alicloud_instance.foo", &instance),
- testCheckPrivateIP(),
- testCheckPublicIP(),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudInstance_vpcRule(t *testing.T) {
- var instance ecs.InstanceAttributesType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
- IDRefreshName: "alicloud_instance.foo",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckInstanceDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccVpcInstanceWithSecurityRule,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckInstanceExists("alicloud_instance.foo", &instance),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "internet_charge_type",
- "PayByBandwidth"),
- resource.TestCheckResourceAttr(
- "alicloud_instance.foo",
- "internet_max_bandwidth_out",
- "5"),
- ),
- },
- },
- })
-}
-
-func testAccCheckInstanceExists(n string, i *ecs.InstanceAttributesType) resource.TestCheckFunc {
- providers := []*schema.Provider{testAccProvider}
- return testAccCheckInstanceExistsWithProviders(n, i, &providers)
-}
-
-func testAccCheckInstanceExistsWithProviders(n string, i *ecs.InstanceAttributesType, providers *[]*schema.Provider) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No ID is set")
- }
- for _, provider := range *providers {
- // Ignore if Meta is empty, this can happen for validation providers
- if provider.Meta() == nil {
- continue
- }
-
- client := provider.Meta().(*AliyunClient)
- instance, err := client.QueryInstancesById(rs.Primary.ID)
- log.Printf("[WARN]get ecs instance %#v", instance)
- if err == nil && instance != nil {
- *i = *instance
- return nil
- }
-
- // Verify the error is what we want
- e, _ := err.(*common.Error)
- if e.ErrorResponse.Message == InstanceNotfound {
- continue
- }
- if err != nil {
- return err
-
- }
- }
-
- return fmt.Errorf("Instance not found")
- }
-}
-
-func testAccCheckInstanceDestroy(s *terraform.State) error {
- return testAccCheckInstanceDestroyWithProvider(s, testAccProvider)
-}
-
-func testAccCheckInstanceDestroyWithProviders(providers *[]*schema.Provider) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- for _, provider := range *providers {
- if provider.Meta() == nil {
- continue
- }
- if err := testAccCheckInstanceDestroyWithProvider(s, provider); err != nil {
- return err
- }
- }
- return nil
- }
-}
-
-func testAccCheckInstanceDestroyWithProvider(s *terraform.State, provider *schema.Provider) error {
- client := provider.Meta().(*AliyunClient)
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "alicloud_instance" {
- continue
- }
-
- // Try to find the resource
- instance, err := client.QueryInstancesById(rs.Primary.ID)
- if err == nil {
- if instance.Status != "" && instance.Status != "Stopped" {
- return fmt.Errorf("Found unstopped instance: %s", instance.InstanceId)
- }
- }
-
- // Verify the error is what we want
- e, _ := err.(*common.Error)
- if e.ErrorResponse.Message == InstanceNotfound {
- continue
- }
-
- return err
- }
-
- return nil
-}
-
-func testAccCheckSystemDiskSize(n string, size int) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- providers := []*schema.Provider{testAccProvider}
- rs, ok := s.RootModule().Resources[n]
-
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- for _, provider := range providers {
- if provider.Meta() == nil {
- continue
- }
- client := provider.Meta().(*AliyunClient)
- systemDisk, err := client.QueryInstanceSystemDisk(rs.Primary.ID)
- if err != nil {
- log.Printf("[ERROR]get system disk size error: %#v", err)
- return err
- }
-
- if systemDisk.Size != size {
- return fmt.Errorf("system disk size not equal %d, the instance system size is %d",
- size, systemDisk.Size)
- }
- }
-
- return nil
- }
-}
-
-const testAccInstanceConfig = `
-resource "alicloud_security_group" "tf_test_foo" {
- name = "tf_test_foo"
- description = "foo"
-}
-
-resource "alicloud_security_group" "tf_test_bar" {
- name = "tf_test_bar"
- description = "bar"
-}
-
-resource "alicloud_instance" "foo" {
- image_id = "ubuntu_140405_32_40G_cloudinit_20161115.vhd"
-
- system_disk_category = "cloud_ssd"
- system_disk_size = 80
-
- instance_type = "ecs.n1.small"
- internet_charge_type = "PayByBandwidth"
- security_groups = ["${alicloud_security_group.tf_test_foo.id}"]
- instance_name = "test_foo"
- io_optimized = "optimized"
-
- tags {
- foo = "bar"
- work = "test"
- }
-}
-`
-const testAccInstanceConfigVPC = `
-data "alicloud_zones" "default" {
- "available_disk_category"= "cloud_efficiency"
- "available_resource_creation"= "VSwitch"
-}
-
-resource "alicloud_vpc" "foo" {
- name = "tf_test_foo"
- cidr_block = "172.16.0.0/12"
-}
-
-resource "alicloud_vswitch" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- cidr_block = "172.16.0.0/21"
- availability_zone = "${data.alicloud_zones.default.zones.0.id}"
-}
-
-resource "alicloud_security_group" "tf_test_foo" {
- name = "tf_test_foo"
- description = "foo"
- vpc_id = "${alicloud_vpc.foo.id}"
-}
-
-resource "alicloud_instance" "foo" {
- # cn-beijing
- vswitch_id = "${alicloud_vswitch.foo.id}"
- image_id = "ubuntu_140405_32_40G_cloudinit_20161115.vhd"
-
- # series II
- instance_type = "ecs.n1.medium"
- io_optimized = "optimized"
- system_disk_category = "cloud_efficiency"
-
- internet_charge_type = "PayByTraffic"
- internet_max_bandwidth_out = 5
- allocate_public_ip = true
- security_groups = ["${alicloud_security_group.tf_test_foo.id}"]
- instance_name = "test_foo"
-}
-
-`
-
-const testAccInstanceConfigUserData = `
-data "alicloud_zones" "default" {
- "available_disk_category"= "cloud_efficiency"
- "available_resource_creation"= "VSwitch"
-}
-
-resource "alicloud_vpc" "foo" {
- name = "tf_test_foo"
- cidr_block = "172.16.0.0/12"
-}
-
-resource "alicloud_vswitch" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- cidr_block = "172.16.0.0/21"
- availability_zone = "${data.alicloud_zones.default.zones.0.id}"
-}
-
-resource "alicloud_security_group" "tf_test_foo" {
- name = "tf_test_foo"
- description = "foo"
- vpc_id = "${alicloud_vpc.foo.id}"
-}
-
-resource "alicloud_instance" "foo" {
- # cn-beijing
- vswitch_id = "${alicloud_vswitch.foo.id}"
- image_id = "ubuntu_140405_32_40G_cloudinit_20161115.vhd"
- # series II
- instance_type = "ecs.n1.medium"
- io_optimized = "optimized"
- system_disk_category = "cloud_efficiency"
- internet_charge_type = "PayByTraffic"
- internet_max_bandwidth_out = 5
- allocate_public_ip = true
- security_groups = ["${alicloud_security_group.tf_test_foo.id}"]
- instance_name = "test_foo"
- user_data = "echo 'net.ipv4.ip_forward=1'>> /etc/sysctl.conf"
-}
-`
-
-const testAccInstanceConfigMultipleRegions = `
-provider "alicloud" {
- alias = "beijing"
- region = "cn-beijing"
-}
-
-provider "alicloud" {
- alias = "shanghai"
- region = "cn-shanghai"
-}
-
-resource "alicloud_security_group" "tf_test_foo" {
- name = "tf_test_foo"
- provider = "alicloud.beijing"
- description = "foo"
-}
-
-resource "alicloud_security_group" "tf_test_bar" {
- name = "tf_test_bar"
- provider = "alicloud.shanghai"
- description = "bar"
-}
-
-resource "alicloud_instance" "foo" {
- # cn-beijing
- provider = "alicloud.beijing"
- image_id = "ubuntu_140405_32_40G_cloudinit_20161115.vhd"
-
- internet_charge_type = "PayByBandwidth"
-
- instance_type = "ecs.n1.medium"
- io_optimized = "optimized"
- system_disk_category = "cloud_efficiency"
- security_groups = ["${alicloud_security_group.tf_test_foo.id}"]
- instance_name = "test_foo"
-}
-
-resource "alicloud_instance" "bar" {
- # cn-shanghai
- provider = "alicloud.shanghai"
- image_id = "ubuntu_140405_32_40G_cloudinit_20161115.vhd"
-
- internet_charge_type = "PayByBandwidth"
-
- instance_type = "ecs.n1.medium"
- io_optimized = "optimized"
- system_disk_category = "cloud_efficiency"
- security_groups = ["${alicloud_security_group.tf_test_bar.id}"]
- instance_name = "test_bar"
-}
-`
-
-const testAccInstanceConfig_multiSecurityGroup = `
-resource "alicloud_security_group" "tf_test_foo" {
- name = "tf_test_foo"
- description = "foo"
-}
-
-resource "alicloud_security_group" "tf_test_bar" {
- name = "tf_test_bar"
- description = "bar"
-}
-
-resource "alicloud_instance" "foo" {
- # cn-beijing
- image_id = "ubuntu_140405_32_40G_cloudinit_20161115.vhd"
-
- instance_type = "ecs.s2.large"
- internet_charge_type = "PayByBandwidth"
- security_groups = ["${alicloud_security_group.tf_test_foo.id}", "${alicloud_security_group.tf_test_bar.id}"]
- instance_name = "test_foo"
- io_optimized = "optimized"
- system_disk_category = "cloud_efficiency"
-}`
-
-const testAccInstanceConfig_multiSecurityGroup_add = `
-resource "alicloud_security_group" "tf_test_foo" {
- name = "tf_test_foo"
- description = "foo"
-}
-
-resource "alicloud_security_group" "tf_test_bar" {
- name = "tf_test_bar"
- description = "bar"
-}
-
-resource "alicloud_security_group" "tf_test_add_sg" {
- name = "tf_test_add_sg"
- description = "sg"
-}
-
-resource "alicloud_instance" "foo" {
- # cn-beijing
- image_id = "ubuntu_140405_32_40G_cloudinit_20161115.vhd"
-
- instance_type = "ecs.s2.large"
- internet_charge_type = "PayByBandwidth"
- security_groups = ["${alicloud_security_group.tf_test_foo.id}", "${alicloud_security_group.tf_test_bar.id}",
- "${alicloud_security_group.tf_test_add_sg.id}"]
- instance_name = "test_foo"
- io_optimized = "optimized"
- system_disk_category = "cloud_efficiency"
-}
-`
-
-const testAccInstanceConfig_multiSecurityGroup_remove = `
-resource "alicloud_security_group" "tf_test_foo" {
- name = "tf_test_foo"
- description = "foo"
-}
-
-resource "alicloud_security_group_rule" "http-in" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "internet"
- policy = "accept"
- port_range = "80/80"
- priority = 1
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
- cidr_ip = "0.0.0.0/0"
-}
-
-resource "alicloud_security_group_rule" "ssh-in" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "internet"
- policy = "accept"
- port_range = "22/22"
- priority = 1
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
- cidr_ip = "0.0.0.0/0"
-}
-
-resource "alicloud_instance" "foo" {
- # cn-beijing
- image_id = "ubuntu_140405_32_40G_cloudinit_20161115.vhd"
-
- instance_type = "ecs.s2.large"
- internet_charge_type = "PayByBandwidth"
- security_groups = ["${alicloud_security_group.tf_test_foo.id}"]
- instance_name = "test_foo"
- io_optimized = "optimized"
- system_disk_category = "cloud_efficiency"
-}
-`
-
-const testAccInstanceConfig_multiSecurityGroupByCount = `
-resource "alicloud_security_group" "tf_test_foo" {
- name = "tf_test_foo"
- count = 2
- description = "foo"
-}
-
-resource "alicloud_instance" "foo" {
- # cn-beijing
- image_id = "ubuntu_140405_32_40G_cloudinit_20161115.vhd"
-
- instance_type = "ecs.s2.large"
- internet_charge_type = "PayByBandwidth"
- security_groups = ["${alicloud_security_group.tf_test_foo.*.id}"]
- instance_name = "test_foo"
- io_optimized = "optimized"
- system_disk_category = "cloud_efficiency"
-}
-`
-
-const testAccInstanceNetworkInstanceSecurityGroups = `
-data "alicloud_zones" "default" {
- "available_disk_category"= "cloud_efficiency"
- "available_resource_creation"= "VSwitch"
-}
-
-resource "alicloud_vpc" "foo" {
- name = "tf_test_foo"
- cidr_block = "172.16.0.0/12"
-}
-
-resource "alicloud_vswitch" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- cidr_block = "172.16.0.0/21"
- availability_zone = "${data.alicloud_zones.default.zones.0.id}"
-}
-
-resource "alicloud_security_group" "tf_test_foo" {
- name = "tf_test_foo"
- description = "foo"
- vpc_id = "${alicloud_vpc.foo.id}"
-}
-
-resource "alicloud_instance" "foo" {
- # cn-beijing
- vswitch_id = "${alicloud_vswitch.foo.id}"
- image_id = "ubuntu_140405_32_40G_cloudinit_20161115.vhd"
-
- # series II
- instance_type = "ecs.n1.medium"
- io_optimized = "optimized"
- system_disk_category = "cloud_efficiency"
-
- security_groups = ["${alicloud_security_group.tf_test_foo.id}"]
- instance_name = "test_foo"
-
- internet_max_bandwidth_out = 5
- allocate_public_ip = "true"
- internet_charge_type = "PayByBandwidth"
-}
-`
-const testAccCheckInstanceConfigTags = `
-resource "alicloud_security_group" "tf_test_foo" {
- name = "tf_test_foo"
- description = "foo"
-}
-
-resource "alicloud_instance" "foo" {
- # cn-beijing
- image_id = "ubuntu_140405_32_40G_cloudinit_20161115.vhd"
-
- # series II
- instance_type = "ecs.n1.medium"
- io_optimized = "optimized"
- internet_charge_type = "PayByBandwidth"
- system_disk_category = "cloud_efficiency"
-
- security_groups = ["${alicloud_security_group.tf_test_foo.id}"]
- instance_name = "test_foo"
-
- tags {
- foo = "bar"
- }
-}
-`
-
-const testAccCheckInstanceConfigTagsUpdate = `
-resource "alicloud_security_group" "tf_test_foo" {
- name = "tf_test_foo"
- description = "foo"
-}
-
-resource "alicloud_instance" "foo" {
- # cn-beijing
- image_id = "ubuntu_140405_32_40G_cloudinit_20161115.vhd"
-
- # series II
- instance_type = "ecs.n1.medium"
- io_optimized = "optimized"
- internet_charge_type = "PayByBandwidth"
- system_disk_category = "cloud_efficiency"
-
- security_groups = ["${alicloud_security_group.tf_test_foo.id}"]
- instance_name = "test_foo"
-
- tags {
- bar = "zzz"
- }
-}
-`
-const testAccCheckInstanceConfigOrigin = `
-resource "alicloud_security_group" "tf_test_foo" {
- name = "tf_test_foo"
- description = "foo"
-}
-
-resource "alicloud_security_group_rule" "http-in" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "internet"
- policy = "accept"
- port_range = "80/80"
- priority = 1
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
- cidr_ip = "0.0.0.0/0"
-}
-
-resource "alicloud_security_group_rule" "ssh-in" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "internet"
- policy = "accept"
- port_range = "22/22"
- priority = 1
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
- cidr_ip = "0.0.0.0/0"
-}
-
-resource "alicloud_instance" "foo" {
- # cn-beijing
- image_id = "ubuntu_140405_32_40G_cloudinit_20161115.vhd"
-
- # series II
- instance_type = "ecs.n1.medium"
- io_optimized = "optimized"
- internet_charge_type = "PayByBandwidth"
- system_disk_category = "cloud_efficiency"
-
- security_groups = ["${alicloud_security_group.tf_test_foo.id}"]
-
- instance_name = "instance_foo"
- host_name = "host-foo"
-}
-`
-
-const testAccCheckInstanceConfigOriginUpdate = `
-resource "alicloud_security_group" "tf_test_foo" {
- name = "tf_test_foo"
- description = "foo"
-}
-
-resource "alicloud_security_group_rule" "http-in" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "internet"
- policy = "accept"
- port_range = "80/80"
- priority = 1
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
- cidr_ip = "0.0.0.0/0"
-}
-
-resource "alicloud_security_group_rule" "ssh-in" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "internet"
- policy = "accept"
- port_range = "22/22"
- priority = 1
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
- cidr_ip = "0.0.0.0/0"
-}
-
-resource "alicloud_instance" "foo" {
- # cn-beijing
- image_id = "ubuntu_140405_32_40G_cloudinit_20161115.vhd"
-
- # series II
- instance_type = "ecs.n1.medium"
- io_optimized = "optimized"
- internet_charge_type = "PayByBandwidth"
- system_disk_category = "cloud_efficiency"
-
- security_groups = ["${alicloud_security_group.tf_test_foo.id}"]
-
- instance_name = "instance_bar"
- host_name = "host-bar"
-}
-`
-
-const testAccInstanceConfigPrivateIP = `
-data "alicloud_zones" "default" {
- "available_disk_category"= "cloud_efficiency"
- "available_resource_creation"= "VSwitch"
-}
-
-resource "alicloud_vpc" "foo" {
- name = "tf_test_foo"
- cidr_block = "172.16.0.0/12"
-}
-
-resource "alicloud_vswitch" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- cidr_block = "172.16.0.0/24"
- availability_zone = "${data.alicloud_zones.default.zones.0.id}"
-}
-
-resource "alicloud_security_group" "tf_test_foo" {
- name = "tf_test_foo"
- description = "foo"
- vpc_id = "${alicloud_vpc.foo.id}"
-}
-
-resource "alicloud_instance" "foo" {
- # cn-beijing
- security_groups = ["${alicloud_security_group.tf_test_foo.id}"]
-
- vswitch_id = "${alicloud_vswitch.foo.id}"
-
- # series II
- instance_type = "ecs.n1.medium"
- io_optimized = "optimized"
- system_disk_category = "cloud_efficiency"
- image_id = "ubuntu_140405_32_40G_cloudinit_20161115.vhd"
- instance_name = "test_foo"
-}
-`
-const testAccInstanceConfigAssociatePublicIP = `
-data "alicloud_zones" "default" {
- "available_disk_category"= "cloud_efficiency"
- "available_resource_creation"= "VSwitch"
-}
-
-resource "alicloud_vpc" "foo" {
- name = "tf_test_foo"
- cidr_block = "172.16.0.0/12"
-}
-
-resource "alicloud_vswitch" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- cidr_block = "172.16.0.0/24"
- availability_zone = "${data.alicloud_zones.default.zones.0.id}"
-}
-
-resource "alicloud_security_group" "tf_test_foo" {
- name = "tf_test_foo"
- description = "foo"
- vpc_id = "${alicloud_vpc.foo.id}"
-}
-
-resource "alicloud_instance" "foo" {
- # cn-beijing
- security_groups = ["${alicloud_security_group.tf_test_foo.id}"]
-
- vswitch_id = "${alicloud_vswitch.foo.id}"
- allocate_public_ip = "true"
- internet_max_bandwidth_out = 5
- internet_charge_type = "PayByBandwidth"
-
- # series II
- instance_type = "ecs.n1.medium"
- io_optimized = "optimized"
- system_disk_category = "cloud_efficiency"
- image_id = "ubuntu_140405_32_40G_cloudinit_20161115.vhd"
- instance_name = "test_foo"
-}
-`
-const testAccVpcInstanceWithSecurityRule = `
-data "alicloud_zones" "default" {
- "available_disk_category"= "cloud_efficiency"
- "available_resource_creation"= "VSwitch"
-}
-
-resource "alicloud_vpc" "foo" {
- name = "tf_test_foo"
- cidr_block = "10.1.0.0/21"
-}
-
-resource "alicloud_vswitch" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- cidr_block = "10.1.1.0/24"
- availability_zone = "${data.alicloud_zones.default.zones.0.id}"
-}
-
-resource "alicloud_security_group" "tf_test_foo" {
- name = "tf_test_foo"
- description = "foo"
- vpc_id = "${alicloud_vpc.foo.id}"
-}
-
-resource "alicloud_security_group_rule" "ingress" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "intranet"
- policy = "accept"
- port_range = "22/22"
- priority = 1
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
- cidr_ip = "0.0.0.0/0"
-}
-
-resource "alicloud_instance" "foo" {
- # cn-beijing
- security_groups = ["${alicloud_security_group.tf_test_foo.id}"]
-
- vswitch_id = "${alicloud_vswitch.foo.id}"
- allocate_public_ip = true
-
- # series II
- instance_charge_type = "PostPaid"
- instance_type = "ecs.n1.small"
- internet_charge_type = "PayByBandwidth"
- internet_max_bandwidth_out = 5
-
- system_disk_category = "cloud_efficiency"
- image_id = "ubuntu_140405_64_40G_cloudinit_20161115.vhd"
- instance_name = "test_foo"
- io_optimized = "optimized"
-}
-`
-const testAccCheckInstanceImageOrigin = `
-data "alicloud_images" "centos" {
- most_recent = true
- owners = "system"
- name_regex = "^centos_6\\w{1,5}[64]{1}.*"
-}
-
-resource "alicloud_vpc" "foo" {
- name = "tf_test_image"
- cidr_block = "10.1.0.0/21"
-}
-
-resource "alicloud_vswitch" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- cidr_block = "10.1.1.0/24"
- availability_zone = "cn-beijing-a"
-}
-
-resource "alicloud_security_group" "tf_test_foo" {
- name = "tf_test_foo"
- description = "foo"
- vpc_id = "${alicloud_vpc.foo.id}"
-}
-
-resource "alicloud_instance" "update_image" {
- image_id = "${data.alicloud_images.centos.images.0.id}"
- availability_zone = "cn-beijing-a"
- system_disk_category = "cloud_efficiency"
- system_disk_size = 50
-
- instance_type = "ecs.n1.small"
- internet_charge_type = "PayByBandwidth"
- instance_name = "update_image"
- io_optimized = "optimized"
- password = "Test12345"
-}
-`
-const testAccCheckInstanceImageUpdate = `
-data "alicloud_images" "ubuntu" {
- most_recent = true
- owners = "system"
- name_regex = "^ubuntu_14\\w{1,5}[64]{1}.*"
-}
-
-resource "alicloud_vpc" "foo" {
- name = "tf_test_image"
- cidr_block = "10.1.0.0/21"
-}
-
-resource "alicloud_vswitch" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- cidr_block = "10.1.1.0/24"
- availability_zone = "cn-beijing-a"
-}
-
-resource "alicloud_security_group" "tf_test_foo" {
- name = "tf_test_foo"
- description = "foo"
- vpc_id = "${alicloud_vpc.foo.id}"
-}
-
-resource "alicloud_instance" "update_image" {
- image_id = "${data.alicloud_images.ubuntu.images.0.id}"
- availability_zone = "cn-beijing-a"
- system_disk_category = "cloud_efficiency"
- system_disk_size = 60
-
- instance_type = "ecs.n1.small"
- internet_charge_type = "PayByBandwidth"
- instance_name = "update_image"
- io_optimized = "optimized"
- password = "Test12345"
-}
-`
diff --git a/builtin/providers/alicloud/resource_alicloud_nat_gateway.go b/builtin/providers/alicloud/resource_alicloud_nat_gateway.go
deleted file mode 100644
index b078ee0a2..000000000
--- a/builtin/providers/alicloud/resource_alicloud_nat_gateway.go
+++ /dev/null
@@ -1,374 +0,0 @@
-package alicloud
-
-import (
- "fmt"
-
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
- "log"
- "strconv"
- "strings"
- "time"
-)
-
-func resourceAliyunNatGateway() *schema.Resource {
- return &schema.Resource{
- Create: resourceAliyunNatGatewayCreate,
- Read: resourceAliyunNatGatewayRead,
- Update: resourceAliyunNatGatewayUpdate,
- Delete: resourceAliyunNatGatewayDelete,
-
- Schema: map[string]*schema.Schema{
- "vpc_id": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
- "spec": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
- "name": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "description": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- },
-
- "bandwidth_package_ids": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
-
- "snat_table_ids": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
-
- "forward_table_ids": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
-
- "bandwidth_packages": &schema.Schema{
- Type: schema.TypeList,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "ip_count": &schema.Schema{
- Type: schema.TypeInt,
- Required: true,
- },
- "bandwidth": &schema.Schema{
- Type: schema.TypeInt,
- Required: true,
- },
- "zone": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "public_ip_addresses": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- },
- },
- Required: true,
- MaxItems: 4,
- },
- },
- }
-}
-
-func resourceAliyunNatGatewayCreate(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).vpcconn
-
- args := &ecs.CreateNatGatewayArgs{
- RegionId: getRegion(d, meta),
- VpcId: d.Get("vpc_id").(string),
- Spec: d.Get("spec").(string),
- }
-
- bandwidthPackages := d.Get("bandwidth_packages").([]interface{})
-
- bandwidthPackageTypes := []ecs.BandwidthPackageType{}
-
- for _, e := range bandwidthPackages {
- pack := e.(map[string]interface{})
- bandwidthPackage := ecs.BandwidthPackageType{
- IpCount: pack["ip_count"].(int),
- Bandwidth: pack["bandwidth"].(int),
- }
- if pack["zone"].(string) != "" {
- bandwidthPackage.Zone = pack["zone"].(string)
- }
-
- bandwidthPackageTypes = append(bandwidthPackageTypes, bandwidthPackage)
- }
-
- args.BandwidthPackage = bandwidthPackageTypes
-
- var name string
- if v, ok := d.GetOk("name"); ok {
- name = v.(string)
- }
-
- args.Name = name
-
- if v, ok := d.GetOk("description"); ok {
- args.Description = v.(string)
- }
- resp, err := conn.CreateNatGateway(args)
- if err != nil {
- return fmt.Errorf("CreateNatGateway got error: %#v", err)
- }
-
- d.SetId(resp.NatGatewayId)
-
- return resourceAliyunNatGatewayRead(d, meta)
-}
-
-func resourceAliyunNatGatewayRead(d *schema.ResourceData, meta interface{}) error {
-
- client := meta.(*AliyunClient)
-
- natGateway, err := client.DescribeNatGateway(d.Id())
- if err != nil {
- if notFoundError(err) {
- d.SetId("")
- return nil
- }
- return err
- }
-
- d.Set("name", natGateway.Name)
- d.Set("spec", natGateway.Spec)
- d.Set("bandwidth_package_ids", strings.Join(natGateway.BandwidthPackageIds.BandwidthPackageId, ","))
- d.Set("snat_table_ids", strings.Join(natGateway.SnatTableIds.SnatTableId, ","))
- d.Set("forward_table_ids", strings.Join(natGateway.ForwardTableIds.ForwardTableId, ","))
- d.Set("description", natGateway.Description)
- d.Set("vpc_id", natGateway.VpcId)
- bindWidthPackages, err := flattenBandWidthPackages(natGateway.BandwidthPackageIds.BandwidthPackageId, meta, d)
- if err != nil {
- log.Printf("[ERROR] bindWidthPackages flattenBandWidthPackages failed. natgateway id is %#v", d.Id())
- } else {
- d.Set("bandwidth_packages", bindWidthPackages)
- }
-
- return nil
-}
-
-func resourceAliyunNatGatewayUpdate(d *schema.ResourceData, meta interface{}) error {
-
- client := meta.(*AliyunClient)
- conn := client.vpcconn
-
- natGateway, err := client.DescribeNatGateway(d.Id())
- if err != nil {
- return err
- }
-
- d.Partial(true)
- attributeUpdate := false
- args := &ecs.ModifyNatGatewayAttributeArgs{
- RegionId: natGateway.RegionId,
- NatGatewayId: natGateway.NatGatewayId,
- }
-
- if d.HasChange("name") {
- d.SetPartial("name")
- var name string
- if v, ok := d.GetOk("name"); ok {
- name = v.(string)
- } else {
- return fmt.Errorf("cann't change name to empty string")
- }
- args.Name = name
-
- attributeUpdate = true
- }
-
- if d.HasChange("description") {
- d.SetPartial("description")
- var description string
- if v, ok := d.GetOk("description"); ok {
- description = v.(string)
- } else {
- return fmt.Errorf("can to change description to empty string")
- }
-
- args.Description = description
-
- attributeUpdate = true
- }
-
- if attributeUpdate {
- if err := conn.ModifyNatGatewayAttribute(args); err != nil {
- return err
- }
- }
-
- if d.HasChange("spec") {
- d.SetPartial("spec")
- var spec ecs.NatGatewaySpec
- if v, ok := d.GetOk("spec"); ok {
- spec = ecs.NatGatewaySpec(v.(string))
- } else {
- // set default to small spec
- spec = ecs.NatGatewaySmallSpec
- }
-
- args := &ecs.ModifyNatGatewaySpecArgs{
- RegionId: natGateway.RegionId,
- NatGatewayId: natGateway.NatGatewayId,
- Spec: spec,
- }
-
- err := conn.ModifyNatGatewaySpec(args)
- if err != nil {
- return fmt.Errorf("%#v %#v", err, *args)
- }
-
- }
- d.Partial(false)
-
- return resourceAliyunNatGatewayRead(d, meta)
-}
-
-func resourceAliyunNatGatewayDelete(d *schema.ResourceData, meta interface{}) error {
-
- client := meta.(*AliyunClient)
- conn := client.vpcconn
-
- return resource.Retry(5*time.Minute, func() *resource.RetryError {
-
- packages, err := conn.DescribeBandwidthPackages(&ecs.DescribeBandwidthPackagesArgs{
- RegionId: getRegion(d, meta),
- NatGatewayId: d.Id(),
- })
- if err != nil {
- log.Printf("[ERROR] Describe bandwidth package is failed, natGateway Id: %s", d.Id())
- return resource.NonRetryableError(err)
- }
-
- retry := false
- for _, pack := range packages {
- err = conn.DeleteBandwidthPackage(&ecs.DeleteBandwidthPackageArgs{
- RegionId: getRegion(d, meta),
- BandwidthPackageId: pack.BandwidthPackageId,
- })
-
- if err != nil {
- er, _ := err.(*common.Error)
- if er.ErrorResponse.Code == NatGatewayInvalidRegionId {
- log.Printf("[ERROR] Delete bandwidth package is failed, bandwidthPackageId: %#v", pack.BandwidthPackageId)
- return resource.NonRetryableError(err)
- }
- retry = true
- }
- }
-
- if retry {
- return resource.RetryableError(fmt.Errorf("Bandwidth package in use - trying again while it is deleted."))
- }
-
- args := &ecs.DeleteNatGatewayArgs{
- RegionId: getRegion(d, meta),
- NatGatewayId: d.Id(),
- }
-
- err = conn.DeleteNatGateway(args)
- if err != nil {
- er, _ := err.(*common.Error)
- if er.ErrorResponse.Code == DependencyViolationBandwidthPackages {
- return resource.RetryableError(fmt.Errorf("NatGateway in use - trying again while it is deleted."))
- }
- }
-
- describeArgs := &ecs.DescribeNatGatewaysArgs{
- RegionId: getRegion(d, meta),
- NatGatewayId: d.Id(),
- }
- gw, _, gwErr := conn.DescribeNatGateways(describeArgs)
-
- if gwErr != nil {
- log.Printf("[ERROR] Describe NatGateways failed.")
- return resource.NonRetryableError(gwErr)
- } else if gw == nil || len(gw) < 1 {
- return nil
- }
-
- return resource.RetryableError(fmt.Errorf("NatGateway in use - trying again while it is deleted."))
- })
-}
-
-func flattenBandWidthPackages(bandWidthPackageIds []string, meta interface{}, d *schema.ResourceData) ([]map[string]interface{}, error) {
-
- packageLen := len(bandWidthPackageIds)
- result := make([]map[string]interface{}, 0, packageLen)
-
- for i := packageLen - 1; i >= 0; i-- {
- packageId := bandWidthPackageIds[i]
- packages, err := getPackages(packageId, meta, d)
- if err != nil {
- log.Printf("[ERROR] NatGateways getPackages failed. packageId is %#v", packageId)
- return result, err
- }
- ipAddress := flattenPackPublicIp(packages.PublicIpAddresses.PublicIpAddresse)
- ipCont, ipContErr := strconv.Atoi(packages.IpCount)
- bandWidth, bandWidthErr := strconv.Atoi(packages.Bandwidth)
- if ipContErr != nil {
- log.Printf("[ERROR] NatGateways getPackages failed: ipCont convert error. packageId is %#v", packageId)
- return result, ipContErr
- }
- if bandWidthErr != nil {
- log.Printf("[ERROR] NatGateways getPackages failed: bandWidthErr convert error. packageId is %#v", packageId)
- return result, bandWidthErr
- }
- l := map[string]interface{}{
- "ip_count": ipCont,
- "bandwidth": bandWidth,
- "zone": packages.ZoneId,
- "public_ip_addresses": ipAddress,
- }
- result = append(result, l)
- }
- return result, nil
-}
-
-func getPackages(packageId string, meta interface{}, d *schema.ResourceData) (*ecs.DescribeBandwidthPackageType, error) {
- client := meta.(*AliyunClient)
- conn := client.vpcconn
- packages, err := conn.DescribeBandwidthPackages(&ecs.DescribeBandwidthPackagesArgs{
- RegionId: getRegion(d, meta),
- BandwidthPackageId: packageId,
- })
-
- if err != nil {
- log.Printf("[ERROR] Describe bandwidth package is failed, BandwidthPackageId Id: %s", packageId)
- return nil, err
- }
-
- if len(packages) == 0 {
- return nil, common.GetClientErrorFromString(InstanceNotfound)
- }
-
- return &packages[0], nil
-
-}
-
-func flattenPackPublicIp(publicIpAddressList []ecs.PublicIpAddresseType) string {
- var result []string
-
- for _, publicIpAddresses := range publicIpAddressList {
- ipAddress := publicIpAddresses.IpAddress
- result = append(result, ipAddress)
- }
-
- return strings.Join(result, ",")
-}
diff --git a/builtin/providers/alicloud/resource_alicloud_nat_gateway_test.go b/builtin/providers/alicloud/resource_alicloud_nat_gateway_test.go
deleted file mode 100644
index 963be3cb1..000000000
--- a/builtin/providers/alicloud/resource_alicloud_nat_gateway_test.go
+++ /dev/null
@@ -1,288 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
- "testing"
-)
-
-func TestAccAlicloudNatGateway_basic(t *testing.T) {
- var nat ecs.NatGatewaySetType
-
- testCheck := func(*terraform.State) error {
- if nat.BusinessStatus != "Normal" {
- return fmt.Errorf("abnormal instance status")
- }
-
- if len(nat.BandwidthPackageIds.BandwidthPackageId) == 0 {
- return fmt.Errorf("no bandwidth package: %#v", nat.BandwidthPackageIds.BandwidthPackageId)
- }
-
- return nil
- }
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_nat_gateway.foo",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckNatGatewayDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccNatGatewayConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckNatGatewayExists(
- "alicloud_nat_gateway.foo", &nat),
- testCheck,
- resource.TestCheckResourceAttr(
- "alicloud_nat_gateway.foo",
- "spec",
- "Small"),
- resource.TestCheckResourceAttr(
- "alicloud_nat_gateway.foo",
- "name",
- "test_foo"),
- testAccCheckNatgatewayIpAddress("alicloud_nat_gateway.foo", &nat),
- ),
- },
- },
- })
-
-}
-
-func TestAccAlicloudNatGateway_spec(t *testing.T) {
- var nat ecs.NatGatewaySetType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_nat_gateway.foo",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckNatGatewayDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccNatGatewayConfigSpec,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckNatGatewayExists(
- "alicloud_nat_gateway.foo", &nat),
- resource.TestCheckResourceAttr(
- "alicloud_nat_gateway.foo",
- "spec",
- "Middle"),
- ),
- },
-
- resource.TestStep{
- Config: testAccNatGatewayConfigSpecUpgrade,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckNatGatewayExists(
- "alicloud_nat_gateway.foo", &nat),
- resource.TestCheckResourceAttr(
- "alicloud_nat_gateway.foo",
- "spec",
- "Large"),
- ),
- },
- },
- })
-
-}
-
-func testAccCheckNatgatewayIpAddress(n string, nat *ecs.NatGatewaySetType) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No NatGateway ID is set")
- }
-
- client := testAccProvider.Meta().(*AliyunClient)
- natGateway, err := client.DescribeNatGateway(rs.Primary.ID)
-
- if err != nil {
- return err
- }
- if natGateway == nil {
- return fmt.Errorf("Natgateway not found")
- }
-
- return nil
- }
-}
-
-func testAccCheckNatGatewayExists(n string, nat *ecs.NatGatewaySetType) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No Gateway ID is set")
- }
-
- client := testAccProvider.Meta().(*AliyunClient)
- instance, err := client.DescribeNatGateway(rs.Primary.ID)
-
- if err != nil {
- return err
- }
- if instance == nil {
- return fmt.Errorf("Nat gateway not found")
- }
-
- *nat = *instance
- return nil
- }
-}
-
-func testAccCheckNatGatewayDestroy(s *terraform.State) error {
- client := testAccProvider.Meta().(*AliyunClient)
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "alicloud_nat_gateway" {
- continue
- }
-
- // Try to find the Nat gateway
- instance, err := client.DescribeNatGateway(rs.Primary.ID)
-
- if instance != nil {
- return fmt.Errorf("Nat gateway still exist")
- }
-
- if err != nil {
- // Verify the error is what we want
- e, _ := err.(*common.Error)
-
- if !notFoundError(e) {
- return err
- }
- }
-
- }
-
- return nil
-}
-
-const testAccNatGatewayConfig = `
-data "alicloud_zones" "default" {
- "available_resource_creation"= "VSwitch"
-}
-
-resource "alicloud_vpc" "foo" {
- name = "tf_test_foo"
- cidr_block = "172.16.0.0/12"
-}
-
-resource "alicloud_vswitch" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- cidr_block = "172.16.0.0/21"
- availability_zone = "${data.alicloud_zones.default.zones.2.id}"
-}
-
-resource "alicloud_nat_gateway" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- spec = "Small"
- name = "test_foo"
- bandwidth_packages = [{
- ip_count = 1
- bandwidth = 5
- zone = "${data.alicloud_zones.default.zones.2.id}"
- }, {
- ip_count = 2
- bandwidth = 6
- zone = "${data.alicloud_zones.default.zones.2.id}"
- }, {
- ip_count = 3
- bandwidth = 7
- zone = "${data.alicloud_zones.default.zones.2.id}"
- }, {
- ip_count = 1
- bandwidth = 8
- zone = "${data.alicloud_zones.default.zones.2.id}"
- }]
- depends_on = [
- "alicloud_vswitch.foo"]
-}
-`
-
-const testAccNatGatewayConfigSpec = `
-data "alicloud_zones" "default" {
- "available_resource_creation"= "VSwitch"
-}
-
-resource "alicloud_vpc" "foo" {
- name = "tf_test_foo"
- cidr_block = "172.16.0.0/12"
-}
-
-resource "alicloud_vswitch" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- cidr_block = "172.16.0.0/21"
- availability_zone = "${data.alicloud_zones.default.zones.0.id}"
-}
-
-resource "alicloud_nat_gateway" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- spec = "Middle"
- name = "test_foo"
- bandwidth_packages = [{
- ip_count = 1
- bandwidth = 5
- zone = "${data.alicloud_zones.default.zones.0.id}"
- }, {
- ip_count = 2
- bandwidth = 10
- zone = "${data.alicloud_zones.default.zones.0.id}"
- }]
- depends_on = [
- "alicloud_vswitch.foo"]
-}
-`
-
-const testAccNatGatewayConfigSpecUpgrade = `
-data "alicloud_zones" "default" {
- "available_resource_creation"= "VSwitch"
-}
-
-resource "alicloud_vpc" "foo" {
- name = "tf_test_foo"
- cidr_block = "172.16.0.0/12"
-}
-
-resource "alicloud_vswitch" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- cidr_block = "172.16.0.0/21"
- availability_zone = "${data.alicloud_zones.default.zones.0.id}"
-}
-
-resource "alicloud_nat_gateway" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- spec = "Large"
- name = "test_foo"
- bandwidth_packages = [{
- ip_count = 1
- bandwidth = 5
- zone = "${data.alicloud_zones.default.zones.0.id}"
- }, {
- ip_count = 2
- bandwidth = 10
- zone = "${data.alicloud_zones.default.zones.0.id}"
- }]
- depends_on = [
- "alicloud_vswitch.foo"]
-}
-`
diff --git a/builtin/providers/alicloud/resource_alicloud_security_group.go b/builtin/providers/alicloud/resource_alicloud_security_group.go
deleted file mode 100644
index b1d60f704..000000000
--- a/builtin/providers/alicloud/resource_alicloud_security_group.go
+++ /dev/null
@@ -1,174 +0,0 @@
-package alicloud
-
-import (
- "fmt"
-
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
- "time"
-)
-
-func resourceAliyunSecurityGroup() *schema.Resource {
- return &schema.Resource{
- Create: resourceAliyunSecurityGroupCreate,
- Read: resourceAliyunSecurityGroupRead,
- Update: resourceAliyunSecurityGroupUpdate,
- Delete: resourceAliyunSecurityGroupDelete,
-
- Schema: map[string]*schema.Schema{
- "name": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ValidateFunc: validateSecurityGroupName,
- },
-
- "description": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ValidateFunc: validateSecurityGroupDescription,
- },
-
- "vpc_id": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
- },
- }
-}
-
-func resourceAliyunSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).ecsconn
-
- args, err := buildAliyunSecurityGroupArgs(d, meta)
- if err != nil {
- return err
- }
-
- securityGroupID, err := conn.CreateSecurityGroup(args)
- if err != nil {
- return err
- }
-
- d.SetId(securityGroupID)
-
- return resourceAliyunSecurityGroupRead(d, meta)
-}
-
-func resourceAliyunSecurityGroupRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).ecsconn
-
- args := &ecs.DescribeSecurityGroupAttributeArgs{
- SecurityGroupId: d.Id(),
- RegionId: getRegion(d, meta),
- }
-
- sg, err := conn.DescribeSecurityGroupAttribute(args)
- if err != nil {
- if notFoundError(err) {
- d.SetId("")
- return nil
- }
- return fmt.Errorf("Error DescribeSecurityGroupAttribute: %#v", err)
- }
-
- if sg == nil {
- d.SetId("")
- return nil
- }
-
- d.Set("name", sg.SecurityGroupName)
- d.Set("description", sg.Description)
-
- return nil
-}
-
-func resourceAliyunSecurityGroupUpdate(d *schema.ResourceData, meta interface{}) error {
-
- conn := meta.(*AliyunClient).ecsconn
-
- d.Partial(true)
- attributeUpdate := false
- args := &ecs.ModifySecurityGroupAttributeArgs{
- SecurityGroupId: d.Id(),
- RegionId: getRegion(d, meta),
- }
-
- if d.HasChange("name") {
- d.SetPartial("name")
- args.SecurityGroupName = d.Get("name").(string)
-
- attributeUpdate = true
- }
-
- if d.HasChange("description") {
- d.SetPartial("description")
- args.Description = d.Get("description").(string)
-
- attributeUpdate = true
- }
- if attributeUpdate {
- if err := conn.ModifySecurityGroupAttribute(args); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func resourceAliyunSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error {
-
- conn := meta.(*AliyunClient).ecsconn
-
- return resource.Retry(5*time.Minute, func() *resource.RetryError {
- err := conn.DeleteSecurityGroup(getRegion(d, meta), d.Id())
-
- if err != nil {
- e, _ := err.(*common.Error)
- if e.ErrorResponse.Code == SgDependencyViolation {
- return resource.RetryableError(fmt.Errorf("Security group in use - trying again while it is deleted."))
- }
- }
-
- sg, err := conn.DescribeSecurityGroupAttribute(&ecs.DescribeSecurityGroupAttributeArgs{
- RegionId: getRegion(d, meta),
- SecurityGroupId: d.Id(),
- })
-
- if err != nil {
- e, _ := err.(*common.Error)
- if e.ErrorResponse.Code == InvalidSecurityGroupIdNotFound {
- return nil
- }
- return resource.NonRetryableError(err)
- } else if sg == nil {
- return nil
- }
-
- return resource.RetryableError(fmt.Errorf("Security group in use - trying again while it is deleted."))
- })
-
-}
-
-func buildAliyunSecurityGroupArgs(d *schema.ResourceData, meta interface{}) (*ecs.CreateSecurityGroupArgs, error) {
-
- args := &ecs.CreateSecurityGroupArgs{
- RegionId: getRegion(d, meta),
- }
-
- if v := d.Get("name").(string); v != "" {
- args.SecurityGroupName = v
- }
-
- if v := d.Get("description").(string); v != "" {
- args.Description = v
- }
-
- if v := d.Get("vpc_id").(string); v != "" {
- args.VpcId = v
- }
-
- return args, nil
-}
diff --git a/builtin/providers/alicloud/resource_alicloud_security_group_rule.go b/builtin/providers/alicloud/resource_alicloud_security_group_rule.go
deleted file mode 100644
index dd671879c..000000000
--- a/builtin/providers/alicloud/resource_alicloud_security_group_rule.go
+++ /dev/null
@@ -1,352 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
- "strings"
- "time"
-)
-
-func resourceAliyunSecurityGroupRule() *schema.Resource {
- return &schema.Resource{
- Create: resourceAliyunSecurityGroupRuleCreate,
- Read: resourceAliyunSecurityGroupRuleRead,
- Delete: resourceAliyunSecurityGroupRuleDelete,
-
- Schema: map[string]*schema.Schema{
- "type": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- ValidateFunc: validateSecurityRuleType,
- Description: "Type of rule, ingress (inbound) or egress (outbound).",
- },
-
- "ip_protocol": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- ValidateFunc: validateSecurityRuleIpProtocol,
- },
-
- "nic_type": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- Computed: true,
- ValidateFunc: validateSecurityRuleNicType,
- },
-
- "policy": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- ValidateFunc: validateSecurityRulePolicy,
- },
-
- "port_range": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
-
- "priority": &schema.Schema{
- Type: schema.TypeInt,
- Optional: true,
- ForceNew: true,
- ValidateFunc: validateSecurityPriority,
- },
-
- "security_group_id": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
-
- "cidr_ip": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- ConflictsWith: []string{"source_security_group_id"},
- },
-
- "source_security_group_id": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- ConflictsWith: []string{"cidr_ip"},
- },
-
- "source_group_owner_account": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
- },
- }
-}
-
-func resourceAliyunSecurityGroupRuleCreate(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
- conn := client.ecsconn
-
- direction := d.Get("type").(string)
- sgId := d.Get("security_group_id").(string)
- ptl := d.Get("ip_protocol").(string)
- port := d.Get("port_range").(string)
- nicType := d.Get("nic_type").(string)
-
- var autherr error
- switch GroupRuleDirection(direction) {
- case GroupRuleIngress:
- args, err := buildAliyunSecurityIngressArgs(d, meta)
- if err != nil {
- return err
- }
- autherr = conn.AuthorizeSecurityGroup(args)
- case GroupRuleEgress:
- args, err := buildAliyunSecurityEgressArgs(d, meta)
- if err != nil {
- return err
- }
- autherr = conn.AuthorizeSecurityGroupEgress(args)
- default:
- return fmt.Errorf("Security Group Rule must be type 'ingress' or type 'egress'")
- }
-
- if autherr != nil {
- return fmt.Errorf(
- "Error authorizing security group rule type %s: %s",
- direction, autherr)
- }
-
- d.SetId(sgId + ":" + direction + ":" + ptl + ":" + port + ":" + nicType)
-
- return resourceAliyunSecurityGroupRuleRead(d, meta)
-}
-
-func resourceAliyunSecurityGroupRuleRead(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
- parts := strings.Split(d.Id(), ":")
- sgId := parts[0]
- direction := parts[1]
- ip_protocol := parts[2]
- port_range := parts[3]
- nic_type := parts[4]
- rule, err := client.DescribeSecurityGroupRule(sgId, direction, nic_type, ip_protocol, port_range)
-
- if err != nil {
- if notFoundError(err) {
- d.SetId("")
- return nil
- }
- return fmt.Errorf("Error SecurityGroup rule: %#v", err)
- }
-
- d.Set("type", rule.Direction)
- d.Set("ip_protocol", strings.ToLower(string(rule.IpProtocol)))
- d.Set("nic_type", rule.NicType)
- d.Set("policy", strings.ToLower(string(rule.Policy)))
- d.Set("port_range", rule.PortRange)
- d.Set("priority", rule.Priority)
- d.Set("security_group_id", sgId)
- //support source and desc by type
- if GroupRuleDirection(direction) == GroupRuleIngress {
- d.Set("cidr_ip", rule.SourceCidrIp)
- d.Set("source_security_group_id", rule.SourceGroupId)
- d.Set("source_group_owner_account", rule.SourceGroupOwnerAccount)
- } else {
- d.Set("cidr_ip", rule.DestCidrIp)
- d.Set("source_security_group_id", rule.DestGroupId)
- d.Set("source_group_owner_account", rule.DestGroupOwnerAccount)
- }
-
- return nil
-}
-
-func deleteSecurityGroupRule(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
- ruleType := d.Get("type").(string)
-
- if GroupRuleDirection(ruleType) == GroupRuleIngress {
- args, err := buildAliyunSecurityIngressArgs(d, meta)
- if err != nil {
- return err
- }
- revokeArgs := &ecs.RevokeSecurityGroupArgs{
- AuthorizeSecurityGroupArgs: *args,
- }
- return client.RevokeSecurityGroup(revokeArgs)
- }
-
- args, err := buildAliyunSecurityEgressArgs(d, meta)
-
- if err != nil {
- return err
- }
- revokeArgs := &ecs.RevokeSecurityGroupEgressArgs{
- AuthorizeSecurityGroupEgressArgs: *args,
- }
- return client.RevokeSecurityGroupEgress(revokeArgs)
-}
-
-func resourceAliyunSecurityGroupRuleDelete(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
- parts := strings.Split(d.Id(), ":")
- sgId, direction, ip_protocol, port_range, nic_type := parts[0], parts[1], parts[2], parts[3], parts[4]
-
- return resource.Retry(5*time.Minute, func() *resource.RetryError {
- err := deleteSecurityGroupRule(d, meta)
-
- if err != nil {
- resource.RetryableError(fmt.Errorf("Security group rule in use - trying again while it is deleted."))
- }
-
- _, err = client.DescribeSecurityGroupRule(sgId, direction, nic_type, ip_protocol, port_range)
- if err != nil {
- if notFoundError(err) {
- return nil
- }
- return resource.NonRetryableError(err)
- }
-
- return resource.RetryableError(fmt.Errorf("Security group rule in use - trying again while it is deleted."))
- })
-
-}
-
-func checkCidrAndSourceGroupId(cidrIp, sourceGroupId string) error {
- if cidrIp == "" && sourceGroupId == "" {
- return fmt.Errorf("Either cidr_ip or source_security_group_id is required.")
- }
-
- if cidrIp != "" && sourceGroupId != "" {
- return fmt.Errorf("You should set only one value of cidr_ip or source_security_group_id.")
- }
- return nil
-}
-func buildAliyunSecurityIngressArgs(d *schema.ResourceData, meta interface{}) (*ecs.AuthorizeSecurityGroupArgs, error) {
- conn := meta.(*AliyunClient).ecsconn
-
- args := &ecs.AuthorizeSecurityGroupArgs{
- RegionId: getRegion(d, meta),
- }
-
- if v := d.Get("ip_protocol").(string); v != "" {
- args.IpProtocol = ecs.IpProtocol(v)
- }
-
- if v := d.Get("port_range").(string); v != "" {
- args.PortRange = v
- }
-
- if v := d.Get("policy").(string); v != "" {
- args.Policy = ecs.PermissionPolicy(v)
- }
-
- if v := d.Get("priority").(int); v != 0 {
- args.Priority = v
- }
-
- if v := d.Get("cidr_ip").(string); v != "" {
- args.SourceCidrIp = v
- }
-
- if v := d.Get("source_security_group_id").(string); v != "" {
- args.SourceGroupId = v
- }
-
- if v := d.Get("source_group_owner_account").(string); v != "" {
- args.SourceGroupOwnerAccount = v
- }
-
- sgId := d.Get("security_group_id").(string)
-
- sgArgs := &ecs.DescribeSecurityGroupAttributeArgs{
- SecurityGroupId: sgId,
- RegionId: getRegion(d, meta),
- }
-
- group, err := conn.DescribeSecurityGroupAttribute(sgArgs)
- if err != nil {
- return nil, fmt.Errorf("Error get security group %s error: %#v", sgId, err)
- }
-
- if v := d.Get("nic_type").(string); v != "" {
- if (group != nil && group.VpcId != "") || args.SourceGroupId != "" {
- if GroupRuleNicType(v) != GroupRuleIntranet {
- return nil, fmt.Errorf("When security group in the vpc or authorizing permission for source security group, " +
- "the nic_type must be 'intranet'.")
- }
- }
- args.NicType = ecs.NicType(v)
- }
-
- args.SecurityGroupId = sgId
-
- return args, nil
-}
-
-func buildAliyunSecurityEgressArgs(d *schema.ResourceData, meta interface{}) (*ecs.AuthorizeSecurityGroupEgressArgs, error) {
- conn := meta.(*AliyunClient).ecsconn
-
- args := &ecs.AuthorizeSecurityGroupEgressArgs{
- RegionId: getRegion(d, meta),
- }
-
- if v := d.Get("ip_protocol").(string); v != "" {
- args.IpProtocol = ecs.IpProtocol(v)
- }
-
- if v := d.Get("port_range").(string); v != "" {
- args.PortRange = v
- }
-
- if v := d.Get("policy").(string); v != "" {
- args.Policy = ecs.PermissionPolicy(v)
- }
-
- if v := d.Get("priority").(int); v != 0 {
- args.Priority = v
- }
-
- if v := d.Get("cidr_ip").(string); v != "" {
- args.DestCidrIp = v
- }
-
- if v := d.Get("source_security_group_id").(string); v != "" {
- args.DestGroupId = v
- }
-
- if v := d.Get("source_group_owner_account").(string); v != "" {
- args.DestGroupOwnerAccount = v
- }
-
- sgId := d.Get("security_group_id").(string)
-
- sgArgs := &ecs.DescribeSecurityGroupAttributeArgs{
- SecurityGroupId: sgId,
- RegionId: getRegion(d, meta),
- }
-
- group, err := conn.DescribeSecurityGroupAttribute(sgArgs)
- if err != nil {
- return nil, fmt.Errorf("Error get security group %s error: %#v", sgId, err)
- }
-
- if v := d.Get("nic_type").(string); v != "" {
- if (group != nil && group.VpcId != "") || args.DestGroupId != "" {
- if GroupRuleNicType(v) != GroupRuleIntranet {
- return nil, fmt.Errorf("When security group in the vpc or authorizing permission for destination security group, " +
- "the nic_type must be 'intranet'.")
- }
- }
- args.NicType = ecs.NicType(v)
- }
-
- args.SecurityGroupId = sgId
-
- return args, nil
-}
diff --git a/builtin/providers/alicloud/resource_alicloud_security_group_rule_test.go b/builtin/providers/alicloud/resource_alicloud_security_group_rule_test.go
deleted file mode 100644
index 0792966f2..000000000
--- a/builtin/providers/alicloud/resource_alicloud_security_group_rule_test.go
+++ /dev/null
@@ -1,428 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
- "log"
- "regexp"
- "strings"
- "testing"
-)
-
-func TestAccAlicloudSecurityGroupRule_Ingress(t *testing.T) {
- var pt ecs.PermissionType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_security_group_rule.ingress",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckSecurityGroupRuleDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccSecurityGroupRuleIngress,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckSecurityGroupRuleExists(
- "alicloud_security_group_rule.ingress", &pt),
- resource.TestCheckResourceAttr(
- "alicloud_security_group_rule.ingress",
- "priority",
- "1"),
- resource.TestCheckResourceAttr(
- "alicloud_security_group_rule.ingress",
- "nic_type",
- "internet"),
- resource.TestCheckResourceAttr(
- "alicloud_security_group_rule.ingress",
- "ip_protocol",
- "tcp"),
- ),
- },
- },
- })
-
-}
-
-func TestAccAlicloudSecurityGroupRule_Egress(t *testing.T) {
- var pt ecs.PermissionType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_security_group_rule.egress",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckSecurityGroupRuleDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccSecurityGroupRuleEgress,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckSecurityGroupRuleExists(
- "alicloud_security_group_rule.egress", &pt),
- resource.TestCheckResourceAttr(
- "alicloud_security_group_rule.egress",
- "port_range",
- "80/80"),
- resource.TestCheckResourceAttr(
- "alicloud_security_group_rule.egress",
- "ip_protocol",
- "udp"),
- ),
- },
- },
- })
-
-}
-
-func TestAccAlicloudSecurityGroupRule_EgressDefaultNicType(t *testing.T) {
- var pt ecs.PermissionType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_security_group_rule.egress",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckSecurityGroupRuleDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccSecurityGroupRuleEgress_emptyNicType,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckSecurityGroupRuleExists(
- "alicloud_security_group_rule.egress", &pt),
- resource.TestCheckResourceAttr(
- "alicloud_security_group_rule.egress",
- "port_range",
- "80/80"),
- resource.TestCheckResourceAttr(
- "alicloud_security_group_rule.egress",
- "nic_type",
- "internet"),
- ),
- },
- },
- })
-
-}
-
-func TestAccAlicloudSecurityGroupRule_Vpc_Ingress(t *testing.T) {
- var pt ecs.PermissionType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_security_group_rule.ingress",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckSecurityGroupRuleDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccSecurityGroupRuleVpcIngress,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckSecurityGroupRuleExists(
- "alicloud_security_group_rule.ingress", &pt),
- resource.TestCheckResourceAttr(
- "alicloud_security_group_rule.ingress",
- "port_range",
- "1/200"),
- resource.TestCheckResourceAttr(
- "alicloud_security_group_rule.ingress",
- "ip_protocol",
- "udp"),
- ),
- },
- },
- })
-
-}
-
-func TestAccAlicloudSecurityGroupRule_MissParameterSourceCidrIp(t *testing.T) {
- var pt ecs.PermissionType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_security_group_rule.egress",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckSecurityGroupRuleDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccSecurityGroupRule_missingSourceCidrIp,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckSecurityGroupRuleExists(
- "alicloud_security_group_rule.egress", &pt),
- resource.TestCheckResourceAttr(
- "alicloud_security_group_rule.egress",
- "port_range",
- "80/80"),
- resource.TestCheckResourceAttr(
- "alicloud_security_group_rule.egress",
- "nic_type",
- "internet"),
- resource.TestCheckResourceAttr(
- "alicloud_security_group_rule.egress",
- "ip_protocol",
- "udp"),
- ),
- },
- },
- })
-
-}
-
-func TestAccAlicloudSecurityGroupRule_SourceSecurityGroup(t *testing.T) {
- var pt ecs.PermissionType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_security_group_rule.ingress",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckSecurityGroupRuleDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccSecurityGroupRuleSourceSecurityGroup,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckSecurityGroupRuleExists(
- "alicloud_security_group_rule.ingress", &pt),
- resource.TestCheckResourceAttr(
- "alicloud_security_group_rule.ingress",
- "port_range",
- "3306/3306"),
- resource.TestMatchResourceAttr(
- "alicloud_security_group_rule.ingress",
- "source_security_group_id",
- regexp.MustCompile("^sg-[a-zA-Z0-9_]+")),
- resource.TestCheckResourceAttr(
- "alicloud_security_group_rule.ingress",
- "cidr_ip",
- ""),
- ),
- },
- },
- })
-
-}
-
-func testAccCheckSecurityGroupRuleExists(n string, m *ecs.PermissionType) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No SecurityGroup Rule ID is set")
- }
-
- client := testAccProvider.Meta().(*AliyunClient)
- log.Printf("[WARN]get sg rule %s", rs.Primary.ID)
- parts := strings.Split(rs.Primary.ID, ":")
- // securityGroupId, direction, nicType, ipProtocol, portRange
- rule, err := client.DescribeSecurityGroupRule(parts[0], parts[1], parts[4], parts[2], parts[3])
-
- if err != nil {
- return err
- }
-
- if rule == nil {
- return fmt.Errorf("SecurityGroup not found")
- }
-
- *m = *rule
- return nil
- }
-}
-
-func testAccCheckSecurityGroupRuleDestroy(s *terraform.State) error {
- client := testAccProvider.Meta().(*AliyunClient)
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "alicloud_security_group_rule" {
- continue
- }
-
- parts := strings.Split(rs.Primary.ID, ":")
- rule, err := client.DescribeSecurityGroupRule(parts[0], parts[1], parts[4], parts[2], parts[3])
-
- if rule != nil {
- return fmt.Errorf("Error SecurityGroup Rule still exist")
- }
-
- // Verify the error is what we want
- if err != nil {
- // Verify the error is what we want
- e, _ := err.(*common.Error)
- if e.ErrorResponse.Code == InvalidSecurityGroupIdNotFound {
- continue
- }
- return err
- }
- }
-
- return nil
-}
-
-const testAccSecurityGroupRuleIngress = `
-resource "alicloud_security_group" "foo" {
- name = "sg_foo"
-}
-
-resource "alicloud_security_group_rule" "ingress" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "internet"
- policy = "accept"
- port_range = "1/200"
- priority = 1
- security_group_id = "${alicloud_security_group.foo.id}"
- cidr_ip = "10.159.6.18/12"
-}
-
-
-`
-
-const testAccSecurityGroupRuleEgress = `
-resource "alicloud_security_group" "foo" {
- name = "sg_foo"
-}
-
-
-resource "alicloud_security_group_rule" "egress" {
- type = "egress"
- ip_protocol = "udp"
- nic_type = "internet"
- policy = "accept"
- port_range = "80/80"
- priority = 1
- security_group_id = "${alicloud_security_group.foo.id}"
- cidr_ip = "10.159.6.18/12"
-}
-
-`
-
-const testAccSecurityGroupRuleEgress_emptyNicType = `
-resource "alicloud_security_group" "foo" {
- name = "sg_foo"
-}
-
-resource "alicloud_security_group_rule" "egress" {
- type = "egress"
- ip_protocol = "udp"
- policy = "accept"
- port_range = "80/80"
- priority = 1
- security_group_id = "${alicloud_security_group.foo.id}"
- cidr_ip = "10.159.6.18/12"
-}
-
-`
-
-const testAccSecurityGroupRuleVpcIngress = `
-resource "alicloud_security_group" "foo" {
- vpc_id = "${alicloud_vpc.vpc.id}"
- name = "sg_foo"
-}
-
-resource "alicloud_vpc" "vpc" {
- cidr_block = "10.1.0.0/21"
-}
-
-resource "alicloud_security_group_rule" "ingress" {
- type = "ingress"
- ip_protocol = "udp"
- nic_type = "intranet"
- policy = "accept"
- port_range = "1/200"
- priority = 1
- security_group_id = "${alicloud_security_group.foo.id}"
- cidr_ip = "10.159.6.18/12"
-}
-
-`
-const testAccSecurityGroupRule_missingSourceCidrIp = `
-resource "alicloud_security_group" "foo" {
- name = "sg_foo"
-}
-
-resource "alicloud_security_group_rule" "egress" {
- security_group_id = "${alicloud_security_group.foo.id}"
- type = "egress"
- cidr_ip= "0.0.0.0/0"
- policy = "accept"
- ip_protocol= "udp"
- port_range= "80/80"
- priority= 1
-}
-
-`
-
-const testAccSecurityGroupRuleMultiIngress = `
-resource "alicloud_security_group" "foo" {
- name = "sg_foo"
-}
-
-resource "alicloud_security_group_rule" "ingress1" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "internet"
- policy = "accept"
- port_range = "1/200"
- priority = 1
- security_group_id = "${alicloud_security_group.foo.id}"
- cidr_ip = "10.159.6.18/12"
-}
-
-resource "alicloud_security_group_rule" "ingress2" {
- type = "ingress"
- ip_protocol = "gre"
- nic_type = "internet"
- policy = "accept"
- port_range = "-1/-1"
- priority = 1
- security_group_id = "${alicloud_security_group.foo.id}"
- cidr_ip = "127.0.1.18/16"
-}
-
-`
-
-const testAccSecurityGroupRuleSourceSecurityGroup = `
-resource "alicloud_security_group" "foo" {
- name = "sg_foo"
-}
-
-resource "alicloud_security_group" "bar" {
- name = "sg_bar"
-}
-
-resource "alicloud_security_group_rule" "ingress" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "intranet"
- policy = "accept"
- port_range = "3306/3306"
- priority = 50
- security_group_id = "${alicloud_security_group.bar.id}"
- source_security_group_id = "${alicloud_security_group.foo.id}"
-}
-
-
-`
diff --git a/builtin/providers/alicloud/resource_alicloud_security_group_test.go b/builtin/providers/alicloud/resource_alicloud_security_group_test.go
deleted file mode 100644
index 19211bc1f..000000000
--- a/builtin/providers/alicloud/resource_alicloud_security_group_test.go
+++ /dev/null
@@ -1,151 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "testing"
-
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
- "log"
-)
-
-func TestAccAlicloudSecurityGroup_basic(t *testing.T) {
- var sg ecs.DescribeSecurityGroupAttributeResponse
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_security_group.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckSecurityGroupDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccSecurityGroupConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckSecurityGroupExists(
- "alicloud_security_group.foo", &sg),
- resource.TestCheckResourceAttr(
- "alicloud_security_group.foo",
- "name",
- "sg_test"),
- ),
- },
- },
- })
-
-}
-
-func TestAccAlicloudSecurityGroup_withVpc(t *testing.T) {
- var sg ecs.DescribeSecurityGroupAttributeResponse
- var vpc ecs.VpcSetType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_security_group.foo",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckSecurityGroupDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccSecurityGroupConfig_withVpc,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckSecurityGroupExists(
- "alicloud_security_group.foo", &sg),
- testAccCheckVpcExists(
- "alicloud_vpc.vpc", &vpc),
- ),
- },
- },
- })
-
-}
-
-func testAccCheckSecurityGroupExists(n string, sg *ecs.DescribeSecurityGroupAttributeResponse) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No SecurityGroup ID is set")
- }
-
- client := testAccProvider.Meta().(*AliyunClient)
- conn := client.ecsconn
- args := &ecs.DescribeSecurityGroupAttributeArgs{
- RegionId: client.Region,
- SecurityGroupId: rs.Primary.ID,
- }
- d, err := conn.DescribeSecurityGroupAttribute(args)
-
- log.Printf("[WARN] security group id %#v", rs.Primary.ID)
-
- if err != nil {
- return err
- }
-
- if d == nil {
- return fmt.Errorf("SecurityGroup not found")
- }
-
- *sg = *d
- return nil
- }
-}
-
-func testAccCheckSecurityGroupDestroy(s *terraform.State) error {
- client := testAccProvider.Meta().(*AliyunClient)
- conn := client.ecsconn
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "alicloud_security_group" {
- continue
- }
-
- // Try to find the SecurityGroup
- args := &ecs.DescribeSecurityGroupsArgs{
- RegionId: client.Region,
- }
-
- groups, _, err := conn.DescribeSecurityGroups(args)
-
- for _, sg := range groups {
- if sg.SecurityGroupId == rs.Primary.ID {
- return fmt.Errorf("Error SecurityGroup still exist")
- }
- }
-
- // Verify the error is what we want
- if err != nil {
- return err
- }
- }
-
- return nil
-}
-
-const testAccSecurityGroupConfig = `
-resource "alicloud_security_group" "foo" {
- name = "sg_test"
-}
-`
-
-const testAccSecurityGroupConfig_withVpc = `
-resource "alicloud_security_group" "foo" {
- vpc_id = "${alicloud_vpc.vpc.id}"
-}
-
-resource "alicloud_vpc" "vpc" {
- cidr_block = "10.1.0.0/21"
-}
-`
diff --git a/builtin/providers/alicloud/resource_alicloud_slb.go b/builtin/providers/alicloud/resource_alicloud_slb.go
deleted file mode 100644
index de8a8906d..000000000
--- a/builtin/providers/alicloud/resource_alicloud_slb.go
+++ /dev/null
@@ -1,611 +0,0 @@
-package alicloud
-
-import (
- "bytes"
- "fmt"
- "strings"
-
- "errors"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/slb"
- "github.com/hashicorp/terraform/helper/hashcode"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
- "time"
-)
-
-func resourceAliyunSlb() *schema.Resource {
- return &schema.Resource{
- Create: resourceAliyunSlbCreate,
- Read: resourceAliyunSlbRead,
- Update: resourceAliyunSlbUpdate,
- Delete: resourceAliyunSlbDelete,
-
- Schema: map[string]*schema.Schema{
- "name": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ValidateFunc: validateSlbName,
- Computed: true,
- },
-
- "internet": &schema.Schema{
- Type: schema.TypeBool,
- Optional: true,
- ForceNew: true,
- },
-
- "vswitch_id": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
-
- "internet_charge_type": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- Default: "paybytraffic",
- ValidateFunc: validateSlbInternetChargeType,
- },
-
- "bandwidth": &schema.Schema{
- Type: schema.TypeInt,
- Optional: true,
- ValidateFunc: validateSlbBandwidth,
- Computed: true,
- },
-
- "listener": &schema.Schema{
- Type: schema.TypeSet,
- Optional: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "instance_port": &schema.Schema{
- Type: schema.TypeInt,
- ValidateFunc: validateInstancePort,
- Required: true,
- },
-
- "lb_port": &schema.Schema{
- Type: schema.TypeInt,
- ValidateFunc: validateInstancePort,
- Required: true,
- },
-
- "lb_protocol": &schema.Schema{
- Type: schema.TypeString,
- ValidateFunc: validateInstanceProtocol,
- Required: true,
- },
-
- "bandwidth": &schema.Schema{
- Type: schema.TypeInt,
- ValidateFunc: validateSlbListenerBandwidth,
- Required: true,
- },
- "scheduler": &schema.Schema{
- Type: schema.TypeString,
- ValidateFunc: validateSlbListenerScheduler,
- Optional: true,
- Default: slb.WRRScheduler,
- },
- //http & https
- "sticky_session": &schema.Schema{
- Type: schema.TypeString,
- ValidateFunc: validateAllowedStringValue([]string{
- string(slb.OnFlag),
- string(slb.OffFlag)}),
- Optional: true,
- Default: slb.OffFlag,
- },
- //http & https
- "sticky_session_type": &schema.Schema{
- Type: schema.TypeString,
- ValidateFunc: validateAllowedStringValue([]string{
- string(slb.InsertStickySessionType),
- string(slb.ServerStickySessionType)}),
- Optional: true,
- },
- //http & https
- "cookie_timeout": &schema.Schema{
- Type: schema.TypeInt,
- ValidateFunc: validateSlbListenerCookieTimeout,
- Optional: true,
- },
- //http & https
- "cookie": &schema.Schema{
- Type: schema.TypeString,
- ValidateFunc: validateSlbListenerCookie,
- Optional: true,
- },
- //tcp & udp
- "persistence_timeout": &schema.Schema{
- Type: schema.TypeInt,
- ValidateFunc: validateSlbListenerPersistenceTimeout,
- Optional: true,
- Default: 0,
- },
- //http & https
- "health_check": &schema.Schema{
- Type: schema.TypeString,
- ValidateFunc: validateAllowedStringValue([]string{
- string(slb.OnFlag),
- string(slb.OffFlag)}),
- Optional: true,
- Default: slb.OffFlag,
- },
- //tcp
- "health_check_type": &schema.Schema{
- Type: schema.TypeString,
- ValidateFunc: validateAllowedStringValue([]string{
- string(slb.TCPHealthCheckType),
- string(slb.HTTPHealthCheckType)}),
- Optional: true,
- Default: slb.TCPHealthCheckType,
- },
- //http & https & tcp
- "health_check_domain": &schema.Schema{
- Type: schema.TypeString,
- ValidateFunc: validateSlbListenerHealthCheckDomain,
- Optional: true,
- },
- //http & https & tcp
- "health_check_uri": &schema.Schema{
- Type: schema.TypeString,
- ValidateFunc: validateSlbListenerHealthCheckUri,
- Optional: true,
- },
- "health_check_connect_port": &schema.Schema{
- Type: schema.TypeInt,
- ValidateFunc: validateSlbListenerHealthCheckConnectPort,
- Optional: true,
- },
- "healthy_threshold": &schema.Schema{
- Type: schema.TypeInt,
- ValidateFunc: validateIntegerInRange(1, 10),
- Optional: true,
- },
- "unhealthy_threshold": &schema.Schema{
- Type: schema.TypeInt,
- ValidateFunc: validateIntegerInRange(1, 10),
- Optional: true,
- },
-
- "health_check_timeout": &schema.Schema{
- Type: schema.TypeInt,
- ValidateFunc: validateIntegerInRange(1, 50),
- Optional: true,
- },
- "health_check_interval": &schema.Schema{
- Type: schema.TypeInt,
- ValidateFunc: validateIntegerInRange(1, 5),
- Optional: true,
- },
- //http & https & tcp
- "health_check_http_code": &schema.Schema{
- Type: schema.TypeString,
- ValidateFunc: validateAllowedSplitStringValue([]string{
- string(slb.HTTP_2XX),
- string(slb.HTTP_3XX),
- string(slb.HTTP_4XX),
- string(slb.HTTP_5XX)}, ","),
- Optional: true,
- },
- //https
- "ssl_certificate_id": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- },
- //https
- //"ca_certificate_id": &schema.Schema{
- // Type: schema.TypeString,
- // Optional: true,
- //},
- },
- },
- Set: resourceAliyunSlbListenerHash,
- },
-
- //deprecated
- "instances": &schema.Schema{
- Type: schema.TypeSet,
- Elem: &schema.Schema{Type: schema.TypeString},
- Optional: true,
- Set: schema.HashString,
- },
-
- "address": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- },
- }
-}
-
-func resourceAliyunSlbCreate(d *schema.ResourceData, meta interface{}) error {
-
- slbconn := meta.(*AliyunClient).slbconn
-
- var slbName string
- if v, ok := d.GetOk("name"); ok {
- slbName = v.(string)
- } else {
- slbName = resource.PrefixedUniqueId("tf-lb-")
- d.Set("name", slbName)
- }
-
- slbArgs := &slb.CreateLoadBalancerArgs{
- RegionId: getRegion(d, meta),
- LoadBalancerName: slbName,
- }
-
- if internet, ok := d.GetOk("internet"); ok && internet.(bool) {
- slbArgs.AddressType = slb.InternetAddressType
- d.Set("internet", true)
- } else {
- slbArgs.AddressType = slb.IntranetAddressType
- d.Set("internet", false)
- }
-
- if v, ok := d.GetOk("internet_charge_type"); ok && v.(string) != "" {
- slbArgs.InternetChargeType = slb.InternetChargeType(v.(string))
- }
-
- if v, ok := d.GetOk("bandwidth"); ok && v.(int) != 0 {
- slbArgs.Bandwidth = v.(int)
- }
-
- if v, ok := d.GetOk("vswitch_id"); ok && v.(string) != "" {
- slbArgs.VSwitchId = v.(string)
- }
- slb, err := slbconn.CreateLoadBalancer(slbArgs)
- if err != nil {
- return err
- }
-
- d.SetId(slb.LoadBalancerId)
-
- return resourceAliyunSlbUpdate(d, meta)
-}
-
-func resourceAliyunSlbRead(d *schema.ResourceData, meta interface{}) error {
- slbconn := meta.(*AliyunClient).slbconn
- loadBalancer, err := slbconn.DescribeLoadBalancerAttribute(d.Id())
- if err != nil {
- if notFoundError(err) {
- d.SetId("")
- return nil
- }
-
- return err
- }
-
- if loadBalancer == nil {
- d.SetId("")
- return nil
- }
-
- d.Set("name", loadBalancer.LoadBalancerName)
-
- if loadBalancer.AddressType == slb.InternetAddressType {
- d.Set("internal", true)
- } else {
- d.Set("internal", false)
- }
- d.Set("internet_charge_type", loadBalancer.InternetChargeType)
- d.Set("bandwidth", loadBalancer.Bandwidth)
- d.Set("vswitch_id", loadBalancer.VSwitchId)
- d.Set("address", loadBalancer.Address)
-
- return nil
-}
-
-func resourceAliyunSlbUpdate(d *schema.ResourceData, meta interface{}) error {
-
- slbconn := meta.(*AliyunClient).slbconn
-
- d.Partial(true)
-
- if d.HasChange("name") {
- err := slbconn.SetLoadBalancerName(d.Id(), d.Get("name").(string))
- if err != nil {
- return err
- }
-
- d.SetPartial("name")
- }
-
- if d.Get("internet") == true && d.Get("internet_charge_type") == "paybybandwidth" {
- //don't intranet web and paybybandwidth, then can modify bandwidth
- if d.HasChange("bandwidth") {
- args := &slb.ModifyLoadBalancerInternetSpecArgs{
- LoadBalancerId: d.Id(),
- Bandwidth: d.Get("bandwidth").(int),
- }
- err := slbconn.ModifyLoadBalancerInternetSpec(args)
- if err != nil {
- return err
- }
-
- d.SetPartial("bandwidth")
- }
- }
-
- if d.HasChange("listener") {
- o, n := d.GetChange("listener")
- os := o.(*schema.Set)
- ns := n.(*schema.Set)
-
- remove, _ := expandListeners(os.Difference(ns).List())
- add, _ := expandListeners(ns.Difference(os).List())
-
- if len(remove) > 0 {
- for _, listener := range remove {
- err := slbconn.DeleteLoadBalancerListener(d.Id(), listener.LoadBalancerPort)
- if err != nil {
- return fmt.Errorf("Failure removing outdated SLB listeners: %#v", err)
- }
- }
- }
-
- if len(add) > 0 {
- for _, listener := range add {
- err := createListener(slbconn, d.Id(), listener)
- if err != nil {
- return fmt.Errorf("Failure add SLB listeners: %#v", err)
- }
- }
- }
-
- d.SetPartial("listener")
- }
-
- // If we currently have instances, or did have instances,
- // we want to figure out what to add and remove from the load
- // balancer
- if d.HasChange("instances") {
- o, n := d.GetChange("instances")
- os := o.(*schema.Set)
- ns := n.(*schema.Set)
- remove := expandBackendServers(os.Difference(ns).List())
- add := expandBackendServers(ns.Difference(os).List())
-
- if len(add) > 0 {
- _, err := slbconn.AddBackendServers(d.Id(), add)
- if err != nil {
- return err
- }
- }
- if len(remove) > 0 {
- removeBackendServers := make([]string, 0, len(remove))
- for _, e := range remove {
- removeBackendServers = append(removeBackendServers, e.ServerId)
- }
- _, err := slbconn.RemoveBackendServers(d.Id(), removeBackendServers)
- if err != nil {
- return err
- }
- }
-
- d.SetPartial("instances")
- }
-
- d.Partial(false)
-
- return resourceAliyunSlbRead(d, meta)
-}
-
-func resourceAliyunSlbDelete(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).slbconn
-
- return resource.Retry(5*time.Minute, func() *resource.RetryError {
- err := conn.DeleteLoadBalancer(d.Id())
-
- if err != nil {
- return resource.NonRetryableError(err)
- }
-
- loadBalancer, err := conn.DescribeLoadBalancerAttribute(d.Id())
- if err != nil {
- e, _ := err.(*common.Error)
- if e.ErrorResponse.Code == LoadBalancerNotFound {
- return nil
- }
- return resource.NonRetryableError(err)
- }
- if loadBalancer != nil {
- return resource.RetryableError(fmt.Errorf("LoadBalancer in use - trying again while it deleted."))
- }
- return nil
- })
-}
-
-func resourceAliyunSlbListenerHash(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%d-", m["instance_port"].(int)))
- buf.WriteString(fmt.Sprintf("%d-", m["lb_port"].(int)))
- buf.WriteString(fmt.Sprintf("%s-",
- strings.ToLower(m["lb_protocol"].(string))))
-
- buf.WriteString(fmt.Sprintf("%d-", m["bandwidth"].(int)))
-
- if v, ok := m["ssl_certificate_id"]; ok {
- buf.WriteString(fmt.Sprintf("%s-", v.(string)))
- }
-
- return hashcode.String(buf.String())
-}
-
-func createListener(conn *slb.Client, loadBalancerId string, listener *Listener) error {
-
- errTypeJudge := func(err error) error {
- if err != nil {
- if listenerType, ok := err.(*ListenerErr); ok {
- if listenerType.ErrType == HealthCheckErrType {
- return fmt.Errorf("When the HealthCheck is %s, then related HealthCheck parameter "+
- "must have.", slb.OnFlag)
- } else if listenerType.ErrType == StickySessionErrType {
- return fmt.Errorf("When the StickySession is %s, then StickySessionType parameter "+
- "must have.", slb.OnFlag)
- } else if listenerType.ErrType == CookieTimeOutErrType {
- return fmt.Errorf("When the StickySession is %s and StickySessionType is %s, "+
- "then CookieTimeout parameter must have.", slb.OnFlag, slb.InsertStickySessionType)
- } else if listenerType.ErrType == CookieErrType {
- return fmt.Errorf("When the StickySession is %s and StickySessionType is %s, "+
- "then Cookie parameter must have.", slb.OnFlag, slb.ServerStickySessionType)
- }
- return fmt.Errorf("slb listener check errtype not found.")
- }
- }
- return nil
- }
-
- if listener.Protocol == strings.ToLower("tcp") {
-
- args := getTcpListenerArgs(loadBalancerId, listener)
-
- if err := conn.CreateLoadBalancerTCPListener(&args); err != nil {
- return err
- }
- } else if listener.Protocol == strings.ToLower("http") {
- args, argsErr := getHttpListenerArgs(loadBalancerId, listener)
- if paramErr := errTypeJudge(argsErr); paramErr != nil {
- return paramErr
- }
-
- if err := conn.CreateLoadBalancerHTTPListener(&args); err != nil {
- return err
- }
- } else if listener.Protocol == strings.ToLower("https") {
- listenerType, err := getHttpListenerType(loadBalancerId, listener)
- if paramErr := errTypeJudge(err); paramErr != nil {
- return paramErr
- }
-
- args := &slb.CreateLoadBalancerHTTPSListenerArgs{
- HTTPListenerType: listenerType,
- }
- if listener.SSLCertificateId == "" {
- return fmt.Errorf("Server Certificated Id cann't be null")
- }
-
- args.ServerCertificateId = listener.SSLCertificateId
-
- if err := conn.CreateLoadBalancerHTTPSListener(args); err != nil {
- return err
- }
- } else if listener.Protocol == strings.ToLower("udp") {
- args := getUdpListenerArgs(loadBalancerId, listener)
-
- if err := conn.CreateLoadBalancerUDPListener(&args); err != nil {
- return err
- }
- }
-
- if err := conn.StartLoadBalancerListener(loadBalancerId, listener.LoadBalancerPort); err != nil {
- return err
- }
-
- return nil
-}
-
-func getTcpListenerArgs(loadBalancerId string, listener *Listener) slb.CreateLoadBalancerTCPListenerArgs {
- args := slb.CreateLoadBalancerTCPListenerArgs{
- LoadBalancerId: loadBalancerId,
- ListenerPort: listener.LoadBalancerPort,
- BackendServerPort: listener.InstancePort,
- Bandwidth: listener.Bandwidth,
- Scheduler: listener.Scheduler,
- PersistenceTimeout: listener.PersistenceTimeout,
- HealthCheckType: listener.HealthCheckType,
- HealthCheckDomain: listener.HealthCheckDomain,
- HealthCheckURI: listener.HealthCheckURI,
- HealthCheckConnectPort: listener.HealthCheckConnectPort,
- HealthyThreshold: listener.HealthyThreshold,
- UnhealthyThreshold: listener.UnhealthyThreshold,
- HealthCheckConnectTimeout: listener.HealthCheckTimeout,
- HealthCheckInterval: listener.HealthCheckInterval,
- HealthCheckHttpCode: listener.HealthCheckHttpCode,
- }
- return args
-}
-
-func getUdpListenerArgs(loadBalancerId string, listener *Listener) slb.CreateLoadBalancerUDPListenerArgs {
- args := slb.CreateLoadBalancerUDPListenerArgs{
- LoadBalancerId: loadBalancerId,
- ListenerPort: listener.LoadBalancerPort,
- BackendServerPort: listener.InstancePort,
- Bandwidth: listener.Bandwidth,
- PersistenceTimeout: listener.PersistenceTimeout,
- HealthCheckConnectTimeout: listener.HealthCheckTimeout,
- HealthCheckInterval: listener.HealthCheckInterval,
- }
- return args
-}
-
-func getHttpListenerType(loadBalancerId string, listener *Listener) (listenType slb.HTTPListenerType, err error) {
-
- if listener.HealthCheck == slb.OnFlag {
- if listener.HealthCheckURI == "" || listener.HealthCheckDomain == "" || listener.HealthCheckConnectPort == 0 ||
- listener.HealthyThreshold == 0 || listener.UnhealthyThreshold == 0 || listener.HealthCheckTimeout == 0 ||
- listener.HealthCheckHttpCode == "" || listener.HealthCheckInterval == 0 {
-
- errMsg := errors.New("err: HealthCheck empty.")
- return listenType, &ListenerErr{HealthCheckErrType, errMsg}
- }
- }
-
- if listener.StickySession == slb.OnFlag {
- if listener.StickySessionType == "" {
- errMsg := errors.New("err: stickySession empty.")
- return listenType, &ListenerErr{StickySessionErrType, errMsg}
- }
-
- if listener.StickySessionType == slb.InsertStickySessionType {
- if listener.CookieTimeout == 0 {
- errMsg := errors.New("err: cookieTimeout empty.")
- return listenType, &ListenerErr{CookieTimeOutErrType, errMsg}
- }
- } else if listener.StickySessionType == slb.ServerStickySessionType {
- if listener.Cookie == "" {
- errMsg := errors.New("err: cookie empty.")
- return listenType, &ListenerErr{CookieErrType, errMsg}
- }
- }
- }
-
- httpListenertType := slb.HTTPListenerType{
- LoadBalancerId: loadBalancerId,
- ListenerPort: listener.LoadBalancerPort,
- BackendServerPort: listener.InstancePort,
- Bandwidth: listener.Bandwidth,
- Scheduler: listener.Scheduler,
- HealthCheck: listener.HealthCheck,
- StickySession: listener.StickySession,
- StickySessionType: listener.StickySessionType,
- CookieTimeout: listener.CookieTimeout,
- Cookie: listener.Cookie,
- HealthCheckDomain: listener.HealthCheckDomain,
- HealthCheckURI: listener.HealthCheckURI,
- HealthCheckConnectPort: listener.HealthCheckConnectPort,
- HealthyThreshold: listener.HealthyThreshold,
- UnhealthyThreshold: listener.UnhealthyThreshold,
- HealthCheckTimeout: listener.HealthCheckTimeout,
- HealthCheckInterval: listener.HealthCheckInterval,
- HealthCheckHttpCode: listener.HealthCheckHttpCode,
- }
-
- return httpListenertType, err
-}
-
-func getHttpListenerArgs(loadBalancerId string, listener *Listener) (listenType slb.CreateLoadBalancerHTTPListenerArgs, err error) {
- httpListenerType, err := getHttpListenerType(loadBalancerId, listener)
- if err != nil {
- return listenType, err
- }
-
- httpArgs := slb.CreateLoadBalancerHTTPListenerArgs(httpListenerType)
- return httpArgs, err
-}
diff --git a/builtin/providers/alicloud/resource_alicloud_slb_attachment.go b/builtin/providers/alicloud/resource_alicloud_slb_attachment.go
deleted file mode 100644
index 74e13c26c..000000000
--- a/builtin/providers/alicloud/resource_alicloud_slb_attachment.go
+++ /dev/null
@@ -1,148 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/hashicorp/terraform/helper/schema"
- "strings"
-)
-
-func resourceAliyunSlbAttachment() *schema.Resource {
- return &schema.Resource{
- Create: resourceAliyunSlbAttachmentCreate,
- Read: resourceAliyunSlbAttachmentRead,
- Update: resourceAliyunSlbAttachmentUpdate,
- Delete: resourceAliyunSlbAttachmentDelete,
-
- Schema: map[string]*schema.Schema{
-
- "slb_id": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
-
- "instances": &schema.Schema{
- Type: schema.TypeSet,
- Elem: &schema.Schema{Type: schema.TypeString},
- Required: true,
- Set: schema.HashString,
- },
-
- "backend_servers": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- },
- }
-}
-
-func resourceAliyunSlbAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
-
- slbId := d.Get("slb_id").(string)
-
- slbconn := meta.(*AliyunClient).slbconn
-
- loadBalancer, err := slbconn.DescribeLoadBalancerAttribute(slbId)
- if err != nil {
- if notFoundError(err) {
- d.SetId("")
- return fmt.Errorf("Special SLB Id not found: %#v", err)
- }
-
- return err
- }
-
- d.SetId(loadBalancer.LoadBalancerId)
-
- return resourceAliyunSlbAttachmentUpdate(d, meta)
-}
-
-func resourceAliyunSlbAttachmentRead(d *schema.ResourceData, meta interface{}) error {
-
- slbconn := meta.(*AliyunClient).slbconn
- loadBalancer, err := slbconn.DescribeLoadBalancerAttribute(d.Id())
- if err != nil {
- if notFoundError(err) {
- d.SetId("")
- return nil
- }
- return fmt.Errorf("Read special SLB Id not found: %#v", err)
- }
-
- if loadBalancer == nil {
- d.SetId("")
- return nil
- }
-
- backendServerType := loadBalancer.BackendServers
- servers := backendServerType.BackendServer
- instanceIds := make([]string, 0, len(servers))
- if len(servers) > 0 {
- for _, e := range servers {
- instanceIds = append(instanceIds, e.ServerId)
- }
- if err != nil {
- return err
- }
- }
-
- d.Set("slb_id", d.Id())
- d.Set("instances", instanceIds)
- d.Set("backend_servers", strings.Join(instanceIds, ","))
-
- return nil
-}
-
-func resourceAliyunSlbAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
-
- slbconn := meta.(*AliyunClient).slbconn
- if d.HasChange("instances") {
- o, n := d.GetChange("instances")
- os := o.(*schema.Set)
- ns := n.(*schema.Set)
- remove := expandBackendServers(os.Difference(ns).List())
- add := expandBackendServers(ns.Difference(os).List())
-
- if len(add) > 0 {
- _, err := slbconn.AddBackendServers(d.Id(), add)
- if err != nil {
- return err
- }
- }
- if len(remove) > 0 {
- removeBackendServers := make([]string, 0, len(remove))
- for _, e := range remove {
- removeBackendServers = append(removeBackendServers, e.ServerId)
- }
- _, err := slbconn.RemoveBackendServers(d.Id(), removeBackendServers)
- if err != nil {
- return err
- }
- }
-
- }
-
- return resourceAliyunSlbAttachmentRead(d, meta)
-
-}
-
-func resourceAliyunSlbAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
-
- slbconn := meta.(*AliyunClient).slbconn
- o := d.Get("instances")
- os := o.(*schema.Set)
- remove := expandBackendServers(os.List())
-
- if len(remove) > 0 {
- removeBackendServers := make([]string, 0, len(remove))
- for _, e := range remove {
- removeBackendServers = append(removeBackendServers, e.ServerId)
- }
- _, err := slbconn.RemoveBackendServers(d.Id(), removeBackendServers)
- if err != nil {
- return err
- }
- }
-
- return nil
-}
diff --git a/builtin/providers/alicloud/resource_alicloud_slb_attachment_test.go b/builtin/providers/alicloud/resource_alicloud_slb_attachment_test.go
deleted file mode 100644
index 5caa4a710..000000000
--- a/builtin/providers/alicloud/resource_alicloud_slb_attachment_test.go
+++ /dev/null
@@ -1,131 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/slb"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
- "log"
- "testing"
-)
-
-func TestAccAlicloudSlbAttachment_basic(t *testing.T) {
- var slb slb.LoadBalancerType
-
- testCheckAttr := func() resource.TestCheckFunc {
- return func(*terraform.State) error {
- log.Printf("testCheckAttr slb BackendServers is: %#v", slb.BackendServers)
- return nil
- }
- }
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_slb_attachment.foo",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckSlbDestroy,
- Steps: []resource.TestStep{
- //test internet_charge_type is paybybandwidth
- resource.TestStep{
- Config: testAccSlbAttachment,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckSlbExists("alicloud_slb_attachment.foo", &slb),
- testCheckAttr(),
- testAccCheckAttachment("alicloud_instance.foo", &slb),
- ),
- },
- },
- })
-}
-
-func testAccCheckAttachment(n string, slb *slb.LoadBalancerType) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No ECS ID is set")
- }
-
- ecsInstanceId := rs.Primary.ID
-
- backendServers := slb.BackendServers.BackendServer
-
- if len(backendServers) == 0 {
- return fmt.Errorf("no SLB backendServer: %#v", backendServers)
- }
-
- log.Printf("slb bacnendservers: %#v", backendServers)
-
- backendServersInstanceId := backendServers[0].ServerId
-
- if ecsInstanceId != backendServersInstanceId {
- return fmt.Errorf("SLB attachment check invalid: ECS instance %s is not equal SLB backendServer %s",
- ecsInstanceId, backendServersInstanceId)
- }
- return nil
- }
-}
-
-const testAccSlbAttachment = `
-resource "alicloud_security_group" "foo" {
- name = "tf_test_foo"
- description = "foo"
-}
-
-resource "alicloud_security_group_rule" "http-in" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "internet"
- policy = "accept"
- port_range = "80/80"
- priority = 1
- security_group_id = "${alicloud_security_group.foo.id}"
- cidr_ip = "0.0.0.0/0"
-}
-
-resource "alicloud_security_group_rule" "ssh-in" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "internet"
- policy = "accept"
- port_range = "22/22"
- priority = 1
- security_group_id = "${alicloud_security_group.foo.id}"
- cidr_ip = "0.0.0.0/0"
-}
-
-resource "alicloud_instance" "foo" {
- # cn-beijing
- image_id = "ubuntu_140405_64_40G_cloudinit_20161115.vhd"
-
- # series II
- instance_type = "ecs.n1.medium"
- internet_charge_type = "PayByBandwidth"
- internet_max_bandwidth_out = "5"
- system_disk_category = "cloud_efficiency"
- io_optimized = "optimized"
-
- security_groups = ["${alicloud_security_group.foo.id}"]
- instance_name = "test_foo"
-}
-
-resource "alicloud_slb" "foo" {
- name = "tf_test_slb_bind"
- internet_charge_type = "paybybandwidth"
- bandwidth = "5"
- internet = "true"
-}
-
-resource "alicloud_slb_attachment" "foo" {
- slb_id = "${alicloud_slb.foo.id}"
- instances = ["${alicloud_instance.foo.id}"]
-}
-
-`
diff --git a/builtin/providers/alicloud/resource_alicloud_slb_test.go b/builtin/providers/alicloud/resource_alicloud_slb_test.go
deleted file mode 100644
index 42308f187..000000000
--- a/builtin/providers/alicloud/resource_alicloud_slb_test.go
+++ /dev/null
@@ -1,322 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/slb"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
- "log"
- "testing"
-)
-
-func TestAccAlicloudSlb_basic(t *testing.T) {
- var slb slb.LoadBalancerType
-
- testCheckAttr := func() resource.TestCheckFunc {
- return func(*terraform.State) error {
- log.Printf("testCheckAttr slb AddressType is: %s", slb.AddressType)
- return nil
- }
- }
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_slb.bindwidth",
-
- Providers: testAccProviders,
- CheckDestroy: testAccCheckSlbDestroy,
- Steps: []resource.TestStep{
- //test internet_charge_type is paybybandwidth
- resource.TestStep{
- Config: testAccSlbBindWidth,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckSlbExists("alicloud_slb.bindwidth", &slb),
- testCheckAttr(),
- resource.TestCheckResourceAttr(
- "alicloud_slb.bindwidth", "internet_charge_type", "paybybandwidth"),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudSlb_traffic(t *testing.T) {
- var slb slb.LoadBalancerType
-
- testCheckAttr := func() resource.TestCheckFunc {
- return func(*terraform.State) error {
- log.Printf("testCheckAttr slb AddressType is: %s", slb.AddressType)
- return nil
- }
- }
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_slb.traffic",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckSlbDestroy,
- Steps: []resource.TestStep{
- //test internet_charge_type is paybytraffic
- resource.TestStep{
- Config: testAccSlbTraffic,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckSlbExists("alicloud_slb.traffic", &slb),
- testCheckAttr(),
- resource.TestCheckResourceAttr(
- "alicloud_slb.traffic", "name", "tf_test_slb_classic"),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudSlb_listener(t *testing.T) {
- var slb slb.LoadBalancerType
-
- testListener := func() resource.TestCheckFunc {
- return func(*terraform.State) error {
- listenerPorts := slb.ListenerPorts.ListenerPort[0]
- if listenerPorts != 2001 {
- return fmt.Errorf("bad loadbalancer listener: %#v", listenerPorts)
- }
-
- return nil
- }
- }
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_slb.listener",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckSlbDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccSlbListener,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckSlbExists("alicloud_slb.listener", &slb),
- resource.TestCheckResourceAttr(
- "alicloud_slb.listener", "name", "tf_test_slb"),
- testAccCheckListenersExists("alicloud_slb.listener", &slb, "http"),
- testListener(),
- ),
- },
- },
- })
-}
-
-func TestAccAlicloudSlb_vpc(t *testing.T) {
- var slb slb.LoadBalancerType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_slb.vpc",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckSlbDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccSlb4Vpc,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckSlbExists("alicloud_slb.vpc", &slb),
- resource.TestCheckResourceAttr(
- "alicloud_slb.vpc", "name", "tf_test_slb_vpc"),
- ),
- },
- },
- })
-}
-
-func testAccCheckSlbExists(n string, slb *slb.LoadBalancerType) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No SLB ID is set")
- }
-
- client := testAccProvider.Meta().(*AliyunClient)
- instance, err := client.DescribeLoadBalancerAttribute(rs.Primary.ID)
-
- if err != nil {
- return err
- }
- if instance == nil {
- return fmt.Errorf("SLB not found")
- }
-
- *slb = *instance
- return nil
- }
-}
-
-func testAccCheckListenersExists(n string, slb *slb.LoadBalancerType, p string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No SLB ID is set")
- }
-
- client := testAccProvider.Meta().(*AliyunClient)
- instance, err := client.DescribeLoadBalancerAttribute(rs.Primary.ID)
-
- if err != nil {
- return err
- }
- if instance == nil {
- return fmt.Errorf("SLB not found")
- }
-
- exist := false
- for _, listener := range instance.ListenerPortsAndProtocol.ListenerPortAndProtocol {
- if listener.ListenerProtocol == p {
- exist = true
- break
- }
- }
-
- if !exist {
- return fmt.Errorf("The %s protocol Listener not found.", p)
- }
- return nil
- }
-}
-
-func testAccCheckSlbDestroy(s *terraform.State) error {
- client := testAccProvider.Meta().(*AliyunClient)
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "alicloud_slb" {
- continue
- }
-
- // Try to find the Slb
- instance, err := client.DescribeLoadBalancerAttribute(rs.Primary.ID)
-
- if instance != nil {
- return fmt.Errorf("SLB still exist")
- }
-
- if err != nil {
- e, _ := err.(*common.Error)
- // Verify the error is what we want
- if e.ErrorResponse.Code != LoadBalancerNotFound {
- return err
- }
-
- }
-
- }
-
- return nil
-}
-
-const testAccSlbBindWidth = `
-resource "alicloud_slb" "bindwidth" {
- name = "tf_test_slb_bindwidth"
- internet_charge_type = "paybybandwidth"
- bandwidth = 5
- internet = true
-}
-`
-
-const testAccSlbTraffic = `
-resource "alicloud_slb" "traffic" {
- name = "tf_test_slb_classic"
-}
-`
-
-const testAccSlbListener = `
-resource "alicloud_slb" "listener" {
- name = "tf_test_slb"
- internet_charge_type = "paybybandwidth"
- bandwidth = 5
- internet = true
- listener = [
- {
- "instance_port" = "2111"
- "lb_port" = "21"
- "lb_protocol" = "tcp"
- "bandwidth" = 1
- "persistence_timeout" = 500
- "health_check_type" = "http"
- },{
- "instance_port" = "8000"
- "lb_port" = "80"
- "lb_protocol" = "http"
- "sticky_session" = "on"
- "sticky_session_type" = "insert"
- "cookie_timeout" = 800
- "bandwidth" = 1
- },{
- "instance_port" = "8001"
- "lb_port" = "81"
- "lb_protocol" = "http"
- "sticky_session" = "on"
- "sticky_session_type" = "server"
- "cookie" = "testslblistenercookie"
- "cookie_timeout" = 1800
- "health_check" = "on"
- "health_check_domain" = "$_ip"
- "health_check_uri" = "/console"
- "health_check_connect_port" = 20
- "healthy_threshold" = 8
- "unhealthy_threshold" = 8
- "health_check_timeout" = 8
- "health_check_interval" = 4
- "health_check_http_code" = "http_2xx"
- "bandwidth" = 1
- },{
- "instance_port" = "2001"
- "lb_port" = "2001"
- "lb_protocol" = "udp"
- "bandwidth" = 1
- "persistence_timeout" = 700
- }]
-}
-`
-
-const testAccSlb4Vpc = `
-data "alicloud_zones" "default" {
- "available_resource_creation"= "VSwitch"
-}
-
-resource "alicloud_vpc" "foo" {
- name = "tf_test_foo"
- cidr_block = "172.16.0.0/12"
-}
-
-resource "alicloud_vswitch" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- cidr_block = "172.16.0.0/21"
- availability_zone = "${data.alicloud_zones.default.zones.0.id}"
-}
-
-resource "alicloud_slb" "vpc" {
- name = "tf_test_slb_vpc"
- //internet_charge_type = "paybybandwidth"
- vswitch_id = "${alicloud_vswitch.foo.id}"
-}
-`
diff --git a/builtin/providers/alicloud/resource_alicloud_snat.go b/builtin/providers/alicloud/resource_alicloud_snat.go
deleted file mode 100644
index 887d50388..000000000
--- a/builtin/providers/alicloud/resource_alicloud_snat.go
+++ /dev/null
@@ -1,134 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func resourceAliyunSnatEntry() *schema.Resource {
- return &schema.Resource{
- Create: resourceAliyunSnatEntryCreate,
- Read: resourceAliyunSnatEntryRead,
- Update: resourceAliyunSnatEntryUpdate,
- Delete: resourceAliyunSnatEntryDelete,
-
- Schema: map[string]*schema.Schema{
- "snat_table_id": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
- "source_vswitch_id": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
- "snat_ip": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
- },
- }
-}
-
-func resourceAliyunSnatEntryCreate(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).vpcconn
-
- args := &ecs.CreateSnatEntryArgs{
- RegionId: getRegion(d, meta),
- SnatTableId: d.Get("snat_table_id").(string),
- SourceVSwitchId: d.Get("source_vswitch_id").(string),
- SnatIp: d.Get("snat_ip").(string),
- }
-
- resp, err := conn.CreateSnatEntry(args)
- if err != nil {
- return fmt.Errorf("CreateSnatEntry got error: %#v", err)
- }
-
- d.SetId(resp.SnatEntryId)
- d.Set("snat_table_id", d.Get("snat_table_id").(string))
-
- return resourceAliyunSnatEntryRead(d, meta)
-}
-
-func resourceAliyunSnatEntryRead(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
-
- snatEntry, err := client.DescribeSnatEntry(d.Get("snat_table_id").(string), d.Id())
-
- if err != nil {
- if notFoundError(err) {
- return nil
- }
- return err
- }
-
- d.Set("snat_table_id", snatEntry.SnatTableId)
- d.Set("source_vswitch_id", snatEntry.SourceVSwitchId)
- d.Set("snat_ip", snatEntry.SnatIp)
-
- return nil
-}
-
-func resourceAliyunSnatEntryUpdate(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
- conn := client.vpcconn
-
- snatEntry, err := client.DescribeSnatEntry(d.Get("snat_table_id").(string), d.Id())
- if err != nil {
- return err
- }
-
- d.Partial(true)
- attributeUpdate := false
- args := &ecs.ModifySnatEntryArgs{
- RegionId: getRegion(d, meta),
- SnatTableId: snatEntry.SnatTableId,
- SnatEntryId: snatEntry.SnatEntryId,
- }
-
- if d.HasChange("snat_ip") {
- d.SetPartial("snat_ip")
- var snat_ip string
- if v, ok := d.GetOk("snat_ip"); ok {
- snat_ip = v.(string)
- } else {
- return fmt.Errorf("cann't change snap_ip to empty string")
- }
- args.SnatIp = snat_ip
-
- attributeUpdate = true
- }
-
- if attributeUpdate {
- if err := conn.ModifySnatEntry(args); err != nil {
- return err
- }
- }
-
- d.Partial(false)
-
- return resourceAliyunSnatEntryRead(d, meta)
-}
-
-func resourceAliyunSnatEntryDelete(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
- conn := client.vpcconn
-
- snatEntryId := d.Id()
- snatTableId := d.Get("snat_table_id").(string)
-
- args := &ecs.DeleteSnatEntryArgs{
- RegionId: getRegion(d, meta),
- SnatTableId: snatTableId,
- SnatEntryId: snatEntryId,
- }
-
- if err := conn.DeleteSnatEntry(args); err != nil {
- return err
- }
-
- return nil
-}
diff --git a/builtin/providers/alicloud/resource_alicloud_snat_test.go b/builtin/providers/alicloud/resource_alicloud_snat_test.go
deleted file mode 100644
index 673ff59dd..000000000
--- a/builtin/providers/alicloud/resource_alicloud_snat_test.go
+++ /dev/null
@@ -1,180 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
- "testing"
-)
-
-func TestAccAlicloudSnat_basic(t *testing.T) {
- var snat ecs.SnatEntrySetType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_snat_entry.foo",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckSnatEntryDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccSnatEntryConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckSnatEntryExists(
- "alicloud_snat_entry.foo", &snat),
- ),
- },
- resource.TestStep{
- Config: testAccSnatEntryUpdate,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckSnatEntryExists(
- "alicloud_snat_entry.foo", &snat),
- ),
- },
- },
- })
-
-}
-
-func testAccCheckSnatEntryDestroy(s *terraform.State) error {
- client := testAccProvider.Meta().(*AliyunClient)
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "alicloud_snat_entry" {
- continue
- }
-
- // Try to find the Snat entry
- instance, err := client.DescribeSnatEntry(rs.Primary.Attributes["snat_table_id"], rs.Primary.ID)
-
- //this special deal cause the DescribeSnatEntry can't find the records would be throw "cant find the snatTable error"
- if instance.SnatEntryId == "" {
- return nil
- }
-
- if instance.SnatEntryId != "" {
- return fmt.Errorf("Snat entry still exist")
- }
-
- if err != nil {
- // Verify the error is what we want
- e, _ := err.(*common.Error)
-
- if !notFoundError(e) {
- return err
- }
- }
-
- }
-
- return nil
-}
-
-func testAccCheckSnatEntryExists(n string, snat *ecs.SnatEntrySetType) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No SnatEntry ID is set")
- }
-
- client := testAccProvider.Meta().(*AliyunClient)
- instance, err := client.DescribeSnatEntry(rs.Primary.Attributes["snat_table_id"], rs.Primary.ID)
-
- if err != nil {
- return err
- }
- if instance.SnatEntryId == "" {
- return fmt.Errorf("SnatEntry not found")
- }
-
- *snat = instance
- return nil
- }
-}
-
-const testAccSnatEntryConfig = `
-data "alicloud_zones" "default" {
- "available_resource_creation"= "VSwitch"
-}
-
-resource "alicloud_vpc" "foo" {
- name = "tf_test_foo"
- cidr_block = "172.16.0.0/12"
-}
-
-resource "alicloud_vswitch" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- cidr_block = "172.16.0.0/21"
- availability_zone = "${data.alicloud_zones.default.zones.2.id}"
-}
-
-resource "alicloud_nat_gateway" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- spec = "Small"
- name = "test_foo"
- bandwidth_packages = [{
- ip_count = 2
- bandwidth = 5
- zone = "${data.alicloud_zones.default.zones.2.id}"
- },{
- ip_count = 1
- bandwidth = 6
- zone = "${data.alicloud_zones.default.zones.2.id}"
- }]
- depends_on = [
- "alicloud_vswitch.foo"]
-}
-resource "alicloud_snat_entry" "foo"{
- snat_table_id = "${alicloud_nat_gateway.foo.snat_table_ids}"
- source_vswitch_id = "${alicloud_vswitch.foo.id}"
- snat_ip = "${alicloud_nat_gateway.foo.bandwidth_packages.0.public_ip_addresses}"
-}
-`
-
-const testAccSnatEntryUpdate = `
-data "alicloud_zones" "default" {
- "available_resource_creation"= "VSwitch"
-}
-
-resource "alicloud_vpc" "foo" {
- name = "tf_test_foo"
- cidr_block = "172.16.0.0/12"
-}
-
-resource "alicloud_vswitch" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- cidr_block = "172.16.0.0/21"
- availability_zone = "${data.alicloud_zones.default.zones.2.id}"
-}
-
-resource "alicloud_nat_gateway" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- spec = "Small"
- name = "test_foo"
- bandwidth_packages = [{
- ip_count = 2
- bandwidth = 5
- zone = "${data.alicloud_zones.default.zones.2.id}"
- },{
- ip_count = 1
- bandwidth = 6
- zone = "${data.alicloud_zones.default.zones.2.id}"
- }]
- depends_on = [
- "alicloud_vswitch.foo"]
-}
-resource "alicloud_snat_entry" "foo"{
- snat_table_id = "${alicloud_nat_gateway.foo.snat_table_ids}"
- source_vswitch_id = "${alicloud_vswitch.foo.id}"
- snat_ip = "${alicloud_nat_gateway.foo.bandwidth_packages.1.public_ip_addresses}"
-}
-`
diff --git a/builtin/providers/alicloud/resource_alicloud_vpc.go b/builtin/providers/alicloud/resource_alicloud_vpc.go
deleted file mode 100644
index 5362c638a..000000000
--- a/builtin/providers/alicloud/resource_alicloud_vpc.go
+++ /dev/null
@@ -1,201 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
- "strings"
- "time"
-)
-
-func resourceAliyunVpc() *schema.Resource {
- return &schema.Resource{
- Create: resourceAliyunVpcCreate,
- Read: resourceAliyunVpcRead,
- Update: resourceAliyunVpcUpdate,
- Delete: resourceAliyunVpcDelete,
-
- Schema: map[string]*schema.Schema{
- "cidr_block": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- ValidateFunc: validateCIDRNetworkAddress,
- },
- "name": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
- if len(value) < 2 || len(value) > 128 {
- errors = append(errors, fmt.Errorf("%s cannot be longer than 128 characters", k))
- }
-
- if strings.HasPrefix(value, "http://") || strings.HasPrefix(value, "https://") {
- errors = append(errors, fmt.Errorf("%s cannot starts with http:// or https://", k))
- }
-
- return
- },
- },
- "description": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
- if len(value) < 2 || len(value) > 256 {
- errors = append(errors, fmt.Errorf("%s cannot be longer than 256 characters", k))
-
- }
- return
- },
- },
- "router_id": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- "router_table_id": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- },
- }
-}
-
-func resourceAliyunVpcCreate(d *schema.ResourceData, meta interface{}) error {
-
- args, err := buildAliyunVpcArgs(d, meta)
- if err != nil {
- return err
- }
-
- ecsconn := meta.(*AliyunClient).ecsconn
-
- var vpc *ecs.CreateVpcResponse
- err = resource.Retry(3*time.Minute, func() *resource.RetryError {
- resp, err := ecsconn.CreateVpc(args)
- if err != nil {
- if e, ok := err.(*common.Error); ok && (e.StatusCode == 400 || e.Code == UnknownError) {
- return resource.RetryableError(fmt.Errorf("Vpc is still creating result from some unknown error -- try again"))
- }
- return resource.NonRetryableError(err)
- }
- vpc = resp
- return nil
- })
- if err != nil {
- return fmt.Errorf("Create vpc got an error :%#v", err)
- }
-
- d.SetId(vpc.VpcId)
- d.Set("router_table_id", vpc.RouteTableId)
-
- err = ecsconn.WaitForVpcAvailable(args.RegionId, vpc.VpcId, 60)
- if err != nil {
- return fmt.Errorf("Timeout when WaitForVpcAvailable")
- }
-
- return resourceAliyunVpcUpdate(d, meta)
-}
-
-func resourceAliyunVpcRead(d *schema.ResourceData, meta interface{}) error {
-
- client := meta.(*AliyunClient)
-
- vpc, err := client.DescribeVpc(d.Id())
- if err != nil {
- return err
- }
-
- if vpc == nil {
- d.SetId("")
- return nil
- }
-
- d.Set("cidr_block", vpc.CidrBlock)
- d.Set("name", vpc.VpcName)
- d.Set("description", vpc.Description)
- d.Set("router_id", vpc.VRouterId)
-
- return nil
-}
-
-func resourceAliyunVpcUpdate(d *schema.ResourceData, meta interface{}) error {
-
- conn := meta.(*AliyunClient).ecsconn
-
- d.Partial(true)
-
- attributeUpdate := false
- args := &ecs.ModifyVpcAttributeArgs{
- VpcId: d.Id(),
- }
-
- if d.HasChange("name") {
- d.SetPartial("name")
- args.VpcName = d.Get("name").(string)
-
- attributeUpdate = true
- }
-
- if d.HasChange("description") {
- d.SetPartial("description")
- args.Description = d.Get("description").(string)
-
- attributeUpdate = true
- }
-
- if attributeUpdate {
- if err := conn.ModifyVpcAttribute(args); err != nil {
- return err
- }
- }
-
- d.Partial(false)
-
- return resourceAliyunVpcRead(d, meta)
-}
-
-func resourceAliyunVpcDelete(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).ecsconn
-
- return resource.Retry(5*time.Minute, func() *resource.RetryError {
- err := conn.DeleteVpc(d.Id())
-
- if err != nil {
- return resource.RetryableError(fmt.Errorf("Vpc in use - trying again while it is deleted."))
- }
-
- args := &ecs.DescribeVpcsArgs{
- RegionId: getRegion(d, meta),
- VpcId: d.Id(),
- }
- vpc, _, descErr := conn.DescribeVpcs(args)
- if descErr != nil {
- return resource.NonRetryableError(err)
- } else if vpc == nil || len(vpc) < 1 {
- return nil
- }
-
- return resource.RetryableError(fmt.Errorf("Vpc in use - trying again while it is deleted."))
- })
-}
-
-func buildAliyunVpcArgs(d *schema.ResourceData, meta interface{}) (*ecs.CreateVpcArgs, error) {
- args := &ecs.CreateVpcArgs{
- RegionId: getRegion(d, meta),
- CidrBlock: d.Get("cidr_block").(string),
- }
-
- if v := d.Get("name").(string); v != "" {
- args.VpcName = v
- }
-
- if v := d.Get("description").(string); v != "" {
- args.Description = v
- }
-
- return args, nil
-}
diff --git a/builtin/providers/alicloud/resource_alicloud_vpc_test.go b/builtin/providers/alicloud/resource_alicloud_vpc_test.go
deleted file mode 100644
index b67c65001..000000000
--- a/builtin/providers/alicloud/resource_alicloud_vpc_test.go
+++ /dev/null
@@ -1,140 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "testing"
-
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAlicloudVpc_basic(t *testing.T) {
- var vpc ecs.VpcSetType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_vpc.foo",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckVpcDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccVpcConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckVpcExists("alicloud_vpc.foo", &vpc),
- resource.TestCheckResourceAttr(
- "alicloud_vpc.foo", "cidr_block", "172.16.0.0/12"),
- resource.TestCheckResourceAttrSet(
- "alicloud_vpc.foo", "router_id"),
- resource.TestCheckResourceAttrSet(
- "alicloud_vpc.foo", "router_table_id"),
- ),
- },
- },
- })
-
-}
-
-func TestAccAlicloudVpc_update(t *testing.T) {
- var vpc ecs.VpcSetType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckVpcDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccVpcConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckVpcExists("alicloud_vpc.foo", &vpc),
- resource.TestCheckResourceAttr(
- "alicloud_vpc.foo", "cidr_block", "172.16.0.0/12"),
- ),
- },
- resource.TestStep{
- Config: testAccVpcConfigUpdate,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckVpcExists("alicloud_vpc.foo", &vpc),
- resource.TestCheckResourceAttr(
- "alicloud_vpc.foo", "name", "tf_test_bar"),
- ),
- },
- },
- })
-}
-
-func testAccCheckVpcExists(n string, vpc *ecs.VpcSetType) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No VPC ID is set")
- }
-
- client := testAccProvider.Meta().(*AliyunClient)
- instance, err := client.DescribeVpc(rs.Primary.ID)
-
- if err != nil {
- return err
- }
- if instance == nil {
- return fmt.Errorf("VPC not found")
- }
-
- *vpc = *instance
- return nil
- }
-}
-
-func testAccCheckVpcDestroy(s *terraform.State) error {
- client := testAccProvider.Meta().(*AliyunClient)
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "alicloud_vpc" {
- continue
- }
-
- // Try to find the VPC
- instance, err := client.DescribeVpc(rs.Primary.ID)
-
- if instance != nil {
- return fmt.Errorf("VPCs still exist")
- }
-
- if err != nil {
- // Verify the error is what we want
- e, _ := err.(*common.Error)
-
- if e.ErrorResponse.Code != "InvalidVpcID.NotFound" {
- return err
- }
- }
-
- }
-
- return nil
-}
-
-const testAccVpcConfig = `
-resource "alicloud_vpc" "foo" {
- name = "tf_test_foo"
- cidr_block = "172.16.0.0/12"
-}
-`
-
-const testAccVpcConfigUpdate = `
-resource "alicloud_vpc" "foo" {
- cidr_block = "172.16.0.0/12"
- name = "tf_test_bar"
-}
-`
diff --git a/builtin/providers/alicloud/resource_alicloud_vroute_entry.go b/builtin/providers/alicloud/resource_alicloud_vroute_entry.go
deleted file mode 100644
index b71e92ffe..000000000
--- a/builtin/providers/alicloud/resource_alicloud_vroute_entry.go
+++ /dev/null
@@ -1,145 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/schema"
- "strings"
-)
-
-func resourceAliyunRouteEntry() *schema.Resource {
- return &schema.Resource{
- Create: resourceAliyunRouteEntryCreate,
- Read: resourceAliyunRouteEntryRead,
- Delete: resourceAliyunRouteEntryDelete,
-
- Schema: map[string]*schema.Schema{
- "router_id": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
- "route_table_id": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
- "destination_cidrblock": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
- "nexthop_type": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- ValidateFunc: validateRouteEntryNextHopType,
- },
- "nexthop_id": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
- },
- }
-}
-
-func resourceAliyunRouteEntryCreate(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).ecsconn
-
- rtId := d.Get("route_table_id").(string)
- rId := d.Get("router_id").(string)
- cidr := d.Get("destination_cidrblock").(string)
- nt := d.Get("nexthop_type").(string)
- ni := d.Get("nexthop_id").(string)
-
- args, err := buildAliyunRouteEntryArgs(d, meta)
- if err != nil {
- return err
- }
- err = conn.CreateRouteEntry(args)
-
- if err != nil {
- return err
- }
- // route_table_id:router_id:destination_cidrblock:nexthop_type:nexthop_id
- d.SetId(rtId + ":" + rId + ":" + cidr + ":" + nt + ":" + ni)
- d.Set("router_id", rId)
-
- if err := conn.WaitForAllRouteEntriesAvailable(rId, rtId, defaultTimeout); err != nil {
- return fmt.Errorf("WaitFor route entry got error: %#v", err)
- }
- return resourceAliyunRouteEntryRead(d, meta)
-}
-
-func resourceAliyunRouteEntryRead(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AliyunClient)
- parts := strings.Split(d.Id(), ":")
- rtId := parts[0]
- //rId := parts[1]
- cidr := parts[2]
- nexthop_type := parts[3]
- nexthop_id := parts[4]
-
- en, err := client.QueryRouteEntry(rtId, cidr, nexthop_type, nexthop_id)
-
- if err != nil {
- if notFoundError(err) {
- d.SetId("")
- return nil
- }
- return fmt.Errorf("Error route entry: %#v", err)
- }
-
- d.Set("route_table_id", en.RouteTableId)
- d.Set("destination_cidrblock", en.DestinationCidrBlock)
- d.Set("nexthop_type", en.NextHopType)
- d.Set("nexthop_id", en.InstanceId)
- return nil
-}
-
-func resourceAliyunRouteEntryDelete(d *schema.ResourceData, meta interface{}) error {
- con := meta.(*AliyunClient).ecsconn
- args, err := buildAliyunRouteEntryDeleteArgs(d, meta)
-
- if err != nil {
- return err
- }
- return con.DeleteRouteEntry(args)
-}
-
-func buildAliyunRouteEntryArgs(d *schema.ResourceData, meta interface{}) (*ecs.CreateRouteEntryArgs, error) {
-
- args := &ecs.CreateRouteEntryArgs{
- RouteTableId: d.Get("route_table_id").(string),
- DestinationCidrBlock: d.Get("destination_cidrblock").(string),
- }
-
- if v := d.Get("nexthop_type").(string); v != "" {
- args.NextHopType = ecs.NextHopType(v)
- }
-
- if v := d.Get("nexthop_id").(string); v != "" {
- args.NextHopId = v
- }
-
- return args, nil
-}
-
-func buildAliyunRouteEntryDeleteArgs(d *schema.ResourceData, meta interface{}) (*ecs.DeleteRouteEntryArgs, error) {
-
- args := &ecs.DeleteRouteEntryArgs{
- RouteTableId: d.Get("route_table_id").(string),
- DestinationCidrBlock: d.Get("destination_cidrblock").(string),
- }
-
- if v := d.Get("destination_cidrblock").(string); v != "" {
- args.DestinationCidrBlock = v
- }
-
- if v := d.Get("nexthop_id").(string); v != "" {
- args.NextHopId = v
- }
-
- return args, nil
-}
diff --git a/builtin/providers/alicloud/resource_alicloud_vroute_entry_test.go b/builtin/providers/alicloud/resource_alicloud_vroute_entry_test.go
deleted file mode 100644
index 8726de64c..000000000
--- a/builtin/providers/alicloud/resource_alicloud_vroute_entry_test.go
+++ /dev/null
@@ -1,186 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
- "strings"
- "testing"
-)
-
-func TestAccAlicloudRouteEntry_Basic(t *testing.T) {
- var rt ecs.RouteTableSetType
- var rn ecs.RouteEntrySetType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_route_entry.foo",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckRouteEntryDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccRouteEntryConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckRouteTableEntryExists(
- "alicloud_route_entry.foo", &rt, &rn),
- resource.TestCheckResourceAttrSet(
- "alicloud_route_entry.foo", "nexthop_id"),
- ),
- },
- },
- })
-
-}
-
-func testAccCheckRouteTableExists(rtId string, t *ecs.RouteTableSetType) error {
- client := testAccProvider.Meta().(*AliyunClient)
- //query route table
- rt, terr := client.QueryRouteTableById(rtId)
-
- if terr != nil {
- return terr
- }
-
- if rt == nil {
- return fmt.Errorf("Route Table not found")
- }
-
- *t = *rt
- return nil
-}
-
-func testAccCheckRouteEntryExists(routeTableId, cidrBlock, nextHopType, nextHopId string, e *ecs.RouteEntrySetType) error {
- client := testAccProvider.Meta().(*AliyunClient)
- //query route table entry
- re, rerr := client.QueryRouteEntry(routeTableId, cidrBlock, nextHopType, nextHopId)
-
- if rerr != nil {
- return rerr
- }
-
- if re == nil {
- return fmt.Errorf("Route Table Entry not found")
- }
-
- *e = *re
- return nil
-}
-
-func testAccCheckRouteTableEntryExists(n string, t *ecs.RouteTableSetType, e *ecs.RouteEntrySetType) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No Route Entry ID is set")
- }
-
- parts := strings.Split(rs.Primary.ID, ":")
-
- //query route table
- err := testAccCheckRouteTableExists(parts[0], t)
-
- if err != nil {
- return err
- }
- //query route table entry
- err = testAccCheckRouteEntryExists(parts[0], parts[2], parts[3], parts[4], e)
- return err
- }
-}
-
-func testAccCheckRouteEntryDestroy(s *terraform.State) error {
- client := testAccProvider.Meta().(*AliyunClient)
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "alicloud_route_entry" {
- continue
- }
-
- parts := strings.Split(rs.Primary.ID, ":")
- re, err := client.QueryRouteEntry(parts[0], parts[2], parts[3], parts[4])
-
- if re != nil {
- return fmt.Errorf("Error Route Entry still exist")
- }
-
- // Verify the error is what we want
- if err != nil {
- if notFoundError(err) {
- return nil
- }
- return err
- }
- }
-
- return nil
-}
-
-const testAccRouteEntryConfig = `
-data "alicloud_zones" "default" {
- "available_resource_creation"= "VSwitch"
-}
-
-resource "alicloud_vpc" "foo" {
- name = "tf_test_foo"
- cidr_block = "10.1.0.0/21"
-}
-
-resource "alicloud_vswitch" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- cidr_block = "10.1.1.0/24"
- availability_zone = "${data.alicloud_zones.default.zones.0.id}"
-}
-
-resource "alicloud_route_entry" "foo" {
- router_id = "${alicloud_vpc.foo.router_id}"
- route_table_id = "${alicloud_vpc.foo.router_table_id}"
- destination_cidrblock = "172.11.1.1/32"
- nexthop_type = "Instance"
- nexthop_id = "${alicloud_instance.foo.id}"
-}
-
-resource "alicloud_security_group" "tf_test_foo" {
- name = "tf_test_foo"
- description = "foo"
- vpc_id = "${alicloud_vpc.foo.id}"
-}
-
-resource "alicloud_security_group_rule" "ingress" {
- type = "ingress"
- ip_protocol = "tcp"
- nic_type = "intranet"
- policy = "accept"
- port_range = "22/22"
- priority = 1
- security_group_id = "${alicloud_security_group.tf_test_foo.id}"
- cidr_ip = "0.0.0.0/0"
-}
-
-resource "alicloud_instance" "foo" {
- # cn-beijing
- security_groups = ["${alicloud_security_group.tf_test_foo.id}"]
-
- vswitch_id = "${alicloud_vswitch.foo.id}"
- allocate_public_ip = true
-
- # series II
- instance_charge_type = "PostPaid"
- instance_type = "ecs.n1.small"
- internet_charge_type = "PayByTraffic"
- internet_max_bandwidth_out = 5
- io_optimized = "optimized"
-
- system_disk_category = "cloud_efficiency"
- image_id = "ubuntu_140405_64_40G_cloudinit_20161115.vhd"
- instance_name = "test_foo"
-}
-
-`
diff --git a/builtin/providers/alicloud/resource_alicloud_vswitch.go b/builtin/providers/alicloud/resource_alicloud_vswitch.go
deleted file mode 100644
index 89e24108e..000000000
--- a/builtin/providers/alicloud/resource_alicloud_vswitch.go
+++ /dev/null
@@ -1,232 +0,0 @@
-package alicloud
-
-import (
- "fmt"
-
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
- "log"
- "time"
-)
-
-func resourceAliyunSubnet() *schema.Resource {
- return &schema.Resource{
- Create: resourceAliyunSwitchCreate,
- Read: resourceAliyunSwitchRead,
- Update: resourceAliyunSwitchUpdate,
- Delete: resourceAliyunSwitchDelete,
-
- Schema: map[string]*schema.Schema{
- "availability_zone": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
- "vpc_id": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
- "cidr_block": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- ValidateFunc: validateSwitchCIDRNetworkAddress,
- },
- "name": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- },
- "description": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- },
- },
- }
-}
-
-func resourceAliyunSwitchCreate(d *schema.ResourceData, meta interface{}) error {
-
- conn := meta.(*AliyunClient).ecsconn
-
- args, err := buildAliyunSwitchArgs(d, meta)
- if err != nil {
- return err
- }
-
- var vswitchID string
- err = resource.Retry(3*time.Minute, func() *resource.RetryError {
- vswId, err := conn.CreateVSwitch(args)
- if err != nil {
- if e, ok := err.(*common.Error); ok && (e.StatusCode == 400 || e.Code == UnknownError) {
- return resource.RetryableError(fmt.Errorf("Vswitch is still creating result from some unknown error -- try again"))
- }
- return resource.NonRetryableError(err)
- }
- vswitchID = vswId
- return nil
- })
-
- if err != nil {
- return fmt.Errorf("Create subnet got an error :%s", err)
- }
-
- d.SetId(vswitchID)
-
- err = conn.WaitForVSwitchAvailable(args.VpcId, vswitchID, 60)
- if err != nil {
- return fmt.Errorf("WaitForVSwitchAvailable got a error: %s", err)
- }
-
- return resourceAliyunSwitchUpdate(d, meta)
-}
-
-func resourceAliyunSwitchRead(d *schema.ResourceData, meta interface{}) error {
-
- conn := meta.(*AliyunClient).ecsconn
-
- args := &ecs.DescribeVSwitchesArgs{
- VpcId: d.Get("vpc_id").(string),
- VSwitchId: d.Id(),
- }
-
- vswitches, _, err := conn.DescribeVSwitches(args)
-
- if err != nil {
- if notFoundError(err) {
- d.SetId("")
- return nil
- }
- return err
- }
-
- if len(vswitches) == 0 {
- d.SetId("")
- return nil
- }
-
- vswitch := vswitches[0]
-
- d.Set("availability_zone", vswitch.ZoneId)
- d.Set("vpc_id", vswitch.VpcId)
- d.Set("cidr_block", vswitch.CidrBlock)
- d.Set("name", vswitch.VSwitchName)
- d.Set("description", vswitch.Description)
-
- return nil
-}
-
-func resourceAliyunSwitchUpdate(d *schema.ResourceData, meta interface{}) error {
-
- conn := meta.(*AliyunClient).ecsconn
-
- d.Partial(true)
-
- attributeUpdate := false
- args := &ecs.ModifyVSwitchAttributeArgs{
- VSwitchId: d.Id(),
- }
-
- if d.HasChange("name") {
- d.SetPartial("name")
- args.VSwitchName = d.Get("name").(string)
-
- attributeUpdate = true
- }
-
- if d.HasChange("description") {
- d.SetPartial("description")
- args.Description = d.Get("description").(string)
-
- attributeUpdate = true
- }
- if attributeUpdate {
- if err := conn.ModifyVSwitchAttribute(args); err != nil {
- return err
- }
-
- }
-
- d.Partial(false)
-
- return resourceAliyunSwitchRead(d, meta)
-}
-
-func resourceAliyunSwitchDelete(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AliyunClient).ecsconn
-
- return resource.Retry(5*time.Minute, func() *resource.RetryError {
- err := conn.DeleteVSwitch(d.Id())
-
- if err != nil {
- e, _ := err.(*common.Error)
- if e.ErrorResponse.Code == VswitcInvalidRegionId {
- log.Printf("[ERROR] Delete Switch is failed.")
- return resource.NonRetryableError(err)
- }
-
- return resource.RetryableError(fmt.Errorf("Switch in use. -- trying again while it is deleted."))
- }
-
- vsw, _, vswErr := conn.DescribeVSwitches(&ecs.DescribeVSwitchesArgs{
- VpcId: d.Get("vpc_id").(string),
- VSwitchId: d.Id(),
- })
-
- if vswErr != nil {
- return resource.NonRetryableError(vswErr)
- } else if vsw == nil || len(vsw) < 1 {
- return nil
- }
-
- return resource.RetryableError(fmt.Errorf("Switch in use. -- trying again while it is deleted."))
- })
-}
-
-func buildAliyunSwitchArgs(d *schema.ResourceData, meta interface{}) (*ecs.CreateVSwitchArgs, error) {
-
- client := meta.(*AliyunClient)
-
- vpcID := d.Get("vpc_id").(string)
-
- vpc, err := client.DescribeVpc(vpcID)
- if err != nil {
- return nil, err
- }
-
- if vpc == nil {
- return nil, fmt.Errorf("vpc_id not found")
- }
-
- zoneID := d.Get("availability_zone").(string)
-
- zone, err := client.DescribeZone(zoneID)
- if err != nil {
- return nil, err
- }
-
- err = client.ResourceAvailable(zone, ecs.ResourceTypeVSwitch)
- if err != nil {
- return nil, err
- }
-
- cidrBlock := d.Get("cidr_block").(string)
-
- args := &ecs.CreateVSwitchArgs{
- VpcId: vpcID,
- ZoneId: zoneID,
- CidrBlock: cidrBlock,
- }
-
- if v, ok := d.GetOk("name"); ok && v != "" {
- args.VSwitchName = v.(string)
- }
-
- if v, ok := d.GetOk("description"); ok && v != "" {
- args.Description = v.(string)
- }
-
- return args, nil
-}
diff --git a/builtin/providers/alicloud/resource_alicloud_vswitch_test.go b/builtin/providers/alicloud/resource_alicloud_vswitch_test.go
deleted file mode 100644
index 1a1a75bd6..000000000
--- a/builtin/providers/alicloud/resource_alicloud_vswitch_test.go
+++ /dev/null
@@ -1,109 +0,0 @@
-package alicloud
-
-import (
- "testing"
-
- "fmt"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAlicloudVswitch_basic(t *testing.T) {
- var vsw ecs.VSwitchSetType
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
-
- // module name
- IDRefreshName: "alicloud_vswitch.foo",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckVswitchDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccVswitchConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckVswitchExists("alicloud_vswitch.foo", &vsw),
- resource.TestCheckResourceAttr(
- "alicloud_vswitch.foo", "cidr_block", "172.16.0.0/21"),
- ),
- },
- },
- })
-
-}
-
-func testAccCheckVswitchExists(n string, vpc *ecs.VSwitchSetType) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No Vswitch ID is set")
- }
-
- client := testAccProvider.Meta().(*AliyunClient)
- instance, err := client.QueryVswitchById(rs.Primary.Attributes["vpc_id"], rs.Primary.ID)
-
- if err != nil {
- return err
- }
- if instance == nil {
- return fmt.Errorf("Vswitch not found")
- }
-
- *vpc = *instance
- return nil
- }
-}
-
-func testAccCheckVswitchDestroy(s *terraform.State) error {
- client := testAccProvider.Meta().(*AliyunClient)
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "alicloud_vswitch" {
- continue
- }
-
- // Try to find the Vswitch
- instance, err := client.QueryVswitchById(rs.Primary.Attributes["vpc_id"], rs.Primary.ID)
-
- if instance != nil {
- return fmt.Errorf("Vswitch still exist")
- }
-
- if err != nil {
- // Verify the error is what we want
- e, _ := err.(*common.Error)
-
- if e.ErrorResponse.Code != "InvalidVswitchID.NotFound" {
- return err
- }
- }
-
- }
-
- return nil
-}
-
-const testAccVswitchConfig = `
-data "alicloud_zones" "default" {
- "available_resource_creation"= "VSwitch"
-}
-
-resource "alicloud_vpc" "foo" {
- name = "tf_test_foo"
- cidr_block = "172.16.0.0/12"
-}
-
-resource "alicloud_vswitch" "foo" {
- vpc_id = "${alicloud_vpc.foo.id}"
- cidr_block = "172.16.0.0/21"
- availability_zone = "${data.alicloud_zones.default.zones.0.id}"
-}
-`
diff --git a/builtin/providers/alicloud/service_alicloud_ecs.go b/builtin/providers/alicloud/service_alicloud_ecs.go
deleted file mode 100644
index 79b6b07fb..000000000
--- a/builtin/providers/alicloud/service_alicloud_ecs.go
+++ /dev/null
@@ -1,259 +0,0 @@
-package alicloud
-
-import (
- "encoding/json"
- "fmt"
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "strings"
-)
-
-func (client *AliyunClient) DescribeImage(imageId string) (*ecs.ImageType, error) {
-
- pagination := common.Pagination{
- PageNumber: 1,
- }
- args := ecs.DescribeImagesArgs{
- Pagination: pagination,
- RegionId: client.Region,
- Status: ecs.ImageStatusAvailable,
- }
-
- var allImages []ecs.ImageType
-
- for {
- images, _, err := client.ecsconn.DescribeImages(&args)
- if err != nil {
- break
- }
-
- if len(images) == 0 {
- break
- }
-
- allImages = append(allImages, images...)
-
- args.Pagination.PageNumber++
- }
-
- if len(allImages) == 0 {
- return nil, common.GetClientErrorFromString("Not found")
- }
-
- var image *ecs.ImageType
- imageIds := []string{}
- for _, im := range allImages {
- if im.ImageId == imageId {
- image = &im
- }
- imageIds = append(imageIds, im.ImageId)
- }
-
- if image == nil {
- return nil, fmt.Errorf("image_id %s not exists in range %s, all images are %s", imageId, client.Region, imageIds)
- }
-
- return image, nil
-}
-
-// DescribeZone validate zoneId is valid in region
-func (client *AliyunClient) DescribeZone(zoneID string) (*ecs.ZoneType, error) {
- zones, err := client.ecsconn.DescribeZones(client.Region)
- if err != nil {
- return nil, fmt.Errorf("error to list zones not found")
- }
-
- var zone *ecs.ZoneType
- zoneIds := []string{}
- for _, z := range zones {
- if z.ZoneId == zoneID {
- zone = &ecs.ZoneType{
- ZoneId: z.ZoneId,
- LocalName: z.LocalName,
- AvailableResourceCreation: z.AvailableResourceCreation,
- AvailableDiskCategories: z.AvailableDiskCategories,
- }
- }
- zoneIds = append(zoneIds, z.ZoneId)
- }
-
- if zone == nil {
- return nil, fmt.Errorf("availability_zone not exists in range %s, all zones are %s", client.Region, zoneIds)
- }
-
- return zone, nil
-}
-
-// return multiIZ list of current region
-func (client *AliyunClient) DescribeMultiIZByRegion() (izs []string, err error) {
- resp, err := client.rdsconn.DescribeRegions()
- if err != nil {
- return nil, fmt.Errorf("error to list regions not found")
- }
- regions := resp.Regions.RDSRegion
-
- zoneIds := []string{}
- for _, r := range regions {
- if r.RegionId == string(client.Region) && strings.Contains(r.ZoneId, MULTI_IZ_SYMBOL) {
- zoneIds = append(zoneIds, r.ZoneId)
- }
- }
-
- return zoneIds, nil
-}
-
-func (client *AliyunClient) QueryInstancesByIds(ids []string) (instances []ecs.InstanceAttributesType, err error) {
- idsStr, jerr := json.Marshal(ids)
- if jerr != nil {
- return nil, jerr
- }
-
- args := ecs.DescribeInstancesArgs{
- RegionId: client.Region,
- InstanceIds: string(idsStr),
- }
-
- instances, _, errs := client.ecsconn.DescribeInstances(&args)
-
- if errs != nil {
- return nil, errs
- }
-
- return instances, nil
-}
-
-func (client *AliyunClient) QueryInstancesById(id string) (instance *ecs.InstanceAttributesType, err error) {
- ids := []string{id}
-
- instances, errs := client.QueryInstancesByIds(ids)
- if errs != nil {
- return nil, errs
- }
-
- if len(instances) == 0 {
- return nil, GetNotFoundErrorFromString(InstanceNotfound)
- }
-
- return &instances[0], nil
-}
-
-func (client *AliyunClient) QueryInstanceSystemDisk(id string) (disk *ecs.DiskItemType, err error) {
- args := ecs.DescribeDisksArgs{
- RegionId: client.Region,
- InstanceId: string(id),
- DiskType: ecs.DiskTypeAllSystem,
- }
- disks, _, err := client.ecsconn.DescribeDisks(&args)
- if err != nil {
- return nil, err
- }
- if len(disks) == 0 {
- return nil, common.GetClientErrorFromString(SystemDiskNotFound)
- }
-
- return &disks[0], nil
-}
-
-// ResourceAvailable check resource available for zone
-func (client *AliyunClient) ResourceAvailable(zone *ecs.ZoneType, resourceType ecs.ResourceType) error {
- available := false
- for _, res := range zone.AvailableResourceCreation.ResourceTypes {
- if res == resourceType {
- available = true
- }
- }
- if !available {
- return fmt.Errorf("%s is not available in %s zone of %s region", resourceType, zone.ZoneId, client.Region)
- }
-
- return nil
-}
-
-func (client *AliyunClient) DiskAvailable(zone *ecs.ZoneType, diskCategory ecs.DiskCategory) error {
- available := false
- for _, dist := range zone.AvailableDiskCategories.DiskCategories {
- if dist == diskCategory {
- available = true
- }
- }
- if !available {
- return fmt.Errorf("%s is not available in %s zone of %s region", diskCategory, zone.ZoneId, client.Region)
- }
- return nil
-}
-
-// todo: support syc
-func (client *AliyunClient) JoinSecurityGroups(instanceId string, securityGroupIds []string) error {
- for _, sid := range securityGroupIds {
- err := client.ecsconn.JoinSecurityGroup(instanceId, sid)
- if err != nil {
- e, _ := err.(*common.Error)
- if e.ErrorResponse.Code != InvalidInstanceIdAlreadyExists {
- return err
- }
- }
- }
-
- return nil
-}
-
-func (client *AliyunClient) LeaveSecurityGroups(instanceId string, securityGroupIds []string) error {
- for _, sid := range securityGroupIds {
- err := client.ecsconn.LeaveSecurityGroup(instanceId, sid)
- if err != nil {
- e, _ := err.(*common.Error)
- if e.ErrorResponse.Code != InvalidSecurityGroupIdNotFound {
- return err
- }
- }
- }
-
- return nil
-}
-
-func (client *AliyunClient) DescribeSecurity(securityGroupId string) (*ecs.DescribeSecurityGroupAttributeResponse, error) {
-
- args := &ecs.DescribeSecurityGroupAttributeArgs{
- RegionId: client.Region,
- SecurityGroupId: securityGroupId,
- }
-
- return client.ecsconn.DescribeSecurityGroupAttribute(args)
-}
-
-func (client *AliyunClient) DescribeSecurityByAttr(securityGroupId, direction, nicType string) (*ecs.DescribeSecurityGroupAttributeResponse, error) {
-
- args := &ecs.DescribeSecurityGroupAttributeArgs{
- RegionId: client.Region,
- SecurityGroupId: securityGroupId,
- Direction: direction,
- NicType: ecs.NicType(nicType),
- }
-
- return client.ecsconn.DescribeSecurityGroupAttribute(args)
-}
-
-func (client *AliyunClient) DescribeSecurityGroupRule(securityGroupId, direction, nicType, ipProtocol, portRange string) (*ecs.PermissionType, error) {
- sg, err := client.DescribeSecurityByAttr(securityGroupId, direction, nicType)
- if err != nil {
- return nil, err
- }
-
- for _, p := range sg.Permissions.Permission {
- if strings.ToLower(string(p.IpProtocol)) == ipProtocol && p.PortRange == portRange {
- return &p, nil
- }
- }
- return nil, GetNotFoundErrorFromString("Security group rule not found")
-
-}
-
-func (client *AliyunClient) RevokeSecurityGroup(args *ecs.RevokeSecurityGroupArgs) error {
- //when the rule is not exist, api will return success(200)
- return client.ecsconn.RevokeSecurityGroup(args)
-}
-
-func (client *AliyunClient) RevokeSecurityGroupEgress(args *ecs.RevokeSecurityGroupEgressArgs) error {
- //when the rule is not exist, api will return success(200)
- return client.ecsconn.RevokeSecurityGroupEgress(args)
-}
diff --git a/builtin/providers/alicloud/service_alicloud_ess.go b/builtin/providers/alicloud/service_alicloud_ess.go
deleted file mode 100644
index 69d514ef2..000000000
--- a/builtin/providers/alicloud/service_alicloud_ess.go
+++ /dev/null
@@ -1,167 +0,0 @@
-package alicloud
-
-import (
- "github.com/denverdino/aliyungo/ess"
-)
-
-func (client *AliyunClient) DescribeScalingGroupById(sgId string) (*ess.ScalingGroupItemType, error) {
- args := ess.DescribeScalingGroupsArgs{
- RegionId: client.Region,
- ScalingGroupId: []string{sgId},
- }
-
- sgs, _, err := client.essconn.DescribeScalingGroups(&args)
- if err != nil {
- return nil, err
- }
-
- if len(sgs) == 0 {
- return nil, GetNotFoundErrorFromString("Scaling group not found")
- }
-
- return &sgs[0], nil
-}
-
-func (client *AliyunClient) DeleteScalingGroupById(sgId string) error {
- args := ess.DeleteScalingGroupArgs{
- ScalingGroupId: sgId,
- ForceDelete: true,
- }
-
- _, err := client.essconn.DeleteScalingGroup(&args)
- return err
-}
-
-func (client *AliyunClient) DescribeScalingConfigurationById(sgId, configId string) (*ess.ScalingConfigurationItemType, error) {
- args := ess.DescribeScalingConfigurationsArgs{
- RegionId: client.Region,
- ScalingGroupId: sgId,
- ScalingConfigurationId: []string{configId},
- }
-
- cs, _, err := client.essconn.DescribeScalingConfigurations(&args)
- if err != nil {
- return nil, err
- }
-
- if len(cs) == 0 {
- return nil, GetNotFoundErrorFromString("Scaling configuration not found")
- }
-
- return &cs[0], nil
-}
-
-func (client *AliyunClient) ActiveScalingConfigurationById(sgId, configId string) error {
- args := ess.ModifyScalingGroupArgs{
- ScalingGroupId: sgId,
- ActiveScalingConfigurationId: configId,
- }
-
- _, err := client.essconn.ModifyScalingGroup(&args)
- return err
-}
-
-func (client *AliyunClient) EnableScalingConfigurationById(sgId, configId string, ids []string) error {
- args := ess.EnableScalingGroupArgs{
- ScalingGroupId: sgId,
- ActiveScalingConfigurationId: configId,
- }
-
- if len(ids) > 0 {
- args.InstanceId = ids
- }
-
- _, err := client.essconn.EnableScalingGroup(&args)
- return err
-}
-
-func (client *AliyunClient) DisableScalingConfigurationById(sgId string) error {
- args := ess.DisableScalingGroupArgs{
- ScalingGroupId: sgId,
- }
-
- _, err := client.essconn.DisableScalingGroup(&args)
- return err
-}
-
-func (client *AliyunClient) DeleteScalingConfigurationById(sgId, configId string) error {
- args := ess.DeleteScalingConfigurationArgs{
- ScalingGroupId: sgId,
- ScalingConfigurationId: configId,
- }
-
- _, err := client.essconn.DeleteScalingConfiguration(&args)
- return err
-}
-
-// Flattens an array of datadisk into a []map[string]interface{}
-func flattenDataDiskMappings(list []ess.DataDiskItemType) []map[string]interface{} {
- result := make([]map[string]interface{}, 0, len(list))
- for _, i := range list {
- l := map[string]interface{}{
- "size": i.Size,
- "category": i.Category,
- "snapshot_id": i.SnapshotId,
- "device": i.Device,
- }
- result = append(result, l)
- }
- return result
-}
-
-func (client *AliyunClient) DescribeScalingRuleById(sgId, ruleId string) (*ess.ScalingRuleItemType, error) {
- args := ess.DescribeScalingRulesArgs{
- RegionId: client.Region,
- ScalingGroupId: sgId,
- ScalingRuleId: []string{ruleId},
- }
-
- cs, _, err := client.essconn.DescribeScalingRules(&args)
- if err != nil {
- return nil, err
- }
-
- if len(cs) == 0 {
- return nil, GetNotFoundErrorFromString("Scaling rule not found")
- }
-
- return &cs[0], nil
-}
-
-func (client *AliyunClient) DeleteScalingRuleById(ruleId string) error {
- args := ess.DeleteScalingRuleArgs{
- RegionId: client.Region,
- ScalingRuleId: ruleId,
- }
-
- _, err := client.essconn.DeleteScalingRule(&args)
- return err
-}
-
-func (client *AliyunClient) DescribeScheduleById(scheduleId string) (*ess.ScheduledTaskItemType, error) {
- args := ess.DescribeScheduledTasksArgs{
- RegionId: client.Region,
- ScheduledTaskId: []string{scheduleId},
- }
-
- cs, _, err := client.essconn.DescribeScheduledTasks(&args)
- if err != nil {
- return nil, err
- }
-
- if len(cs) == 0 {
- return nil, GetNotFoundErrorFromString("Schedule not found")
- }
-
- return &cs[0], nil
-}
-
-func (client *AliyunClient) DeleteScheduleById(scheduleId string) error {
- args := ess.DeleteScheduledTaskArgs{
- RegionId: client.Region,
- ScheduledTaskId: scheduleId,
- }
-
- _, err := client.essconn.DeleteScheduledTask(&args)
- return err
-}
diff --git a/builtin/providers/alicloud/service_alicloud_rds.go b/builtin/providers/alicloud/service_alicloud_rds.go
deleted file mode 100644
index 700a5d138..000000000
--- a/builtin/providers/alicloud/service_alicloud_rds.go
+++ /dev/null
@@ -1,288 +0,0 @@
-package alicloud
-
-import (
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/rds"
- "strings"
-)
-
-//
-// _______________ _______________ _______________
-// | | ______param______\ | | _____request_____\ | |
-// | Business | | Service | | SDK/API |
-// | | __________________ | | __________________ | |
-// |______________| \ (obj, err) |______________| \ (status, cont) |______________|
-// | |
-// |A. {instance, nil} |a. {200, content}
-// |B. {nil, error} |b. {200, nil}
-// |c. {4xx, nil}
-//
-// The API return 200 for resource not found.
-// When getInstance is empty, then throw InstanceNotfound error.
-// That the business layer only need to check error.
-func (client *AliyunClient) DescribeDBInstanceById(id string) (instance *rds.DBInstanceAttribute, err error) {
- arrtArgs := rds.DescribeDBInstancesArgs{
- DBInstanceId: id,
- }
- resp, err := client.rdsconn.DescribeDBInstanceAttribute(&arrtArgs)
- if err != nil {
- return nil, err
- }
-
- attr := resp.Items.DBInstanceAttribute
-
- if len(attr) <= 0 {
- return nil, GetNotFoundErrorFromString("DB instance not found")
- }
-
- return &attr[0], nil
-}
-
-func (client *AliyunClient) CreateAccountByInfo(instanceId, username, pwd string) error {
- conn := client.rdsconn
- args := rds.CreateAccountArgs{
- DBInstanceId: instanceId,
- AccountName: username,
- AccountPassword: pwd,
- }
-
- if _, err := conn.CreateAccount(&args); err != nil {
- return err
- }
-
- if err := conn.WaitForAccount(instanceId, username, rds.Available, 200); err != nil {
- return err
- }
- return nil
-}
-
-func (client *AliyunClient) CreateDatabaseByInfo(instanceId, dbName, charset, desp string) error {
- conn := client.rdsconn
- args := rds.CreateDatabaseArgs{
- DBInstanceId: instanceId,
- DBName: dbName,
- CharacterSetName: charset,
- DBDescription: desp,
- }
- _, err := conn.CreateDatabase(&args)
- return err
-}
-
-func (client *AliyunClient) DescribeDatabaseByName(instanceId, dbName string) (ds []rds.Database, err error) {
- conn := client.rdsconn
- args := rds.DescribeDatabasesArgs{
- DBInstanceId: instanceId,
- DBName: dbName,
- }
-
- resp, err := conn.DescribeDatabases(&args)
- if err != nil {
- return nil, err
- }
-
- return resp.Databases.Database, nil
-}
-
-func (client *AliyunClient) GrantDBPrivilege2Account(instanceId, username, dbName string) error {
- conn := client.rdsconn
- pargs := rds.GrantAccountPrivilegeArgs{
- DBInstanceId: instanceId,
- AccountName: username,
- DBName: dbName,
- AccountPrivilege: rds.ReadWrite,
- }
- if _, err := conn.GrantAccountPrivilege(&pargs); err != nil {
- return err
- }
-
- if err := conn.WaitForAccountPrivilege(instanceId, username, dbName, rds.ReadWrite, 200); err != nil {
- return err
- }
- return nil
-}
-
-func (client *AliyunClient) AllocateDBPublicConnection(instanceId, port string) error {
- conn := client.rdsconn
- args := rds.AllocateInstancePublicConnectionArgs{
- DBInstanceId: instanceId,
- ConnectionStringPrefix: instanceId + "o",
- Port: port,
- }
-
- if _, err := conn.AllocateInstancePublicConnection(&args); err != nil {
- return err
- }
-
- if err := conn.WaitForPublicConnection(instanceId, 600); err != nil {
- return err
- }
- return nil
-}
-
-func (client *AliyunClient) ConfigDBBackup(instanceId, backupTime, backupPeriod string, retentionPeriod int) error {
- bargs := rds.BackupPolicy{
- PreferredBackupTime: backupTime,
- PreferredBackupPeriod: backupPeriod,
- BackupRetentionPeriod: retentionPeriod,
- }
- args := rds.ModifyBackupPolicyArgs{
- DBInstanceId: instanceId,
- BackupPolicy: bargs,
- }
-
- if _, err := client.rdsconn.ModifyBackupPolicy(&args); err != nil {
- return err
- }
-
- if err := client.rdsconn.WaitForInstance(instanceId, rds.Running, 600); err != nil {
- return err
- }
- return nil
-}
-
-func (client *AliyunClient) ModifyDBSecurityIps(instanceId, ips string) error {
- sargs := rds.DBInstanceIPArray{
- SecurityIps: ips,
- }
-
- args := rds.ModifySecurityIpsArgs{
- DBInstanceId: instanceId,
- DBInstanceIPArray: sargs,
- }
-
- if _, err := client.rdsconn.ModifySecurityIps(&args); err != nil {
- return err
- }
-
- if err := client.rdsconn.WaitForInstance(instanceId, rds.Running, 600); err != nil {
- return err
- }
- return nil
-}
-
-func (client *AliyunClient) DescribeDBSecurityIps(instanceId string) (ips []rds.DBInstanceIPList, err error) {
- args := rds.DescribeDBInstanceIPsArgs{
- DBInstanceId: instanceId,
- }
-
- resp, err := client.rdsconn.DescribeDBInstanceIPs(&args)
- if err != nil {
- return nil, err
- }
- return resp.Items.DBInstanceIPArray, nil
-}
-
-func (client *AliyunClient) GetSecurityIps(instanceId string) ([]string, error) {
- arr, err := client.DescribeDBSecurityIps(instanceId)
- if err != nil {
- return nil, err
- }
- var ips, separator string
- for _, ip := range arr {
- ips += separator + ip.SecurityIPList
- separator = COMMA_SEPARATED
- }
- return strings.Split(ips, COMMA_SEPARATED), nil
-}
-
-func (client *AliyunClient) ModifyDBClassStorage(instanceId, class, storage string) error {
- conn := client.rdsconn
- args := rds.ModifyDBInstanceSpecArgs{
- DBInstanceId: instanceId,
- PayType: rds.Postpaid,
- DBInstanceClass: class,
- DBInstanceStorage: storage,
- }
-
- if _, err := conn.ModifyDBInstanceSpec(&args); err != nil {
- return err
- }
-
- if err := conn.WaitForInstance(instanceId, rds.Running, 600); err != nil {
- return err
- }
- return nil
-}
-
-// turn period to TimeType
-func TransformPeriod2Time(period int, chargeType string) (ut int, tt common.TimeType) {
- if chargeType == string(rds.Postpaid) {
- return 1, common.Day
- }
-
- if period >= 1 && period <= 9 {
- return period, common.Month
- }
-
- if period == 12 {
- return 1, common.Year
- }
-
- if period == 24 {
- return 2, common.Year
- }
- return 0, common.Day
-
-}
-
-// turn TimeType to Period
-func TransformTime2Period(ut int, tt common.TimeType) (period int) {
- if tt == common.Year {
- return 12 * ut
- }
-
- return ut
-
-}
-
-// Flattens an array of databases into a []map[string]interface{}
-func flattenDatabaseMappings(list []rds.Database) []map[string]interface{} {
- result := make([]map[string]interface{}, 0, len(list))
- for _, i := range list {
- l := map[string]interface{}{
- "db_name": i.DBName,
- "character_set_name": i.CharacterSetName,
- "db_description": i.DBDescription,
- }
- result = append(result, l)
- }
- return result
-}
-
-func flattenDBBackup(list []rds.BackupPolicy) []map[string]interface{} {
- result := make([]map[string]interface{}, 0, len(list))
- for _, i := range list {
- l := map[string]interface{}{
- "preferred_backup_period": i.PreferredBackupPeriod,
- "preferred_backup_time": i.PreferredBackupTime,
- "backup_retention_period": i.LogBackupRetentionPeriod,
- }
- result = append(result, l)
- }
- return result
-}
-
-func flattenDBSecurityIPs(list []rds.DBInstanceIPList) []map[string]interface{} {
- result := make([]map[string]interface{}, 0, len(list))
- for _, i := range list {
- l := map[string]interface{}{
- "security_ips": i.SecurityIPList,
- }
- result = append(result, l)
- }
- return result
-}
-
-// Flattens an array of databases connection into a []map[string]interface{}
-func flattenDBConnections(list []rds.DBInstanceNetInfo) []map[string]interface{} {
- result := make([]map[string]interface{}, 0, len(list))
- for _, i := range list {
- l := map[string]interface{}{
- "connection_string": i.ConnectionString,
- "ip_type": i.IPType,
- "ip_address": i.IPAddress,
- }
- result = append(result, l)
- }
- return result
-}
diff --git a/builtin/providers/alicloud/service_alicloud_slb.go b/builtin/providers/alicloud/service_alicloud_slb.go
deleted file mode 100644
index 9fc473018..000000000
--- a/builtin/providers/alicloud/service_alicloud_slb.go
+++ /dev/null
@@ -1,21 +0,0 @@
-package alicloud
-
-import (
- "github.com/denverdino/aliyungo/slb"
-)
-
-func (client *AliyunClient) DescribeLoadBalancerAttribute(slbId string) (*slb.LoadBalancerType, error) {
- loadBalancer, err := client.slbconn.DescribeLoadBalancerAttribute(slbId)
- if err != nil {
- if notFoundError(err) {
- return nil, nil
- }
- return nil, err
- }
-
- if loadBalancer != nil {
- return loadBalancer, nil
- }
-
- return nil, nil
-}
diff --git a/builtin/providers/alicloud/service_alicloud_vpc.go b/builtin/providers/alicloud/service_alicloud_vpc.go
deleted file mode 100644
index 491ab034f..000000000
--- a/builtin/providers/alicloud/service_alicloud_vpc.go
+++ /dev/null
@@ -1,227 +0,0 @@
-package alicloud
-
-import (
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "strings"
-)
-
-func (client *AliyunClient) DescribeEipAddress(allocationId string) (*ecs.EipAddressSetType, error) {
-
- args := ecs.DescribeEipAddressesArgs{
- RegionId: client.Region,
- AllocationId: allocationId,
- }
-
- eips, _, err := client.ecsconn.DescribeEipAddresses(&args)
- if err != nil {
- return nil, err
- }
- if len(eips) == 0 {
- return nil, common.GetClientErrorFromString("Not found")
- }
-
- return &eips[0], nil
-}
-
-func (client *AliyunClient) DescribeNatGateway(natGatewayId string) (*ecs.NatGatewaySetType, error) {
-
- args := &ecs.DescribeNatGatewaysArgs{
- RegionId: client.Region,
- NatGatewayId: natGatewayId,
- }
-
- natGateways, _, err := client.vpcconn.DescribeNatGateways(args)
- //fmt.Println("natGateways %#v", natGateways)
- if err != nil {
- return nil, err
- }
-
- if len(natGateways) == 0 {
- return nil, common.GetClientErrorFromString("Not found")
- }
-
- return &natGateways[0], nil
-}
-
-func (client *AliyunClient) DescribeVpc(vpcId string) (*ecs.VpcSetType, error) {
- args := ecs.DescribeVpcsArgs{
- RegionId: client.Region,
- VpcId: vpcId,
- }
-
- vpcs, _, err := client.ecsconn.DescribeVpcs(&args)
- if err != nil {
- if notFoundError(err) {
- return nil, nil
- }
- return nil, err
- }
-
- if len(vpcs) == 0 {
- return nil, nil
- }
-
- return &vpcs[0], nil
-}
-
-func (client *AliyunClient) DescribeSnatEntry(snatTableId string, snatEntryId string) (ecs.SnatEntrySetType, error) {
-
- var resultSnat ecs.SnatEntrySetType
-
- args := &ecs.DescribeSnatTableEntriesArgs{
- RegionId: client.Region,
- SnatTableId: snatTableId,
- }
-
- snatEntries, _, err := client.vpcconn.DescribeSnatTableEntries(args)
-
- //this special deal cause the DescribeSnatEntry can't find the records would be throw "cant find the snatTable error"
- //so judge the snatEntries length priority
- if len(snatEntries) == 0 {
- return resultSnat, common.GetClientErrorFromString(InstanceNotfound)
- }
-
- if err != nil {
- return resultSnat, err
- }
-
- findSnat := false
-
- for _, snat := range snatEntries {
- if snat.SnatEntryId == snatEntryId {
- resultSnat = snat
- findSnat = true
- }
- }
- if !findSnat {
- return resultSnat, common.GetClientErrorFromString(NotFindSnatEntryBySnatId)
- }
-
- return resultSnat, nil
-}
-
-func (client *AliyunClient) DescribeForwardEntry(forwardTableId string, forwardEntryId string) (ecs.ForwardTableEntrySetType, error) {
-
- var resultFoward ecs.ForwardTableEntrySetType
-
- args := &ecs.DescribeForwardTableEntriesArgs{
- RegionId: client.Region,
- ForwardTableId: forwardTableId,
- }
-
- forwardEntries, _, err := client.vpcconn.DescribeForwardTableEntries(args)
-
- //this special deal cause the DescribeSnatEntry can't find the records would be throw "cant find the snatTable error"
- //so judge the snatEntries length priority
- if len(forwardEntries) == 0 {
- return resultFoward, common.GetClientErrorFromString(InstanceNotfound)
- }
-
- findForward := false
-
- for _, forward := range forwardEntries {
- if forward.ForwardEntryId == forwardEntryId {
- resultFoward = forward
- findForward = true
- }
- }
- if !findForward {
- return resultFoward, common.GetClientErrorFromString(NotFindForwardEntryByForwardId)
- }
-
- if err != nil {
- return resultFoward, err
- }
-
- return resultFoward, nil
-}
-
-// describe vswitch by param filters
-func (client *AliyunClient) QueryVswitches(args *ecs.DescribeVSwitchesArgs) (vswitches []ecs.VSwitchSetType, err error) {
- vsws, _, err := client.ecsconn.DescribeVSwitches(args)
- if err != nil {
- if notFoundError(err) {
- return nil, nil
- }
- return nil, err
- }
-
- return vsws, nil
-}
-
-func (client *AliyunClient) QueryVswitchById(vpcId, vswitchId string) (vsw *ecs.VSwitchSetType, err error) {
- args := &ecs.DescribeVSwitchesArgs{
- VpcId: vpcId,
- VSwitchId: vswitchId,
- }
- vsws, err := client.QueryVswitches(args)
- if err != nil {
- return nil, err
- }
-
- if len(vsws) == 0 {
- return nil, nil
- }
-
- return &vsws[0], nil
-}
-
-func (client *AliyunClient) QueryRouteTables(args *ecs.DescribeRouteTablesArgs) (routeTables []ecs.RouteTableSetType, err error) {
- rts, _, err := client.ecsconn.DescribeRouteTables(args)
- if err != nil {
- return nil, err
- }
-
- return rts, nil
-}
-
-func (client *AliyunClient) QueryRouteTableById(routeTableId string) (rt *ecs.RouteTableSetType, err error) {
- args := &ecs.DescribeRouteTablesArgs{
- RouteTableId: routeTableId,
- }
- rts, err := client.QueryRouteTables(args)
- if err != nil {
- return nil, err
- }
-
- if len(rts) == 0 {
- return nil, &common.Error{ErrorResponse: common.ErrorResponse{Message: Notfound}}
- }
-
- return &rts[0], nil
-}
-
-func (client *AliyunClient) QueryRouteEntry(routeTableId, cidrBlock, nextHopType, nextHopId string) (rn *ecs.RouteEntrySetType, err error) {
- rt, errs := client.QueryRouteTableById(routeTableId)
- if errs != nil {
- return nil, errs
- }
-
- for _, e := range rt.RouteEntrys.RouteEntry {
- if strings.ToLower(string(e.DestinationCidrBlock)) == cidrBlock {
- return &e, nil
- }
- }
- return nil, GetNotFoundErrorFromString("Vpc router entry not found")
-}
-
-func (client *AliyunClient) GetVpcIdByVSwitchId(vswitchId string) (vpcId string, err error) {
-
- vs, _, err := client.ecsconn.DescribeVpcs(&ecs.DescribeVpcsArgs{
- RegionId: client.Region,
- })
- if err != nil {
- return "", err
- }
-
- for _, v := range vs {
- for _, sw := range v.VSwitchIds.VSwitchId {
- if sw == vswitchId {
- return v.VpcId, nil
- }
- }
- }
-
- return "", &common.Error{ErrorResponse: common.ErrorResponse{Message: Notfound}}
-}
diff --git a/builtin/providers/alicloud/tags.go b/builtin/providers/alicloud/tags.go
deleted file mode 100644
index a2d906ab9..000000000
--- a/builtin/providers/alicloud/tags.go
+++ /dev/null
@@ -1,126 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "log"
-
- "github.com/denverdino/aliyungo/ecs"
- "github.com/hashicorp/terraform/helper/schema"
- "strings"
-)
-
-func String(v string) *string {
- return &v
-}
-
-// tagsSchema returns the schema to use for tags.
-//
-func tagsSchema() *schema.Schema {
- return &schema.Schema{
- Type: schema.TypeMap,
- //Elem: &schema.Schema{Type: schema.TypeString},
- Optional: true,
- }
-}
-
-// setTags is a helper to set the tags for a resource. It expects the
-// tags field to be named "tags"
-func setTags(client *AliyunClient, resourceType ecs.TagResourceType, d *schema.ResourceData) error {
-
- conn := client.ecsconn
-
- if d.HasChange("tags") {
- oraw, nraw := d.GetChange("tags")
- o := oraw.(map[string]interface{})
- n := nraw.(map[string]interface{})
- create, remove := diffTags(tagsFromMap(o), tagsFromMap(n))
-
- // Set tags
- if len(remove) > 0 {
- log.Printf("[DEBUG] Removing tags: %#v from %s", remove, d.Id())
- err := RemoveTags(conn, &RemoveTagsArgs{
- RegionId: client.Region,
- ResourceId: d.Id(),
- ResourceType: resourceType,
- Tag: remove,
- })
- if err != nil {
- return fmt.Errorf("Remove tags got error: %s", err)
- }
- }
-
- if len(create) > 0 {
- log.Printf("[DEBUG] Creating tags: %s for %s", create, d.Id())
- err := AddTags(conn, &AddTagsArgs{
- RegionId: client.Region,
- ResourceId: d.Id(),
- ResourceType: resourceType,
- Tag: create,
- })
- if err != nil {
- return fmt.Errorf("Creating tags got error: %s", err)
- }
- }
- }
-
- return nil
-}
-
-// diffTags takes our tags locally and the ones remotely and returns
-// the set of tags that must be created, and the set of tags that must
-// be destroyed.
-func diffTags(oldTags, newTags []Tag) ([]Tag, []Tag) {
- // First, we're creating everything we have
- create := make(map[string]interface{})
- for _, t := range newTags {
- create[t.Key] = t.Value
- }
-
- // Build the list of what to remove
- var remove []Tag
- for _, t := range oldTags {
- old, ok := create[t.Key]
- if !ok || old != t.Value {
- // Delete it!
- remove = append(remove, t)
- }
- }
-
- return tagsFromMap(create), remove
-}
-
-// tagsFromMap returns the tags for the given map of data.
-func tagsFromMap(m map[string]interface{}) []Tag {
- result := make([]Tag, 0, len(m))
- for k, v := range m {
- result = append(result, Tag{
- Key: k,
- Value: v.(string),
- })
- }
-
- return result
-}
-
-func tagsToMap(tags []ecs.TagItemType) map[string]string {
- result := make(map[string]string)
- for _, t := range tags {
- result[t.TagKey] = t.TagValue
- }
-
- return result
-}
-
-func tagsToString(tags []ecs.TagItemType) string {
- result := make([]string, 0, len(tags))
-
- for _, tag := range tags {
- ecsTags := ecs.TagItemType{
- TagKey: tag.TagKey,
- TagValue: tag.TagValue,
- }
- result = append(result, ecsTags.TagKey+":"+ecsTags.TagValue)
- }
-
- return strings.Join(result, ",")
-}
diff --git a/builtin/providers/alicloud/validators.go b/builtin/providers/alicloud/validators.go
deleted file mode 100644
index 4c3c82f3e..000000000
--- a/builtin/providers/alicloud/validators.go
+++ /dev/null
@@ -1,578 +0,0 @@
-package alicloud
-
-import (
- "fmt"
- "net"
- "strconv"
- "strings"
-
- "github.com/denverdino/aliyungo/common"
- "github.com/denverdino/aliyungo/ecs"
- "github.com/denverdino/aliyungo/slb"
- "github.com/hashicorp/terraform/helper/schema"
- "regexp"
-)
-
-// common
-func validateInstancePort(v interface{}, k string) (ws []string, errors []error) {
- value := v.(int)
- if value < 1 || value > 65535 {
- errors = append(errors, fmt.Errorf(
- "%q must be a valid port between 1 and 65535",
- k))
- return
- }
- return
-}
-
-func validateInstanceProtocol(v interface{}, k string) (ws []string, errors []error) {
- protocol := v.(string)
- if !isProtocolValid(protocol) {
- errors = append(errors, fmt.Errorf(
- "%q is an invalid value. Valid values are either http, https, tcp or udp",
- k))
- return
- }
- return
-}
-
-// ecs
-func validateDiskCategory(v interface{}, k string) (ws []string, errors []error) {
- category := ecs.DiskCategory(v.(string))
- if category != ecs.DiskCategoryCloud && category != ecs.DiskCategoryCloudEfficiency && category != ecs.DiskCategoryCloudSSD {
- errors = append(errors, fmt.Errorf("%s must be one of %s %s %s", k, ecs.DiskCategoryCloud, ecs.DiskCategoryCloudEfficiency, ecs.DiskCategoryCloudSSD))
- }
-
- return
-}
-
-func validateInstanceName(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
- if len(value) < 2 || len(value) > 128 {
- errors = append(errors, fmt.Errorf("%q cannot be longer than 128 characters", k))
- }
-
- if strings.HasPrefix(value, "http://") || strings.HasPrefix(value, "https://") {
- errors = append(errors, fmt.Errorf("%s cannot starts with http:// or https://", k))
- }
-
- return
-}
-
-func validateInstanceDescription(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
- if len(value) < 2 || len(value) > 256 {
- errors = append(errors, fmt.Errorf("%q cannot be longer than 256 characters", k))
-
- }
- return
-}
-
-func validateDiskName(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
-
- if value == "" {
- return
- }
-
- if len(value) < 2 || len(value) > 128 {
- errors = append(errors, fmt.Errorf("%q cannot be longer than 128 characters", k))
- }
-
- if strings.HasPrefix(value, "http://") || strings.HasPrefix(value, "https://") {
- errors = append(errors, fmt.Errorf("%s cannot starts with http:// or https://", k))
- }
-
- return
-}
-
-func validateDiskDescription(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
- if len(value) < 2 || len(value) > 256 {
- errors = append(errors, fmt.Errorf("%q cannot be longer than 256 characters", k))
-
- }
- return
-}
-
-//security group
-func validateSecurityGroupName(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
- if len(value) < 2 || len(value) > 128 {
- errors = append(errors, fmt.Errorf("%q cannot be longer than 128 characters", k))
- }
-
- if strings.HasPrefix(value, "http://") || strings.HasPrefix(value, "https://") {
- errors = append(errors, fmt.Errorf("%s cannot starts with http:// or https://", k))
- }
-
- return
-}
-
-func validateSecurityGroupDescription(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
- if len(value) < 2 || len(value) > 256 {
- errors = append(errors, fmt.Errorf("%q cannot be longer than 256 characters", k))
-
- }
- return
-}
-
-func validateSecurityRuleType(v interface{}, k string) (ws []string, errors []error) {
- rt := GroupRuleDirection(v.(string))
- if rt != GroupRuleIngress && rt != GroupRuleEgress {
- errors = append(errors, fmt.Errorf("%s must be one of %s %s", k, GroupRuleIngress, GroupRuleEgress))
- }
-
- return
-}
-
-func validateSecurityRuleIpProtocol(v interface{}, k string) (ws []string, errors []error) {
- pt := GroupRuleIpProtocol(v.(string))
- if pt != GroupRuleTcp && pt != GroupRuleUdp && pt != GroupRuleIcmp && pt != GroupRuleGre && pt != GroupRuleAll {
- errors = append(errors, fmt.Errorf("%s must be one of %s %s %s %s %s", k,
- GroupRuleTcp, GroupRuleUdp, GroupRuleIcmp, GroupRuleGre, GroupRuleAll))
- }
-
- return
-}
-
-func validateSecurityRuleNicType(v interface{}, k string) (ws []string, errors []error) {
- pt := GroupRuleNicType(v.(string))
- if pt != GroupRuleInternet && pt != GroupRuleIntranet {
- errors = append(errors, fmt.Errorf("%s must be one of %s %s", k, GroupRuleInternet, GroupRuleIntranet))
- }
-
- return
-}
-
-func validateSecurityRulePolicy(v interface{}, k string) (ws []string, errors []error) {
- pt := GroupRulePolicy(v.(string))
- if pt != GroupRulePolicyAccept && pt != GroupRulePolicyDrop {
- errors = append(errors, fmt.Errorf("%s must be one of %s %s", k, GroupRulePolicyAccept, GroupRulePolicyDrop))
- }
-
- return
-}
-
-func validateSecurityPriority(v interface{}, k string) (ws []string, errors []error) {
- value := v.(int)
- if value < 1 || value > 100 {
- errors = append(errors, fmt.Errorf(
- "%q must be a valid authorization policy priority between 1 and 100",
- k))
- return
- }
- return
-}
-
-// validateCIDRNetworkAddress ensures that the string value is a valid CIDR that
-// represents a network address - it adds an error otherwise
-func validateCIDRNetworkAddress(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
- _, ipnet, err := net.ParseCIDR(value)
- if err != nil {
- errors = append(errors, fmt.Errorf(
- "%q must contain a valid CIDR, got error parsing: %s", k, err))
- return
- }
-
- if ipnet == nil || value != ipnet.String() {
- errors = append(errors, fmt.Errorf(
- "%q must contain a valid network CIDR, expected %q, got %q",
- k, ipnet, value))
- }
-
- return
-}
-
-func validateRouteEntryNextHopType(v interface{}, k string) (ws []string, errors []error) {
- nht := ecs.NextHopType(v.(string))
- if nht != ecs.NextHopIntance && nht != ecs.NextHopTunnel {
- errors = append(errors, fmt.Errorf("%s must be one of %s %s", k,
- ecs.NextHopIntance, ecs.NextHopTunnel))
- }
-
- return
-}
-
-func validateSwitchCIDRNetworkAddress(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
- _, ipnet, err := net.ParseCIDR(value)
- if err != nil {
- errors = append(errors, fmt.Errorf(
- "%q must contain a valid CIDR, got error parsing: %s", k, err))
- return
- }
-
- if ipnet == nil || value != ipnet.String() {
- errors = append(errors, fmt.Errorf(
- "%q must contain a valid network CIDR, expected %q, got %q",
- k, ipnet, value))
- return
- }
-
- mark, _ := strconv.Atoi(strings.Split(ipnet.String(), "/")[1])
- if mark < 16 || mark > 29 {
- errors = append(errors, fmt.Errorf(
- "%q must contain a network CIDR which mark between 16 and 29",
- k))
- }
-
- return
-}
-
-// validateIoOptimized ensures that the string value is a valid IoOptimized that
-// represents a IoOptimized - it adds an error otherwise
-func validateIoOptimized(v interface{}, k string) (ws []string, errors []error) {
- if value := v.(string); value != "" {
- ioOptimized := ecs.IoOptimized(value)
- if ioOptimized != ecs.IoOptimizedNone &&
- ioOptimized != ecs.IoOptimizedOptimized {
- errors = append(errors, fmt.Errorf(
- "%q must contain a valid IoOptimized, expected %s or %s, got %q",
- k, ecs.IoOptimizedNone, ecs.IoOptimizedOptimized, ioOptimized))
- }
- }
-
- return
-}
-
-// validateInstanceNetworkType ensures that the string value is a classic or vpc
-func validateInstanceNetworkType(v interface{}, k string) (ws []string, errors []error) {
- if value := v.(string); value != "" {
- network := InstanceNetWork(value)
- if network != ClassicNet &&
- network != VpcNet {
- errors = append(errors, fmt.Errorf(
- "%q must contain a valid InstanceNetworkType, expected %s or %s, go %q",
- k, ClassicNet, VpcNet, network))
- }
- }
- return
-}
-
-func validateInstanceChargeType(v interface{}, k string) (ws []string, errors []error) {
- if value := v.(string); value != "" {
- chargeType := common.InstanceChargeType(value)
- if chargeType != common.PrePaid &&
- chargeType != common.PostPaid {
- errors = append(errors, fmt.Errorf(
- "%q must contain a valid InstanceChargeType, expected %s or %s, got %q",
- k, common.PrePaid, common.PostPaid, chargeType))
- }
- }
-
- return
-}
-
-func validateInternetChargeType(v interface{}, k string) (ws []string, errors []error) {
- if value := v.(string); value != "" {
- chargeType := common.InternetChargeType(value)
- if chargeType != common.PayByBandwidth &&
- chargeType != common.PayByTraffic {
- errors = append(errors, fmt.Errorf(
- "%q must contain a valid InstanceChargeType, expected %s or %s, got %q",
- k, common.PayByBandwidth, common.PayByTraffic, chargeType))
- }
- }
-
- return
-}
-
-func validateInternetMaxBandWidthOut(v interface{}, k string) (ws []string, errors []error) {
- value := v.(int)
- if value < 0 || value > 100 {
- errors = append(errors, fmt.Errorf(
- "%q must be a valid internet bandwidth out between 0 and 100",
- k))
- return
- }
- return
-}
-
-// SLB
-func validateSlbName(v interface{}, k string) (ws []string, errors []error) {
- if value := v.(string); value != "" {
- if len(value) < 1 || len(value) > 80 {
- errors = append(errors, fmt.Errorf(
- "%q must be a valid load balancer name characters between 1 and 80",
- k))
- return
- }
- }
-
- return
-}
-
-func validateSlbInternetChargeType(v interface{}, k string) (ws []string, errors []error) {
- if value := v.(string); value != "" {
- chargeType := common.InternetChargeType(value)
-
- if chargeType != "paybybandwidth" &&
- chargeType != "paybytraffic" {
- errors = append(errors, fmt.Errorf(
- "%q must contain a valid InstanceChargeType, expected %s or %s, got %q",
- k, "paybybandwidth", "paybytraffic", value))
- }
- }
-
- return
-}
-
-func validateSlbBandwidth(v interface{}, k string) (ws []string, errors []error) {
- value := v.(int)
- if value < 1 || value > 1000 {
- errors = append(errors, fmt.Errorf(
- "%q must be a valid load balancer bandwidth between 1 and 1000",
- k))
- return
- }
- return
-}
-
-func validateSlbListenerBandwidth(v interface{}, k string) (ws []string, errors []error) {
- value := v.(int)
- if (value < 1 || value > 1000) && value != -1 {
- errors = append(errors, fmt.Errorf(
- "%q must be a valid load balancer bandwidth between 1 and 1000 or -1",
- k))
- return
- }
- return
-}
-
-func validateSlbListenerScheduler(v interface{}, k string) (ws []string, errors []error) {
- if value := v.(string); value != "" {
- scheduler := slb.SchedulerType(value)
-
- if scheduler != "wrr" && scheduler != "wlc" {
- errors = append(errors, fmt.Errorf(
- "%q must contain a valid SchedulerType, expected %s or %s, got %q",
- k, "wrr", "wlc", value))
- }
- }
-
- return
-}
-
-func validateSlbListenerCookie(v interface{}, k string) (ws []string, errors []error) {
- if value := v.(string); value != "" {
- if len(value) < 1 || len(value) > 200 {
- errors = append(errors, fmt.Errorf("%q cannot be longer than 200 characters", k))
- }
- }
- return
-}
-
-func validateSlbListenerCookieTimeout(v interface{}, k string) (ws []string, errors []error) {
- value := v.(int)
- if value < 0 || value > 86400 {
- errors = append(errors, fmt.Errorf(
- "%q must be a valid load balancer cookie timeout between 0 and 86400",
- k))
- return
- }
- return
-}
-
-func validateSlbListenerPersistenceTimeout(v interface{}, k string) (ws []string, errors []error) {
- value := v.(int)
- if value < 0 || value > 3600 {
- errors = append(errors, fmt.Errorf(
- "%q must be a valid load balancer persistence timeout between 0 and 86400",
- k))
- return
- }
- return
-}
-
-func validateSlbListenerHealthCheckDomain(v interface{}, k string) (ws []string, errors []error) {
- if value := v.(string); value != "" {
- //the len add "$_ip",so to max is 84
- if len(value) < 1 || len(value) > 84 {
- errors = append(errors, fmt.Errorf("%q cannot be longer than 84 characters", k))
- }
- }
- return
-}
-
-func validateSlbListenerHealthCheckUri(v interface{}, k string) (ws []string, errors []error) {
- if value := v.(string); value != "" {
- if len(value) < 1 || len(value) > 80 {
- errors = append(errors, fmt.Errorf("%q cannot be longer than 80 characters", k))
- }
- }
- return
-}
-
-func validateSlbListenerHealthCheckConnectPort(v interface{}, k string) (ws []string, errors []error) {
- value := v.(int)
- if value < 1 || value > 65535 {
- if value != -520 {
- errors = append(errors, fmt.Errorf(
- "%q must be a valid load balancer health check connect port between 1 and 65535 or -520",
- k))
- return
- }
-
- }
- return
-}
-
-func validateDBBackupPeriod(v interface{}, k string) (ws []string, errors []error) {
- days := []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
- value := v.(string)
- exist := false
- for _, d := range days {
- if value == d {
- exist = true
- break
- }
- }
- if !exist {
- errors = append(errors, fmt.Errorf(
- "%q must contain a valid backup period value should in array %#v, got %q",
- k, days, value))
- }
-
- return
-}
-
-func validateAllowedStringValue(ss []string) schema.SchemaValidateFunc {
- return func(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
- existed := false
- for _, s := range ss {
- if s == value {
- existed = true
- break
- }
- }
- if !existed {
- errors = append(errors, fmt.Errorf(
- "%q must contain a valid string value should in array %#v, got %q",
- k, ss, value))
- }
- return
-
- }
-}
-
-func validateAllowedSplitStringValue(ss []string, splitStr string) schema.SchemaValidateFunc {
- return func(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
- existed := false
- tsList := strings.Split(value, splitStr)
-
- for _, ts := range tsList {
- existed = false
- for _, s := range ss {
- if ts == s {
- existed = true
- break
- }
- }
- }
- if !existed {
- errors = append(errors, fmt.Errorf(
- "%q must contain a valid string value should in %#v, got %q",
- k, ss, value))
- }
- return
-
- }
-}
-
-func validateAllowedIntValue(is []int) schema.SchemaValidateFunc {
- return func(v interface{}, k string) (ws []string, errors []error) {
- value := v.(int)
- existed := false
- for _, i := range is {
- if i == value {
- existed = true
- break
- }
- }
- if !existed {
- errors = append(errors, fmt.Errorf(
- "%q must contain a valid int value should in array %#v, got %q",
- k, is, value))
- }
- return
-
- }
-}
-
-func validateIntegerInRange(min, max int) schema.SchemaValidateFunc {
- return func(v interface{}, k string) (ws []string, errors []error) {
- value := v.(int)
- if value < min {
- errors = append(errors, fmt.Errorf(
- "%q cannot be lower than %d: %d", k, min, value))
- }
- if value > max {
- errors = append(errors, fmt.Errorf(
- "%q cannot be higher than %d: %d", k, max, value))
- }
- return
- }
-}
-
-//data source validate func
-//data_source_alicloud_image
-func validateNameRegex(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
-
- if _, err := regexp.Compile(value); err != nil {
- errors = append(errors, fmt.Errorf(
- "%q contains an invalid regular expression: %s",
- k, err))
- }
- return
-}
-
-func validateImageOwners(v interface{}, k string) (ws []string, errors []error) {
- if value := v.(string); value != "" {
- owners := ecs.ImageOwnerAlias(value)
- if owners != ecs.ImageOwnerSystem &&
- owners != ecs.ImageOwnerSelf &&
- owners != ecs.ImageOwnerOthers &&
- owners != ecs.ImageOwnerMarketplace &&
- owners != ecs.ImageOwnerDefault {
- errors = append(errors, fmt.Errorf(
- "%q must contain a valid Image owner , expected %s, %s, %s, %s or %s, got %q",
- k, ecs.ImageOwnerSystem, ecs.ImageOwnerSelf, ecs.ImageOwnerOthers, ecs.ImageOwnerMarketplace, ecs.ImageOwnerDefault, owners))
- }
- }
- return
-}
-
-func validateRegion(v interface{}, k string) (ws []string, errors []error) {
- if value := v.(string); value != "" {
- region := common.Region(value)
- var valid string
- for _, re := range common.ValidRegions {
- if region == re {
- return
- }
- valid = valid + ", " + string(re)
- }
- errors = append(errors, fmt.Errorf(
- "%q must contain a valid Region ID , expected %#v, got %q",
- k, valid, value))
-
- }
- return
-}
-
-func validateForwardPort(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
- if value != "any" {
- valueConv, err := strconv.Atoi(value)
- if err != nil || valueConv < 1 || valueConv > 65535 {
- errors = append(errors, fmt.Errorf("%q must be a valid port between 1 and 65535 or any ", k))
- }
- }
- return
-}
diff --git a/builtin/providers/alicloud/validators_test.go b/builtin/providers/alicloud/validators_test.go
deleted file mode 100644
index 3160c496c..000000000
--- a/builtin/providers/alicloud/validators_test.go
+++ /dev/null
@@ -1,502 +0,0 @@
-package alicloud
-
-import "testing"
-
-func TestValidateInstancePort(t *testing.T) {
- validPorts := []int{1, 22, 80, 100, 8088, 65535}
- for _, v := range validPorts {
- _, errors := validateInstancePort(v, "instance_port")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid instance port number between 1 and 65535: %q", v, errors)
- }
- }
-
- invalidPorts := []int{-10, -1, 0}
- for _, v := range invalidPorts {
- _, errors := validateInstancePort(v, "instance_port")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid instance port number", v)
- }
- }
-}
-
-func TestValidateInstanceProtocol(t *testing.T) {
- validProtocols := []string{"http", "tcp", "https", "udp"}
- for _, v := range validProtocols {
- _, errors := validateInstanceProtocol(v, "instance_protocol")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid instance protocol: %q", v, errors)
- }
- }
-
- invalidProtocols := []string{"HTTP", "abc", "ecmp", "dubbo"}
- for _, v := range invalidProtocols {
- _, errors := validateInstanceProtocol(v, "instance_protocol")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid instance protocol", v)
- }
- }
-}
-
-func TestValidateInstanceDiskCategory(t *testing.T) {
- validDiskCategory := []string{"cloud", "cloud_efficiency", "cloud_ssd"}
- for _, v := range validDiskCategory {
- _, errors := validateDiskCategory(v, "instance_disk_category")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid instance disk category: %q", v, errors)
- }
- }
-
- invalidDiskCategory := []string{"all", "ephemeral", "ephemeral_ssd", "ALL", "efficiency"}
- for _, v := range invalidDiskCategory {
- _, errors := validateDiskCategory(v, "instance_disk_category")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid instance disk category", v)
- }
- }
-}
-
-func TestValidateInstanceName(t *testing.T) {
- validInstanceName := []string{"hi", "hi http://", "some word + any word &", "http", "中文"}
- for _, v := range validInstanceName {
- _, errors := validateInstanceName(v, "instance_name")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid instance name: %q", v, errors)
- }
- }
-
- invalidInstanceName := []string{"y", "http://", "https://", "+"}
- for _, v := range invalidInstanceName {
- _, errors := validateInstanceName(v, "instance_name")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid instance name", v)
- }
- }
-}
-
-func TestValidateInstanceDescription(t *testing.T) {
- validInstanceDescription := []string{"hi", "hi http://", "some word + any word &", "http://", "中文"}
- for _, v := range validInstanceDescription {
- _, errors := validateInstanceDescription(v, "instance_description")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid instance description: %q", v, errors)
- }
- }
-
- invalidvalidInstanceDescription := []string{"y", ""}
- for _, v := range invalidvalidInstanceDescription {
- _, errors := validateInstanceName(v, "instance_description")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid instance description", v)
- }
- }
-}
-
-func TestValidateSecurityGroupName(t *testing.T) {
- validSecurityGroupName := []string{"hi", "hi http://", "some word + any word &", "http", "中文", "12345"}
- for _, v := range validSecurityGroupName {
- _, errors := validateSecurityGroupName(v, "security_group_name")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid security group name: %q", v, errors)
- }
- }
-
- invalidSecurityGroupName := []string{"y", "http://", "https://", "+"}
- for _, v := range invalidSecurityGroupName {
- _, errors := validateSecurityGroupName(v, "security_group_name")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid security group name", v)
- }
- }
-}
-
-func TestValidateSecurityGroupDescription(t *testing.T) {
- validSecurityGroupDescription := []string{"hi", "hi http://", "some word + any word &", "http://", "中文"}
- for _, v := range validSecurityGroupDescription {
- _, errors := validateSecurityGroupDescription(v, "security_group_description")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid security group description: %q", v, errors)
- }
- }
-
- invalidSecurityGroupDescription := []string{"y", ""}
- for _, v := range invalidSecurityGroupDescription {
- _, errors := validateSecurityGroupDescription(v, "security_group_description")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid security group description", v)
- }
- }
-}
-
-func TestValidateSecurityRuleType(t *testing.T) {
- validSecurityRuleType := []string{"ingress", "egress"}
- for _, v := range validSecurityRuleType {
- _, errors := validateSecurityRuleType(v, "security_rule_type")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid security rule type: %q", v, errors)
- }
- }
-
- invalidSecurityRuleType := []string{"y", "gress", "in", "out"}
- for _, v := range invalidSecurityRuleType {
- _, errors := validateSecurityRuleType(v, "security_rule_type")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid security rule type", v)
- }
- }
-}
-
-func TestValidateSecurityRuleIpProtocol(t *testing.T) {
- validIpProtocol := []string{"tcp", "udp", "icmp", "gre", "all"}
- for _, v := range validIpProtocol {
- _, errors := validateSecurityRuleIpProtocol(v, "security_rule_ip_protocol")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid ip protocol: %q", v, errors)
- }
- }
-
- invalidIpProtocol := []string{"y", "ecmp", "http", "https"}
- for _, v := range invalidIpProtocol {
- _, errors := validateSecurityRuleIpProtocol(v, "security_rule_ip_protocol")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid ip protocol", v)
- }
- }
-}
-
-func TestValidateSecurityRuleNicType(t *testing.T) {
- validRuleNicType := []string{"intranet", "internet"}
- for _, v := range validRuleNicType {
- _, errors := validateSecurityRuleNicType(v, "security_rule_nic_type")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid nic type: %q", v, errors)
- }
- }
-
- invalidRuleNicType := []string{"inter", "ecmp", "http", "https"}
- for _, v := range invalidRuleNicType {
- _, errors := validateSecurityRuleNicType(v, "security_rule_nic_type")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid nic type", v)
- }
- }
-}
-
-func TestValidateSecurityRulePolicy(t *testing.T) {
- validRulePolicy := []string{"accept", "drop"}
- for _, v := range validRulePolicy {
- _, errors := validateSecurityRulePolicy(v, "security_rule_policy")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid security rule policy: %q", v, errors)
- }
- }
-
- invalidRulePolicy := []string{"inter", "ecmp", "http", "https"}
- for _, v := range invalidRulePolicy {
- _, errors := validateSecurityRulePolicy(v, "security_rule_policy")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid security rule policy", v)
- }
- }
-}
-
-func TestValidateSecurityRulePriority(t *testing.T) {
- validPriority := []int{1, 50, 100}
- for _, v := range validPriority {
- _, errors := validateSecurityPriority(v, "security_rule_priority")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid security rule priority: %q", v, errors)
- }
- }
-
- invalidPriority := []int{-1, 0, 101}
- for _, v := range invalidPriority {
- _, errors := validateSecurityPriority(v, "security_rule_priority")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid security rule priority", v)
- }
- }
-}
-
-func TestValidateCIDRNetworkAddress(t *testing.T) {
- validCIDRNetworkAddress := []string{"192.168.10.0/24", "0.0.0.0/0", "10.121.10.0/24"}
- for _, v := range validCIDRNetworkAddress {
- _, errors := validateCIDRNetworkAddress(v, "cidr_network_address")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid cidr network address: %q", v, errors)
- }
- }
-
- invalidCIDRNetworkAddress := []string{"1.2.3.4", "0x38732/21"}
- for _, v := range invalidCIDRNetworkAddress {
- _, errors := validateCIDRNetworkAddress(v, "cidr_network_address")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid cidr network address", v)
- }
- }
-}
-
-func TestValidateRouteEntryNextHopType(t *testing.T) {
- validNexthopType := []string{"Instance", "Tunnel"}
- for _, v := range validNexthopType {
- _, errors := validateRouteEntryNextHopType(v, "route_entry_nexthop_type")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid route entry nexthop type: %q", v, errors)
- }
- }
-
- invalidNexthopType := []string{"ri", "vpc"}
- for _, v := range invalidNexthopType {
- _, errors := validateRouteEntryNextHopType(v, "route_entry_nexthop_type")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid route entry nexthop type", v)
- }
- }
-}
-
-func TestValidateSwitchCIDRNetworkAddress(t *testing.T) {
- validSwitchCIDRNetworkAddress := []string{"192.168.10.0/24", "0.0.0.0/16", "127.0.0.0/29", "10.121.10.0/24"}
- for _, v := range validSwitchCIDRNetworkAddress {
- _, errors := validateSwitchCIDRNetworkAddress(v, "switch_cidr_network_address")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid switch cidr network address: %q", v, errors)
- }
- }
-
- invalidSwitchCIDRNetworkAddress := []string{"1.2.3.4", "0x38732/21", "10.121.10.0/15", "10.121.10.0/30", "256.121.10.0/22"}
- for _, v := range invalidSwitchCIDRNetworkAddress {
- _, errors := validateSwitchCIDRNetworkAddress(v, "switch_cidr_network_address")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid switch cidr network address", v)
- }
- }
-}
-
-func TestValidateIoOptimized(t *testing.T) {
- validIoOptimized := []string{"", "none", "optimized"}
- for _, v := range validIoOptimized {
- _, errors := validateIoOptimized(v, "ioOptimized")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid IoOptimized value: %q", v, errors)
- }
- }
-
- invalidIoOptimized := []string{"true", "ioOptimized"}
- for _, v := range invalidIoOptimized {
- _, errors := validateIoOptimized(v, "ioOptimized")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid IoOptimized value", v)
- }
- }
-}
-
-func TestValidateInstanceNetworkType(t *testing.T) {
- validInstanceNetworkType := []string{"", "classic", "vpc"}
- for _, v := range validInstanceNetworkType {
- _, errors := validateInstanceNetworkType(v, "instance_network_type")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid instance network type value: %q", v, errors)
- }
- }
-
- invalidInstanceNetworkType := []string{"Classic", "vswitch", "123"}
- for _, v := range invalidInstanceNetworkType {
- _, errors := validateInstanceNetworkType(v, "instance_network_type")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid instance network type value", v)
- }
- }
-}
-
-func TestValidateInstanceChargeType(t *testing.T) {
- validInstanceChargeType := []string{"", "PrePaid", "PostPaid"}
- for _, v := range validInstanceChargeType {
- _, errors := validateInstanceChargeType(v, "instance_charge_type")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid instance charge type value: %q", v, errors)
- }
- }
-
- invalidInstanceChargeType := []string{"prepay", "yearly", "123"}
- for _, v := range invalidInstanceChargeType {
- _, errors := validateInstanceChargeType(v, "instance_charge_type")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid instance charge type value", v)
- }
- }
-}
-
-func TestValidateInternetChargeType(t *testing.T) {
- validInternetChargeType := []string{"", "PayByBandwidth", "PayByTraffic"}
- for _, v := range validInternetChargeType {
- _, errors := validateInternetChargeType(v, "internet_charge_type")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid internet charge type value: %q", v, errors)
- }
- }
-
- invalidInternetChargeType := []string{"paybybandwidth", "paybytraffic", "123"}
- for _, v := range invalidInternetChargeType {
- _, errors := validateInternetChargeType(v, "internet_charge_type")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid internet charge type value", v)
- }
- }
-}
-
-func TestValidateInternetMaxBandWidthOut(t *testing.T) {
- validInternetMaxBandWidthOut := []int{1, 22, 100}
- for _, v := range validInternetMaxBandWidthOut {
- _, errors := validateInternetMaxBandWidthOut(v, "internet_max_bandwidth_out")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid internet max bandwidth out value: %q", v, errors)
- }
- }
-
- invalidInternetMaxBandWidthOut := []int{-2, 101, 123}
- for _, v := range invalidInternetMaxBandWidthOut {
- _, errors := validateInternetMaxBandWidthOut(v, "internet_max_bandwidth_out")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid internet max bandwidth out value", v)
- }
- }
-}
-
-func TestValidateSlbName(t *testing.T) {
- validSlbName := []string{"h", "http://", "123", "hello, aliyun! "}
- for _, v := range validSlbName {
- _, errors := validateSlbName(v, "slb_name")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid slb name: %q", v, errors)
- }
- }
-
- // todo: add invalid case
-}
-
-func TestValidateSlbInternetChargeType(t *testing.T) {
- validSlbInternetChargeType := []string{"paybybandwidth", "paybytraffic"}
- for _, v := range validSlbInternetChargeType {
- _, errors := validateSlbInternetChargeType(v, "slb_internet_charge_type")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid slb internet charge type value: %q", v, errors)
- }
- }
-
- invalidSlbInternetChargeType := []string{"PayByBandwidth", "PayByTraffic"}
- for _, v := range invalidSlbInternetChargeType {
- _, errors := validateSlbInternetChargeType(v, "slb_internet_charge_type")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid slb internet charge type value", v)
- }
- }
-}
-
-func TestValidateSlbBandwidth(t *testing.T) {
- validSlbBandwidth := []int{1, 22, 1000}
- for _, v := range validSlbBandwidth {
- _, errors := validateSlbBandwidth(v, "slb_bandwidth")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid slb bandwidth value: %q", v, errors)
- }
- }
-
- invalidSlbBandwidth := []int{-2, 0, 1001}
- for _, v := range invalidSlbBandwidth {
- _, errors := validateSlbBandwidth(v, "slb_bandwidth")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid slb bandwidth value", v)
- }
- }
-}
-
-func TestValidateSlbListenerBandwidth(t *testing.T) {
- validSlbListenerBandwidth := []int{-1, 1, 22, 1000}
- for _, v := range validSlbListenerBandwidth {
- _, errors := validateSlbListenerBandwidth(v, "slb_bandwidth")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid slb listener bandwidth value: %q", v, errors)
- }
- }
-
- invalidSlbListenerBandwidth := []int{-2, 0, -10, 1001}
- for _, v := range invalidSlbListenerBandwidth {
- _, errors := validateSlbListenerBandwidth(v, "slb_bandwidth")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid slb listener bandwidth value", v)
- }
- }
-}
-
-func TestValidateAllowedStringValue(t *testing.T) {
- exceptValues := []string{"aliyun", "alicloud", "alibaba"}
- validValues := []string{"aliyun"}
- for _, v := range validValues {
- _, errors := validateAllowedStringValue(exceptValues)(v, "allowvalue")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid value in %#v: %q", v, exceptValues, errors)
- }
- }
-
- invalidValues := []string{"ali", "alidata", "terraform"}
- for _, v := range invalidValues {
- _, errors := validateAllowedStringValue(exceptValues)(v, "allowvalue")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid value", v)
- }
- }
-}
-
-func TestValidateAllowedStringSplitValue(t *testing.T) {
- exceptValues := []string{"aliyun", "alicloud", "alibaba"}
- validValues := "aliyun,alicloud"
- _, errors := validateAllowedSplitStringValue(exceptValues, ",")(validValues, "allowvalue")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid value in %#v: %q", validValues, exceptValues, errors)
- }
-
- invalidValues := "ali,alidata"
- _, invalidErr := validateAllowedSplitStringValue(exceptValues, ",")(invalidValues, "allowvalue")
- if len(invalidErr) == 0 {
- t.Fatalf("%q should be an invalid value", invalidValues)
- }
-}
-
-func TestValidateAllowedIntValue(t *testing.T) {
- exceptValues := []int{1, 3, 5, 6}
- validValues := []int{1, 3, 5, 6}
- for _, v := range validValues {
- _, errors := validateAllowedIntValue(exceptValues)(v, "allowvalue")
- if len(errors) != 0 {
- t.Fatalf("%q should be a valid value in %#v: %q", v, exceptValues, errors)
- }
- }
-
- invalidValues := []int{0, 7, 10}
- for _, v := range invalidValues {
- _, errors := validateAllowedIntValue(exceptValues)(v, "allowvalue")
- if len(errors) == 0 {
- t.Fatalf("%q should be an invalid value", v)
- }
- }
-}
-
-func TestValidateIntegerInRange(t *testing.T) {
- validIntegers := []int{-259, 0, 1, 5, 999}
- min := -259
- max := 999
- for _, v := range validIntegers {
- _, errors := validateIntegerInRange(min, max)(v, "name")
- if len(errors) != 0 {
- t.Fatalf("%q should be an integer in range (%d, %d): %q", v, min, max, errors)
- }
- }
-
- invalidIntegers := []int{-260, -99999, 1000, 25678}
- for _, v := range invalidIntegers {
- _, errors := validateIntegerInRange(min, max)(v, "name")
- if len(errors) == 0 {
- t.Fatalf("%q should be an integer outside range (%d, %d)", v, min, max)
- }
- }
-}
diff --git a/builtin/providers/archive/.gitignore b/builtin/providers/archive/.gitignore
deleted file mode 100644
index c4c4ffc6a..000000000
--- a/builtin/providers/archive/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-*.zip
diff --git a/builtin/providers/archive/archiver.go b/builtin/providers/archive/archiver.go
deleted file mode 100644
index c216f4620..000000000
--- a/builtin/providers/archive/archiver.go
+++ /dev/null
@@ -1,48 +0,0 @@
-package archive
-
-import (
- "fmt"
- "os"
-)
-
-type Archiver interface {
- ArchiveContent(content []byte, infilename string) error
- ArchiveFile(infilename string) error
- ArchiveDir(indirname string) error
- ArchiveMultiple(content map[string][]byte) error
-}
-
-type ArchiverBuilder func(filepath string) Archiver
-
-var archiverBuilders = map[string]ArchiverBuilder{
- "zip": NewZipArchiver,
-}
-
-func getArchiver(archiveType string, filepath string) Archiver {
- if builder, ok := archiverBuilders[archiveType]; ok {
- return builder(filepath)
- }
- return nil
-}
-
-func assertValidFile(infilename string) (os.FileInfo, error) {
- fi, err := os.Stat(infilename)
- if err != nil && os.IsNotExist(err) {
- return fi, fmt.Errorf("could not archive missing file: %s", infilename)
- }
- return fi, err
-}
-
-func assertValidDir(indirname string) (os.FileInfo, error) {
- fi, err := os.Stat(indirname)
- if err != nil {
- if os.IsNotExist(err) {
- return fi, fmt.Errorf("could not archive missing directory: %s", indirname)
- }
- return fi, err
- }
- if !fi.IsDir() {
- return fi, fmt.Errorf("could not archive directory that is a file: %s", indirname)
- }
- return fi, nil
-}
diff --git a/builtin/providers/archive/data_source_archive_file.go b/builtin/providers/archive/data_source_archive_file.go
deleted file mode 100644
index 218629cba..000000000
--- a/builtin/providers/archive/data_source_archive_file.go
+++ /dev/null
@@ -1,205 +0,0 @@
-package archive
-
-import (
- "bytes"
- "crypto/md5"
- "crypto/sha1"
- "crypto/sha256"
- "encoding/base64"
- "encoding/hex"
- "fmt"
- "io/ioutil"
- "os"
- "path"
-
- "github.com/hashicorp/terraform/helper/hashcode"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceFile() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceFileRead,
-
- Schema: map[string]*schema.Schema{
- "type": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
- "source": &schema.Schema{
- Type: schema.TypeSet,
- Optional: true,
- Computed: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "content": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
- "filename": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
- },
- },
- ConflictsWith: []string{"source_file", "source_dir", "source_content", "source_content_filename"},
- Set: func(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%s-", m["filename"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["content"].(string)))
- return hashcode.String(buf.String())
- },
- },
- "source_content": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- ConflictsWith: []string{"source_file", "source_dir"},
- },
- "source_content_filename": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- ConflictsWith: []string{"source_file", "source_dir"},
- },
- "source_file": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- ConflictsWith: []string{"source_content", "source_content_filename", "source_dir"},
- },
- "source_dir": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- ConflictsWith: []string{"source_content", "source_content_filename", "source_file"},
- },
- "output_path": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
- "output_size": &schema.Schema{
- Type: schema.TypeInt,
- Computed: true,
- ForceNew: true,
- },
- "output_sha": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- ForceNew: true,
- Description: "SHA1 checksum of output file",
- },
- "output_base64sha256": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- ForceNew: true,
- Description: "Base64 Encoded SHA256 checksum of output file",
- },
- "output_md5": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- ForceNew: true,
- Description: "MD5 of output file",
- },
- },
- }
-}
-
-func dataSourceFileRead(d *schema.ResourceData, meta interface{}) error {
- outputPath := d.Get("output_path").(string)
-
- outputDirectory := path.Dir(outputPath)
- if outputDirectory != "" {
- if _, err := os.Stat(outputDirectory); err != nil {
- if err := os.MkdirAll(outputDirectory, 0755); err != nil {
- return err
- }
- }
- }
-
- if err := archive(d); err != nil {
- return err
- }
-
- // Generate archived file stats
- fi, err := os.Stat(outputPath)
- if err != nil {
- return err
- }
-
- sha1, base64sha256, md5, err := genFileShas(outputPath)
- if err != nil {
-
- return fmt.Errorf("could not generate file checksum sha256: %s", err)
- }
- d.Set("output_sha", sha1)
- d.Set("output_base64sha256", base64sha256)
- d.Set("output_md5", md5)
-
- d.Set("output_size", fi.Size())
- d.SetId(d.Get("output_sha").(string))
-
- return nil
-}
-
-func archive(d *schema.ResourceData) error {
- archiveType := d.Get("type").(string)
- outputPath := d.Get("output_path").(string)
-
- archiver := getArchiver(archiveType, outputPath)
- if archiver == nil {
- return fmt.Errorf("archive type not supported: %s", archiveType)
- }
-
- if dir, ok := d.GetOk("source_dir"); ok {
- if err := archiver.ArchiveDir(dir.(string)); err != nil {
- return fmt.Errorf("error archiving directory: %s", err)
- }
- } else if file, ok := d.GetOk("source_file"); ok {
- if err := archiver.ArchiveFile(file.(string)); err != nil {
- return fmt.Errorf("error archiving file: %s", err)
- }
- } else if filename, ok := d.GetOk("source_content_filename"); ok {
- content := d.Get("source_content").(string)
- if err := archiver.ArchiveContent([]byte(content), filename.(string)); err != nil {
- return fmt.Errorf("error archiving content: %s", err)
- }
- } else if v, ok := d.GetOk("source"); ok {
- vL := v.(*schema.Set).List()
- content := make(map[string][]byte)
- for _, v := range vL {
- src := v.(map[string]interface{})
- content[src["filename"].(string)] = []byte(src["content"].(string))
- }
- if err := archiver.ArchiveMultiple(content); err != nil {
- return fmt.Errorf("error archiving content: %s", err)
- }
- } else {
- return fmt.Errorf("one of 'source_dir', 'source_file', 'source_content_filename' must be specified")
- }
- return nil
-}
-
-func genFileShas(filename string) (string, string, string, error) {
- data, err := ioutil.ReadFile(filename)
- if err != nil {
- return "", "", "", fmt.Errorf("could not compute file '%s' checksum: %s", filename, err)
- }
- h := sha1.New()
- h.Write([]byte(data))
- sha1 := hex.EncodeToString(h.Sum(nil))
-
- h256 := sha256.New()
- h256.Write([]byte(data))
- shaSum := h256.Sum(nil)
- sha256base64 := base64.StdEncoding.EncodeToString(shaSum[:])
-
- md5 := md5.New()
- md5.Write([]byte(data))
- md5Sum := hex.EncodeToString(md5.Sum(nil))
-
- return sha1, sha256base64, md5Sum, nil
-}
diff --git a/builtin/providers/archive/data_source_archive_file_test.go b/builtin/providers/archive/data_source_archive_file_test.go
deleted file mode 100644
index e1ccc4705..000000000
--- a/builtin/providers/archive/data_source_archive_file_test.go
+++ /dev/null
@@ -1,127 +0,0 @@
-package archive
-
-import (
- "fmt"
- "os"
- "regexp"
- "testing"
-
- r "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccArchiveFile_Basic(t *testing.T) {
- var fileSize string
- r.Test(t, r.TestCase{
- Providers: testProviders,
- Steps: []r.TestStep{
- r.TestStep{
- Config: testAccArchiveFileContentConfig,
- Check: r.ComposeTestCheckFunc(
- testAccArchiveFileExists("zip_file_acc_test.zip", &fileSize),
- r.TestCheckResourceAttrPtr("data.archive_file.foo", "output_size", &fileSize),
-
- // We just check the hashes for syntax rather than exact
- // content since we don't want to break if the archive
- // library starts generating different bytes that are
- // functionally equivalent.
- r.TestMatchResourceAttr(
- "data.archive_file.foo", "output_base64sha256",
- regexp.MustCompile(`^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$`),
- ),
- r.TestMatchResourceAttr(
- "data.archive_file.foo", "output_md5", regexp.MustCompile(`^[0-9a-f]{32}$`),
- ),
- r.TestMatchResourceAttr(
- "data.archive_file.foo", "output_sha", regexp.MustCompile(`^[0-9a-f]{40}$`),
- ),
- ),
- },
- r.TestStep{
- Config: testAccArchiveFileFileConfig,
- Check: r.ComposeTestCheckFunc(
- testAccArchiveFileExists("zip_file_acc_test.zip", &fileSize),
- r.TestCheckResourceAttrPtr("data.archive_file.foo", "output_size", &fileSize),
- ),
- },
- r.TestStep{
- Config: testAccArchiveFileDirConfig,
- Check: r.ComposeTestCheckFunc(
- testAccArchiveFileExists("zip_file_acc_test.zip", &fileSize),
- r.TestCheckResourceAttrPtr("data.archive_file.foo", "output_size", &fileSize),
- ),
- },
- r.TestStep{
- Config: testAccArchiveFileMultiConfig,
- Check: r.ComposeTestCheckFunc(
- testAccArchiveFileExists("zip_file_acc_test.zip", &fileSize),
- r.TestCheckResourceAttrPtr("data.archive_file.foo", "output_size", &fileSize),
- ),
- },
- r.TestStep{
- Config: testAccArchiveFileOutputPath,
- Check: r.ComposeTestCheckFunc(
- testAccArchiveFileExists(fmt.Sprintf("%s/test.zip", tmpDir), &fileSize),
- ),
- },
- },
- })
-}
-
-func testAccArchiveFileExists(filename string, fileSize *string) r.TestCheckFunc {
- return func(s *terraform.State) error {
- *fileSize = ""
- fi, err := os.Stat(filename)
- if err != nil {
- return err
- }
- *fileSize = fmt.Sprintf("%d", fi.Size())
- return nil
- }
-}
-
-var testAccArchiveFileContentConfig = `
-data "archive_file" "foo" {
- type = "zip"
- source_content = "This is some content"
- source_content_filename = "content.txt"
- output_path = "zip_file_acc_test.zip"
-}
-`
-
-var tmpDir = os.TempDir() + "/test"
-var testAccArchiveFileOutputPath = fmt.Sprintf(`
-data "archive_file" "foo" {
- type = "zip"
- source_content = "This is some content"
- source_content_filename = "content.txt"
- output_path = "%s/test.zip"
-}
-`, tmpDir)
-
-var testAccArchiveFileFileConfig = `
-data "archive_file" "foo" {
- type = "zip"
- source_file = "test-fixtures/test-file.txt"
- output_path = "zip_file_acc_test.zip"
-}
-`
-
-var testAccArchiveFileDirConfig = `
-data "archive_file" "foo" {
- type = "zip"
- source_dir = "test-fixtures/test-dir"
- output_path = "zip_file_acc_test.zip"
-}
-`
-
-var testAccArchiveFileMultiConfig = `
-data "archive_file" "foo" {
- type = "zip"
- source {
- filename = "content.txt"
- content = "This is some content"
- }
- output_path = "zip_file_acc_test.zip"
-}
-`
diff --git a/builtin/providers/archive/provider.go b/builtin/providers/archive/provider.go
deleted file mode 100644
index 195b9342a..000000000
--- a/builtin/providers/archive/provider.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package archive
-
-import (
- "github.com/hashicorp/terraform/helper/schema"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func Provider() terraform.ResourceProvider {
- return &schema.Provider{
- DataSourcesMap: map[string]*schema.Resource{
- "archive_file": dataSourceFile(),
- },
- ResourcesMap: map[string]*schema.Resource{
- "archive_file": schema.DataSourceResourceShim(
- "archive_file",
- dataSourceFile(),
- ),
- },
- }
-}
diff --git a/builtin/providers/archive/provider_test.go b/builtin/providers/archive/provider_test.go
deleted file mode 100644
index 13cd92e30..000000000
--- a/builtin/providers/archive/provider_test.go
+++ /dev/null
@@ -1,18 +0,0 @@
-package archive
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/schema"
- "github.com/hashicorp/terraform/terraform"
-)
-
-var testProviders = map[string]terraform.ResourceProvider{
- "archive": Provider(),
-}
-
-func TestProvider(t *testing.T) {
- if err := Provider().(*schema.Provider).InternalValidate(); err != nil {
- t.Fatalf("err: %s", err)
- }
-}
diff --git a/builtin/providers/archive/test-fixtures/test-dir/file1.txt b/builtin/providers/archive/test-fixtures/test-dir/file1.txt
deleted file mode 100644
index 28bf5b1fb..000000000
--- a/builtin/providers/archive/test-fixtures/test-dir/file1.txt
+++ /dev/null
@@ -1 +0,0 @@
-This is file 1
\ No newline at end of file
diff --git a/builtin/providers/archive/test-fixtures/test-dir/file2.txt b/builtin/providers/archive/test-fixtures/test-dir/file2.txt
deleted file mode 100644
index 4419d52b7..000000000
--- a/builtin/providers/archive/test-fixtures/test-dir/file2.txt
+++ /dev/null
@@ -1 +0,0 @@
-This is file 2
\ No newline at end of file
diff --git a/builtin/providers/archive/test-fixtures/test-dir/file3.txt b/builtin/providers/archive/test-fixtures/test-dir/file3.txt
deleted file mode 100644
index 819cd4d48..000000000
--- a/builtin/providers/archive/test-fixtures/test-dir/file3.txt
+++ /dev/null
@@ -1 +0,0 @@
-This is file 3
\ No newline at end of file
diff --git a/builtin/providers/archive/test-fixtures/test-file.txt b/builtin/providers/archive/test-fixtures/test-file.txt
deleted file mode 100644
index 417be07f3..000000000
--- a/builtin/providers/archive/test-fixtures/test-file.txt
+++ /dev/null
@@ -1 +0,0 @@
-This is test content
\ No newline at end of file
diff --git a/builtin/providers/archive/zip_archiver.go b/builtin/providers/archive/zip_archiver.go
deleted file mode 100644
index 0bbdd8825..000000000
--- a/builtin/providers/archive/zip_archiver.go
+++ /dev/null
@@ -1,136 +0,0 @@
-package archive
-
-import (
- "archive/zip"
- "fmt"
- "io/ioutil"
- "os"
- "path/filepath"
- "sort"
-)
-
-type ZipArchiver struct {
- filepath string
- filewriter *os.File
- writer *zip.Writer
-}
-
-func NewZipArchiver(filepath string) Archiver {
- return &ZipArchiver{
- filepath: filepath,
- }
-}
-
-func (a *ZipArchiver) ArchiveContent(content []byte, infilename string) error {
- if err := a.open(); err != nil {
- return err
- }
- defer a.close()
-
- f, err := a.writer.Create(infilename)
- if err != nil {
- return err
- }
-
- _, err = f.Write(content)
- return err
-}
-
-func (a *ZipArchiver) ArchiveFile(infilename string) error {
- fi, err := assertValidFile(infilename)
- if err != nil {
- return err
- }
-
- content, err := ioutil.ReadFile(infilename)
- if err != nil {
- return err
- }
-
- return a.ArchiveContent(content, fi.Name())
-}
-
-func (a *ZipArchiver) ArchiveDir(indirname string) error {
- _, err := assertValidDir(indirname)
- if err != nil {
- return err
- }
-
- if err := a.open(); err != nil {
- return err
- }
- defer a.close()
-
- return filepath.Walk(indirname, func(path string, info os.FileInfo, err error) error {
- if info.IsDir() {
- return nil
- }
- if err != nil {
- return err
- }
- relname, err := filepath.Rel(indirname, path)
- if err != nil {
- return fmt.Errorf("error relativizing file for archival: %s", err)
- }
- f, err := a.writer.Create(relname)
- if err != nil {
- return fmt.Errorf("error creating file inside archive: %s", err)
- }
- content, err := ioutil.ReadFile(path)
- if err != nil {
- return fmt.Errorf("error reading file for archival: %s", err)
- }
- _, err = f.Write(content)
- return err
- })
-
-}
-
-func (a *ZipArchiver) ArchiveMultiple(content map[string][]byte) error {
- if err := a.open(); err != nil {
- return err
- }
- defer a.close()
-
- // Ensure files are processed in the same order so hashes don't change
- keys := make([]string, len(content))
- i := 0
- for k := range content {
- keys[i] = k
- i++
- }
- sort.Strings(keys)
-
- for _, filename := range keys {
- f, err := a.writer.Create(filename)
- if err != nil {
- return err
- }
- _, err = f.Write(content[filename])
- if err != nil {
- return err
- }
- }
- return nil
-}
-
-func (a *ZipArchiver) open() error {
- f, err := os.Create(a.filepath)
- if err != nil {
- return err
- }
- a.filewriter = f
- a.writer = zip.NewWriter(f)
- return nil
-}
-
-func (a *ZipArchiver) close() {
- if a.writer != nil {
- a.writer.Close()
- a.writer = nil
- }
- if a.filewriter != nil {
- a.filewriter.Close()
- a.filewriter = nil
- }
-}
diff --git a/builtin/providers/archive/zip_archiver_test.go b/builtin/providers/archive/zip_archiver_test.go
deleted file mode 100644
index 34a272724..000000000
--- a/builtin/providers/archive/zip_archiver_test.go
+++ /dev/null
@@ -1,101 +0,0 @@
-package archive
-
-import (
- "archive/zip"
- "io/ioutil"
- "testing"
-)
-
-func TestZipArchiver_Content(t *testing.T) {
- zipfilepath := "archive-content.zip"
- archiver := NewZipArchiver(zipfilepath)
- if err := archiver.ArchiveContent([]byte("This is some content"), "content.txt"); err != nil {
- t.Fatalf("unexpected error: %s", err)
- }
-
- ensureContents(t, zipfilepath, map[string][]byte{
- "content.txt": []byte("This is some content"),
- })
-}
-
-func TestZipArchiver_File(t *testing.T) {
- zipfilepath := "archive-file.zip"
- archiver := NewZipArchiver(zipfilepath)
- if err := archiver.ArchiveFile("./test-fixtures/test-file.txt"); err != nil {
- t.Fatalf("unexpected error: %s", err)
- }
-
- ensureContents(t, zipfilepath, map[string][]byte{
- "test-file.txt": []byte("This is test content"),
- })
-}
-
-func TestZipArchiver_Dir(t *testing.T) {
- zipfilepath := "archive-dir.zip"
- archiver := NewZipArchiver(zipfilepath)
- if err := archiver.ArchiveDir("./test-fixtures/test-dir"); err != nil {
- t.Fatalf("unexpected error: %s", err)
- }
-
- ensureContents(t, zipfilepath, map[string][]byte{
- "file1.txt": []byte("This is file 1"),
- "file2.txt": []byte("This is file 2"),
- "file3.txt": []byte("This is file 3"),
- })
-}
-
-func TestZipArchiver_Multiple(t *testing.T) {
- zipfilepath := "archive-content.zip"
- content := map[string][]byte{
- "file1.txt": []byte("This is file 1"),
- "file2.txt": []byte("This is file 2"),
- "file3.txt": []byte("This is file 3"),
- }
-
- archiver := NewZipArchiver(zipfilepath)
- if err := archiver.ArchiveMultiple(content); err != nil {
- t.Fatalf("unexpected error: %s", err)
- }
-
- ensureContents(t, zipfilepath, content)
-
-}
-
-func ensureContents(t *testing.T, zipfilepath string, wants map[string][]byte) {
- r, err := zip.OpenReader(zipfilepath)
- if err != nil {
- t.Fatalf("could not open zip file: %s", err)
- }
- defer r.Close()
-
- if len(r.File) != len(wants) {
- t.Errorf("mismatched file count, got %d, want %d", len(r.File), len(wants))
- }
- for _, cf := range r.File {
- ensureContent(t, wants, cf)
- }
-}
-
-func ensureContent(t *testing.T, wants map[string][]byte, got *zip.File) {
- want, ok := wants[got.Name]
- if !ok {
- t.Errorf("additional file in zip: %s", got.Name)
- return
- }
-
- r, err := got.Open()
- if err != nil {
- t.Errorf("could not open file: %s", err)
- }
- defer r.Close()
- gotContentBytes, err := ioutil.ReadAll(r)
- if err != nil {
- t.Errorf("could not read file: %s", err)
- }
-
- wantContent := string(want)
- gotContent := string(gotContentBytes)
- if gotContent != wantContent {
- t.Errorf("mismatched content\ngot\n%s\nwant\n%s", gotContent, wantContent)
- }
-}
diff --git a/builtin/providers/arukas/config.go b/builtin/providers/arukas/config.go
deleted file mode 100644
index 330c4a76b..000000000
--- a/builtin/providers/arukas/config.go
+++ /dev/null
@@ -1,52 +0,0 @@
-package arukas
-
-import (
- API "github.com/arukasio/cli"
- "os"
- "time"
-)
-
-const (
- JSONTokenParamName = "ARUKAS_JSON_API_TOKEN"
- JSONSecretParamName = "ARUKAS_JSON_API_SECRET"
- JSONUrlParamName = "ARUKAS_JSON_API_URL"
- JSONDebugParamName = "ARUKAS_DEBUG"
- JSONTimeoutParamName = "ARUKAS_TIMEOUT"
-)
-
-type Config struct {
- Token string
- Secret string
- URL string
- Trace string
- Timeout int
-}
-
-func (c *Config) NewClient() (*ArukasClient, error) {
-
- os.Setenv(JSONTokenParamName, c.Token)
- os.Setenv(JSONSecretParamName, c.Secret)
- os.Setenv(JSONUrlParamName, c.URL)
- os.Setenv(JSONDebugParamName, c.Trace)
-
- client, err := API.NewClient()
- if err != nil {
- return nil, err
- }
- client.UserAgent = "Terraform for Arukas"
-
- timeout := time.Duration(0)
- if c.Timeout > 0 {
- timeout = time.Duration(c.Timeout) * time.Second
- }
-
- return &ArukasClient{
- Client: client,
- Timeout: timeout,
- }, nil
-}
-
-type ArukasClient struct {
- *API.Client
- Timeout time.Duration
-}
diff --git a/builtin/providers/arukas/provider.go b/builtin/providers/arukas/provider.go
deleted file mode 100644
index 81f4a3264..000000000
--- a/builtin/providers/arukas/provider.go
+++ /dev/null
@@ -1,59 +0,0 @@
-package arukas
-
-import (
- "github.com/hashicorp/terraform/helper/schema"
- "github.com/hashicorp/terraform/terraform"
-)
-
-// Provider returns a terraform.ResourceProvider.
-func Provider() terraform.ResourceProvider {
- return &schema.Provider{
- Schema: map[string]*schema.Schema{
- "token": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- DefaultFunc: schema.EnvDefaultFunc(JSONTokenParamName, nil),
- Description: "your Arukas APIKey(token)",
- },
- "secret": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- DefaultFunc: schema.EnvDefaultFunc(JSONSecretParamName, nil),
- Description: "your Arukas APIKey(secret)",
- },
- "api_url": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- DefaultFunc: schema.EnvDefaultFunc(JSONUrlParamName, "https://app.arukas.io/api/"),
- Description: "default Arukas API url",
- },
- "trace": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- DefaultFunc: schema.EnvDefaultFunc(JSONDebugParamName, ""),
- },
- "timeout": &schema.Schema{
- Type: schema.TypeInt,
- Optional: true,
- DefaultFunc: schema.EnvDefaultFunc(JSONTimeoutParamName, "900"),
- },
- },
- ResourcesMap: map[string]*schema.Resource{
- "arukas_container": resourceArukasContainer(),
- },
- ConfigureFunc: providerConfigure,
- }
-}
-
-func providerConfigure(d *schema.ResourceData) (interface{}, error) {
-
- config := Config{
- Token: d.Get("token").(string),
- Secret: d.Get("secret").(string),
- URL: d.Get("api_url").(string),
- Trace: d.Get("trace").(string),
- Timeout: d.Get("timeout").(int),
- }
-
- return config.NewClient()
-}
diff --git a/builtin/providers/arukas/provider_test.go b/builtin/providers/arukas/provider_test.go
deleted file mode 100644
index d1b5d87e6..000000000
--- a/builtin/providers/arukas/provider_test.go
+++ /dev/null
@@ -1,38 +0,0 @@
-package arukas
-
-import (
- "os"
- "testing"
-
- "github.com/hashicorp/terraform/helper/schema"
- "github.com/hashicorp/terraform/terraform"
-)
-
-var testAccProviders map[string]terraform.ResourceProvider
-var testAccProvider *schema.Provider
-
-func init() {
- testAccProvider = Provider().(*schema.Provider)
- testAccProviders = map[string]terraform.ResourceProvider{
- "arukas": testAccProvider,
- }
-}
-
-func TestProvider(t *testing.T) {
- if err := Provider().(*schema.Provider).InternalValidate(); err != nil {
- t.Fatalf("err: %s", err)
- }
-}
-
-func TestProvider_impl(t *testing.T) {
- var _ terraform.ResourceProvider = Provider()
-}
-
-func testAccPreCheck(t *testing.T) {
- if v := os.Getenv("ARUKAS_JSON_API_TOKEN"); v == "" {
- t.Fatal("ARUKAS_JSON_API_TOKEN must be set for acceptance tests")
- }
- if v := os.Getenv("ARUKAS_JSON_API_SECRET"); v == "" {
- t.Fatal("ARUKAS_JSON_API_SECRET must be set for acceptance tests")
- }
-}
diff --git a/builtin/providers/arukas/resource_arukas_container.go b/builtin/providers/arukas/resource_arukas_container.go
deleted file mode 100644
index cb40dfc0f..000000000
--- a/builtin/providers/arukas/resource_arukas_container.go
+++ /dev/null
@@ -1,289 +0,0 @@
-package arukas
-
-import (
- "fmt"
- "strings"
-
- API "github.com/arukasio/cli"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func resourceArukasContainer() *schema.Resource {
- return &schema.Resource{
- Create: resourceArukasContainerCreate,
- Read: resourceArukasContainerRead,
- Update: resourceArukasContainerUpdate,
- Delete: resourceArukasContainerDelete,
- Importer: &schema.ResourceImporter{
- State: schema.ImportStatePassthrough,
- },
- Schema: map[string]*schema.Schema{
- "name": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
- "image": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
- "instances": &schema.Schema{
- Type: schema.TypeInt,
- Optional: true,
- Default: 1,
- ValidateFunc: validateIntegerInRange(1, 10),
- },
- "memory": &schema.Schema{
- Type: schema.TypeInt,
- Optional: true,
- Default: 256,
- ValidateFunc: validateIntInWord([]string{"256", "512"}),
- },
- "endpoint": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "ports": &schema.Schema{
- Type: schema.TypeList,
- Required: true,
- MaxItems: 20,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "protocol": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Default: "tcp",
- ValidateFunc: validateStringInWord([]string{"tcp", "udp"}),
- },
- "number": &schema.Schema{
- Type: schema.TypeInt,
- Optional: true,
- Default: "80",
- ValidateFunc: validateIntegerInRange(1, 65535),
- },
- },
- },
- },
- "environments": &schema.Schema{
- Type: schema.TypeList,
- Optional: true,
- MaxItems: 20,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "key": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
- "value": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
- },
- },
- },
- "cmd": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- },
- "port_mappings": &schema.Schema{
- Type: schema.TypeList,
- Computed: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "host": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- "ipaddress": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- "container_port": &schema.Schema{
- Type: schema.TypeInt,
- Computed: true,
- },
- "service_port": &schema.Schema{
- Type: schema.TypeInt,
- Computed: true,
- },
- },
- },
- },
- "endpoint_full_hostname": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- "endpoint_full_url": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- "app_id": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- },
- }
-}
-
-func resourceArukasContainerCreate(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*ArukasClient)
-
- var appSet API.AppSet
-
- // create an app
- newApp := API.App{Name: d.Get("name").(string)}
-
- var parsedEnvs API.Envs
- var parsedPorts API.Ports
-
- if rawEnvs, ok := d.GetOk("environments"); ok {
- parsedEnvs = expandEnvs(rawEnvs)
- }
- if rawPorts, ok := d.GetOk("ports"); ok {
- parsedPorts = expandPorts(rawPorts)
- }
-
- newContainer := API.Container{
- Envs: parsedEnvs,
- Ports: parsedPorts,
- ImageName: d.Get("image").(string),
- Mem: d.Get("memory").(int),
- Instances: d.Get("instances").(int),
- Cmd: d.Get("cmd").(string),
-
- Name: d.Get("endpoint").(string),
- }
- newAppSet := API.AppSet{
- App: newApp,
- Container: newContainer,
- }
-
- // create
- if err := client.Post(&appSet, "/app-sets", newAppSet); err != nil {
- return err
- }
-
- // start container
- if err := client.Post(nil, fmt.Sprintf("/containers/%s/power", appSet.Container.ID), nil); err != nil {
- return err
- }
-
- d.SetId(appSet.Container.ID)
-
- stateConf := &resource.StateChangeConf{
- Target: []string{"running"},
- Pending: []string{"stopped", "booting"},
- Timeout: client.Timeout,
- Refresh: func() (interface{}, string, error) {
- var container API.Container
- err := client.Get(&container, fmt.Sprintf("/containers/%s", appSet.Container.ID))
- if err != nil {
- return nil, "", err
- }
-
- return container, container.StatusText, nil
- },
- }
- _, err := stateConf.WaitForState()
- if err != nil {
- return err
- }
-
- return resourceArukasContainerRead(d, meta)
-}
-
-func resourceArukasContainerRead(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*ArukasClient)
-
- var container API.Container
- var app API.App
-
- if err := client.Get(&container, fmt.Sprintf("/containers/%s", d.Id())); err != nil {
- return err
- }
- if err := client.Get(&app, fmt.Sprintf("/apps/%s", container.AppID)); err != nil {
- return err
- }
-
- d.Set("app_id", container.AppID)
- d.Set("name", app.Name)
- d.Set("image", container.ImageName)
- d.Set("instances", container.Instances)
- d.Set("memory", container.Mem)
- endpoint := container.Endpoint
- if strings.HasSuffix(endpoint, ".arukascloud.io") {
- endpoint = strings.Replace(endpoint, ".arukascloud.io", "", -1)
- }
-
- d.Set("endpoint", endpoint)
- d.Set("endpoint_full_hostname", container.Endpoint)
- d.Set("endpoint_full_url", fmt.Sprintf("https://%s", container.Endpoint))
-
- d.Set("cmd", container.Cmd)
-
- //ports
- d.Set("ports", flattenPorts(container.Ports))
-
- //port mappings
- d.Set("port_mappings", flattenPortMappings(container.PortMappings))
-
- //envs
- d.Set("environments", flattenEnvs(container.Envs))
-
- return nil
-}
-
-func resourceArukasContainerUpdate(d *schema.ResourceData, meta interface{}) error {
-
- client := meta.(*ArukasClient)
- var container API.Container
-
- if err := client.Get(&container, fmt.Sprintf("/containers/%s", d.Id())); err != nil {
- return err
- }
-
- var parsedEnvs API.Envs
- var parsedPorts API.Ports
-
- if rawEnvs, ok := d.GetOk("environments"); ok {
- parsedEnvs = expandEnvs(rawEnvs)
- }
- if rawPorts, ok := d.GetOk("ports"); ok {
- parsedPorts = expandPorts(rawPorts)
- }
-
- newContainer := API.Container{
- Envs: parsedEnvs,
- Ports: parsedPorts,
- ImageName: d.Get("image").(string),
- Mem: d.Get("memory").(int),
- Instances: d.Get("instances").(int),
- Cmd: d.Get("cmd").(string),
- Name: d.Get("endpoint").(string),
- }
-
- // update
- if err := client.Patch(nil, fmt.Sprintf("/containers/%s", d.Id()), newContainer); err != nil {
- return err
- }
-
- return resourceArukasContainerRead(d, meta)
-
-}
-
-func resourceArukasContainerDelete(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*ArukasClient)
- var container API.Container
-
- if err := client.Get(&container, fmt.Sprintf("/containers/%s", d.Id())); err != nil {
- return err
- }
-
- if err := client.Delete(fmt.Sprintf("/apps/%s", container.AppID)); err != nil {
- return err
- }
-
- return nil
-}
diff --git a/builtin/providers/arukas/resource_arukas_container_test.go b/builtin/providers/arukas/resource_arukas_container_test.go
deleted file mode 100644
index 3fabc9b0d..000000000
--- a/builtin/providers/arukas/resource_arukas_container_test.go
+++ /dev/null
@@ -1,301 +0,0 @@
-package arukas
-
-import (
- "fmt"
- API "github.com/arukasio/cli"
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
- "testing"
-)
-
-func TestAccArukasContainer_Basic(t *testing.T) {
- var container API.Container
- randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)
- name := fmt.Sprintf("terraform_acc_test_%s", randString)
- endpoint := fmt.Sprintf("terraform-acc-test-endpoint-%s", randString)
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckArukasContainerDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccCheckArukasContainerConfig_basic(randString),
- Check: resource.ComposeTestCheckFunc(
- testAccCheckArukasContainerExists("arukas_container.foobar", &container),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "name", name),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "image", "nginx:latest"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "instances", "1"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "memory", "256"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "endpoint", endpoint),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "ports.#", "1"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "ports.0.protocol", "tcp"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "ports.0.number", "80"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "environments.#", "1"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "environments.0.key", "key"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "environments.0.value", "value"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "port_mappings.#", "1"),
- ),
- },
- },
- })
-}
-
-func TestAccArukasContainer_Update(t *testing.T) {
- var container API.Container
- randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)
- name := fmt.Sprintf("terraform_acc_test_%s", randString)
- updatedName := fmt.Sprintf("terraform_acc_test_update_%s", randString)
- endpoint := fmt.Sprintf("terraform-acc-test-endpoint-%s", randString)
- updatedEndpoint := fmt.Sprintf("terraform-acc-test-endpoint-update-%s", randString)
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckArukasContainerDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccCheckArukasContainerConfig_basic(randString),
- Check: resource.ComposeTestCheckFunc(
- testAccCheckArukasContainerExists("arukas_container.foobar", &container),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "name", name),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "image", "nginx:latest"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "instances", "1"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "memory", "256"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "endpoint", endpoint),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "ports.#", "1"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "ports.0.protocol", "tcp"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "ports.0.number", "80"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "environments.#", "1"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "environments.0.key", "key"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "environments.0.value", "value"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "port_mappings.#", "1"),
- ),
- },
- resource.TestStep{
- Config: testAccCheckArukasContainerConfig_update(randString),
- Check: resource.ComposeTestCheckFunc(
- testAccCheckArukasContainerExists("arukas_container.foobar", &container),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "name", updatedName),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "image", "nginx:latest"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "instances", "2"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "memory", "512"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "endpoint", updatedEndpoint),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "ports.#", "2"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "ports.0.protocol", "tcp"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "ports.0.number", "80"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "ports.1.protocol", "tcp"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "ports.1.number", "443"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "environments.#", "2"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "environments.0.key", "key"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "environments.0.value", "value"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "environments.1.key", "key_upd"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "environments.1.value", "value_upd"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "port_mappings.#", "4"),
- ),
- },
- },
- })
-}
-
-func TestAccArukasContainer_Minimum(t *testing.T) {
- var container API.Container
- randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)
- name := fmt.Sprintf("terraform_acc_test_minimum_%s", randString)
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckArukasContainerDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccCheckArukasContainerConfig_minimum(randString),
- Check: resource.ComposeTestCheckFunc(
- testAccCheckArukasContainerExists("arukas_container.foobar", &container),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "name", name),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "image", "nginx:latest"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "instances", "1"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "memory", "256"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "ports.#", "1"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "ports.0.protocol", "tcp"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "ports.0.number", "80"),
- resource.TestCheckResourceAttr(
- "arukas_container.foobar", "port_mappings.#", "1"),
- ),
- },
- },
- })
-}
-
-func TestAccArukasContainer_Import(t *testing.T) {
- resourceName := "arukas_container.foobar"
- randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckArukasContainerDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccCheckArukasContainerConfig_basic(randString),
- },
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
-
-func testAccCheckArukasContainerExists(n string, container *API.Container) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
-
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No Container ID is set")
- }
- client := testAccProvider.Meta().(*ArukasClient)
- var foundContainer API.Container
- err := client.Get(&foundContainer, fmt.Sprintf("/containers/%s", rs.Primary.ID))
-
- if err != nil {
- return err
- }
-
- if foundContainer.ID != rs.Primary.ID {
- return fmt.Errorf("Container not found")
- }
-
- *container = foundContainer
-
- return nil
- }
-}
-
-func testAccCheckArukasContainerDestroy(s *terraform.State) error {
- client := testAccProvider.Meta().(*ArukasClient)
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "arukas_container" {
- continue
- }
-
- err := client.Get(nil, fmt.Sprintf("/containers/%s", rs.Primary.ID))
-
- if err == nil {
- return fmt.Errorf("Note still exists")
- }
- }
-
- return nil
-}
-
-func testAccCheckArukasContainerConfig_basic(randString string) string {
- return fmt.Sprintf(`
-resource "arukas_container" "foobar" {
- name = "terraform_acc_test_%s"
- image = "nginx:latest"
- instances = 1
- memory = 256
- endpoint = "terraform-acc-test-endpoint-%s"
- ports = {
- protocol = "tcp"
- number = "80"
- }
- environments {
- key = "key"
- value = "value"
- }
-}`, randString, randString)
-}
-
-func testAccCheckArukasContainerConfig_update(randString string) string {
- return fmt.Sprintf(`
-resource "arukas_container" "foobar" {
- name = "terraform_acc_test_update_%s"
- image = "nginx:latest"
- instances = 2
- memory = 512
- endpoint = "terraform-acc-test-endpoint-update-%s"
- ports = {
- protocol = "tcp"
- number = "80"
- }
- ports = {
- protocol = "tcp"
- number = "443"
- }
- environments {
- key = "key"
- value = "value"
- }
- environments {
- key = "key_upd"
- value = "value_upd"
- }
-}`, randString, randString)
-}
-
-func testAccCheckArukasContainerConfig_minimum(randString string) string {
- return fmt.Sprintf(`
-resource "arukas_container" "foobar" {
- name = "terraform_acc_test_minimum_%s"
- image = "nginx:latest"
- ports = {
- number = "80"
- }
-}`, randString)
-}
diff --git a/builtin/providers/arukas/structure.go b/builtin/providers/arukas/structure.go
deleted file mode 100644
index 155de034c..000000000
--- a/builtin/providers/arukas/structure.go
+++ /dev/null
@@ -1,110 +0,0 @@
-package arukas
-
-import (
- API "github.com/arukasio/cli"
- "github.com/hashicorp/terraform/helper/schema"
- "net"
-)
-
-// Takes the result of flatmap.Expand for an array of strings
-// and returns a []string
-func expandStringList(configured []interface{}) []string {
- vs := make([]string, 0, len(configured))
- for _, v := range configured {
- vs = append(vs, string(v.(string)))
- }
- return vs
-}
-
-// Takes the result of schema.Set of strings and returns a []string
-func expandStringSet(configured *schema.Set) []string {
- return expandStringList(configured.List())
-}
-
-// Takes list of pointers to strings. Expand to an array
-// of raw strings and returns a []interface{}
-// to keep compatibility w/ schema.NewSetschema.NewSet
-func flattenStringList(list []string) []interface{} {
- vs := make([]interface{}, 0, len(list))
- for _, v := range list {
- vs = append(vs, v)
- }
- return vs
-}
-
-func expandEnvs(configured interface{}) API.Envs {
- var envs API.Envs
- if configured == nil {
- return envs
- }
- rawEnvs := configured.([]interface{})
- for _, raw := range rawEnvs {
- env := raw.(map[string]interface{})
- envs = append(envs, API.Env{Key: env["key"].(string), Value: env["value"].(string)})
- }
- return envs
-}
-
-func flattenEnvs(envs API.Envs) []interface{} {
- var ret []interface{}
- for _, env := range envs {
- r := map[string]interface{}{}
- r["key"] = env.Key
- r["value"] = env.Value
- ret = append(ret, r)
- }
- return ret
-}
-
-func expandPorts(configured interface{}) API.Ports {
- var ports API.Ports
- if configured == nil {
- return ports
- }
- rawPorts := configured.([]interface{})
- for _, raw := range rawPorts {
- port := raw.(map[string]interface{})
- ports = append(ports, API.Port{Protocol: port["protocol"].(string), Number: port["number"].(int)})
- }
- return ports
-}
-
-func flattenPorts(ports API.Ports) []interface{} {
- var ret []interface{}
- for _, port := range ports {
- r := map[string]interface{}{}
- r["protocol"] = port.Protocol
- r["number"] = port.Number
- ret = append(ret, r)
- }
- return ret
-}
-func flattenPortMappings(ports API.PortMappings) []interface{} {
- var ret []interface{}
- for _, tasks := range ports {
- for _, port := range tasks {
- r := map[string]interface{}{}
- ip := ""
-
- addrs, err := net.LookupHost(port.Host)
- if err == nil && len(addrs) > 0 {
- ip = addrs[0]
- }
-
- r["host"] = port.Host
- r["ipaddress"] = ip
- r["container_port"] = port.ContainerPort
- r["service_port"] = port.ServicePort
- ret = append(ret, r)
- }
- }
- return ret
-}
-
-func forceString(target interface{}) string {
- if target == nil {
- return ""
- }
-
- return target.(string)
-}
diff --git a/builtin/providers/arukas/validators.go b/builtin/providers/arukas/validators.go
deleted file mode 100644
index e1c6a866c..000000000
--- a/builtin/providers/arukas/validators.go
+++ /dev/null
@@ -1,92 +0,0 @@
-package arukas
-
-import (
- "fmt"
- "github.com/hashicorp/terraform/helper/schema"
- "strings"
-)
-
-func validateMaxLength(minLength, maxLength int) schema.SchemaValidateFunc {
- return func(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
- if len(value) < minLength {
- errors = append(errors, fmt.Errorf(
- "%q cannot be shorter than %d characters: %q", k, minLength, value))
- }
- if len(value) > maxLength {
- errors = append(errors, fmt.Errorf(
- "%q cannot be longer than %d characters: %q", k, maxLength, value))
- }
- return
- }
-}
-
-func validateIntegerInRange(min, max int) schema.SchemaValidateFunc {
- return func(v interface{}, k string) (ws []string, errors []error) {
- value := v.(int)
- if value < min {
- errors = append(errors, fmt.Errorf(
- "%q cannot be lower than %d: %d", k, min, value))
- }
- if value > max {
- errors = append(errors, fmt.Errorf(
- "%q cannot be higher than %d: %d", k, max, value))
- }
- return
- }
-}
-
-func validateStringInWord(allowWords []string) schema.SchemaValidateFunc {
- return func(v interface{}, k string) (ws []string, errors []error) {
- var found bool
- for _, t := range allowWords {
- if v.(string) == t {
- found = true
- }
- }
- if !found {
- errors = append(errors, fmt.Errorf("%q must be one of [%s]", k, strings.Join(allowWords, "/")))
-
- }
- return
- }
-}
-
-func validateIntInWord(allowWords []string) schema.SchemaValidateFunc {
- return func(v interface{}, k string) (ws []string, errors []error) {
- var found bool
- for _, t := range allowWords {
- if fmt.Sprintf("%d", v.(int)) == t {
- found = true
- }
- }
- if !found {
- errors = append(errors, fmt.Errorf("%q must be one of [%s]", k, strings.Join(allowWords, "/")))
-
- }
- return
- }
-}
-
-func validateDNSRecordValue() schema.SchemaValidateFunc {
- return func(v interface{}, k string) (ws []string, errors []error) {
- var rtype, value string
-
- values := v.(map[string]interface{})
- rtype = values["type"].(string)
- value = values["value"].(string)
- switch rtype {
- case "MX", "NS", "CNAME":
- if rtype == "MX" {
- if values["priority"] == nil {
- errors = append(errors, fmt.Errorf("%q required when TYPE was MX", k))
- }
- }
- if !strings.HasSuffix(value, ".") {
- errors = append(errors, fmt.Errorf("%q must be period at the end [%s]", k, value))
- }
- }
- return
- }
-
-}
diff --git a/builtin/providers/atlas/data_source_artifact.go b/builtin/providers/atlas/data_source_artifact.go
deleted file mode 100644
index 7dcfdbe81..000000000
--- a/builtin/providers/atlas/data_source_artifact.go
+++ /dev/null
@@ -1,149 +0,0 @@
-package atlas
-
-import (
- "fmt"
-
- "github.com/hashicorp/atlas-go/v1"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAtlasArtifact() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceArtifactRead,
-
- Schema: map[string]*schema.Schema{
- "name": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
-
- "type": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
-
- "build": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
-
- "version": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
-
- "metadata_keys": &schema.Schema{
- Type: schema.TypeSet,
- Optional: true,
- ForceNew: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- Set: schema.HashString,
- },
-
- "metadata": &schema.Schema{
- Type: schema.TypeMap,
- Optional: true,
- ForceNew: true,
- },
-
- "file_url": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
-
- "metadata_full": &schema.Schema{
- Type: schema.TypeMap,
- Computed: true,
- },
-
- "slug": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
-
- "version_real": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- },
- }
-}
-
-func dataSourceArtifactRead(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*atlas.Client)
-
- // Parse the slug from the name given of the artifact since the API
- // expects these to be split.
- user, name, err := atlas.ParseSlug(d.Get("name").(string))
- if err != nil {
- return err
- }
-
- // Filter by version or build if given
- var build, version string
- if v, ok := d.GetOk("version"); ok {
- version = v.(string)
- } else if b, ok := d.GetOk("build"); ok {
- build = b.(string)
- }
-
- // If we have neither, default to latest version
- if build == "" && version == "" {
- version = "latest"
- }
-
- // Compile the metadata search params
- md := make(map[string]string)
- for _, v := range d.Get("metadata_keys").(*schema.Set).List() {
- md[v.(string)] = atlas.MetadataAnyValue
- }
- for k, v := range d.Get("metadata").(map[string]interface{}) {
- md[k] = v.(string)
- }
-
- // Do the search!
- vs, err := client.ArtifactSearch(&atlas.ArtifactSearchOpts{
- User: user,
- Name: name,
- Type: d.Get("type").(string),
- Build: build,
- Version: version,
- Metadata: md,
- })
- if err != nil {
- return fmt.Errorf(
- "Error searching for artifact '%s/%s': %s",
- user, name, err)
- }
-
- if len(vs) == 0 {
- return fmt.Errorf("No matching artifact for '%s/%s'", user, name)
- } else if len(vs) > 1 {
- return fmt.Errorf(
- "Got %d results for '%s/%s', only one is allowed",
- len(vs), user, name)
- }
- v := vs[0]
-
- d.SetId(v.ID)
- if v.ID == "" {
- d.SetId(fmt.Sprintf("%s %d", v.Tag, v.Version))
- }
- d.Set("version_real", v.Version)
- d.Set("metadata_full", cleanMetadata(v.Metadata))
- d.Set("slug", v.Slug)
-
- d.Set("file_url", "")
- if u, err := client.ArtifactFileURL(v); err != nil {
- return fmt.Errorf(
- "Error reading file URL: %s", err)
- } else if u != nil {
- d.Set("file_url", u.String())
- }
-
- return nil
-}
diff --git a/builtin/providers/atlas/data_source_artifact_test.go b/builtin/providers/atlas/data_source_artifact_test.go
deleted file mode 100644
index c6d503b3b..000000000
--- a/builtin/providers/atlas/data_source_artifact_test.go
+++ /dev/null
@@ -1,150 +0,0 @@
-package atlas
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccDataSourceArtifact_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDataArtifact_basic,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckDataArtifactState("name", "hashicorp/tf-provider-test"),
- ),
- },
- },
- })
-}
-
-func TestAccDataSourceArtifact_metadata(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDataArtifact_metadata,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckDataArtifactState("name", "hashicorp/tf-provider-test"),
- testAccCheckDataArtifactState("id", "x86"),
- testAccCheckDataArtifactState("metadata_full.arch", "x86"),
- ),
- },
- },
- })
-}
-
-func TestAccDataSourceArtifact_metadataSet(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDataArtifact_metadataSet,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckDataArtifactState("name", "hashicorp/tf-provider-test"),
- testAccCheckDataArtifactState("id", "x64"),
- testAccCheckDataArtifactState("metadata_full.arch", "x64"),
- ),
- },
- },
- })
-}
-
-func TestAccDataSourceArtifact_buildLatest(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDataArtifact_buildLatest,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckDataArtifactState("name", "hashicorp/tf-provider-test"),
- ),
- },
- },
- })
-}
-
-func TestAccDataSourceArtifact_versionAny(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDataArtifact_versionAny,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckDataArtifactState("name", "hashicorp/tf-provider-test"),
- ),
- },
- },
- })
-}
-
-func testAccCheckDataArtifactState(key, value string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources["data.atlas_artifact.foobar"]
- if !ok {
- return fmt.Errorf("Not found: %s", "data.atlas_artifact.foobar")
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No ID is set")
- }
-
- p := rs.Primary
- if p.Attributes[key] != value {
- return fmt.Errorf(
- "%s != %s (actual: %s)", key, value, p.Attributes[key])
- }
-
- return nil
- }
-}
-
-const testAccDataArtifact_basic = `
-data "atlas_artifact" "foobar" {
- name = "hashicorp/tf-provider-test"
- type = "foo"
-}`
-
-const testAccDataArtifact_metadata = `
-data "atlas_artifact" "foobar" {
- name = "hashicorp/tf-provider-test"
- type = "foo"
- metadata {
- arch = "x86"
- }
- version = "any"
-}`
-
-const testAccDataArtifact_metadataSet = `
-data "atlas_artifact" "foobar" {
- name = "hashicorp/tf-provider-test"
- type = "foo"
- metadata_keys = ["arch"]
- version = "any"
-}`
-
-const testAccDataArtifact_buildLatest = `
-data "atlas_artifact" "foobar" {
- name = "hashicorp/tf-provider-test"
- type = "foo"
- build = "latest"
- metadata {
- arch = "x86"
- }
-}`
-
-const testAccDataArtifact_versionAny = `
-data "atlas_artifact" "foobar" {
- name = "hashicorp/tf-provider-test"
- type = "foo"
- version = "any"
-}`
diff --git a/builtin/providers/atlas/provider.go b/builtin/providers/atlas/provider.go
deleted file mode 100644
index 14928de63..000000000
--- a/builtin/providers/atlas/provider.go
+++ /dev/null
@@ -1,71 +0,0 @@
-package atlas
-
-import (
- "github.com/hashicorp/atlas-go/v1"
- "github.com/hashicorp/terraform/helper/schema"
- "github.com/hashicorp/terraform/terraform"
-)
-
-const (
- // defaultAtlasServer is the default endpoint for Atlas if
- // none is specified.
- defaultAtlasServer = "https://atlas.hashicorp.com"
-)
-
-// Provider returns a terraform.ResourceProvider.
-func Provider() terraform.ResourceProvider {
- return &schema.Provider{
- Schema: map[string]*schema.Schema{
- "token": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- DefaultFunc: schema.EnvDefaultFunc("ATLAS_TOKEN", nil),
- Description: descriptions["token"],
- },
-
- "address": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- DefaultFunc: schema.EnvDefaultFunc("ATLAS_ADDRESS", defaultAtlasServer),
- Description: descriptions["address"],
- },
- },
-
- DataSourcesMap: map[string]*schema.Resource{
- "atlas_artifact": dataSourceAtlasArtifact(),
- },
-
- ResourcesMap: map[string]*schema.Resource{
- "atlas_artifact": resourceArtifact(),
- },
-
- ConfigureFunc: providerConfigure,
- }
-}
-
-func providerConfigure(d *schema.ResourceData) (interface{}, error) {
- var err error
- client := atlas.DefaultClient()
- if v := d.Get("address").(string); v != "" {
- client, err = atlas.NewClient(v)
- if err != nil {
- return nil, err
- }
- }
- client.DefaultHeader.Set(terraform.VersionHeader, terraform.VersionString())
- client.Token = d.Get("token").(string)
-
- return client, nil
-}
-
-var descriptions map[string]string
-
-func init() {
- descriptions = map[string]string{
- "address": "The address of the Atlas server. If blank, the public\n" +
- "server at atlas.hashicorp.com will be used.",
-
- "token": "The access token for reading artifacts. This is required\n" +
- "if reading private artifacts.",
- }
-}
diff --git a/builtin/providers/atlas/provider_test.go b/builtin/providers/atlas/provider_test.go
deleted file mode 100644
index cd03dc3a5..000000000
--- a/builtin/providers/atlas/provider_test.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package atlas
-
-import (
- "os"
- "testing"
-
- "github.com/hashicorp/terraform/helper/schema"
- "github.com/hashicorp/terraform/terraform"
-)
-
-var testAccProviders map[string]terraform.ResourceProvider
-var testAccProvider *schema.Provider
-
-func init() {
- testAccProvider = Provider().(*schema.Provider)
- testAccProviders = map[string]terraform.ResourceProvider{
- "atlas": testAccProvider,
- }
-}
-
-func TestProvider(t *testing.T) {
- if err := Provider().(*schema.Provider).InternalValidate(); err != nil {
- t.Fatalf("err: %s", err)
- }
-}
-
-func TestProvider_impl(t *testing.T) {
- var _ terraform.ResourceProvider = Provider()
-}
-
-func testAccPreCheck(t *testing.T) {
- if v := os.Getenv("ATLAS_TOKEN"); v == "" {
- t.Fatal("ATLAS_TOKEN must be set for acceptance tests")
- }
-}
diff --git a/builtin/providers/atlas/resource_artifact.go b/builtin/providers/atlas/resource_artifact.go
deleted file mode 100644
index 4967de412..000000000
--- a/builtin/providers/atlas/resource_artifact.go
+++ /dev/null
@@ -1,176 +0,0 @@
-package atlas
-
-import (
- "fmt"
- "regexp"
-
- "github.com/hashicorp/atlas-go/v1"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-var (
- // saneMetaKey is used to sanitize the metadata keys so that
- // they can be accessed as a variable interpolation from TF
- saneMetaKey = regexp.MustCompile("[^a-zA-Z0-9-_]")
-)
-
-func resourceArtifact() *schema.Resource {
- return &schema.Resource{
- Create: resourceArtifactRead,
- Read: resourceArtifactRead,
- Delete: resourceArtifactDelete,
-
- Schema: map[string]*schema.Schema{
- "name": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- Deprecated: `atlas_artifact is now deprecated. Use the Atlas Artifact Data Source instead. See https://www.terraform.io/docs/providers/terraform-enterprise/d/artifact.html`,
- },
-
- "type": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
-
- "build": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
-
- "version": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
-
- "metadata_keys": &schema.Schema{
- Type: schema.TypeSet,
- Optional: true,
- ForceNew: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- Set: schema.HashString,
- },
-
- "metadata": &schema.Schema{
- Type: schema.TypeMap,
- Optional: true,
- ForceNew: true,
- },
-
- "file_url": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
-
- "metadata_full": &schema.Schema{
- Type: schema.TypeMap,
- Computed: true,
- },
-
- "slug": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
-
- "version_real": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- },
- }
-}
-
-func resourceArtifactRead(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*atlas.Client)
-
- // Parse the slug from the name given of the artifact since the API
- // expects these to be split.
- user, name, err := atlas.ParseSlug(d.Get("name").(string))
- if err != nil {
- return err
- }
-
- // Filter by version or build if given
- var build, version string
- if v, ok := d.GetOk("version"); ok {
- version = v.(string)
- } else if b, ok := d.GetOk("build"); ok {
- build = b.(string)
- }
-
- // If we have neither, default to latest version
- if build == "" && version == "" {
- version = "latest"
- }
-
- // Compile the metadata search params
- md := make(map[string]string)
- for _, v := range d.Get("metadata_keys").(*schema.Set).List() {
- md[v.(string)] = atlas.MetadataAnyValue
- }
- for k, v := range d.Get("metadata").(map[string]interface{}) {
- md[k] = v.(string)
- }
-
- // Do the search!
- vs, err := client.ArtifactSearch(&atlas.ArtifactSearchOpts{
- User: user,
- Name: name,
- Type: d.Get("type").(string),
- Build: build,
- Version: version,
- Metadata: md,
- })
- if err != nil {
- return fmt.Errorf(
- "Error searching for artifact '%s/%s': %s",
- user, name, err)
- }
-
- if len(vs) == 0 {
- return fmt.Errorf("No matching artifact for '%s/%s'", user, name)
- } else if len(vs) > 1 {
- return fmt.Errorf(
- "Got %d results for '%s/%s', only one is allowed",
- len(vs), user, name)
- }
- v := vs[0]
-
- d.SetId(v.ID)
- if v.ID == "" {
- d.SetId(fmt.Sprintf("%s %d", v.Tag, v.Version))
- }
- d.Set("version_real", v.Version)
- d.Set("metadata_full", cleanMetadata(v.Metadata))
- d.Set("slug", v.Slug)
-
- d.Set("file_url", "")
- if u, err := client.ArtifactFileURL(v); err != nil {
- return fmt.Errorf(
- "Error reading file URL: %s", err)
- } else if u != nil {
- d.Set("file_url", u.String())
- }
-
- return nil
-}
-
-func resourceArtifactDelete(d *schema.ResourceData, meta interface{}) error {
- // This just always succeeds since this is a readonly element.
- d.SetId("")
- return nil
-}
-
-// cleanMetadata is used to ensure the metadata is accessible as
-// a variable by doing a simple re-write.
-func cleanMetadata(in map[string]string) map[string]string {
- out := make(map[string]string, len(in))
- for k, v := range in {
- sane := saneMetaKey.ReplaceAllString(k, "-")
- out[sane] = v
- }
- return out
-}
diff --git a/builtin/providers/atlas/resource_artifact_test.go b/builtin/providers/atlas/resource_artifact_test.go
deleted file mode 100644
index 440b954e4..000000000
--- a/builtin/providers/atlas/resource_artifact_test.go
+++ /dev/null
@@ -1,150 +0,0 @@
-package atlas
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccArtifact_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccArtifact_basic,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckArtifactState("name", "hashicorp/tf-provider-test"),
- ),
- },
- },
- })
-}
-
-func TestAccArtifact_metadata(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccArtifact_metadata,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckArtifactState("name", "hashicorp/tf-provider-test"),
- testAccCheckArtifactState("id", "x86"),
- testAccCheckArtifactState("metadata_full.arch", "x86"),
- ),
- },
- },
- })
-}
-
-func TestAccArtifact_metadataSet(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccArtifact_metadataSet,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckArtifactState("name", "hashicorp/tf-provider-test"),
- testAccCheckArtifactState("id", "x64"),
- testAccCheckArtifactState("metadata_full.arch", "x64"),
- ),
- },
- },
- })
-}
-
-func TestAccArtifact_buildLatest(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccArtifact_buildLatest,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckArtifactState("name", "hashicorp/tf-provider-test"),
- ),
- },
- },
- })
-}
-
-func TestAccArtifact_versionAny(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccArtifact_versionAny,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckArtifactState("name", "hashicorp/tf-provider-test"),
- ),
- },
- },
- })
-}
-
-func testAccCheckArtifactState(key, value string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources["atlas_artifact.foobar"]
- if !ok {
- return fmt.Errorf("Not found: %s", "atlas_artifact.foobar")
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No ID is set")
- }
-
- p := rs.Primary
- if p.Attributes[key] != value {
- return fmt.Errorf(
- "%s != %s (actual: %s)", key, value, p.Attributes[key])
- }
-
- return nil
- }
-}
-
-const testAccArtifact_basic = `
-resource "atlas_artifact" "foobar" {
- name = "hashicorp/tf-provider-test"
- type = "foo"
-}`
-
-const testAccArtifact_metadata = `
-resource "atlas_artifact" "foobar" {
- name = "hashicorp/tf-provider-test"
- type = "foo"
- metadata {
- arch = "x86"
- }
- version = "any"
-}`
-
-const testAccArtifact_metadataSet = `
-resource "atlas_artifact" "foobar" {
- name = "hashicorp/tf-provider-test"
- type = "foo"
- metadata_keys = ["arch"]
- version = "any"
-}`
-
-const testAccArtifact_buildLatest = `
-resource "atlas_artifact" "foobar" {
- name = "hashicorp/tf-provider-test"
- type = "foo"
- build = "latest"
- metadata {
- arch = "x86"
- }
-}`
-
-const testAccArtifact_versionAny = `
-resource "atlas_artifact" "foobar" {
- name = "hashicorp/tf-provider-test"
- type = "foo"
- version = "any"
-}`
diff --git a/builtin/providers/aws/auth_helpers.go b/builtin/providers/aws/auth_helpers.go
deleted file mode 100644
index e808d4d39..000000000
--- a/builtin/providers/aws/auth_helpers.go
+++ /dev/null
@@ -1,217 +0,0 @@
-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/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"
-)
-
-func GetAccountInfo(iamconn *iam.IAM, stsconn *sts.STS, authProviderName string) (string, string, 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 {
- // This can be triggered when no IAM Role is assigned
- // or AWS just happens to return invalid response
- return "", "", fmt.Errorf("Failed getting EC2 IAM info: %s", err)
- }
-
- return parseAccountInfoFromArn(info.InstanceProfileArn)
- }
-
- // Then 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)
- }
-
- 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)
-
- // 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 {
- return "", "", fmt.Errorf("Failed getting account ID via 'iam:ListRoles': %s", err)
- }
-
- if len(outRoles.Roles) < 1 {
- return "", "", errors.New("Failed getting account ID via 'iam:ListRoles': No roles available")
- }
-
- 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-evaulated 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 timeout low as we don't want to wait in non-EC2 environments
- client.Timeout = 100 * time.Millisecond
- cfg := &aws.Config{
- HTTPClient: client,
- }
- usedEndpoint := setOptionalEndpoint(cfg)
-
- 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 ""
-}
diff --git a/builtin/providers/aws/auth_helpers_test.go b/builtin/providers/aws/auth_helpers_test.go
deleted file mode 100644
index 25120c43b..000000000
--- a/builtin/providers/aws/auth_helpers_test.go
+++ /dev/null
@@ -1,902 +0,0 @@
-package aws
-
-import (
- "encoding/json"
- "fmt"
- "io/ioutil"
- "log"
- "net/http"
- "net/http/httptest"
- "os"
- "testing"
-
- "github.com/aws/aws-sdk-go/aws/awserr"
- "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
- "github.com/aws/aws-sdk-go/service/iam"
- "github.com/aws/aws-sdk-go/service/sts"
-)
-
-func TestAWSGetAccountInfo_shouldBeValid_fromEC2Role(t *testing.T) {
- resetEnv := unsetEnv(t)
- defer resetEnv()
- // capture the test server's close method, to call after the test returns
- awsTs := awsEnv(t)
- defer awsTs()
-
- closeEmpty, emptySess, err := getMockedAwsApiSession("zero", []*awsMockEndpoint{})
- defer closeEmpty()
- if err != nil {
- t.Fatal(err)
- }
-
- iamConn := iam.New(emptySess)
- stsConn := sts.New(emptySess)
-
- part, id, err := GetAccountInfo(iamConn, stsConn, ec2rolecreds.ProviderName)
- if err != nil {
- t.Fatalf("Getting account ID from EC2 metadata API failed: %s", err)
- }
-
- expectedPart := "aws"
- if part != expectedPart {
- t.Fatalf("Expected partition: %s, given: %s", expectedPart, part)
- }
-
- expectedAccountId := "123456789013"
- if id != expectedAccountId {
- t.Fatalf("Expected account ID: %s, given: %s", expectedAccountId, id)
- }
-}
-
-func TestAWSGetAccountInfo_shouldBeValid_EC2RoleHasPriority(t *testing.T) {
- resetEnv := unsetEnv(t)
- defer resetEnv()
- // capture the test server's close method, to call after the test returns
- awsTs := awsEnv(t)
- defer awsTs()
-
- iamEndpoints := []*awsMockEndpoint{
- {
- Request: &awsMockRequest{"POST", "/", "Action=GetUser&Version=2010-05-08"},
- Response: &awsMockResponse{200, iamResponse_GetUser_valid, "text/xml"},
- },
- }
- closeIam, iamSess, err := getMockedAwsApiSession("IAM", iamEndpoints)
- defer closeIam()
- if err != nil {
- t.Fatal(err)
- }
- iamConn := iam.New(iamSess)
- closeSts, stsSess, err := getMockedAwsApiSession("STS", []*awsMockEndpoint{})
- defer closeSts()
- if err != nil {
- t.Fatal(err)
- }
- stsConn := sts.New(stsSess)
-
- part, id, err := GetAccountInfo(iamConn, stsConn, ec2rolecreds.ProviderName)
- if err != nil {
- t.Fatalf("Getting account ID from EC2 metadata API failed: %s", err)
- }
-
- expectedPart := "aws"
- if part != expectedPart {
- t.Fatalf("Expected partition: %s, given: %s", expectedPart, part)
- }
-
- expectedAccountId := "123456789013"
- if id != expectedAccountId {
- t.Fatalf("Expected account ID: %s, given: %s", expectedAccountId, id)
- }
-}
-
-func TestAWSGetAccountInfo_shouldBeValid_fromIamUser(t *testing.T) {
- iamEndpoints := []*awsMockEndpoint{
- {
- Request: &awsMockRequest{"POST", "/", "Action=GetUser&Version=2010-05-08"},
- Response: &awsMockResponse{200, iamResponse_GetUser_valid, "text/xml"},
- },
- }
-
- closeIam, iamSess, err := getMockedAwsApiSession("IAM", iamEndpoints)
- defer closeIam()
- if err != nil {
- t.Fatal(err)
- }
- closeSts, stsSess, err := getMockedAwsApiSession("STS", []*awsMockEndpoint{})
- defer closeSts()
- if err != nil {
- t.Fatal(err)
- }
-
- iamConn := iam.New(iamSess)
- stsConn := sts.New(stsSess)
-
- part, id, err := GetAccountInfo(iamConn, stsConn, "")
- if err != nil {
- t.Fatalf("Getting account ID via GetUser failed: %s", err)
- }
-
- expectedPart := "aws"
- if part != expectedPart {
- t.Fatalf("Expected partition: %s, given: %s", expectedPart, part)
- }
-
- expectedAccountId := "123456789012"
- if id != expectedAccountId {
- t.Fatalf("Expected account ID: %s, given: %s", expectedAccountId, id)
- }
-}
-
-func TestAWSGetAccountInfo_shouldBeValid_fromGetCallerIdentity(t *testing.T) {
- iamEndpoints := []*awsMockEndpoint{
- {
- Request: &awsMockRequest{"POST", "/", "Action=GetUser&Version=2010-05-08"},
- Response: &awsMockResponse{403, iamResponse_GetUser_unauthorized, "text/xml"},
- },
- }
- closeIam, iamSess, err := getMockedAwsApiSession("IAM", iamEndpoints)
- defer closeIam()
- if err != nil {
- t.Fatal(err)
- }
-
- stsEndpoints := []*awsMockEndpoint{
- {
- Request: &awsMockRequest{"POST", "/", "Action=GetCallerIdentity&Version=2011-06-15"},
- Response: &awsMockResponse{200, stsResponse_GetCallerIdentity_valid, "text/xml"},
- },
- }
- closeSts, stsSess, err := getMockedAwsApiSession("STS", stsEndpoints)
- defer closeSts()
- if err != nil {
- t.Fatal(err)
- }
-
- iamConn := iam.New(iamSess)
- stsConn := sts.New(stsSess)
-
- part, id, err := GetAccountInfo(iamConn, stsConn, "")
- if err != nil {
- t.Fatalf("Getting account ID via GetUser failed: %s", err)
- }
-
- expectedPart := "aws"
- if part != expectedPart {
- t.Fatalf("Expected partition: %s, given: %s", expectedPart, part)
- }
-
- expectedAccountId := "123456789012"
- if id != expectedAccountId {
- t.Fatalf("Expected account ID: %s, given: %s", expectedAccountId, id)
- }
-}
-
-func TestAWSGetAccountInfo_shouldBeValid_fromIamListRoles(t *testing.T) {
- iamEndpoints := []*awsMockEndpoint{
- {
- Request: &awsMockRequest{"POST", "/", "Action=GetUser&Version=2010-05-08"},
- Response: &awsMockResponse{403, iamResponse_GetUser_unauthorized, "text/xml"},
- },
- {
- Request: &awsMockRequest{"POST", "/", "Action=ListRoles&MaxItems=1&Version=2010-05-08"},
- Response: &awsMockResponse{200, iamResponse_ListRoles_valid, "text/xml"},
- },
- }
- closeIam, iamSess, err := getMockedAwsApiSession("IAM", iamEndpoints)
- defer closeIam()
- if err != nil {
- t.Fatal(err)
- }
-
- stsEndpoints := []*awsMockEndpoint{
- {
- Request: &awsMockRequest{"POST", "/", "Action=GetCallerIdentity&Version=2011-06-15"},
- Response: &awsMockResponse{403, stsResponse_GetCallerIdentity_unauthorized, "text/xml"},
- },
- }
- closeSts, stsSess, err := getMockedAwsApiSession("STS", stsEndpoints)
- defer closeSts()
- if err != nil {
- t.Fatal(err)
- }
-
- iamConn := iam.New(iamSess)
- stsConn := sts.New(stsSess)
-
- part, id, err := GetAccountInfo(iamConn, stsConn, "")
- if err != nil {
- t.Fatalf("Getting account ID via ListRoles failed: %s", err)
- }
-
- expectedPart := "aws"
- if part != expectedPart {
- t.Fatalf("Expected partition: %s, given: %s", expectedPart, part)
- }
-
- expectedAccountId := "123456789012"
- if id != expectedAccountId {
- t.Fatalf("Expected account ID: %s, given: %s", expectedAccountId, id)
- }
-}
-
-func TestAWSGetAccountInfo_shouldBeValid_federatedRole(t *testing.T) {
- iamEndpoints := []*awsMockEndpoint{
- {
- Request: &awsMockRequest{"POST", "/", "Action=GetUser&Version=2010-05-08"},
- Response: &awsMockResponse{400, iamResponse_GetUser_federatedFailure, "text/xml"},
- },
- {
- Request: &awsMockRequest{"POST", "/", "Action=ListRoles&MaxItems=1&Version=2010-05-08"},
- Response: &awsMockResponse{200, iamResponse_ListRoles_valid, "text/xml"},
- },
- }
- closeIam, iamSess, err := getMockedAwsApiSession("IAM", iamEndpoints)
- defer closeIam()
- if err != nil {
- t.Fatal(err)
- }
-
- closeSts, stsSess, err := getMockedAwsApiSession("STS", []*awsMockEndpoint{})
- defer closeSts()
- if err != nil {
- t.Fatal(err)
- }
-
- iamConn := iam.New(iamSess)
- stsConn := sts.New(stsSess)
-
- part, id, err := GetAccountInfo(iamConn, stsConn, "")
- if err != nil {
- t.Fatalf("Getting account ID via ListRoles failed: %s", err)
- }
-
- expectedPart := "aws"
- if part != expectedPart {
- t.Fatalf("Expected partition: %s, given: %s", expectedPart, part)
- }
-
- expectedAccountId := "123456789012"
- if id != expectedAccountId {
- t.Fatalf("Expected account ID: %s, given: %s", expectedAccountId, id)
- }
-}
-
-func TestAWSGetAccountInfo_shouldError_unauthorizedFromIam(t *testing.T) {
- iamEndpoints := []*awsMockEndpoint{
- {
- Request: &awsMockRequest{"POST", "/", "Action=GetUser&Version=2010-05-08"},
- Response: &awsMockResponse{403, iamResponse_GetUser_unauthorized, "text/xml"},
- },
- {
- Request: &awsMockRequest{"POST", "/", "Action=ListRoles&MaxItems=1&Version=2010-05-08"},
- Response: &awsMockResponse{403, iamResponse_ListRoles_unauthorized, "text/xml"},
- },
- }
- closeIam, iamSess, err := getMockedAwsApiSession("IAM", iamEndpoints)
- defer closeIam()
- if err != nil {
- t.Fatal(err)
- }
-
- closeSts, stsSess, err := getMockedAwsApiSession("STS", []*awsMockEndpoint{})
- defer closeSts()
- if err != nil {
- t.Fatal(err)
- }
-
- iamConn := iam.New(iamSess)
- stsConn := sts.New(stsSess)
-
- part, id, err := GetAccountInfo(iamConn, stsConn, "")
- if err == nil {
- t.Fatal("Expected error when getting account ID")
- }
-
- if part != "" {
- t.Fatalf("Expected no partition, given: %s", part)
- }
-
- if id != "" {
- t.Fatalf("Expected no account ID, given: %s", id)
- }
-}
-
-func TestAWSParseAccountInfoFromArn(t *testing.T) {
- validArn := "arn:aws:iam::101636750127:instance-profile/aws-elasticbeanstalk-ec2-role"
- expectedPart := "aws"
- expectedId := "101636750127"
- part, id, err := parseAccountInfoFromArn(validArn)
- if err != nil {
- t.Fatalf("Expected no error when parsing valid ARN: %s", err)
- }
- if part != expectedPart {
- t.Fatalf("Parsed part doesn't match with expected (%q != %q)", part, expectedPart)
- }
- if id != expectedId {
- t.Fatalf("Parsed id doesn't match with expected (%q != %q)", id, expectedId)
- }
-
- invalidArn := "blablah"
- part, id, err = parseAccountInfoFromArn(invalidArn)
- if err == nil {
- t.Fatalf("Expected error when parsing invalid ARN (%q)", invalidArn)
- }
-}
-
-func TestAWSGetCredentials_shouldError(t *testing.T) {
- resetEnv := unsetEnv(t)
- defer resetEnv()
- cfg := Config{}
-
- c, err := GetCredentials(&cfg)
- if awsErr, ok := err.(awserr.Error); ok {
- if awsErr.Code() != "NoCredentialProviders" {
- t.Fatal("Expected NoCredentialProviders error")
- }
- }
- _, err = c.Get()
- if awsErr, ok := err.(awserr.Error); ok {
- if awsErr.Code() != "NoCredentialProviders" {
- t.Fatal("Expected NoCredentialProviders error")
- }
- }
- if err == nil {
- t.Fatal("Expected an error with empty env, keys, and IAM in AWS Config")
- }
-}
-
-func TestAWSGetCredentials_shouldBeStatic(t *testing.T) {
- simple := []struct {
- Key, Secret, Token string
- }{
- {
- Key: "test",
- Secret: "secret",
- }, {
- Key: "test",
- Secret: "test",
- Token: "test",
- },
- }
-
- for _, c := range simple {
- cfg := Config{
- AccessKey: c.Key,
- SecretKey: c.Secret,
- Token: c.Token,
- }
-
- creds, err := GetCredentials(&cfg)
- if err != nil {
- t.Fatalf("Error gettings creds: %s", err)
- }
- if creds == nil {
- t.Fatal("Expected a static creds provider to be returned")
- }
-
- v, err := creds.Get()
- if err != nil {
- t.Fatalf("Error gettings creds: %s", err)
- }
-
- if v.AccessKeyID != c.Key {
- t.Fatalf("AccessKeyID mismatch, expected: (%s), got (%s)", c.Key, v.AccessKeyID)
- }
- if v.SecretAccessKey != c.Secret {
- t.Fatalf("SecretAccessKey mismatch, expected: (%s), got (%s)", c.Secret, v.SecretAccessKey)
- }
- if v.SessionToken != c.Token {
- t.Fatalf("SessionToken mismatch, expected: (%s), got (%s)", c.Token, v.SessionToken)
- }
- }
-}
-
-// TestAWSGetCredentials_shouldIAM is designed to test the scenario of running Terraform
-// from an EC2 instance, without environment variables or manually supplied
-// credentials.
-func TestAWSGetCredentials_shouldIAM(t *testing.T) {
- // clear AWS_* environment variables
- resetEnv := unsetEnv(t)
- defer resetEnv()
-
- // capture the test server's close method, to call after the test returns
- ts := awsEnv(t)
- defer ts()
-
- // An empty config, no key supplied
- cfg := Config{}
-
- creds, err := GetCredentials(&cfg)
- if err != nil {
- t.Fatalf("Error gettings creds: %s", err)
- }
- if creds == nil {
- t.Fatal("Expected a static creds provider to be returned")
- }
-
- v, err := creds.Get()
- if err != nil {
- t.Fatalf("Error gettings creds: %s", err)
- }
- if v.AccessKeyID != "somekey" {
- t.Fatalf("AccessKeyID mismatch, expected: (somekey), got (%s)", v.AccessKeyID)
- }
- if v.SecretAccessKey != "somesecret" {
- t.Fatalf("SecretAccessKey mismatch, expected: (somesecret), got (%s)", v.SecretAccessKey)
- }
- if v.SessionToken != "sometoken" {
- t.Fatalf("SessionToken mismatch, expected: (sometoken), got (%s)", v.SessionToken)
- }
-}
-
-// TestAWSGetCredentials_shouldIAM is designed to test the scenario of running Terraform
-// from an EC2 instance, without environment variables or manually supplied
-// credentials.
-func TestAWSGetCredentials_shouldIgnoreIAM(t *testing.T) {
- resetEnv := unsetEnv(t)
- defer resetEnv()
- // capture the test server's close method, to call after the test returns
- ts := awsEnv(t)
- defer ts()
- simple := []struct {
- Key, Secret, Token string
- }{
- {
- Key: "test",
- Secret: "secret",
- }, {
- Key: "test",
- Secret: "test",
- Token: "test",
- },
- }
-
- for _, c := range simple {
- cfg := Config{
- AccessKey: c.Key,
- SecretKey: c.Secret,
- Token: c.Token,
- }
-
- creds, err := GetCredentials(&cfg)
- if err != nil {
- t.Fatalf("Error gettings creds: %s", err)
- }
- if creds == nil {
- t.Fatal("Expected a static creds provider to be returned")
- }
-
- v, err := creds.Get()
- if err != nil {
- t.Fatalf("Error gettings creds: %s", err)
- }
- if v.AccessKeyID != c.Key {
- t.Fatalf("AccessKeyID mismatch, expected: (%s), got (%s)", c.Key, v.AccessKeyID)
- }
- if v.SecretAccessKey != c.Secret {
- t.Fatalf("SecretAccessKey mismatch, expected: (%s), got (%s)", c.Secret, v.SecretAccessKey)
- }
- if v.SessionToken != c.Token {
- t.Fatalf("SessionToken mismatch, expected: (%s), got (%s)", c.Token, v.SessionToken)
- }
- }
-}
-
-func TestAWSGetCredentials_shouldErrorWithInvalidEndpoint(t *testing.T) {
- resetEnv := unsetEnv(t)
- defer resetEnv()
- // capture the test server's close method, to call after the test returns
- ts := invalidAwsEnv(t)
- defer ts()
-
- creds, err := GetCredentials(&Config{})
- if err != nil {
- t.Fatalf("Error gettings creds: %s", err)
- }
- if creds == nil {
- t.Fatal("Expected a static creds provider to be returned")
- }
-
- v, err := creds.Get()
- if err == nil {
- t.Fatal("Expected error returned when getting creds w/ invalid EC2 endpoint")
- }
-
- if v.ProviderName != "" {
- t.Fatalf("Expected provider name to be empty, %q given", v.ProviderName)
- }
-}
-
-func TestAWSGetCredentials_shouldIgnoreInvalidEndpoint(t *testing.T) {
- resetEnv := unsetEnv(t)
- defer resetEnv()
- // capture the test server's close method, to call after the test returns
- ts := invalidAwsEnv(t)
- defer ts()
-
- creds, err := GetCredentials(&Config{AccessKey: "accessKey", SecretKey: "secretKey"})
- if err != nil {
- t.Fatalf("Error gettings creds: %s", err)
- }
- v, err := creds.Get()
- if err != nil {
- t.Fatalf("Getting static credentials w/ invalid EC2 endpoint failed: %s", err)
- }
- if creds == nil {
- t.Fatal("Expected a static creds provider to be returned")
- }
-
- if v.ProviderName != "StaticProvider" {
- t.Fatalf("Expected provider name to be %q, %q given", "StaticProvider", v.ProviderName)
- }
-
- if v.AccessKeyID != "accessKey" {
- t.Fatalf("Static Access Key %q doesn't match: %s", "accessKey", v.AccessKeyID)
- }
-
- if v.SecretAccessKey != "secretKey" {
- t.Fatalf("Static Secret Key %q doesn't match: %s", "secretKey", v.SecretAccessKey)
- }
-}
-
-func TestAWSGetCredentials_shouldCatchEC2RoleProvider(t *testing.T) {
- resetEnv := unsetEnv(t)
- defer resetEnv()
- // capture the test server's close method, to call after the test returns
- ts := awsEnv(t)
- defer ts()
-
- creds, err := GetCredentials(&Config{})
- if err != nil {
- t.Fatalf("Error gettings creds: %s", err)
- }
- if creds == nil {
- t.Fatal("Expected an EC2Role creds provider to be returned")
- }
-
- v, err := creds.Get()
- if err != nil {
- t.Fatalf("Expected no error when getting creds: %s", err)
- }
- expectedProvider := "EC2RoleProvider"
- if v.ProviderName != expectedProvider {
- t.Fatalf("Expected provider name to be %q, %q given",
- expectedProvider, v.ProviderName)
- }
-}
-
-var credentialsFileContents = `[myprofile]
-aws_access_key_id = accesskey
-aws_secret_access_key = secretkey
-`
-
-func TestAWSGetCredentials_shouldBeShared(t *testing.T) {
- file, err := ioutil.TempFile(os.TempDir(), "terraform_aws_cred")
- if err != nil {
- t.Fatalf("Error writing temporary credentials file: %s", err)
- }
- _, err = file.WriteString(credentialsFileContents)
- if err != nil {
- t.Fatalf("Error writing temporary credentials to file: %s", err)
- }
- err = file.Close()
- if err != nil {
- t.Fatalf("Error closing temporary credentials file: %s", err)
- }
-
- defer os.Remove(file.Name())
-
- resetEnv := unsetEnv(t)
- defer resetEnv()
-
- if err := os.Setenv("AWS_PROFILE", "myprofile"); err != nil {
- t.Fatalf("Error resetting env var AWS_PROFILE: %s", err)
- }
- if err := os.Setenv("AWS_SHARED_CREDENTIALS_FILE", file.Name()); err != nil {
- t.Fatalf("Error resetting env var AWS_SHARED_CREDENTIALS_FILE: %s", err)
- }
-
- creds, err := GetCredentials(&Config{Profile: "myprofile", CredsFilename: file.Name()})
- if err != nil {
- t.Fatalf("Error gettings creds: %s", err)
- }
- if creds == nil {
- t.Fatal("Expected a provider chain to be returned")
- }
-
- v, err := creds.Get()
- if err != nil {
- t.Fatalf("Error gettings creds: %s", err)
- }
-
- if v.AccessKeyID != "accesskey" {
- t.Fatalf("AccessKeyID mismatch, expected (%s), got (%s)", "accesskey", v.AccessKeyID)
- }
-
- if v.SecretAccessKey != "secretkey" {
- t.Fatalf("SecretAccessKey mismatch, expected (%s), got (%s)", "accesskey", v.AccessKeyID)
- }
-}
-
-func TestAWSGetCredentials_shouldBeENV(t *testing.T) {
- // need to set the environment variables to a dummy string, as we don't know
- // what they may be at runtime without hardcoding here
- s := "some_env"
- resetEnv := setEnv(s, t)
-
- defer resetEnv()
-
- cfg := Config{}
- creds, err := GetCredentials(&cfg)
- if err != nil {
- t.Fatalf("Error gettings creds: %s", err)
- }
- if creds == nil {
- t.Fatalf("Expected a static creds provider to be returned")
- }
-
- v, err := creds.Get()
- if err != nil {
- t.Fatalf("Error gettings creds: %s", err)
- }
- if v.AccessKeyID != s {
- t.Fatalf("AccessKeyID mismatch, expected: (%s), got (%s)", s, v.AccessKeyID)
- }
- if v.SecretAccessKey != s {
- t.Fatalf("SecretAccessKey mismatch, expected: (%s), got (%s)", s, v.SecretAccessKey)
- }
- if v.SessionToken != s {
- t.Fatalf("SessionToken mismatch, expected: (%s), got (%s)", s, v.SessionToken)
- }
-}
-
-// unsetEnv unsets environment variables for testing a "clean slate" with no
-// credentials in the environment
-func unsetEnv(t *testing.T) func() {
- // Grab any existing AWS keys and preserve. In some tests we'll unset these, so
- // we need to have them and restore them after
- e := getEnv()
- if err := os.Unsetenv("AWS_ACCESS_KEY_ID"); err != nil {
- t.Fatalf("Error unsetting env var AWS_ACCESS_KEY_ID: %s", err)
- }
- if err := os.Unsetenv("AWS_SECRET_ACCESS_KEY"); err != nil {
- t.Fatalf("Error unsetting env var AWS_SECRET_ACCESS_KEY: %s", err)
- }
- if err := os.Unsetenv("AWS_SESSION_TOKEN"); err != nil {
- t.Fatalf("Error unsetting env var AWS_SESSION_TOKEN: %s", err)
- }
- if err := os.Unsetenv("AWS_PROFILE"); err != nil {
- t.Fatalf("Error unsetting env var AWS_PROFILE: %s", err)
- }
- if err := os.Unsetenv("AWS_SHARED_CREDENTIALS_FILE"); err != nil {
- t.Fatalf("Error unsetting env var AWS_SHARED_CREDENTIALS_FILE: %s", err)
- }
-
- return func() {
- // re-set all the envs we unset above
- if err := os.Setenv("AWS_ACCESS_KEY_ID", e.Key); err != nil {
- t.Fatalf("Error resetting env var AWS_ACCESS_KEY_ID: %s", err)
- }
- if err := os.Setenv("AWS_SECRET_ACCESS_KEY", e.Secret); err != nil {
- t.Fatalf("Error resetting env var AWS_SECRET_ACCESS_KEY: %s", err)
- }
- if err := os.Setenv("AWS_SESSION_TOKEN", e.Token); err != nil {
- t.Fatalf("Error resetting env var AWS_SESSION_TOKEN: %s", err)
- }
- if err := os.Setenv("AWS_PROFILE", e.Profile); err != nil {
- t.Fatalf("Error resetting env var AWS_PROFILE: %s", err)
- }
- if err := os.Setenv("AWS_SHARED_CREDENTIALS_FILE", e.CredsFilename); err != nil {
- t.Fatalf("Error resetting env var AWS_SHARED_CREDENTIALS_FILE: %s", err)
- }
- }
-}
-
-func setEnv(s string, t *testing.T) func() {
- e := getEnv()
- // Set all the envs to a dummy value
- if err := os.Setenv("AWS_ACCESS_KEY_ID", s); err != nil {
- t.Fatalf("Error setting env var AWS_ACCESS_KEY_ID: %s", err)
- }
- if err := os.Setenv("AWS_SECRET_ACCESS_KEY", s); err != nil {
- t.Fatalf("Error setting env var AWS_SECRET_ACCESS_KEY: %s", err)
- }
- if err := os.Setenv("AWS_SESSION_TOKEN", s); err != nil {
- t.Fatalf("Error setting env var AWS_SESSION_TOKEN: %s", err)
- }
- if err := os.Setenv("AWS_PROFILE", s); err != nil {
- t.Fatalf("Error setting env var AWS_PROFILE: %s", err)
- }
- if err := os.Setenv("AWS_SHARED_CREDENTIALS_FILE", s); err != nil {
- t.Fatalf("Error setting env var AWS_SHARED_CREDENTIALS_FLE: %s", err)
- }
-
- return func() {
- // re-set all the envs we unset above
- if err := os.Setenv("AWS_ACCESS_KEY_ID", e.Key); err != nil {
- t.Fatalf("Error resetting env var AWS_ACCESS_KEY_ID: %s", err)
- }
- if err := os.Setenv("AWS_SECRET_ACCESS_KEY", e.Secret); err != nil {
- t.Fatalf("Error resetting env var AWS_SECRET_ACCESS_KEY: %s", err)
- }
- if err := os.Setenv("AWS_SESSION_TOKEN", e.Token); err != nil {
- t.Fatalf("Error resetting env var AWS_SESSION_TOKEN: %s", err)
- }
- if err := os.Setenv("AWS_PROFILE", e.Profile); err != nil {
- t.Fatalf("Error setting env var AWS_PROFILE: %s", err)
- }
- if err := os.Setenv("AWS_SHARED_CREDENTIALS_FILE", s); err != nil {
- t.Fatalf("Error setting env var AWS_SHARED_CREDENTIALS_FLE: %s", err)
- }
- }
-}
-
-// awsEnv establishes a httptest server to mock out the internal AWS Metadata
-// service. IAM Credentials are retrieved by the EC2RoleProvider, which makes
-// API calls to this internal URL. By replacing the server with a test server,
-// we can simulate an AWS environment
-func awsEnv(t *testing.T) func() {
- routes := routes{}
- if err := json.Unmarshal([]byte(metadataApiRoutes), &routes); err != nil {
- t.Fatalf("Failed to unmarshal JSON in AWS ENV test: %s", err)
- }
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "text/plain")
- w.Header().Add("Server", "MockEC2")
- log.Printf("[DEBUG] Mocker server received request to %q", r.RequestURI)
- for _, e := range routes.Endpoints {
- if r.RequestURI == e.Uri {
- fmt.Fprintln(w, e.Body)
- w.WriteHeader(200)
- return
- }
- }
- w.WriteHeader(400)
- }))
-
- os.Setenv("AWS_METADATA_URL", ts.URL+"/latest")
- return ts.Close
-}
-
-// invalidAwsEnv establishes a httptest server to simulate behaviour
-// when endpoint doesn't respond as expected
-func invalidAwsEnv(t *testing.T) func() {
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(400)
- }))
-
- os.Setenv("AWS_METADATA_URL", ts.URL+"/latest")
- return ts.Close
-}
-
-func getEnv() *currentEnv {
- // Grab any existing AWS keys and preserve. In some tests we'll unset these, so
- // we need to have them and restore them after
- return ¤tEnv{
- Key: os.Getenv("AWS_ACCESS_KEY_ID"),
- Secret: os.Getenv("AWS_SECRET_ACCESS_KEY"),
- Token: os.Getenv("AWS_SESSION_TOKEN"),
- Profile: os.Getenv("AWS_PROFILE"),
- CredsFilename: os.Getenv("AWS_SHARED_CREDENTIALS_FILE"),
- }
-}
-
-// struct to preserve the current environment
-type currentEnv struct {
- Key, Secret, Token, Profile, CredsFilename string
-}
-
-type routes struct {
- Endpoints []*endpoint `json:"endpoints"`
-}
-type endpoint struct {
- Uri string `json:"uri"`
- Body string `json:"body"`
-}
-
-const metadataApiRoutes = `
-{
- "endpoints": [
- {
- "uri": "/latest/meta-data/instance-id",
- "body": "mock-instance-id"
- },
- {
- "uri": "/latest/meta-data/iam/info",
- "body": "{\"Code\": \"Success\",\"LastUpdated\": \"2016-03-17T12:27:32Z\",\"InstanceProfileArn\": \"arn:aws:iam::123456789013:instance-profile/my-instance-profile\",\"InstanceProfileId\": \"AIPAABCDEFGHIJKLMN123\"}"
- },
- {
- "uri": "/latest/meta-data/iam/security-credentials",
- "body": "test_role"
- },
- {
- "uri": "/latest/meta-data/iam/security-credentials/test_role",
- "body": "{\"Code\":\"Success\",\"LastUpdated\":\"2015-12-11T17:17:25Z\",\"Type\":\"AWS-HMAC\",\"AccessKeyId\":\"somekey\",\"SecretAccessKey\":\"somesecret\",\"Token\":\"sometoken\"}"
- }
- ]
-}
-`
-
-const iamResponse_GetUser_valid = `
-
-
- AIDACKCEVSQ6C2EXAMPLE
- /division_abc/subdivision_xyz/
- Bob
- arn:aws:iam::123456789012:user/division_abc/subdivision_xyz/Bob
- 2013-10-02T17:01:44Z
- 2014-10-10T14:37:51Z
-
-
-
- 7a62c49f-347e-4fc4-9331-6e8eEXAMPLE
-
-`
-
-const iamResponse_GetUser_unauthorized = `
-
- Sender
- AccessDenied
- User: arn:aws:iam::123456789012:user/Bob is not authorized to perform: iam:GetUser on resource: arn:aws:iam::123456789012:user/Bob
-
- 7a62c49f-347e-4fc4-9331-6e8eEXAMPLE
-`
-
-const stsResponse_GetCallerIdentity_valid = `
-
- arn:aws:iam::123456789012:user/Alice
- AKIAI44QH8DHBEXAMPLE
- 123456789012
-
-
- 01234567-89ab-cdef-0123-456789abcdef
-
-`
-
-const stsResponse_GetCallerIdentity_unauthorized = `
-
- Sender
- AccessDenied
- User: arn:aws:iam::123456789012:user/Bob is not authorized to perform: sts:GetCallerIdentity
-
- 01234567-89ab-cdef-0123-456789abcdef
-`
-
-const iamResponse_GetUser_federatedFailure = `
-
- Sender
- ValidationError
- Must specify userName when calling with non-User credentials
-
- 7a62c49f-347e-4fc4-9331-6e8eEXAMPLE
-`
-
-const iamResponse_ListRoles_valid = `
-
- true
- AWceSSsKsazQ4IEplT9o4hURCzBs00iavlEvEXAMPLE
-
-
- /
- %7B%22Version%22%3A%222008-10-17%22%2C%22Statement%22%3A%5B%7B%22Sid%22%3A%22%22%2C%22Effect%22%3A%22Allow%22%2C%22Principal%22%3A%7B%22Service%22%3A%22ec2.amazonaws.com%22%7D%2C%22Action%22%3A%22sts%3AAssumeRole%22%7D%5D%7D
- AROACKCEVSQ6C2EXAMPLE
- elasticbeanstalk-role
- arn:aws:iam::123456789012:role/elasticbeanstalk-role
- 2013-10-02T17:01:44Z
-
-
-
-
- 7a62c49f-347e-4fc4-9331-6e8eEXAMPLE
-
-`
-
-const iamResponse_ListRoles_unauthorized = `
-
- Sender
- AccessDenied
- User: arn:aws:iam::123456789012:user/Bob is not authorized to perform: iam:ListRoles on resource: arn:aws:iam::123456789012:role/
-
- 7a62c49f-347e-4fc4-9331-6e8eEXAMPLE
-`
diff --git a/builtin/providers/aws/autoscaling_tags.go b/builtin/providers/aws/autoscaling_tags.go
deleted file mode 100644
index 5c0911505..000000000
--- a/builtin/providers/aws/autoscaling_tags.go
+++ /dev/null
@@ -1,317 +0,0 @@
-package aws
-
-import (
- "bytes"
- "fmt"
- "log"
- "regexp"
- "strconv"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/autoscaling"
- "github.com/hashicorp/terraform/helper/hashcode"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-// autoscalingTagSchema returns the schema to use for the tag element.
-func autoscalingTagSchema() *schema.Schema {
- return &schema.Schema{
- Type: schema.TypeSet,
- Optional: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "key": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
-
- "value": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
-
- "propagate_at_launch": &schema.Schema{
- Type: schema.TypeBool,
- Required: true,
- },
- },
- },
- Set: autoscalingTagToHash,
- }
-}
-
-func autoscalingTagToHash(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%s-", m["key"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["value"].(string)))
- buf.WriteString(fmt.Sprintf("%t-", m["propagate_at_launch"].(bool)))
-
- return hashcode.String(buf.String())
-}
-
-// setTags is a helper to set the tags for a resource. It expects the
-// tags field to be named "tag"
-func setAutoscalingTags(conn *autoscaling.AutoScaling, d *schema.ResourceData) error {
- resourceID := d.Get("name").(string)
- var createTags, removeTags []*autoscaling.Tag
-
- if d.HasChange("tag") || d.HasChange("tags") {
- oraw, nraw := d.GetChange("tag")
- o := setToMapByKey(oraw.(*schema.Set), "key")
- n := setToMapByKey(nraw.(*schema.Set), "key")
-
- old, err := autoscalingTagsFromMap(o, resourceID)
- if err != nil {
- return err
- }
-
- new, err := autoscalingTagsFromMap(n, resourceID)
- if err != nil {
- return err
- }
-
- c, r, err := diffAutoscalingTags(old, new, resourceID)
- if err != nil {
- return err
- }
-
- createTags = append(createTags, c...)
- removeTags = append(removeTags, r...)
-
- oraw, nraw = d.GetChange("tags")
- old, err = autoscalingTagsFromList(oraw.([]interface{}), resourceID)
- if err != nil {
- return err
- }
-
- new, err = autoscalingTagsFromList(nraw.([]interface{}), resourceID)
- if err != nil {
- return err
- }
-
- c, r, err = diffAutoscalingTags(old, new, resourceID)
- if err != nil {
- return err
- }
-
- createTags = append(createTags, c...)
- removeTags = append(removeTags, r...)
- }
-
- // Set tags
- if len(removeTags) > 0 {
- log.Printf("[DEBUG] Removing autoscaling tags: %#v", removeTags)
-
- remove := autoscaling.DeleteTagsInput{
- Tags: removeTags,
- }
-
- if _, err := conn.DeleteTags(&remove); err != nil {
- return err
- }
- }
-
- if len(createTags) > 0 {
- log.Printf("[DEBUG] Creating autoscaling tags: %#v", createTags)
-
- create := autoscaling.CreateOrUpdateTagsInput{
- Tags: createTags,
- }
-
- if _, err := conn.CreateOrUpdateTags(&create); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-// diffTags takes our tags locally and the ones remotely and returns
-// the set of tags that must be created, and the set of tags that must
-// be destroyed.
-func diffAutoscalingTags(oldTags, newTags []*autoscaling.Tag, resourceID string) ([]*autoscaling.Tag, []*autoscaling.Tag, error) {
- // First, we're creating everything we have
- create := make(map[string]interface{})
- for _, t := range newTags {
- tag := map[string]interface{}{
- "key": *t.Key,
- "value": *t.Value,
- "propagate_at_launch": *t.PropagateAtLaunch,
- }
- create[*t.Key] = tag
- }
-
- // Build the list of what to remove
- var remove []*autoscaling.Tag
- for _, t := range oldTags {
- old, ok := create[*t.Key].(map[string]interface{})
-
- if !ok || old["value"] != *t.Value || old["propagate_at_launch"] != *t.PropagateAtLaunch {
- // Delete it!
- remove = append(remove, t)
- }
- }
-
- createTags, err := autoscalingTagsFromMap(create, resourceID)
- if err != nil {
- return nil, nil, err
- }
-
- return createTags, remove, nil
-}
-
-func autoscalingTagsFromList(vs []interface{}, resourceID string) ([]*autoscaling.Tag, error) {
- result := make([]*autoscaling.Tag, 0, len(vs))
- for _, tag := range vs {
- attr, ok := tag.(map[string]interface{})
- if !ok {
- continue
- }
-
- t, err := autoscalingTagFromMap(attr, resourceID)
- if err != nil {
- return nil, err
- }
-
- if t != nil {
- result = append(result, t)
- }
- }
- return result, nil
-}
-
-// tagsFromMap returns the tags for the given map of data.
-func autoscalingTagsFromMap(m map[string]interface{}, resourceID string) ([]*autoscaling.Tag, error) {
- result := make([]*autoscaling.Tag, 0, len(m))
- for _, v := range m {
- attr, ok := v.(map[string]interface{})
- if !ok {
- continue
- }
-
- t, err := autoscalingTagFromMap(attr, resourceID)
- if err != nil {
- return nil, err
- }
-
- if t != nil {
- result = append(result, t)
- }
- }
-
- return result, nil
-}
-
-func autoscalingTagFromMap(attr map[string]interface{}, resourceID string) (*autoscaling.Tag, error) {
- if _, ok := attr["key"]; !ok {
- return nil, fmt.Errorf("%s: invalid tag attributes: key missing", resourceID)
- }
-
- if _, ok := attr["value"]; !ok {
- return nil, fmt.Errorf("%s: invalid tag attributes: value missing", resourceID)
- }
-
- if _, ok := attr["propagate_at_launch"]; !ok {
- return nil, fmt.Errorf("%s: invalid tag attributes: propagate_at_launch missing", resourceID)
- }
-
- var propagateAtLaunch bool
- var err error
-
- if v, ok := attr["propagate_at_launch"].(bool); ok {
- propagateAtLaunch = v
- }
-
- if v, ok := attr["propagate_at_launch"].(string); ok {
- if propagateAtLaunch, err = strconv.ParseBool(v); err != nil {
- return nil, fmt.Errorf(
- "%s: invalid tag attribute: invalid value for propagate_at_launch: %s",
- resourceID,
- v,
- )
- }
- }
-
- t := &autoscaling.Tag{
- Key: aws.String(attr["key"].(string)),
- Value: aws.String(attr["value"].(string)),
- PropagateAtLaunch: aws.Bool(propagateAtLaunch),
- ResourceId: aws.String(resourceID),
- ResourceType: aws.String("auto-scaling-group"),
- }
-
- if tagIgnoredAutoscaling(t) {
- return nil, nil
- }
-
- return t, nil
-}
-
-// autoscalingTagsToMap turns the list of tags into a map.
-func autoscalingTagsToMap(ts []*autoscaling.Tag) map[string]interface{} {
- tags := make(map[string]interface{})
- for _, t := range ts {
- tag := map[string]interface{}{
- "key": *t.Key,
- "value": *t.Value,
- "propagate_at_launch": *t.PropagateAtLaunch,
- }
- tags[*t.Key] = tag
- }
-
- return tags
-}
-
-// autoscalingTagDescriptionsToMap turns the list of tags into a map.
-func autoscalingTagDescriptionsToMap(ts *[]*autoscaling.TagDescription) map[string]map[string]interface{} {
- tags := make(map[string]map[string]interface{})
- for _, t := range *ts {
- tag := map[string]interface{}{
- "key": *t.Key,
- "value": *t.Value,
- "propagate_at_launch": *t.PropagateAtLaunch,
- }
- tags[*t.Key] = tag
- }
-
- return tags
-}
-
-// autoscalingTagDescriptionsToSlice turns the list of tags into a slice.
-func autoscalingTagDescriptionsToSlice(ts []*autoscaling.TagDescription) []map[string]interface{} {
- tags := make([]map[string]interface{}, 0, len(ts))
- for _, t := range ts {
- tags = append(tags, map[string]interface{}{
- "key": *t.Key,
- "value": *t.Value,
- "propagate_at_launch": *t.PropagateAtLaunch,
- })
- }
-
- return tags
-}
-
-func setToMapByKey(s *schema.Set, key string) map[string]interface{} {
- result := make(map[string]interface{})
- for _, rawData := range s.List() {
- data := rawData.(map[string]interface{})
- result[data[key].(string)] = data
- }
-
- return result
-}
-
-// compare a tag against a list of strings and checks if it should
-// be ignored or not
-func tagIgnoredAutoscaling(t *autoscaling.Tag) bool {
- filter := []string{"^aws:"}
- for _, v := range filter {
- log.Printf("[DEBUG] Matching %v with %v\n", v, *t.Key)
- if r, _ := regexp.MatchString(v, *t.Key); r == true {
- log.Printf("[DEBUG] Found AWS specific tag %s (val: %s), ignoring.\n", *t.Key, *t.Value)
- return true
- }
- }
- return false
-}
diff --git a/builtin/providers/aws/autoscaling_tags_test.go b/builtin/providers/aws/autoscaling_tags_test.go
deleted file mode 100644
index 0107764d1..000000000
--- a/builtin/providers/aws/autoscaling_tags_test.go
+++ /dev/null
@@ -1,158 +0,0 @@
-package aws
-
-import (
- "fmt"
- "reflect"
- "testing"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/autoscaling"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestDiffAutoscalingTags(t *testing.T) {
- cases := []struct {
- Old, New map[string]interface{}
- Create, Remove map[string]interface{}
- }{
- // Basic add/remove
- {
- Old: map[string]interface{}{
- "Name": map[string]interface{}{
- "key": "Name",
- "value": "bar",
- "propagate_at_launch": true,
- },
- },
- New: map[string]interface{}{
- "DifferentTag": map[string]interface{}{
- "key": "DifferentTag",
- "value": "baz",
- "propagate_at_launch": true,
- },
- },
- Create: map[string]interface{}{
- "DifferentTag": map[string]interface{}{
- "key": "DifferentTag",
- "value": "baz",
- "propagate_at_launch": true,
- },
- },
- Remove: map[string]interface{}{
- "Name": map[string]interface{}{
- "key": "Name",
- "value": "bar",
- "propagate_at_launch": true,
- },
- },
- },
-
- // Modify
- {
- Old: map[string]interface{}{
- "Name": map[string]interface{}{
- "key": "Name",
- "value": "bar",
- "propagate_at_launch": true,
- },
- },
- New: map[string]interface{}{
- "Name": map[string]interface{}{
- "key": "Name",
- "value": "baz",
- "propagate_at_launch": false,
- },
- },
- Create: map[string]interface{}{
- "Name": map[string]interface{}{
- "key": "Name",
- "value": "baz",
- "propagate_at_launch": false,
- },
- },
- Remove: map[string]interface{}{
- "Name": map[string]interface{}{
- "key": "Name",
- "value": "bar",
- "propagate_at_launch": true,
- },
- },
- },
- }
-
- var resourceID = "sample"
-
- for i, tc := range cases {
- awsTagsOld, err := autoscalingTagsFromMap(tc.Old, resourceID)
- if err != nil {
- t.Fatalf("%d: unexpected error convertig old tags: %v", i, err)
- }
-
- awsTagsNew, err := autoscalingTagsFromMap(tc.New, resourceID)
- if err != nil {
- t.Fatalf("%d: unexpected error convertig new tags: %v", i, err)
- }
-
- c, r, err := diffAutoscalingTags(awsTagsOld, awsTagsNew, resourceID)
- if err != nil {
- t.Fatalf("%d: unexpected error diff'ing tags: %v", i, err)
- }
-
- cm := autoscalingTagsToMap(c)
- rm := autoscalingTagsToMap(r)
- if !reflect.DeepEqual(cm, tc.Create) {
- t.Fatalf("%d: bad create: \n%#v\n%#v", i, cm, tc.Create)
- }
- if !reflect.DeepEqual(rm, tc.Remove) {
- t.Fatalf("%d: bad remove: \n%#v\n%#v", i, rm, tc.Remove)
- }
- }
-}
-
-// testAccCheckTags can be used to check the tags on a resource.
-func testAccCheckAutoscalingTags(
- ts *[]*autoscaling.TagDescription, key string, expected map[string]interface{}) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- m := autoscalingTagDescriptionsToMap(ts)
- v, ok := m[key]
- if !ok {
- return fmt.Errorf("Missing tag: %s", key)
- }
-
- if v["value"] != expected["value"].(string) ||
- v["propagate_at_launch"] != expected["propagate_at_launch"].(bool) {
- return fmt.Errorf("%s: bad value: %s", key, v)
- }
-
- return nil
- }
-}
-
-func testAccCheckAutoscalingTagNotExists(ts *[]*autoscaling.TagDescription, key string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- m := autoscalingTagDescriptionsToMap(ts)
- if _, ok := m[key]; ok {
- return fmt.Errorf("Tag exists when it should not: %s", key)
- }
-
- return nil
- }
-}
-
-func TestIgnoringTagsAutoscaling(t *testing.T) {
- var ignoredTags []*autoscaling.Tag
- ignoredTags = append(ignoredTags, &autoscaling.Tag{
- Key: aws.String("aws:cloudformation:logical-id"),
- Value: aws.String("foo"),
- })
- ignoredTags = append(ignoredTags, &autoscaling.Tag{
- Key: aws.String("aws:foo:bar"),
- Value: aws.String("baz"),
- })
- for _, tag := range ignoredTags {
- if !tagIgnoredAutoscaling(tag) {
- t.Fatalf("Tag %v with value %v not ignored, but should be!", *tag.Key, *tag.Value)
- }
- }
-}
diff --git a/builtin/providers/aws/aws_sweeper_test.go b/builtin/providers/aws/aws_sweeper_test.go
deleted file mode 100644
index 57f403c76..000000000
--- a/builtin/providers/aws/aws_sweeper_test.go
+++ /dev/null
@@ -1,37 +0,0 @@
-package aws
-
-import (
- "fmt"
- "os"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestMain(m *testing.M) {
- resource.TestMain(m)
-}
-
-// sharedClientForRegion returns a common AWSClient setup needed for the sweeper
-// functions for a given region
-func sharedClientForRegion(region string) (interface{}, error) {
- if os.Getenv("AWS_ACCESS_KEY_ID") == "" {
- return nil, fmt.Errorf("empty AWS_ACCESS_KEY_ID")
- }
-
- if os.Getenv("AWS_SECRET_ACCESS_KEY") == "" {
- return nil, fmt.Errorf("empty AWS_SECRET_ACCESS_KEY")
- }
-
- conf := &Config{
- Region: region,
- }
-
- // configures a default client for the region, using the above env vars
- client, err := conf.Client()
- if err != nil {
- return nil, fmt.Errorf("error getting AWS client")
- }
-
- return client, nil
-}
diff --git a/builtin/providers/aws/awserr.go b/builtin/providers/aws/awserr.go
deleted file mode 100644
index 8fc056801..000000000
--- a/builtin/providers/aws/awserr.go
+++ /dev/null
@@ -1,14 +0,0 @@
-package aws
-
-import (
- "strings"
-
- "github.com/aws/aws-sdk-go/aws/awserr"
-)
-
-func isAWSErr(err error, code string, message string) bool {
- if err, ok := err.(awserr.Error); ok {
- return err.Code() == code && strings.Contains(err.Message(), message)
- }
- return false
-}
diff --git a/builtin/providers/aws/cloudfront_distribution_configuration_structure.go b/builtin/providers/aws/cloudfront_distribution_configuration_structure.go
deleted file mode 100644
index a47217647..000000000
--- a/builtin/providers/aws/cloudfront_distribution_configuration_structure.go
+++ /dev/null
@@ -1,1140 +0,0 @@
-// CloudFront DistributionConfig structure helpers.
-//
-// These functions assist in pulling in data from Terraform resource
-// configuration for the aws_cloudfront_distribution resource, as there are
-// several sub-fields that require their own data type, and do not necessarily
-// 1-1 translate to resource configuration.
-
-package aws
-
-import (
- "bytes"
- "fmt"
- "reflect"
- "sort"
- "strconv"
- "time"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/cloudfront"
- "github.com/hashicorp/terraform/flatmap"
- "github.com/hashicorp/terraform/helper/hashcode"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-// cloudFrontRoute53ZoneID defines the route 53 zone ID for CloudFront. This
-// is used to set the zone_id attribute.
-const cloudFrontRoute53ZoneID = "Z2FDTNDATAQYW2"
-
-// Define Sort interface for []*string so we can ensure the order of
-// geo_restrictions.locations
-type StringPtrSlice []*string
-
-func (p StringPtrSlice) Len() int { return len(p) }
-func (p StringPtrSlice) Less(i, j int) bool { return *p[i] < *p[j] }
-func (p StringPtrSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
-
-// Assemble the *cloudfront.DistributionConfig variable. Calls out to various
-// expander functions to convert attributes and sub-attributes to the various
-// complex structures which are necessary to properly build the
-// DistributionConfig structure.
-//
-// Used by the aws_cloudfront_distribution Create and Update functions.
-func expandDistributionConfig(d *schema.ResourceData) *cloudfront.DistributionConfig {
- distributionConfig := &cloudfront.DistributionConfig{
- CacheBehaviors: expandCacheBehaviors(d.Get("cache_behavior").(*schema.Set)),
- CustomErrorResponses: expandCustomErrorResponses(d.Get("custom_error_response").(*schema.Set)),
- DefaultCacheBehavior: expandDefaultCacheBehavior(d.Get("default_cache_behavior").(*schema.Set).List()[0].(map[string]interface{})),
- Enabled: aws.Bool(d.Get("enabled").(bool)),
- IsIPV6Enabled: aws.Bool(d.Get("is_ipv6_enabled").(bool)),
- HttpVersion: aws.String(d.Get("http_version").(string)),
- Origins: expandOrigins(d.Get("origin").(*schema.Set)),
- PriceClass: aws.String(d.Get("price_class").(string)),
- }
- // This sets CallerReference if it's still pending computation (ie: new resource)
- if v, ok := d.GetOk("caller_reference"); ok == false {
- distributionConfig.CallerReference = aws.String(time.Now().Format(time.RFC3339Nano))
- } else {
- distributionConfig.CallerReference = aws.String(v.(string))
- }
- if v, ok := d.GetOk("comment"); ok {
- distributionConfig.Comment = aws.String(v.(string))
- } else {
- distributionConfig.Comment = aws.String("")
- }
- if v, ok := d.GetOk("default_root_object"); ok {
- distributionConfig.DefaultRootObject = aws.String(v.(string))
- } else {
- distributionConfig.DefaultRootObject = aws.String("")
- }
- if v, ok := d.GetOk("logging_config"); ok {
- distributionConfig.Logging = expandLoggingConfig(v.(*schema.Set).List()[0].(map[string]interface{}))
- } else {
- distributionConfig.Logging = expandLoggingConfig(nil)
- }
- if v, ok := d.GetOk("aliases"); ok {
- distributionConfig.Aliases = expandAliases(v.(*schema.Set))
- } else {
- distributionConfig.Aliases = expandAliases(schema.NewSet(aliasesHash, []interface{}{}))
- }
- if v, ok := d.GetOk("restrictions"); ok {
- distributionConfig.Restrictions = expandRestrictions(v.(*schema.Set).List()[0].(map[string]interface{}))
- }
- if v, ok := d.GetOk("viewer_certificate"); ok {
- distributionConfig.ViewerCertificate = expandViewerCertificate(v.(*schema.Set).List()[0].(map[string]interface{}))
- }
- if v, ok := d.GetOk("web_acl_id"); ok {
- distributionConfig.WebACLId = aws.String(v.(string))
- } else {
- distributionConfig.WebACLId = aws.String("")
- }
-
- return distributionConfig
-}
-
-// Unpack the *cloudfront.DistributionConfig variable and set resource data.
-// Calls out to flatten functions to convert the DistributionConfig
-// sub-structures to their respective attributes in the
-// aws_cloudfront_distribution resource.
-//
-// Used by the aws_cloudfront_distribution Read function.
-func flattenDistributionConfig(d *schema.ResourceData, distributionConfig *cloudfront.DistributionConfig) error {
- var err error
-
- d.Set("enabled", distributionConfig.Enabled)
- d.Set("is_ipv6_enabled", distributionConfig.IsIPV6Enabled)
- d.Set("price_class", distributionConfig.PriceClass)
- d.Set("hosted_zone_id", cloudFrontRoute53ZoneID)
-
- err = d.Set("default_cache_behavior", flattenDefaultCacheBehavior(distributionConfig.DefaultCacheBehavior))
- if err != nil {
- return err
- }
- err = d.Set("viewer_certificate", flattenViewerCertificate(distributionConfig.ViewerCertificate))
- if err != nil {
- return err
- }
-
- if distributionConfig.CallerReference != nil {
- d.Set("caller_reference", distributionConfig.CallerReference)
- }
- if distributionConfig.Comment != nil {
- if *distributionConfig.Comment != "" {
- d.Set("comment", distributionConfig.Comment)
- }
- }
- if distributionConfig.DefaultRootObject != nil {
- d.Set("default_root_object", distributionConfig.DefaultRootObject)
- }
- if distributionConfig.HttpVersion != nil {
- d.Set("http_version", distributionConfig.HttpVersion)
- }
- if distributionConfig.WebACLId != nil {
- d.Set("web_acl_id", distributionConfig.WebACLId)
- }
-
- if distributionConfig.CustomErrorResponses != nil {
- err = d.Set("custom_error_response", flattenCustomErrorResponses(distributionConfig.CustomErrorResponses))
- if err != nil {
- return err
- }
- }
- if distributionConfig.CacheBehaviors != nil {
- err = d.Set("cache_behavior", flattenCacheBehaviors(distributionConfig.CacheBehaviors))
- if err != nil {
- return err
- }
- }
-
- if distributionConfig.Logging != nil && *distributionConfig.Logging.Enabled {
- err = d.Set("logging_config", flattenLoggingConfig(distributionConfig.Logging))
- } else {
- err = d.Set("logging_config", schema.NewSet(loggingConfigHash, []interface{}{}))
- }
- if err != nil {
- return err
- }
-
- if distributionConfig.Aliases != nil {
- err = d.Set("aliases", flattenAliases(distributionConfig.Aliases))
- if err != nil {
- return err
- }
- }
- if distributionConfig.Restrictions != nil {
- err = d.Set("restrictions", flattenRestrictions(distributionConfig.Restrictions))
- if err != nil {
- return err
- }
- }
- if *distributionConfig.Origins.Quantity > 0 {
- err = d.Set("origin", flattenOrigins(distributionConfig.Origins))
- if err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func expandDefaultCacheBehavior(m map[string]interface{}) *cloudfront.DefaultCacheBehavior {
- cb := expandCacheBehavior(m)
- var dcb cloudfront.DefaultCacheBehavior
-
- simpleCopyStruct(cb, &dcb)
- return &dcb
-}
-
-func flattenDefaultCacheBehavior(dcb *cloudfront.DefaultCacheBehavior) *schema.Set {
- m := make(map[string]interface{})
- var cb cloudfront.CacheBehavior
-
- simpleCopyStruct(dcb, &cb)
- m = flattenCacheBehavior(&cb)
- return schema.NewSet(defaultCacheBehaviorHash, []interface{}{m})
-}
-
-// Assemble the hash for the aws_cloudfront_distribution default_cache_behavior
-// TypeSet attribute.
-func defaultCacheBehaviorHash(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%t-", m["compress"].(bool)))
- buf.WriteString(fmt.Sprintf("%s-", m["viewer_protocol_policy"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["target_origin_id"].(string)))
- buf.WriteString(fmt.Sprintf("%d-", forwardedValuesHash(m["forwarded_values"].(*schema.Set).List()[0].(map[string]interface{}))))
- buf.WriteString(fmt.Sprintf("%d-", m["min_ttl"].(int)))
- if d, ok := m["trusted_signers"]; ok {
- for _, e := range sortInterfaceSlice(d.([]interface{})) {
- buf.WriteString(fmt.Sprintf("%s-", e.(string)))
- }
- }
- if d, ok := m["max_ttl"]; ok {
- buf.WriteString(fmt.Sprintf("%d-", d.(int)))
- }
- if d, ok := m["smooth_streaming"]; ok {
- buf.WriteString(fmt.Sprintf("%t-", d.(bool)))
- }
- if d, ok := m["default_ttl"]; ok {
- buf.WriteString(fmt.Sprintf("%d-", d.(int)))
- }
- if d, ok := m["allowed_methods"]; ok {
- for _, e := range sortInterfaceSlice(d.([]interface{})) {
- buf.WriteString(fmt.Sprintf("%s-", e.(string)))
- }
- }
- if d, ok := m["cached_methods"]; ok {
- for _, e := range sortInterfaceSlice(d.([]interface{})) {
- buf.WriteString(fmt.Sprintf("%s-", e.(string)))
- }
- }
- if d, ok := m["lambda_function_association"]; ok {
- var associations []interface{}
- switch d.(type) {
- case *schema.Set:
- associations = d.(*schema.Set).List()
- default:
- associations = d.([]interface{})
- }
- for _, lfa := range associations {
- buf.WriteString(fmt.Sprintf("%d-", lambdaFunctionAssociationHash(lfa.(map[string]interface{}))))
- }
- }
- return hashcode.String(buf.String())
-}
-
-func expandCacheBehaviors(s *schema.Set) *cloudfront.CacheBehaviors {
- var qty int64
- var items []*cloudfront.CacheBehavior
- for _, v := range s.List() {
- items = append(items, expandCacheBehavior(v.(map[string]interface{})))
- qty++
- }
- return &cloudfront.CacheBehaviors{
- Quantity: aws.Int64(qty),
- Items: items,
- }
-}
-
-func flattenCacheBehaviors(cbs *cloudfront.CacheBehaviors) *schema.Set {
- s := []interface{}{}
- for _, v := range cbs.Items {
- s = append(s, flattenCacheBehavior(v))
- }
- return schema.NewSet(cacheBehaviorHash, s)
-}
-
-func expandCacheBehavior(m map[string]interface{}) *cloudfront.CacheBehavior {
- cb := &cloudfront.CacheBehavior{
- Compress: aws.Bool(m["compress"].(bool)),
- ViewerProtocolPolicy: aws.String(m["viewer_protocol_policy"].(string)),
- TargetOriginId: aws.String(m["target_origin_id"].(string)),
- ForwardedValues: expandForwardedValues(m["forwarded_values"].(*schema.Set).List()[0].(map[string]interface{})),
- MinTTL: aws.Int64(int64(m["min_ttl"].(int))),
- MaxTTL: aws.Int64(int64(m["max_ttl"].(int))),
- DefaultTTL: aws.Int64(int64(m["default_ttl"].(int))),
- }
- if v, ok := m["trusted_signers"]; ok {
- cb.TrustedSigners = expandTrustedSigners(v.([]interface{}))
- } else {
- cb.TrustedSigners = expandTrustedSigners([]interface{}{})
- }
-
- if v, ok := m["lambda_function_association"]; ok {
- cb.LambdaFunctionAssociations = expandLambdaFunctionAssociations(v.(*schema.Set).List())
- }
-
- if v, ok := m["smooth_streaming"]; ok {
- cb.SmoothStreaming = aws.Bool(v.(bool))
- }
- if v, ok := m["allowed_methods"]; ok {
- cb.AllowedMethods = expandAllowedMethods(v.([]interface{}))
- }
- if v, ok := m["cached_methods"]; ok {
- cb.AllowedMethods.CachedMethods = expandCachedMethods(v.([]interface{}))
- }
- if v, ok := m["path_pattern"]; ok {
- cb.PathPattern = aws.String(v.(string))
- }
- return cb
-}
-
-func flattenCacheBehavior(cb *cloudfront.CacheBehavior) map[string]interface{} {
- m := make(map[string]interface{})
-
- m["compress"] = *cb.Compress
- m["viewer_protocol_policy"] = *cb.ViewerProtocolPolicy
- m["target_origin_id"] = *cb.TargetOriginId
- m["forwarded_values"] = schema.NewSet(forwardedValuesHash, []interface{}{flattenForwardedValues(cb.ForwardedValues)})
- m["min_ttl"] = int(*cb.MinTTL)
-
- if len(cb.TrustedSigners.Items) > 0 {
- m["trusted_signers"] = flattenTrustedSigners(cb.TrustedSigners)
- }
- if len(cb.LambdaFunctionAssociations.Items) > 0 {
- m["lambda_function_association"] = flattenLambdaFunctionAssociations(cb.LambdaFunctionAssociations)
- }
- if cb.MaxTTL != nil {
- m["max_ttl"] = int(*cb.MaxTTL)
- }
- if cb.SmoothStreaming != nil {
- m["smooth_streaming"] = *cb.SmoothStreaming
- }
- if cb.DefaultTTL != nil {
- m["default_ttl"] = int(*cb.DefaultTTL)
- }
- if cb.AllowedMethods != nil {
- m["allowed_methods"] = flattenAllowedMethods(cb.AllowedMethods)
- }
- if cb.AllowedMethods.CachedMethods != nil {
- m["cached_methods"] = flattenCachedMethods(cb.AllowedMethods.CachedMethods)
- }
- if cb.PathPattern != nil {
- m["path_pattern"] = *cb.PathPattern
- }
- return m
-}
-
-// Assemble the hash for the aws_cloudfront_distribution cache_behavior
-// TypeSet attribute.
-func cacheBehaviorHash(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%t-", m["compress"].(bool)))
- buf.WriteString(fmt.Sprintf("%s-", m["viewer_protocol_policy"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["target_origin_id"].(string)))
- buf.WriteString(fmt.Sprintf("%d-", forwardedValuesHash(m["forwarded_values"].(*schema.Set).List()[0].(map[string]interface{}))))
- buf.WriteString(fmt.Sprintf("%d-", m["min_ttl"].(int)))
- if d, ok := m["trusted_signers"]; ok {
- for _, e := range sortInterfaceSlice(d.([]interface{})) {
- buf.WriteString(fmt.Sprintf("%s-", e.(string)))
- }
- }
- if d, ok := m["max_ttl"]; ok {
- buf.WriteString(fmt.Sprintf("%d-", d.(int)))
- }
- if d, ok := m["smooth_streaming"]; ok {
- buf.WriteString(fmt.Sprintf("%t-", d.(bool)))
- }
- if d, ok := m["default_ttl"]; ok {
- buf.WriteString(fmt.Sprintf("%d-", d.(int)))
- }
- if d, ok := m["allowed_methods"]; ok {
- for _, e := range sortInterfaceSlice(d.([]interface{})) {
- buf.WriteString(fmt.Sprintf("%s-", e.(string)))
- }
- }
- if d, ok := m["cached_methods"]; ok {
- for _, e := range sortInterfaceSlice(d.([]interface{})) {
- buf.WriteString(fmt.Sprintf("%s-", e.(string)))
- }
- }
- if d, ok := m["path_pattern"]; ok {
- buf.WriteString(fmt.Sprintf("%s-", d))
- }
- if d, ok := m["lambda_function_association"]; ok {
- var associations []interface{}
- switch d.(type) {
- case *schema.Set:
- associations = d.(*schema.Set).List()
- default:
- associations = d.([]interface{})
- }
- for _, lfa := range associations {
- buf.WriteString(fmt.Sprintf("%d-", lambdaFunctionAssociationHash(lfa.(map[string]interface{}))))
- }
- }
- return hashcode.String(buf.String())
-}
-
-func expandTrustedSigners(s []interface{}) *cloudfront.TrustedSigners {
- var ts cloudfront.TrustedSigners
- if len(s) > 0 {
- ts.Quantity = aws.Int64(int64(len(s)))
- ts.Items = expandStringList(s)
- ts.Enabled = aws.Bool(true)
- } else {
- ts.Quantity = aws.Int64(0)
- ts.Enabled = aws.Bool(false)
- }
- return &ts
-}
-
-func flattenTrustedSigners(ts *cloudfront.TrustedSigners) []interface{} {
- if ts.Items != nil {
- return flattenStringList(ts.Items)
- }
- return []interface{}{}
-}
-
-func lambdaFunctionAssociationHash(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%s-", m["event_type"].(string)))
- buf.WriteString(fmt.Sprintf("%s", m["lambda_arn"].(string)))
- return hashcode.String(buf.String())
-}
-
-func expandLambdaFunctionAssociations(v interface{}) *cloudfront.LambdaFunctionAssociations {
- if v == nil {
- return &cloudfront.LambdaFunctionAssociations{
- Quantity: aws.Int64(0),
- }
- }
-
- s := v.([]interface{})
- var lfa cloudfront.LambdaFunctionAssociations
- lfa.Quantity = aws.Int64(int64(len(s)))
- lfa.Items = make([]*cloudfront.LambdaFunctionAssociation, len(s))
- for i, lf := range s {
- lfa.Items[i] = expandLambdaFunctionAssociation(lf.(map[string]interface{}))
- }
- return &lfa
-}
-
-func expandLambdaFunctionAssociation(lf map[string]interface{}) *cloudfront.LambdaFunctionAssociation {
- var lfa cloudfront.LambdaFunctionAssociation
- if v, ok := lf["event_type"]; ok {
- lfa.EventType = aws.String(v.(string))
- }
- if v, ok := lf["lambda_arn"]; ok {
- lfa.LambdaFunctionARN = aws.String(v.(string))
- }
- return &lfa
-}
-
-func flattenLambdaFunctionAssociations(lfa *cloudfront.LambdaFunctionAssociations) *schema.Set {
- s := schema.NewSet(lambdaFunctionAssociationHash, []interface{}{})
- for _, v := range lfa.Items {
- s.Add(flattenLambdaFunctionAssociation(v))
- }
- return s
-}
-
-func flattenLambdaFunctionAssociation(lfa *cloudfront.LambdaFunctionAssociation) map[string]interface{} {
- m := map[string]interface{}{}
- if lfa != nil {
- m["event_type"] = *lfa.EventType
- m["lambda_arn"] = *lfa.LambdaFunctionARN
- }
- return m
-}
-
-func expandForwardedValues(m map[string]interface{}) *cloudfront.ForwardedValues {
- fv := &cloudfront.ForwardedValues{
- QueryString: aws.Bool(m["query_string"].(bool)),
- }
- if v, ok := m["cookies"]; ok && v.(*schema.Set).Len() > 0 {
- fv.Cookies = expandCookiePreference(v.(*schema.Set).List()[0].(map[string]interface{}))
- }
- if v, ok := m["headers"]; ok {
- fv.Headers = expandHeaders(v.([]interface{}))
- }
- if v, ok := m["query_string_cache_keys"]; ok {
- fv.QueryStringCacheKeys = expandQueryStringCacheKeys(v.([]interface{}))
- }
- return fv
-}
-
-func flattenForwardedValues(fv *cloudfront.ForwardedValues) map[string]interface{} {
- m := make(map[string]interface{})
- m["query_string"] = *fv.QueryString
- if fv.Cookies != nil {
- m["cookies"] = schema.NewSet(cookiePreferenceHash, []interface{}{flattenCookiePreference(fv.Cookies)})
- }
- if fv.Headers != nil {
- m["headers"] = flattenHeaders(fv.Headers)
- }
- if fv.QueryStringCacheKeys != nil {
- m["query_string_cache_keys"] = flattenQueryStringCacheKeys(fv.QueryStringCacheKeys)
- }
- return m
-}
-
-// Assemble the hash for the aws_cloudfront_distribution forwarded_values
-// TypeSet attribute.
-func forwardedValuesHash(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%t-", m["query_string"].(bool)))
- if d, ok := m["cookies"]; ok && d.(*schema.Set).Len() > 0 {
- buf.WriteString(fmt.Sprintf("%d-", cookiePreferenceHash(d.(*schema.Set).List()[0].(map[string]interface{}))))
- }
- if d, ok := m["headers"]; ok {
- for _, e := range sortInterfaceSlice(d.([]interface{})) {
- buf.WriteString(fmt.Sprintf("%s-", e.(string)))
- }
- }
- if d, ok := m["query_string_cache_keys"]; ok {
- for _, e := range sortInterfaceSlice(d.([]interface{})) {
- buf.WriteString(fmt.Sprintf("%s-", e.(string)))
- }
- }
- return hashcode.String(buf.String())
-}
-
-func expandHeaders(d []interface{}) *cloudfront.Headers {
- return &cloudfront.Headers{
- Quantity: aws.Int64(int64(len(d))),
- Items: expandStringList(d),
- }
-}
-
-func flattenHeaders(h *cloudfront.Headers) []interface{} {
- if h.Items != nil {
- return flattenStringList(h.Items)
- }
- return []interface{}{}
-}
-
-func expandQueryStringCacheKeys(d []interface{}) *cloudfront.QueryStringCacheKeys {
- return &cloudfront.QueryStringCacheKeys{
- Quantity: aws.Int64(int64(len(d))),
- Items: expandStringList(d),
- }
-}
-
-func flattenQueryStringCacheKeys(k *cloudfront.QueryStringCacheKeys) []interface{} {
- if k.Items != nil {
- return flattenStringList(k.Items)
- }
- return []interface{}{}
-}
-
-func expandCookiePreference(m map[string]interface{}) *cloudfront.CookiePreference {
- cp := &cloudfront.CookiePreference{
- Forward: aws.String(m["forward"].(string)),
- }
- if v, ok := m["whitelisted_names"]; ok {
- cp.WhitelistedNames = expandCookieNames(v.([]interface{}))
- }
- return cp
-}
-
-func flattenCookiePreference(cp *cloudfront.CookiePreference) map[string]interface{} {
- m := make(map[string]interface{})
- m["forward"] = *cp.Forward
- if cp.WhitelistedNames != nil {
- m["whitelisted_names"] = flattenCookieNames(cp.WhitelistedNames)
- }
- return m
-}
-
-// Assemble the hash for the aws_cloudfront_distribution cookies
-// TypeSet attribute.
-func cookiePreferenceHash(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%s-", m["forward"].(string)))
- if d, ok := m["whitelisted_names"]; ok {
- for _, e := range sortInterfaceSlice(d.([]interface{})) {
- buf.WriteString(fmt.Sprintf("%s-", e.(string)))
- }
- }
- return hashcode.String(buf.String())
-}
-
-func expandCookieNames(d []interface{}) *cloudfront.CookieNames {
- return &cloudfront.CookieNames{
- Quantity: aws.Int64(int64(len(d))),
- Items: expandStringList(d),
- }
-}
-
-func flattenCookieNames(cn *cloudfront.CookieNames) []interface{} {
- if cn.Items != nil {
- return flattenStringList(cn.Items)
- }
- return []interface{}{}
-}
-
-func expandAllowedMethods(s []interface{}) *cloudfront.AllowedMethods {
- return &cloudfront.AllowedMethods{
- Quantity: aws.Int64(int64(len(s))),
- Items: expandStringList(s),
- }
-}
-
-func flattenAllowedMethods(am *cloudfront.AllowedMethods) []interface{} {
- if am.Items != nil {
- return flattenStringList(am.Items)
- }
- return []interface{}{}
-}
-
-func expandCachedMethods(s []interface{}) *cloudfront.CachedMethods {
- return &cloudfront.CachedMethods{
- Quantity: aws.Int64(int64(len(s))),
- Items: expandStringList(s),
- }
-}
-
-func flattenCachedMethods(cm *cloudfront.CachedMethods) []interface{} {
- if cm.Items != nil {
- return flattenStringList(cm.Items)
- }
- return []interface{}{}
-}
-
-func expandOrigins(s *schema.Set) *cloudfront.Origins {
- qty := 0
- items := []*cloudfront.Origin{}
- for _, v := range s.List() {
- items = append(items, expandOrigin(v.(map[string]interface{})))
- qty++
- }
- return &cloudfront.Origins{
- Quantity: aws.Int64(int64(qty)),
- Items: items,
- }
-}
-
-func flattenOrigins(ors *cloudfront.Origins) *schema.Set {
- s := []interface{}{}
- for _, v := range ors.Items {
- s = append(s, flattenOrigin(v))
- }
- return schema.NewSet(originHash, s)
-}
-
-func expandOrigin(m map[string]interface{}) *cloudfront.Origin {
- origin := &cloudfront.Origin{
- Id: aws.String(m["origin_id"].(string)),
- DomainName: aws.String(m["domain_name"].(string)),
- }
- if v, ok := m["custom_header"]; ok {
- origin.CustomHeaders = expandCustomHeaders(v.(*schema.Set))
- }
- if v, ok := m["custom_origin_config"]; ok {
- if s := v.(*schema.Set).List(); len(s) > 0 {
- origin.CustomOriginConfig = expandCustomOriginConfig(s[0].(map[string]interface{}))
- }
- }
- if v, ok := m["origin_path"]; ok {
- origin.OriginPath = aws.String(v.(string))
- }
- if v, ok := m["s3_origin_config"]; ok {
- if s := v.(*schema.Set).List(); len(s) > 0 {
- origin.S3OriginConfig = expandS3OriginConfig(s[0].(map[string]interface{}))
- }
- }
-
- // if both custom and s3 origin are missing, add an empty s3 origin
- // One or the other must be specified, but the S3 origin can be "empty"
- if origin.S3OriginConfig == nil && origin.CustomOriginConfig == nil {
- origin.S3OriginConfig = &cloudfront.S3OriginConfig{
- OriginAccessIdentity: aws.String(""),
- }
- }
-
- return origin
-}
-
-func flattenOrigin(or *cloudfront.Origin) map[string]interface{} {
- m := make(map[string]interface{})
- m["origin_id"] = *or.Id
- m["domain_name"] = *or.DomainName
- if or.CustomHeaders != nil {
- m["custom_header"] = flattenCustomHeaders(or.CustomHeaders)
- }
- if or.CustomOriginConfig != nil {
- m["custom_origin_config"] = schema.NewSet(customOriginConfigHash, []interface{}{flattenCustomOriginConfig(or.CustomOriginConfig)})
- }
- if or.OriginPath != nil {
- m["origin_path"] = *or.OriginPath
- }
- if or.S3OriginConfig != nil {
- if or.S3OriginConfig.OriginAccessIdentity != nil && *or.S3OriginConfig.OriginAccessIdentity != "" {
- m["s3_origin_config"] = schema.NewSet(s3OriginConfigHash, []interface{}{flattenS3OriginConfig(or.S3OriginConfig)})
- }
- }
- return m
-}
-
-// Assemble the hash for the aws_cloudfront_distribution origin
-// TypeSet attribute.
-func originHash(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%s-", m["origin_id"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["domain_name"].(string)))
- if v, ok := m["custom_header"]; ok {
- buf.WriteString(fmt.Sprintf("%d-", customHeadersHash(v.(*schema.Set))))
- }
- if v, ok := m["custom_origin_config"]; ok {
- if s := v.(*schema.Set).List(); len(s) > 0 {
- buf.WriteString(fmt.Sprintf("%d-", customOriginConfigHash((s[0].(map[string]interface{})))))
- }
- }
- if v, ok := m["origin_path"]; ok {
- buf.WriteString(fmt.Sprintf("%s-", v.(string)))
- }
- if v, ok := m["s3_origin_config"]; ok {
- if s := v.(*schema.Set).List(); len(s) > 0 {
- buf.WriteString(fmt.Sprintf("%d-", s3OriginConfigHash((s[0].(map[string]interface{})))))
- }
- }
- return hashcode.String(buf.String())
-}
-
-func expandCustomHeaders(s *schema.Set) *cloudfront.CustomHeaders {
- qty := 0
- items := []*cloudfront.OriginCustomHeader{}
- for _, v := range s.List() {
- items = append(items, expandOriginCustomHeader(v.(map[string]interface{})))
- qty++
- }
- return &cloudfront.CustomHeaders{
- Quantity: aws.Int64(int64(qty)),
- Items: items,
- }
-}
-
-func flattenCustomHeaders(chs *cloudfront.CustomHeaders) *schema.Set {
- s := []interface{}{}
- for _, v := range chs.Items {
- s = append(s, flattenOriginCustomHeader(v))
- }
- return schema.NewSet(originCustomHeaderHash, s)
-}
-
-func expandOriginCustomHeader(m map[string]interface{}) *cloudfront.OriginCustomHeader {
- return &cloudfront.OriginCustomHeader{
- HeaderName: aws.String(m["name"].(string)),
- HeaderValue: aws.String(m["value"].(string)),
- }
-}
-
-func flattenOriginCustomHeader(och *cloudfront.OriginCustomHeader) map[string]interface{} {
- return map[string]interface{}{
- "name": *och.HeaderName,
- "value": *och.HeaderValue,
- }
-}
-
-// Helper function used by originHash to get a composite hash for all
-// aws_cloudfront_distribution custom_header attributes.
-func customHeadersHash(s *schema.Set) int {
- var buf bytes.Buffer
- for _, v := range s.List() {
- buf.WriteString(fmt.Sprintf("%d-", originCustomHeaderHash(v)))
- }
- return hashcode.String(buf.String())
-}
-
-// Assemble the hash for the aws_cloudfront_distribution custom_header
-// TypeSet attribute.
-func originCustomHeaderHash(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%s-", m["name"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["value"].(string)))
- return hashcode.String(buf.String())
-}
-
-func expandCustomOriginConfig(m map[string]interface{}) *cloudfront.CustomOriginConfig {
-
- customOrigin := &cloudfront.CustomOriginConfig{
- OriginProtocolPolicy: aws.String(m["origin_protocol_policy"].(string)),
- HTTPPort: aws.Int64(int64(m["http_port"].(int))),
- HTTPSPort: aws.Int64(int64(m["https_port"].(int))),
- OriginSslProtocols: expandCustomOriginConfigSSL(m["origin_ssl_protocols"].([]interface{})),
- OriginReadTimeout: aws.Int64(int64(m["origin_read_timeout"].(int))),
- OriginKeepaliveTimeout: aws.Int64(int64(m["origin_keepalive_timeout"].(int))),
- }
-
- return customOrigin
-}
-
-func flattenCustomOriginConfig(cor *cloudfront.CustomOriginConfig) map[string]interface{} {
-
- customOrigin := map[string]interface{}{
- "origin_protocol_policy": *cor.OriginProtocolPolicy,
- "http_port": int(*cor.HTTPPort),
- "https_port": int(*cor.HTTPSPort),
- "origin_ssl_protocols": flattenCustomOriginConfigSSL(cor.OriginSslProtocols),
- "origin_read_timeout": int(*cor.OriginReadTimeout),
- "origin_keepalive_timeout": int(*cor.OriginKeepaliveTimeout),
- }
-
- return customOrigin
-}
-
-// Assemble the hash for the aws_cloudfront_distribution custom_origin_config
-// TypeSet attribute.
-func customOriginConfigHash(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%s-", m["origin_protocol_policy"].(string)))
- buf.WriteString(fmt.Sprintf("%d-", m["http_port"].(int)))
- buf.WriteString(fmt.Sprintf("%d-", m["https_port"].(int)))
- for _, v := range sortInterfaceSlice(m["origin_ssl_protocols"].([]interface{})) {
- buf.WriteString(fmt.Sprintf("%s-", v.(string)))
- }
- buf.WriteString(fmt.Sprintf("%d-", m["origin_keepalive_timeout"].(int)))
- buf.WriteString(fmt.Sprintf("%d-", m["origin_read_timeout"].(int)))
-
- return hashcode.String(buf.String())
-}
-
-func expandCustomOriginConfigSSL(s []interface{}) *cloudfront.OriginSslProtocols {
- items := expandStringList(s)
- return &cloudfront.OriginSslProtocols{
- Quantity: aws.Int64(int64(len(items))),
- Items: items,
- }
-}
-
-func flattenCustomOriginConfigSSL(osp *cloudfront.OriginSslProtocols) []interface{} {
- return flattenStringList(osp.Items)
-}
-
-func expandS3OriginConfig(m map[string]interface{}) *cloudfront.S3OriginConfig {
- return &cloudfront.S3OriginConfig{
- OriginAccessIdentity: aws.String(m["origin_access_identity"].(string)),
- }
-}
-
-func flattenS3OriginConfig(s3o *cloudfront.S3OriginConfig) map[string]interface{} {
- return map[string]interface{}{
- "origin_access_identity": *s3o.OriginAccessIdentity,
- }
-}
-
-// Assemble the hash for the aws_cloudfront_distribution s3_origin_config
-// TypeSet attribute.
-func s3OriginConfigHash(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%s-", m["origin_access_identity"].(string)))
- return hashcode.String(buf.String())
-}
-
-func expandCustomErrorResponses(s *schema.Set) *cloudfront.CustomErrorResponses {
- qty := 0
- items := []*cloudfront.CustomErrorResponse{}
- for _, v := range s.List() {
- items = append(items, expandCustomErrorResponse(v.(map[string]interface{})))
- qty++
- }
- return &cloudfront.CustomErrorResponses{
- Quantity: aws.Int64(int64(qty)),
- Items: items,
- }
-}
-
-func flattenCustomErrorResponses(ers *cloudfront.CustomErrorResponses) *schema.Set {
- s := []interface{}{}
- for _, v := range ers.Items {
- s = append(s, flattenCustomErrorResponse(v))
- }
- return schema.NewSet(customErrorResponseHash, s)
-}
-
-func expandCustomErrorResponse(m map[string]interface{}) *cloudfront.CustomErrorResponse {
- er := cloudfront.CustomErrorResponse{
- ErrorCode: aws.Int64(int64(m["error_code"].(int))),
- }
- if v, ok := m["error_caching_min_ttl"]; ok {
- er.ErrorCachingMinTTL = aws.Int64(int64(v.(int)))
- }
- if v, ok := m["response_code"]; ok && v.(int) != 0 {
- er.ResponseCode = aws.String(strconv.Itoa(v.(int)))
- } else {
- er.ResponseCode = aws.String("")
- }
- if v, ok := m["response_page_path"]; ok {
- er.ResponsePagePath = aws.String(v.(string))
- }
-
- return &er
-}
-
-func flattenCustomErrorResponse(er *cloudfront.CustomErrorResponse) map[string]interface{} {
- m := make(map[string]interface{})
- m["error_code"] = int(*er.ErrorCode)
- if er.ErrorCachingMinTTL != nil {
- m["error_caching_min_ttl"] = int(*er.ErrorCachingMinTTL)
- }
- if er.ResponseCode != nil {
- m["response_code"], _ = strconv.Atoi(*er.ResponseCode)
- }
- if er.ResponsePagePath != nil {
- m["response_page_path"] = *er.ResponsePagePath
- }
- return m
-}
-
-// Assemble the hash for the aws_cloudfront_distribution custom_error_response
-// TypeSet attribute.
-func customErrorResponseHash(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%d-", m["error_code"].(int)))
- if v, ok := m["error_caching_min_ttl"]; ok {
- buf.WriteString(fmt.Sprintf("%d-", v.(int)))
- }
- if v, ok := m["response_code"]; ok {
- buf.WriteString(fmt.Sprintf("%d-", v.(int)))
- }
- if v, ok := m["response_page_path"]; ok {
- buf.WriteString(fmt.Sprintf("%s-", v.(string)))
- }
- return hashcode.String(buf.String())
-}
-
-func expandLoggingConfig(m map[string]interface{}) *cloudfront.LoggingConfig {
- var lc cloudfront.LoggingConfig
- if m != nil {
- lc.Prefix = aws.String(m["prefix"].(string))
- lc.Bucket = aws.String(m["bucket"].(string))
- lc.IncludeCookies = aws.Bool(m["include_cookies"].(bool))
- lc.Enabled = aws.Bool(true)
- } else {
- lc.Prefix = aws.String("")
- lc.Bucket = aws.String("")
- lc.IncludeCookies = aws.Bool(false)
- lc.Enabled = aws.Bool(false)
- }
- return &lc
-}
-
-func flattenLoggingConfig(lc *cloudfront.LoggingConfig) *schema.Set {
- m := make(map[string]interface{})
- m["prefix"] = *lc.Prefix
- m["bucket"] = *lc.Bucket
- m["include_cookies"] = *lc.IncludeCookies
- return schema.NewSet(loggingConfigHash, []interface{}{m})
-}
-
-// Assemble the hash for the aws_cloudfront_distribution logging_config
-// TypeSet attribute.
-func loggingConfigHash(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%s-", m["prefix"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["bucket"].(string)))
- buf.WriteString(fmt.Sprintf("%t-", m["include_cookies"].(bool)))
- return hashcode.String(buf.String())
-}
-
-func expandAliases(as *schema.Set) *cloudfront.Aliases {
- s := as.List()
- var aliases cloudfront.Aliases
- if len(s) > 0 {
- aliases.Quantity = aws.Int64(int64(len(s)))
- aliases.Items = expandStringList(s)
- } else {
- aliases.Quantity = aws.Int64(0)
- }
- return &aliases
-}
-
-func flattenAliases(aliases *cloudfront.Aliases) *schema.Set {
- if aliases.Items != nil {
- return schema.NewSet(aliasesHash, flattenStringList(aliases.Items))
- }
- return schema.NewSet(aliasesHash, []interface{}{})
-}
-
-// Assemble the hash for the aws_cloudfront_distribution aliases
-// TypeSet attribute.
-func aliasesHash(v interface{}) int {
- return hashcode.String(v.(string))
-}
-
-func expandRestrictions(m map[string]interface{}) *cloudfront.Restrictions {
- return &cloudfront.Restrictions{
- GeoRestriction: expandGeoRestriction(m["geo_restriction"].(*schema.Set).List()[0].(map[string]interface{})),
- }
-}
-
-func flattenRestrictions(r *cloudfront.Restrictions) *schema.Set {
- m := make(map[string]interface{})
- s := schema.NewSet(geoRestrictionHash, []interface{}{flattenGeoRestriction(r.GeoRestriction)})
- m["geo_restriction"] = s
- return schema.NewSet(restrictionsHash, []interface{}{m})
-}
-
-// Assemble the hash for the aws_cloudfront_distribution restrictions
-// TypeSet attribute.
-func restrictionsHash(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%d-", geoRestrictionHash(m["geo_restriction"].(*schema.Set).List()[0].(map[string]interface{}))))
- return hashcode.String(buf.String())
-}
-
-func expandGeoRestriction(m map[string]interface{}) *cloudfront.GeoRestriction {
- gr := cloudfront.GeoRestriction{
- RestrictionType: aws.String(m["restriction_type"].(string)),
- }
- if v, ok := m["locations"]; ok {
- gr.Quantity = aws.Int64(int64(len(v.([]interface{}))))
- gr.Items = expandStringList(v.([]interface{}))
- sort.Sort(StringPtrSlice(gr.Items))
- } else {
- gr.Quantity = aws.Int64(0)
- }
- return &gr
-}
-
-func flattenGeoRestriction(gr *cloudfront.GeoRestriction) map[string]interface{} {
- m := make(map[string]interface{})
-
- m["restriction_type"] = *gr.RestrictionType
- if gr.Items != nil {
- sort.Sort(StringPtrSlice(gr.Items))
- m["locations"] = flattenStringList(gr.Items)
- }
- return m
-}
-
-// Assemble the hash for the aws_cloudfront_distribution geo_restriction
-// TypeSet attribute.
-func geoRestrictionHash(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- // All keys added in alphabetical order.
- buf.WriteString(fmt.Sprintf("%s-", m["restriction_type"].(string)))
- if v, ok := m["locations"]; ok {
- for _, w := range sortInterfaceSlice(v.([]interface{})) {
- buf.WriteString(fmt.Sprintf("%s-", w.(string)))
- }
- }
- return hashcode.String(buf.String())
-}
-
-func expandViewerCertificate(m map[string]interface{}) *cloudfront.ViewerCertificate {
- var vc cloudfront.ViewerCertificate
- if v, ok := m["iam_certificate_id"]; ok && v != "" {
- vc.IAMCertificateId = aws.String(v.(string))
- vc.SSLSupportMethod = aws.String(m["ssl_support_method"].(string))
- } else if v, ok := m["acm_certificate_arn"]; ok && v != "" {
- vc.ACMCertificateArn = aws.String(v.(string))
- vc.SSLSupportMethod = aws.String(m["ssl_support_method"].(string))
- } else {
- vc.CloudFrontDefaultCertificate = aws.Bool(m["cloudfront_default_certificate"].(bool))
- }
- if v, ok := m["minimum_protocol_version"]; ok && v != "" {
- vc.MinimumProtocolVersion = aws.String(v.(string))
- }
- return &vc
-}
-
-func flattenViewerCertificate(vc *cloudfront.ViewerCertificate) *schema.Set {
- m := make(map[string]interface{})
-
- if vc.IAMCertificateId != nil {
- m["iam_certificate_id"] = *vc.IAMCertificateId
- m["ssl_support_method"] = *vc.SSLSupportMethod
- }
- if vc.ACMCertificateArn != nil {
- m["acm_certificate_arn"] = *vc.ACMCertificateArn
- m["ssl_support_method"] = *vc.SSLSupportMethod
- }
- if vc.CloudFrontDefaultCertificate != nil {
- m["cloudfront_default_certificate"] = *vc.CloudFrontDefaultCertificate
- }
- if vc.MinimumProtocolVersion != nil {
- m["minimum_protocol_version"] = *vc.MinimumProtocolVersion
- }
- return schema.NewSet(viewerCertificateHash, []interface{}{m})
-}
-
-// Assemble the hash for the aws_cloudfront_distribution viewer_certificate
-// TypeSet attribute.
-func viewerCertificateHash(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- if v, ok := m["iam_certificate_id"]; ok && v.(string) != "" {
- buf.WriteString(fmt.Sprintf("%s-", v.(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["ssl_support_method"].(string)))
- } else if v, ok := m["acm_certificate_arn"]; ok && v.(string) != "" {
- buf.WriteString(fmt.Sprintf("%s-", v.(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["ssl_support_method"].(string)))
- } else {
- buf.WriteString(fmt.Sprintf("%t-", m["cloudfront_default_certificate"].(bool)))
- }
- if v, ok := m["minimum_protocol_version"]; ok && v.(string) != "" {
- buf.WriteString(fmt.Sprintf("%s-", v.(string)))
- }
- return hashcode.String(buf.String())
-}
-
-// Do a top-level copy of struct fields from one struct to another. Used to
-// copy fields between CacheBehavior and DefaultCacheBehavior structs.
-func simpleCopyStruct(src, dst interface{}) {
- s := reflect.ValueOf(src).Elem()
- d := reflect.ValueOf(dst).Elem()
-
- for i := 0; i < s.NumField(); i++ {
- if s.Field(i).CanSet() == true {
- if s.Field(i).Interface() != nil {
- for j := 0; j < d.NumField(); j++ {
- if d.Type().Field(j).Name == s.Type().Field(i).Name {
- d.Field(j).Set(s.Field(i))
- }
- }
- }
- }
- }
-}
-
-// Convert *cloudfront.ActiveTrustedSigners to a flatmap.Map type, which ensures
-// it can probably be inserted into the schema.TypeMap type used by the
-// active_trusted_signers attribute.
-func flattenActiveTrustedSigners(ats *cloudfront.ActiveTrustedSigners) flatmap.Map {
- m := make(map[string]interface{})
- s := []interface{}{}
- m["enabled"] = *ats.Enabled
-
- for _, v := range ats.Items {
- signer := make(map[string]interface{})
- signer["aws_account_number"] = *v.AwsAccountNumber
- signer["key_pair_ids"] = aws.StringValueSlice(v.KeyPairIds.Items)
- s = append(s, signer)
- }
- m["items"] = s
- return flatmap.Flatten(m)
-}
diff --git a/builtin/providers/aws/cloudfront_distribution_configuration_structure_test.go b/builtin/providers/aws/cloudfront_distribution_configuration_structure_test.go
deleted file mode 100644
index cb594d48e..000000000
--- a/builtin/providers/aws/cloudfront_distribution_configuration_structure_test.go
+++ /dev/null
@@ -1,1161 +0,0 @@
-package aws
-
-import (
- "reflect"
- "testing"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/cloudfront"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func defaultCacheBehaviorConf() map[string]interface{} {
- return map[string]interface{}{
- "viewer_protocol_policy": "allow-all",
- "target_origin_id": "myS3Origin",
- "forwarded_values": schema.NewSet(forwardedValuesHash, []interface{}{forwardedValuesConf()}),
- "min_ttl": 86400,
- "trusted_signers": trustedSignersConf(),
- "lambda_function_association": lambdaFunctionAssociationsConf(),
- "max_ttl": 365000000,
- "smooth_streaming": false,
- "default_ttl": 86400,
- "allowed_methods": allowedMethodsConf(),
- "cached_methods": cachedMethodsConf(),
- "compress": true,
- }
-}
-
-func cacheBehaviorConf1() map[string]interface{} {
- cb := defaultCacheBehaviorConf()
- cb["path_pattern"] = "/path1"
- return cb
-}
-
-func cacheBehaviorConf2() map[string]interface{} {
- cb := defaultCacheBehaviorConf()
- cb["path_pattern"] = "/path2"
- return cb
-}
-
-func cacheBehaviorsConf() *schema.Set {
- return schema.NewSet(cacheBehaviorHash, []interface{}{cacheBehaviorConf1(), cacheBehaviorConf2()})
-}
-
-func trustedSignersConf() []interface{} {
- return []interface{}{"1234567890EX", "1234567891EX"}
-}
-
-func lambdaFunctionAssociationsConf() *schema.Set {
- x := []interface{}{
- map[string]interface{}{
- "event_type": "viewer-request",
- "lambda_arn": "arn:aws:lambda:us-east-1:999999999:function1:alias",
- },
- map[string]interface{}{
- "event_type": "origin-response",
- "lambda_arn": "arn:aws:lambda:us-east-1:999999999:function2:alias",
- },
- }
-
- return schema.NewSet(lambdaFunctionAssociationHash, x)
-}
-
-func forwardedValuesConf() map[string]interface{} {
- return map[string]interface{}{
- "query_string": true,
- "query_string_cache_keys": queryStringCacheKeysConf(),
- "cookies": schema.NewSet(cookiePreferenceHash, []interface{}{cookiePreferenceConf()}),
- "headers": headersConf(),
- }
-}
-
-func headersConf() []interface{} {
- return []interface{}{"X-Example1", "X-Example2"}
-}
-
-func queryStringCacheKeysConf() []interface{} {
- return []interface{}{"foo", "bar"}
-}
-
-func cookiePreferenceConf() map[string]interface{} {
- return map[string]interface{}{
- "forward": "whitelist",
- "whitelisted_names": cookieNamesConf(),
- }
-}
-
-func cookieNamesConf() []interface{} {
- return []interface{}{"Example1", "Example2"}
-}
-
-func allowedMethodsConf() []interface{} {
- return []interface{}{"DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"}
-}
-
-func cachedMethodsConf() []interface{} {
- return []interface{}{"GET", "HEAD", "OPTIONS"}
-}
-
-func originCustomHeadersConf() *schema.Set {
- return schema.NewSet(originCustomHeaderHash, []interface{}{originCustomHeaderConf1(), originCustomHeaderConf2()})
-}
-
-func originCustomHeaderConf1() map[string]interface{} {
- return map[string]interface{}{
- "name": "X-Custom-Header1",
- "value": "samplevalue",
- }
-}
-
-func originCustomHeaderConf2() map[string]interface{} {
- return map[string]interface{}{
- "name": "X-Custom-Header2",
- "value": "samplevalue",
- }
-}
-
-func customOriginConf() map[string]interface{} {
- return map[string]interface{}{
- "origin_protocol_policy": "http-only",
- "http_port": 80,
- "https_port": 443,
- "origin_ssl_protocols": customOriginSslProtocolsConf(),
- "origin_read_timeout": 30,
- "origin_keepalive_timeout": 5,
- }
-}
-
-func customOriginSslProtocolsConf() []interface{} {
- return []interface{}{"SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"}
-}
-
-func s3OriginConf() map[string]interface{} {
- return map[string]interface{}{
- "origin_access_identity": "origin-access-identity/cloudfront/E127EXAMPLE51Z",
- }
-}
-
-func originWithCustomConf() map[string]interface{} {
- return map[string]interface{}{
- "origin_id": "CustomOrigin",
- "domain_name": "www.example.com",
- "origin_path": "/",
- "custom_origin_config": schema.NewSet(customOriginConfigHash, []interface{}{customOriginConf()}),
- "custom_header": originCustomHeadersConf(),
- }
-}
-func originWithS3Conf() map[string]interface{} {
- return map[string]interface{}{
- "origin_id": "S3Origin",
- "domain_name": "s3.example.com",
- "origin_path": "/",
- "s3_origin_config": schema.NewSet(s3OriginConfigHash, []interface{}{s3OriginConf()}),
- "custom_header": originCustomHeadersConf(),
- }
-}
-
-func multiOriginConf() *schema.Set {
- return schema.NewSet(originHash, []interface{}{originWithCustomConf(), originWithS3Conf()})
-}
-
-func geoRestrictionWhitelistConf() map[string]interface{} {
- return map[string]interface{}{
- "restriction_type": "whitelist",
- "locations": []interface{}{"CA", "GB", "US"},
- }
-}
-
-func geoRestrictionsConf() map[string]interface{} {
- return map[string]interface{}{
- "geo_restriction": schema.NewSet(geoRestrictionHash, []interface{}{geoRestrictionWhitelistConf()}),
- }
-}
-
-func geoRestrictionConfNoItems() map[string]interface{} {
- return map[string]interface{}{
- "restriction_type": "none",
- }
-}
-
-func customErrorResponsesConf() []interface{} {
- return []interface{}{
- map[string]interface{}{
- "error_code": 404,
- "error_caching_min_ttl": 30,
- "response_code": 200,
- "response_page_path": "/error-pages/404.html",
- },
- map[string]interface{}{
- "error_code": 403,
- "error_caching_min_ttl": 15,
- "response_code": 404,
- "response_page_path": "/error-pages/404.html",
- },
- }
-}
-
-func aliasesConf() *schema.Set {
- return schema.NewSet(aliasesHash, []interface{}{"example.com", "www.example.com"})
-}
-
-func loggingConfigConf() map[string]interface{} {
- return map[string]interface{}{
- "include_cookies": false,
- "bucket": "mylogs.s3.amazonaws.com",
- "prefix": "myprefix",
- }
-}
-
-func customErrorResponsesConfSet() *schema.Set {
- return schema.NewSet(customErrorResponseHash, customErrorResponsesConf())
-}
-
-func customErrorResponsesConfFirst() map[string]interface{} {
- return customErrorResponsesConf()[0].(map[string]interface{})
-}
-
-func customErrorResponseConfNoResponseCode() map[string]interface{} {
- er := customErrorResponsesConf()[0].(map[string]interface{})
- er["response_code"] = 0
- er["response_page_path"] = ""
- return er
-}
-
-func viewerCertificateConfSetCloudFrontDefault() map[string]interface{} {
- return map[string]interface{}{
- "acm_certificate_arn": "",
- "cloudfront_default_certificate": true,
- "iam_certificate_id": "",
- "minimum_protocol_version": "",
- "ssl_support_method": "",
- }
-}
-
-func viewerCertificateConfSetIAM() map[string]interface{} {
- return map[string]interface{}{
- "acm_certificate_arn": "",
- "cloudfront_default_certificate": false,
- "iam_certificate_id": "iamcert-01234567",
- "ssl_support_method": "vip",
- "minimum_protocol_version": "TLSv1",
- }
-}
-
-func viewerCertificateConfSetACM() map[string]interface{} {
- return map[string]interface{}{
- "acm_certificate_arn": "arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012",
- "cloudfront_default_certificate": false,
- "iam_certificate_id": "",
- "ssl_support_method": "sni-only",
- "minimum_protocol_version": "TLSv1",
- }
-}
-
-func TestCloudFrontStructure_expandDefaultCacheBehavior(t *testing.T) {
- data := defaultCacheBehaviorConf()
- dcb := expandDefaultCacheBehavior(data)
- if dcb == nil {
- t.Fatalf("ExpandDefaultCacheBehavior returned nil")
- }
- if *dcb.Compress != true {
- t.Fatalf("Expected Compress to be true, got %v", *dcb.Compress)
- }
- if *dcb.ViewerProtocolPolicy != "allow-all" {
- t.Fatalf("Expected ViewerProtocolPolicy to be allow-all, got %v", *dcb.ViewerProtocolPolicy)
- }
- if *dcb.TargetOriginId != "myS3Origin" {
- t.Fatalf("Expected TargetOriginId to be allow-all, got %v", *dcb.TargetOriginId)
- }
- if reflect.DeepEqual(dcb.ForwardedValues.Headers.Items, expandStringList(headersConf())) != true {
- t.Fatalf("Expected Items to be %v, got %v", headersConf(), dcb.ForwardedValues.Headers.Items)
- }
- if *dcb.MinTTL != 86400 {
- t.Fatalf("Expected MinTTL to be 86400, got %v", *dcb.MinTTL)
- }
- if reflect.DeepEqual(dcb.TrustedSigners.Items, expandStringList(trustedSignersConf())) != true {
- t.Fatalf("Expected TrustedSigners.Items to be %v, got %v", trustedSignersConf(), dcb.TrustedSigners.Items)
- }
- if *dcb.MaxTTL != 365000000 {
- t.Fatalf("Expected MaxTTL to be 365000000, got %v", *dcb.MaxTTL)
- }
- if *dcb.SmoothStreaming != false {
- t.Fatalf("Expected SmoothStreaming to be false, got %v", *dcb.SmoothStreaming)
- }
- if *dcb.DefaultTTL != 86400 {
- t.Fatalf("Expected DefaultTTL to be 86400, got %v", *dcb.DefaultTTL)
- }
- if *dcb.LambdaFunctionAssociations.Quantity != 2 {
- t.Fatalf("Expected LambdaFunctionAssociations to be 2, got %v", *dcb.LambdaFunctionAssociations.Quantity)
- }
- if reflect.DeepEqual(dcb.AllowedMethods.Items, expandStringList(allowedMethodsConf())) != true {
- t.Fatalf("Expected TrustedSigners.Items to be %v, got %v", allowedMethodsConf(), dcb.AllowedMethods.Items)
- }
- if reflect.DeepEqual(dcb.AllowedMethods.CachedMethods.Items, expandStringList(cachedMethodsConf())) != true {
- t.Fatalf("Expected TrustedSigners.Items to be %v, got %v", cachedMethodsConf(), dcb.AllowedMethods.CachedMethods.Items)
- }
-}
-
-func TestCloudFrontStructure_flattenDefaultCacheBehavior(t *testing.T) {
- in := defaultCacheBehaviorConf()
- dcb := expandDefaultCacheBehavior(in)
- out := flattenDefaultCacheBehavior(dcb)
- diff := schema.NewSet(defaultCacheBehaviorHash, []interface{}{in}).Difference(out)
-
- if len(diff.List()) > 0 {
- t.Fatalf("Expected out to be %v, got %v, diff: %v", in, out, diff)
- }
-}
-
-func TestCloudFrontStructure_expandCacheBehavior(t *testing.T) {
- data := cacheBehaviorConf1()
- cb := expandCacheBehavior(data)
- if *cb.Compress != true {
- t.Fatalf("Expected Compress to be true, got %v", *cb.Compress)
- }
- if *cb.ViewerProtocolPolicy != "allow-all" {
- t.Fatalf("Expected ViewerProtocolPolicy to be allow-all, got %v", *cb.ViewerProtocolPolicy)
- }
- if *cb.TargetOriginId != "myS3Origin" {
- t.Fatalf("Expected TargetOriginId to be myS3Origin, got %v", *cb.TargetOriginId)
- }
- if reflect.DeepEqual(cb.ForwardedValues.Headers.Items, expandStringList(headersConf())) != true {
- t.Fatalf("Expected Items to be %v, got %v", headersConf(), cb.ForwardedValues.Headers.Items)
- }
- if *cb.MinTTL != 86400 {
- t.Fatalf("Expected MinTTL to be 86400, got %v", *cb.MinTTL)
- }
- if reflect.DeepEqual(cb.TrustedSigners.Items, expandStringList(trustedSignersConf())) != true {
- t.Fatalf("Expected TrustedSigners.Items to be %v, got %v", trustedSignersConf(), cb.TrustedSigners.Items)
- }
- if *cb.MaxTTL != 365000000 {
- t.Fatalf("Expected MaxTTL to be 365000000, got %v", *cb.MaxTTL)
- }
- if *cb.SmoothStreaming != false {
- t.Fatalf("Expected SmoothStreaming to be false, got %v", *cb.SmoothStreaming)
- }
- if *cb.DefaultTTL != 86400 {
- t.Fatalf("Expected DefaultTTL to be 86400, got %v", *cb.DefaultTTL)
- }
- if *cb.LambdaFunctionAssociations.Quantity != 2 {
- t.Fatalf("Expected LambdaFunctionAssociations to be 2, got %v", *cb.LambdaFunctionAssociations.Quantity)
- }
- if reflect.DeepEqual(cb.AllowedMethods.Items, expandStringList(allowedMethodsConf())) != true {
- t.Fatalf("Expected AllowedMethods.Items to be %v, got %v", allowedMethodsConf(), cb.AllowedMethods.Items)
- }
- if reflect.DeepEqual(cb.AllowedMethods.CachedMethods.Items, expandStringList(cachedMethodsConf())) != true {
- t.Fatalf("Expected AllowedMethods.CachedMethods.Items to be %v, got %v", cachedMethodsConf(), cb.AllowedMethods.CachedMethods.Items)
- }
- if *cb.PathPattern != "/path1" {
- t.Fatalf("Expected PathPattern to be /path1, got %v", *cb.PathPattern)
- }
-}
-
-func TestCloudFrontStructure_flattenCacheBehavior(t *testing.T) {
- in := cacheBehaviorConf1()
- cb := expandCacheBehavior(in)
- out := flattenCacheBehavior(cb)
- var diff *schema.Set
- if out["compress"] != true {
- t.Fatalf("Expected out[compress] to be true, got %v", out["compress"])
- }
- if out["viewer_protocol_policy"] != "allow-all" {
- t.Fatalf("Expected out[viewer_protocol_policy] to be allow-all, got %v", out["viewer_protocol_policy"])
- }
- if out["target_origin_id"] != "myS3Origin" {
- t.Fatalf("Expected out[target_origin_id] to be myS3Origin, got %v", out["target_origin_id"])
- }
-
- var outSet, ok = out["lambda_function_association"].(*schema.Set)
- if !ok {
- t.Fatalf("out['lambda_function_association'] is not a slice as expected: %#v", out["lambda_function_association"])
- }
-
- inSet, ok := in["lambda_function_association"].(*schema.Set)
- if !ok {
- t.Fatalf("in['lambda_function_association'] is not a set as expected: %#v", in["lambda_function_association"])
- }
-
- if !inSet.Equal(outSet) {
- t.Fatalf("in / out sets are not equal, in: \n%#v\n\nout: \n%#v\n", inSet, outSet)
- }
-
- diff = out["forwarded_values"].(*schema.Set).Difference(in["forwarded_values"].(*schema.Set))
- if len(diff.List()) > 0 {
- t.Fatalf("Expected out[forwarded_values] to be %v, got %v, diff: %v", out["forwarded_values"], in["forwarded_values"], diff)
- }
- if out["min_ttl"] != int(86400) {
- t.Fatalf("Expected out[min_ttl] to be 86400 (int), got %v", out["forwarded_values"])
- }
- if reflect.DeepEqual(out["trusted_signers"], in["trusted_signers"]) != true {
- t.Fatalf("Expected out[trusted_signers] to be %v, got %v", in["trusted_signers"], out["trusted_signers"])
- }
- if out["max_ttl"] != int(365000000) {
- t.Fatalf("Expected out[max_ttl] to be 365000000 (int), got %v", out["max_ttl"])
- }
- if out["smooth_streaming"] != false {
- t.Fatalf("Expected out[smooth_streaming] to be false, got %v", out["smooth_streaming"])
- }
- if out["default_ttl"] != int(86400) {
- t.Fatalf("Expected out[default_ttl] to be 86400 (int), got %v", out["default_ttl"])
- }
- if reflect.DeepEqual(out["allowed_methods"], in["allowed_methods"]) != true {
- t.Fatalf("Expected out[allowed_methods] to be %v, got %v", in["allowed_methods"], out["allowed_methods"])
- }
- if reflect.DeepEqual(out["cached_methods"], in["cached_methods"]) != true {
- t.Fatalf("Expected out[cached_methods] to be %v, got %v", in["cached_methods"], out["cached_methods"])
- }
- if out["path_pattern"] != "/path1" {
- t.Fatalf("Expected out[path_pattern] to be /path1, got %v", out["path_pattern"])
- }
-}
-
-func TestCloudFrontStructure_expandCacheBehaviors(t *testing.T) {
- data := cacheBehaviorsConf()
- cbs := expandCacheBehaviors(data)
- if *cbs.Quantity != 2 {
- t.Fatalf("Expected Quantity to be 2, got %v", *cbs.Quantity)
- }
- if *cbs.Items[0].TargetOriginId != "myS3Origin" {
- t.Fatalf("Expected first Item's TargetOriginId to be myS3Origin, got %v", *cbs.Items[0].TargetOriginId)
- }
-}
-
-func TestCloudFrontStructure_flattenCacheBehaviors(t *testing.T) {
- in := cacheBehaviorsConf()
- cbs := expandCacheBehaviors(in)
- out := flattenCacheBehaviors(cbs)
- diff := in.Difference(out)
-
- if len(diff.List()) > 0 {
- t.Fatalf("Expected out to be %v, got %v, diff: %v", in, out, diff)
- }
-}
-
-func TestCloudFrontStructure_expandTrustedSigners(t *testing.T) {
- data := trustedSignersConf()
- ts := expandTrustedSigners(data)
- if *ts.Quantity != 2 {
- t.Fatalf("Expected Quantity to be 2, got %v", *ts.Quantity)
- }
- if *ts.Enabled != true {
- t.Fatalf("Expected Enabled to be true, got %v", *ts.Enabled)
- }
- if reflect.DeepEqual(ts.Items, expandStringList(data)) != true {
- t.Fatalf("Expected Items to be %v, got %v", data, ts.Items)
- }
-}
-
-func TestCloudFrontStructure_flattenTrustedSigners(t *testing.T) {
- in := trustedSignersConf()
- ts := expandTrustedSigners(in)
- out := flattenTrustedSigners(ts)
-
- if reflect.DeepEqual(in, out) != true {
- t.Fatalf("Expected out to be %v, got %v", in, out)
- }
-}
-
-func TestCloudFrontStructure_expandTrustedSigners_empty(t *testing.T) {
- data := []interface{}{}
- ts := expandTrustedSigners(data)
- if *ts.Quantity != 0 {
- t.Fatalf("Expected Quantity to be 0, got %v", *ts.Quantity)
- }
- if *ts.Enabled != false {
- t.Fatalf("Expected Enabled to be true, got %v", *ts.Enabled)
- }
- if ts.Items != nil {
- t.Fatalf("Expected Items to be nil, got %v", ts.Items)
- }
-}
-
-func TestCloudFrontStructure_expandLambdaFunctionAssociations(t *testing.T) {
- data := lambdaFunctionAssociationsConf()
- lfa := expandLambdaFunctionAssociations(data.List())
- if *lfa.Quantity != 2 {
- t.Fatalf("Expected Quantity to be 2, got %v", *lfa.Quantity)
- }
- if len(lfa.Items) != 2 {
- t.Fatalf("Expected Items to be len 2, got %v", len(lfa.Items))
- }
- if et := "viewer-request"; *lfa.Items[0].EventType != et {
- t.Fatalf("Expected first Item's EventType to be %q, got %q", et, *lfa.Items[0].EventType)
- }
- if et := "origin-response"; *lfa.Items[1].EventType != et {
- t.Fatalf("Expected second Item's EventType to be %q, got %q", et, *lfa.Items[1].EventType)
- }
-}
-
-func TestCloudFrontStructure_flattenlambdaFunctionAssociations(t *testing.T) {
- in := lambdaFunctionAssociationsConf()
- lfa := expandLambdaFunctionAssociations(in.List())
- out := flattenLambdaFunctionAssociations(lfa)
-
- if reflect.DeepEqual(in.List(), out.List()) != true {
- t.Fatalf("Expected out to be %v, got %v", in, out)
- }
-}
-
-func TestCloudFrontStructure_expandlambdaFunctionAssociations_empty(t *testing.T) {
- data := new(schema.Set)
- lfa := expandLambdaFunctionAssociations(data.List())
- if *lfa.Quantity != 0 {
- t.Fatalf("Expected Quantity to be 0, got %v", *lfa.Quantity)
- }
- if len(lfa.Items) != 0 {
- t.Fatalf("Expected Items to be len 0, got %v", len(lfa.Items))
- }
- if reflect.DeepEqual(lfa.Items, []*cloudfront.LambdaFunctionAssociation{}) != true {
- t.Fatalf("Expected Items to be empty, got %v", lfa.Items)
- }
-}
-
-func TestCloudFrontStructure_expandForwardedValues(t *testing.T) {
- data := forwardedValuesConf()
- fv := expandForwardedValues(data)
- if *fv.QueryString != true {
- t.Fatalf("Expected QueryString to be true, got %v", *fv.QueryString)
- }
- if reflect.DeepEqual(fv.Cookies.WhitelistedNames.Items, expandStringList(cookieNamesConf())) != true {
- t.Fatalf("Expected Cookies.WhitelistedNames.Items to be %v, got %v", cookieNamesConf(), fv.Cookies.WhitelistedNames.Items)
- }
- if reflect.DeepEqual(fv.Headers.Items, expandStringList(headersConf())) != true {
- t.Fatalf("Expected Headers.Items to be %v, got %v", headersConf(), fv.Headers.Items)
- }
-}
-
-func TestCloudFrontStructure_flattenForwardedValues(t *testing.T) {
- in := forwardedValuesConf()
- fv := expandForwardedValues(in)
- out := flattenForwardedValues(fv)
-
- if out["query_string"] != true {
- t.Fatalf("Expected out[query_string] to be true, got %v", out["query_string"])
- }
- if out["cookies"].(*schema.Set).Equal(in["cookies"].(*schema.Set)) != true {
- t.Fatalf("Expected out[cookies] to be %v, got %v", in["cookies"], out["cookies"])
- }
- if reflect.DeepEqual(out["headers"], in["headers"]) != true {
- t.Fatalf("Expected out[headers] to be %v, got %v", in["headers"], out["headers"])
- }
-}
-
-func TestCloudFrontStructure_expandHeaders(t *testing.T) {
- data := headersConf()
- h := expandHeaders(data)
- if *h.Quantity != 2 {
- t.Fatalf("Expected Quantity to be 2, got %v", *h.Quantity)
- }
- if reflect.DeepEqual(h.Items, expandStringList(data)) != true {
- t.Fatalf("Expected Items to be %v, got %v", data, h.Items)
- }
-}
-
-func TestCloudFrontStructure_flattenHeaders(t *testing.T) {
- in := headersConf()
- h := expandHeaders(in)
- out := flattenHeaders(h)
-
- if reflect.DeepEqual(in, out) != true {
- t.Fatalf("Expected out to be %v, got %v", in, out)
- }
-}
-
-func TestCloudFrontStructure_expandQueryStringCacheKeys(t *testing.T) {
- data := queryStringCacheKeysConf()
- k := expandQueryStringCacheKeys(data)
- if *k.Quantity != 2 {
- t.Fatalf("Expected Quantity to be 2, got %v", *k.Quantity)
- }
- if reflect.DeepEqual(k.Items, expandStringList(data)) != true {
- t.Fatalf("Expected Items to be %v, got %v", data, k.Items)
- }
-}
-
-func TestCloudFrontStructure_flattenQueryStringCacheKeys(t *testing.T) {
- in := queryStringCacheKeysConf()
- k := expandQueryStringCacheKeys(in)
- out := flattenQueryStringCacheKeys(k)
-
- if reflect.DeepEqual(in, out) != true {
- t.Fatalf("Expected out to be %v, got %v", in, out)
- }
-}
-
-func TestCloudFrontStructure_expandCookiePreference(t *testing.T) {
- data := cookiePreferenceConf()
- cp := expandCookiePreference(data)
- if *cp.Forward != "whitelist" {
- t.Fatalf("Expected Forward to be whitelist, got %v", *cp.Forward)
- }
- if reflect.DeepEqual(cp.WhitelistedNames.Items, expandStringList(cookieNamesConf())) != true {
- t.Fatalf("Expected WhitelistedNames.Items to be %v, got %v", cookieNamesConf(), cp.WhitelistedNames.Items)
- }
-}
-
-func TestCloudFrontStructure_flattenCookiePreference(t *testing.T) {
- in := cookiePreferenceConf()
- cp := expandCookiePreference(in)
- out := flattenCookiePreference(cp)
-
- if reflect.DeepEqual(in, out) != true {
- t.Fatalf("Expected out to be %v, got %v", in, out)
- }
-}
-
-func TestCloudFrontStructure_expandCookieNames(t *testing.T) {
- data := cookieNamesConf()
- cn := expandCookieNames(data)
- if *cn.Quantity != 2 {
- t.Fatalf("Expected Quantity to be 2, got %v", *cn.Quantity)
- }
- if reflect.DeepEqual(cn.Items, expandStringList(data)) != true {
- t.Fatalf("Expected Items to be %v, got %v", data, cn.Items)
- }
-}
-
-func TestCloudFrontStructure_flattenCookieNames(t *testing.T) {
- in := cookieNamesConf()
- cn := expandCookieNames(in)
- out := flattenCookieNames(cn)
-
- if reflect.DeepEqual(in, out) != true {
- t.Fatalf("Expected out to be %v, got %v", in, out)
- }
-}
-
-func TestCloudFrontStructure_expandAllowedMethods(t *testing.T) {
- data := allowedMethodsConf()
- am := expandAllowedMethods(data)
- if *am.Quantity != 7 {
- t.Fatalf("Expected Quantity to be 7, got %v", *am.Quantity)
- }
- if reflect.DeepEqual(am.Items, expandStringList(data)) != true {
- t.Fatalf("Expected Items to be %v, got %v", data, am.Items)
- }
-}
-
-func TestCloudFrontStructure_flattenAllowedMethods(t *testing.T) {
- in := allowedMethodsConf()
- am := expandAllowedMethods(in)
- out := flattenAllowedMethods(am)
-
- if reflect.DeepEqual(in, out) != true {
- t.Fatalf("Expected out to be %v, got %v", in, out)
- }
-}
-
-func TestCloudFrontStructure_expandCachedMethods(t *testing.T) {
- data := cachedMethodsConf()
- cm := expandCachedMethods(data)
- if *cm.Quantity != 3 {
- t.Fatalf("Expected Quantity to be 3, got %v", *cm.Quantity)
- }
- if reflect.DeepEqual(cm.Items, expandStringList(data)) != true {
- t.Fatalf("Expected Items to be %v, got %v", data, cm.Items)
- }
-}
-
-func TestCloudFrontStructure_flattenCachedMethods(t *testing.T) {
- in := cachedMethodsConf()
- cm := expandCachedMethods(in)
- out := flattenCachedMethods(cm)
-
- if reflect.DeepEqual(in, out) != true {
- t.Fatalf("Expected out to be %v, got %v", in, out)
- }
-}
-
-func TestCloudFrontStructure_expandOrigins(t *testing.T) {
- data := multiOriginConf()
- origins := expandOrigins(data)
- if *origins.Quantity != 2 {
- t.Fatalf("Expected Quantity to be 2, got %v", *origins.Quantity)
- }
- if *origins.Items[0].OriginPath != "/" {
- t.Fatalf("Expected first Item's OriginPath to be /, got %v", *origins.Items[0].OriginPath)
- }
-}
-
-func TestCloudFrontStructure_flattenOrigins(t *testing.T) {
- in := multiOriginConf()
- origins := expandOrigins(in)
- out := flattenOrigins(origins)
- diff := in.Difference(out)
-
- if len(diff.List()) > 0 {
- t.Fatalf("Expected out to be %v, got %v, diff: %v", in, out, diff)
- }
-}
-
-func TestCloudFrontStructure_expandOrigin(t *testing.T) {
- data := originWithCustomConf()
- or := expandOrigin(data)
- if *or.Id != "CustomOrigin" {
- t.Fatalf("Expected Id to be CustomOrigin, got %v", *or.Id)
- }
- if *or.DomainName != "www.example.com" {
- t.Fatalf("Expected DomainName to be www.example.com, got %v", *or.DomainName)
- }
- if *or.OriginPath != "/" {
- t.Fatalf("Expected OriginPath to be /, got %v", *or.OriginPath)
- }
- if *or.CustomOriginConfig.OriginProtocolPolicy != "http-only" {
- t.Fatalf("Expected CustomOriginConfig.OriginProtocolPolicy to be http-only, got %v", *or.CustomOriginConfig.OriginProtocolPolicy)
- }
- if *or.CustomHeaders.Items[0].HeaderValue != "samplevalue" {
- t.Fatalf("Expected CustomHeaders.Items[0].HeaderValue to be samplevalue, got %v", *or.CustomHeaders.Items[0].HeaderValue)
- }
-}
-
-func TestCloudFrontStructure_flattenOrigin(t *testing.T) {
- in := originWithCustomConf()
- or := expandOrigin(in)
- out := flattenOrigin(or)
-
- if out["origin_id"] != "CustomOrigin" {
- t.Fatalf("Expected out[origin_id] to be CustomOrigin, got %v", out["origin_id"])
- }
- if out["domain_name"] != "www.example.com" {
- t.Fatalf("Expected out[domain_name] to be www.example.com, got %v", out["domain_name"])
- }
- if out["origin_path"] != "/" {
- t.Fatalf("Expected out[origin_path] to be /, got %v", out["origin_path"])
- }
- if out["custom_origin_config"].(*schema.Set).Equal(in["custom_origin_config"].(*schema.Set)) != true {
- t.Fatalf("Expected out[custom_origin_config] to be %v, got %v", in["custom_origin_config"], out["custom_origin_config"])
- }
-}
-
-func TestCloudFrontStructure_expandCustomHeaders(t *testing.T) {
- in := originCustomHeadersConf()
- chs := expandCustomHeaders(in)
- if *chs.Quantity != 2 {
- t.Fatalf("Expected Quantity to be 2, got %v", *chs.Quantity)
- }
- if *chs.Items[0].HeaderValue != "samplevalue" {
- t.Fatalf("Expected first Item's HeaderValue to be samplevalue, got %v", *chs.Items[0].HeaderValue)
- }
-}
-
-func TestCloudFrontStructure_flattenCustomHeaders(t *testing.T) {
- in := originCustomHeadersConf()
- chs := expandCustomHeaders(in)
- out := flattenCustomHeaders(chs)
- diff := in.Difference(out)
-
- if len(diff.List()) > 0 {
- t.Fatalf("Expected out to be %v, got %v, diff: %v", in, out, diff)
- }
-}
-
-func TestCloudFrontStructure_flattenOriginCustomHeader(t *testing.T) {
- in := originCustomHeaderConf1()
- och := expandOriginCustomHeader(in)
- out := flattenOriginCustomHeader(och)
-
- if out["name"] != "X-Custom-Header1" {
- t.Fatalf("Expected out[name] to be X-Custom-Header1, got %v", out["name"])
- }
- if out["value"] != "samplevalue" {
- t.Fatalf("Expected out[value] to be samplevalue, got %v", out["value"])
- }
-}
-
-func TestCloudFrontStructure_expandOriginCustomHeader(t *testing.T) {
- in := originCustomHeaderConf1()
- och := expandOriginCustomHeader(in)
-
- if *och.HeaderName != "X-Custom-Header1" {
- t.Fatalf("Expected HeaderName to be X-Custom-Header1, got %v", *och.HeaderName)
- }
- if *och.HeaderValue != "samplevalue" {
- t.Fatalf("Expected HeaderValue to be samplevalue, got %v", *och.HeaderValue)
- }
-}
-
-func TestCloudFrontStructure_expandCustomOriginConfig(t *testing.T) {
- data := customOriginConf()
- co := expandCustomOriginConfig(data)
- if *co.OriginProtocolPolicy != "http-only" {
- t.Fatalf("Expected OriginProtocolPolicy to be http-only, got %v", *co.OriginProtocolPolicy)
- }
- if *co.HTTPPort != 80 {
- t.Fatalf("Expected HTTPPort to be 80, got %v", *co.HTTPPort)
- }
- if *co.HTTPSPort != 443 {
- t.Fatalf("Expected HTTPSPort to be 443, got %v", *co.HTTPSPort)
- }
- if *co.OriginReadTimeout != 30 {
- t.Fatalf("Expected Origin Read Timeout to be 30, got %v", *co.OriginReadTimeout)
- }
- if *co.OriginKeepaliveTimeout != 5 {
- t.Fatalf("Expected Origin Keepalive Timeout to be 5, got %v", *co.OriginKeepaliveTimeout)
- }
-}
-
-func TestCloudFrontStructure_flattenCustomOriginConfig(t *testing.T) {
- in := customOriginConf()
- co := expandCustomOriginConfig(in)
- out := flattenCustomOriginConfig(co)
-
- if reflect.DeepEqual(in, out) != true {
- t.Fatalf("Expected out to be %v, got %v", in, out)
- }
-}
-
-func TestCloudFrontStructure_expandCustomOriginConfigSSL(t *testing.T) {
- in := customOriginSslProtocolsConf()
- ocs := expandCustomOriginConfigSSL(in)
- if *ocs.Quantity != 4 {
- t.Fatalf("Expected Quantity to be 4, got %v", *ocs.Quantity)
- }
- if *ocs.Items[0] != "SSLv3" {
- t.Fatalf("Expected first Item to be SSLv3, got %v", *ocs.Items[0])
- }
-}
-
-func TestCloudFrontStructure_flattenCustomOriginConfigSSL(t *testing.T) {
- in := customOriginSslProtocolsConf()
- ocs := expandCustomOriginConfigSSL(in)
- out := flattenCustomOriginConfigSSL(ocs)
-
- if reflect.DeepEqual(in, out) != true {
- t.Fatalf("Expected out to be %v, got %v", in, out)
- }
-}
-
-func TestCloudFrontStructure_expandS3OriginConfig(t *testing.T) {
- data := s3OriginConf()
- s3o := expandS3OriginConfig(data)
- if *s3o.OriginAccessIdentity != "origin-access-identity/cloudfront/E127EXAMPLE51Z" {
- t.Fatalf("Expected OriginAccessIdentity to be origin-access-identity/cloudfront/E127EXAMPLE51Z, got %v", *s3o.OriginAccessIdentity)
- }
-}
-
-func TestCloudFrontStructure_flattenS3OriginConfig(t *testing.T) {
- in := s3OriginConf()
- s3o := expandS3OriginConfig(in)
- out := flattenS3OriginConfig(s3o)
-
- if reflect.DeepEqual(in, out) != true {
- t.Fatalf("Expected out to be %v, got %v", in, out)
- }
-}
-
-func TestCloudFrontStructure_expandCustomErrorResponses(t *testing.T) {
- data := customErrorResponsesConfSet()
- ers := expandCustomErrorResponses(data)
- if *ers.Quantity != 2 {
- t.Fatalf("Expected Quantity to be 2, got %v", *ers.Quantity)
- }
- if *ers.Items[0].ResponsePagePath != "/error-pages/404.html" {
- t.Fatalf("Expected ResponsePagePath in first Item to be /error-pages/404.html, got %v", *ers.Items[0].ResponsePagePath)
- }
-}
-
-func TestCloudFrontStructure_flattenCustomErrorResponses(t *testing.T) {
- in := customErrorResponsesConfSet()
- ers := expandCustomErrorResponses(in)
- out := flattenCustomErrorResponses(ers)
-
- if in.Equal(out) != true {
- t.Fatalf("Expected out to be %v, got %v", in, out)
- }
-}
-
-func TestCloudFrontStructure_expandCustomErrorResponse(t *testing.T) {
- data := customErrorResponsesConfFirst()
- er := expandCustomErrorResponse(data)
- if *er.ErrorCode != 404 {
- t.Fatalf("Expected ErrorCode to be 404, got %v", *er.ErrorCode)
- }
- if *er.ErrorCachingMinTTL != 30 {
- t.Fatalf("Expected ErrorCachingMinTTL to be 30, got %v", *er.ErrorCachingMinTTL)
- }
- if *er.ResponseCode != "200" {
- t.Fatalf("Expected ResponseCode to be 200 (as string), got %v", *er.ResponseCode)
- }
- if *er.ResponsePagePath != "/error-pages/404.html" {
- t.Fatalf("Expected ResponsePagePath to be /error-pages/404.html, got %v", *er.ResponsePagePath)
- }
-}
-
-func TestCloudFrontStructure_expandCustomErrorResponse_emptyResponseCode(t *testing.T) {
- data := customErrorResponseConfNoResponseCode()
- er := expandCustomErrorResponse(data)
- if *er.ResponseCode != "" {
- t.Fatalf("Expected ResponseCode to be empty string, got %v", *er.ResponseCode)
- }
- if *er.ResponsePagePath != "" {
- t.Fatalf("Expected ResponsePagePath to be empty string, got %v", *er.ResponsePagePath)
- }
-}
-
-func TestCloudFrontStructure_flattenCustomErrorResponse(t *testing.T) {
- in := customErrorResponsesConfFirst()
- er := expandCustomErrorResponse(in)
- out := flattenCustomErrorResponse(er)
-
- if reflect.DeepEqual(in, out) != true {
- t.Fatalf("Expected out to be %v, got %v", in, out)
- }
-}
-
-func TestCloudFrontStructure_expandLoggingConfig(t *testing.T) {
- data := loggingConfigConf()
-
- lc := expandLoggingConfig(data)
- if *lc.Enabled != true {
- t.Fatalf("Expected Enabled to be true, got %v", *lc.Enabled)
- }
- if *lc.Prefix != "myprefix" {
- t.Fatalf("Expected Prefix to be myprefix, got %v", *lc.Prefix)
- }
- if *lc.Bucket != "mylogs.s3.amazonaws.com" {
- t.Fatalf("Expected Bucket to be mylogs.s3.amazonaws.com, got %v", *lc.Bucket)
- }
- if *lc.IncludeCookies != false {
- t.Fatalf("Expected IncludeCookies to be false, got %v", *lc.IncludeCookies)
- }
-}
-
-func TestCloudFrontStructure_expandLoggingConfig_nilValue(t *testing.T) {
- lc := expandLoggingConfig(nil)
- if *lc.Enabled != false {
- t.Fatalf("Expected Enabled to be false, got %v", *lc.Enabled)
- }
- if *lc.Prefix != "" {
- t.Fatalf("Expected Prefix to be blank, got %v", *lc.Prefix)
- }
- if *lc.Bucket != "" {
- t.Fatalf("Expected Bucket to be blank, got %v", *lc.Bucket)
- }
- if *lc.IncludeCookies != false {
- t.Fatalf("Expected IncludeCookies to be false, got %v", *lc.IncludeCookies)
- }
-}
-
-func TestCloudFrontStructure_flattenLoggingConfig(t *testing.T) {
- in := loggingConfigConf()
- lc := expandLoggingConfig(in)
- out := flattenLoggingConfig(lc)
- diff := schema.NewSet(loggingConfigHash, []interface{}{in}).Difference(out)
-
- if len(diff.List()) > 0 {
- t.Fatalf("Expected out to be %v, got %v, diff: %v", in, out, diff)
- }
-}
-
-func TestCloudFrontStructure_expandAliases(t *testing.T) {
- data := aliasesConf()
- a := expandAliases(data)
- if *a.Quantity != 2 {
- t.Fatalf("Expected Quantity to be 2, got %v", *a.Quantity)
- }
- if reflect.DeepEqual(a.Items, expandStringList(data.List())) != true {
- t.Fatalf("Expected Items to be [example.com www.example.com], got %v", a.Items)
- }
-}
-
-func TestCloudFrontStructure_flattenAliases(t *testing.T) {
- in := aliasesConf()
- a := expandAliases(in)
- out := flattenAliases(a)
- diff := in.Difference(out)
-
- if len(diff.List()) > 0 {
- t.Fatalf("Expected out to be %v, got %v, diff: %v", in, out, diff)
- }
-}
-
-func TestCloudFrontStructure_expandRestrictions(t *testing.T) {
- data := geoRestrictionsConf()
- r := expandRestrictions(data)
- if *r.GeoRestriction.RestrictionType != "whitelist" {
- t.Fatalf("Expected GeoRestriction.RestrictionType to be whitelist, got %v", *r.GeoRestriction.RestrictionType)
- }
-}
-
-func TestCloudFrontStructure_flattenRestrictions(t *testing.T) {
- in := geoRestrictionsConf()
- r := expandRestrictions(in)
- out := flattenRestrictions(r)
- diff := schema.NewSet(restrictionsHash, []interface{}{in}).Difference(out)
-
- if len(diff.List()) > 0 {
- t.Fatalf("Expected out to be %v, got %v, diff: %v", in, out, diff)
- }
-}
-
-func TestCloudFrontStructure_expandGeoRestriction_whitelist(t *testing.T) {
- data := geoRestrictionWhitelistConf()
- gr := expandGeoRestriction(data)
- if *gr.RestrictionType != "whitelist" {
- t.Fatalf("Expected RestrictionType to be whitelist, got %v", *gr.RestrictionType)
- }
- if *gr.Quantity != 3 {
- t.Fatalf("Expected Quantity to be 3, got %v", *gr.Quantity)
- }
- if reflect.DeepEqual(gr.Items, aws.StringSlice([]string{"CA", "GB", "US"})) != true {
- t.Fatalf("Expected Items be [CA, GB, US], got %v", gr.Items)
- }
-}
-
-func TestCloudFrontStructure_flattenGeoRestriction_whitelist(t *testing.T) {
- in := geoRestrictionWhitelistConf()
- gr := expandGeoRestriction(in)
- out := flattenGeoRestriction(gr)
-
- if reflect.DeepEqual(in, out) != true {
- t.Fatalf("Expected out to be %v, got %v", in, out)
- }
-}
-
-func TestCloudFrontStructure_expandGeoRestriction_no_items(t *testing.T) {
- data := geoRestrictionConfNoItems()
- gr := expandGeoRestriction(data)
- if *gr.RestrictionType != "none" {
- t.Fatalf("Expected RestrictionType to be none, got %v", *gr.RestrictionType)
- }
- if *gr.Quantity != 0 {
- t.Fatalf("Expected Quantity to be 0, got %v", *gr.Quantity)
- }
- if gr.Items != nil {
- t.Fatalf("Expected Items to not be set, got %v", gr.Items)
- }
-}
-
-func TestCloudFrontStructure_flattenGeoRestriction_no_items(t *testing.T) {
- in := geoRestrictionConfNoItems()
- gr := expandGeoRestriction(in)
- out := flattenGeoRestriction(gr)
-
- if reflect.DeepEqual(in, out) != true {
- t.Fatalf("Expected out to be %v, got %v", in, out)
- }
-}
-
-func TestCloudFrontStructure_expandViewerCertificate_cloudfront_default_certificate(t *testing.T) {
- data := viewerCertificateConfSetCloudFrontDefault()
- vc := expandViewerCertificate(data)
- if vc.ACMCertificateArn != nil {
- t.Fatalf("Expected ACMCertificateArn to be unset, got %v", *vc.ACMCertificateArn)
- }
- if *vc.CloudFrontDefaultCertificate != true {
- t.Fatalf("Expected CloudFrontDefaultCertificate to be true, got %v", *vc.CloudFrontDefaultCertificate)
- }
- if vc.IAMCertificateId != nil {
- t.Fatalf("Expected IAMCertificateId to not be set, got %v", *vc.IAMCertificateId)
- }
- if vc.SSLSupportMethod != nil {
- t.Fatalf("Expected IAMCertificateId to not be set, got %v", *vc.SSLSupportMethod)
- }
- if vc.MinimumProtocolVersion != nil {
- t.Fatalf("Expected IAMCertificateId to not be set, got %v", *vc.MinimumProtocolVersion)
- }
-}
-
-func TestCloudFrontStructure_flattenViewerCertificate_cloudfront_default_certificate(t *testing.T) {
- in := viewerCertificateConfSetCloudFrontDefault()
- vc := expandViewerCertificate(in)
- out := flattenViewerCertificate(vc)
- diff := schema.NewSet(viewerCertificateHash, []interface{}{in}).Difference(out)
-
- if len(diff.List()) > 0 {
- t.Fatalf("Expected out to be %v, got %v, diff: %v", in, out, diff)
- }
-}
-
-func TestCloudFrontStructure_expandViewerCertificate_iam_certificate_id(t *testing.T) {
- data := viewerCertificateConfSetIAM()
- vc := expandViewerCertificate(data)
- if vc.ACMCertificateArn != nil {
- t.Fatalf("Expected ACMCertificateArn to be unset, got %v", *vc.ACMCertificateArn)
- }
- if vc.CloudFrontDefaultCertificate != nil {
- t.Fatalf("Expected CloudFrontDefaultCertificate to be unset, got %v", *vc.CloudFrontDefaultCertificate)
- }
- if *vc.IAMCertificateId != "iamcert-01234567" {
- t.Fatalf("Expected IAMCertificateId to be iamcert-01234567, got %v", *vc.IAMCertificateId)
- }
- if *vc.SSLSupportMethod != "vip" {
- t.Fatalf("Expected IAMCertificateId to be vip, got %v", *vc.SSLSupportMethod)
- }
- if *vc.MinimumProtocolVersion != "TLSv1" {
- t.Fatalf("Expected IAMCertificateId to be TLSv1, got %v", *vc.MinimumProtocolVersion)
- }
-}
-
-func TestCloudFrontStructure_expandViewerCertificate_acm_certificate_arn(t *testing.T) {
- data := viewerCertificateConfSetACM()
- vc := expandViewerCertificate(data)
- if *vc.ACMCertificateArn != "arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012" {
- t.Fatalf("Expected ACMCertificateArn to be arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012, got %v", *vc.ACMCertificateArn)
- }
- if vc.CloudFrontDefaultCertificate != nil {
- t.Fatalf("Expected CloudFrontDefaultCertificate to be unset, got %v", *vc.CloudFrontDefaultCertificate)
- }
- if vc.IAMCertificateId != nil {
- t.Fatalf("Expected IAMCertificateId to be unset, got %v", *vc.IAMCertificateId)
- }
- if *vc.SSLSupportMethod != "sni-only" {
- t.Fatalf("Expected IAMCertificateId to be sni-only, got %v", *vc.SSLSupportMethod)
- }
- if *vc.MinimumProtocolVersion != "TLSv1" {
- t.Fatalf("Expected IAMCertificateId to be TLSv1, got %v", *vc.MinimumProtocolVersion)
- }
-}
-
-func TestCloudFrontStructure_falttenViewerCertificate_iam_certificate_id(t *testing.T) {
- in := viewerCertificateConfSetIAM()
- vc := expandViewerCertificate(in)
- out := flattenViewerCertificate(vc)
- diff := schema.NewSet(viewerCertificateHash, []interface{}{in}).Difference(out)
-
- if len(diff.List()) > 0 {
- t.Fatalf("Expected out to be %v, got %v, diff: %v", in, out, diff)
- }
-}
-
-func TestCloudFrontStructure_falttenViewerCertificate_acm_certificate_arn(t *testing.T) {
- in := viewerCertificateConfSetACM()
- vc := expandViewerCertificate(in)
- out := flattenViewerCertificate(vc)
- diff := schema.NewSet(viewerCertificateHash, []interface{}{in}).Difference(out)
-
- if len(diff.List()) > 0 {
- t.Fatalf("Expected out to be %v, got %v, diff: %v", in, out, diff)
- }
-}
-
-func TestCloudFrontStructure_viewerCertificateHash_IAM(t *testing.T) {
- in := viewerCertificateConfSetIAM()
- out := viewerCertificateHash(in)
- expected := 1157261784
-
- if expected != out {
- t.Fatalf("Expected %v, got %v", expected, out)
- }
-}
-
-func TestCloudFrontStructure_viewerCertificateHash_ACM(t *testing.T) {
- in := viewerCertificateConfSetACM()
- out := viewerCertificateHash(in)
- expected := 2883600425
-
- if expected != out {
- t.Fatalf("Expected %v, got %v", expected, out)
- }
-}
-
-func TestCloudFrontStructure_viewerCertificateHash_default(t *testing.T) {
- in := viewerCertificateConfSetCloudFrontDefault()
- out := viewerCertificateHash(in)
- expected := 69840937
-
- if expected != out {
- t.Fatalf("Expected %v, got %v", expected, out)
- }
-}
diff --git a/builtin/providers/aws/config.go b/builtin/providers/aws/config.go
deleted file mode 100644
index dd1149b91..000000000
--- a/builtin/providers/aws/config.go
+++ /dev/null
@@ -1,510 +0,0 @@
-package aws
-
-import (
- "crypto/tls"
- "errors"
- "fmt"
- "log"
- "net/http"
- "os"
- "strings"
- "time"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/aws/awserr"
- "github.com/aws/aws-sdk-go/aws/request"
- "github.com/aws/aws-sdk-go/aws/session"
- "github.com/aws/aws-sdk-go/service/acm"
- "github.com/aws/aws-sdk-go/service/apigateway"
- "github.com/aws/aws-sdk-go/service/applicationautoscaling"
- "github.com/aws/aws-sdk-go/service/autoscaling"
- "github.com/aws/aws-sdk-go/service/cloudformation"
- "github.com/aws/aws-sdk-go/service/cloudfront"
- "github.com/aws/aws-sdk-go/service/cloudtrail"
- "github.com/aws/aws-sdk-go/service/cloudwatch"
- "github.com/aws/aws-sdk-go/service/cloudwatchevents"
- "github.com/aws/aws-sdk-go/service/cloudwatchlogs"
- "github.com/aws/aws-sdk-go/service/codebuild"
- "github.com/aws/aws-sdk-go/service/codecommit"
- "github.com/aws/aws-sdk-go/service/codedeploy"
- "github.com/aws/aws-sdk-go/service/codepipeline"
- "github.com/aws/aws-sdk-go/service/cognitoidentity"
- "github.com/aws/aws-sdk-go/service/configservice"
- "github.com/aws/aws-sdk-go/service/databasemigrationservice"
- "github.com/aws/aws-sdk-go/service/devicefarm"
- "github.com/aws/aws-sdk-go/service/directoryservice"
- "github.com/aws/aws-sdk-go/service/dynamodb"
- "github.com/aws/aws-sdk-go/service/ec2"
- "github.com/aws/aws-sdk-go/service/ecr"
- "github.com/aws/aws-sdk-go/service/ecs"
- "github.com/aws/aws-sdk-go/service/efs"
- "github.com/aws/aws-sdk-go/service/elasticache"
- "github.com/aws/aws-sdk-go/service/elasticbeanstalk"
- elasticsearch "github.com/aws/aws-sdk-go/service/elasticsearchservice"
- "github.com/aws/aws-sdk-go/service/elastictranscoder"
- "github.com/aws/aws-sdk-go/service/elb"
- "github.com/aws/aws-sdk-go/service/elbv2"
- "github.com/aws/aws-sdk-go/service/emr"
- "github.com/aws/aws-sdk-go/service/firehose"
- "github.com/aws/aws-sdk-go/service/glacier"
- "github.com/aws/aws-sdk-go/service/iam"
- "github.com/aws/aws-sdk-go/service/inspector"
- "github.com/aws/aws-sdk-go/service/kinesis"
- "github.com/aws/aws-sdk-go/service/kms"
- "github.com/aws/aws-sdk-go/service/lambda"
- "github.com/aws/aws-sdk-go/service/lightsail"
- "github.com/aws/aws-sdk-go/service/opsworks"
- "github.com/aws/aws-sdk-go/service/rds"
- "github.com/aws/aws-sdk-go/service/redshift"
- "github.com/aws/aws-sdk-go/service/route53"
- "github.com/aws/aws-sdk-go/service/s3"
- "github.com/aws/aws-sdk-go/service/ses"
- "github.com/aws/aws-sdk-go/service/sfn"
- "github.com/aws/aws-sdk-go/service/simpledb"
- "github.com/aws/aws-sdk-go/service/sns"
- "github.com/aws/aws-sdk-go/service/sqs"
- "github.com/aws/aws-sdk-go/service/ssm"
- "github.com/aws/aws-sdk-go/service/sts"
- "github.com/aws/aws-sdk-go/service/waf"
- "github.com/aws/aws-sdk-go/service/wafregional"
- "github.com/davecgh/go-spew/spew"
- "github.com/hashicorp/errwrap"
- "github.com/hashicorp/go-cleanhttp"
- "github.com/hashicorp/terraform/helper/logging"
- "github.com/hashicorp/terraform/terraform"
-)
-
-type Config struct {
- AccessKey string
- SecretKey string
- CredsFilename string
- Profile string
- Token string
- Region string
- MaxRetries int
-
- AssumeRoleARN string
- AssumeRoleExternalID string
- AssumeRoleSessionName string
- AssumeRolePolicy string
-
- AllowedAccountIds []interface{}
- ForbiddenAccountIds []interface{}
-
- CloudFormationEndpoint string
- CloudWatchEndpoint string
- CloudWatchEventsEndpoint string
- CloudWatchLogsEndpoint string
- DynamoDBEndpoint string
- DeviceFarmEndpoint string
- Ec2Endpoint string
- ElbEndpoint string
- IamEndpoint string
- KinesisEndpoint string
- KmsEndpoint string
- RdsEndpoint string
- S3Endpoint string
- SnsEndpoint string
- SqsEndpoint string
- Insecure bool
-
- SkipCredsValidation bool
- SkipGetEC2Platforms bool
- SkipRegionValidation bool
- SkipRequestingAccountId bool
- SkipMetadataApiCheck bool
- S3ForcePathStyle bool
-}
-
-type AWSClient struct {
- cfconn *cloudformation.CloudFormation
- cloudfrontconn *cloudfront.CloudFront
- cloudtrailconn *cloudtrail.CloudTrail
- cloudwatchconn *cloudwatch.CloudWatch
- cloudwatchlogsconn *cloudwatchlogs.CloudWatchLogs
- cloudwatcheventsconn *cloudwatchevents.CloudWatchEvents
- cognitoconn *cognitoidentity.CognitoIdentity
- configconn *configservice.ConfigService
- devicefarmconn *devicefarm.DeviceFarm
- dmsconn *databasemigrationservice.DatabaseMigrationService
- dsconn *directoryservice.DirectoryService
- dynamodbconn *dynamodb.DynamoDB
- ec2conn *ec2.EC2
- ecrconn *ecr.ECR
- ecsconn *ecs.ECS
- efsconn *efs.EFS
- elbconn *elb.ELB
- elbv2conn *elbv2.ELBV2
- emrconn *emr.EMR
- esconn *elasticsearch.ElasticsearchService
- acmconn *acm.ACM
- apigateway *apigateway.APIGateway
- appautoscalingconn *applicationautoscaling.ApplicationAutoScaling
- autoscalingconn *autoscaling.AutoScaling
- s3conn *s3.S3
- sesConn *ses.SES
- simpledbconn *simpledb.SimpleDB
- sqsconn *sqs.SQS
- snsconn *sns.SNS
- stsconn *sts.STS
- redshiftconn *redshift.Redshift
- r53conn *route53.Route53
- partition string
- accountid string
- supportedplatforms []string
- region string
- rdsconn *rds.RDS
- iamconn *iam.IAM
- kinesisconn *kinesis.Kinesis
- kmsconn *kms.KMS
- firehoseconn *firehose.Firehose
- inspectorconn *inspector.Inspector
- elasticacheconn *elasticache.ElastiCache
- elasticbeanstalkconn *elasticbeanstalk.ElasticBeanstalk
- elastictranscoderconn *elastictranscoder.ElasticTranscoder
- lambdaconn *lambda.Lambda
- lightsailconn *lightsail.Lightsail
- opsworksconn *opsworks.OpsWorks
- glacierconn *glacier.Glacier
- codebuildconn *codebuild.CodeBuild
- codedeployconn *codedeploy.CodeDeploy
- codecommitconn *codecommit.CodeCommit
- codepipelineconn *codepipeline.CodePipeline
- sfnconn *sfn.SFN
- ssmconn *ssm.SSM
- wafconn *waf.WAF
- wafregionalconn *wafregional.WAFRegional
-}
-
-func (c *AWSClient) S3() *s3.S3 {
- return c.s3conn
-}
-
-func (c *AWSClient) DynamoDB() *dynamodb.DynamoDB {
- return c.dynamodbconn
-}
-
-func (c *AWSClient) IsGovCloud() bool {
- if c.region == "us-gov-west-1" {
- return true
- }
- return false
-}
-
-func (c *AWSClient) IsChinaCloud() bool {
- if c.region == "cn-north-1" {
- return true
- }
- return false
-}
-
-// Client configures and returns a fully initialized AWSClient
-func (c *Config) Client() (interface{}, error) {
- // Get the auth and region. This can fail if keys/regions were not
- // specified and we're attempting to use the environment.
- if c.SkipRegionValidation {
- log.Println("[INFO] Skipping region validation")
- } else {
- log.Println("[INFO] Building AWS region structure")
- err := c.ValidateRegion()
- if err != nil {
- return nil, err
- }
- }
-
- var client AWSClient
- // store AWS region in client struct, for region specific operations such as
- // bucket storage in S3
- client.region = c.Region
-
- log.Println("[INFO] Building AWS auth structure")
- creds, err := GetCredentials(c)
- if err != nil {
- return nil, err
- }
- // Call Get to check for credential provider. If nothing found, we'll get an
- // error, and we can present it nicely to the user
- 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),
- }
-
- if logging.IsDebugOrHigher() {
- awsConfig.LogLevel = aws.LogLevel(aws.LogDebugWithHTTPBody)
- awsConfig.Logger = awsLogger{}
- }
-
- if c.Insecure {
- transport := awsConfig.HTTPClient.Transport.(*http.Transport)
- transport.TLSClientConfig = &tls.Config{
- InsecureSkipVerify: true,
- }
- }
-
- // Set up base session
- sess, err := session.NewSession(awsConfig)
- if err != nil {
- return nil, errwrap.Wrapf("Error creating AWS session: {{err}}", err)
- }
-
- sess.Handlers.Build.PushBackNamed(addTerraformVersionToUserAgent)
-
- if extraDebug := os.Getenv("TERRAFORM_AWS_AUTHFAILURE_DEBUG"); extraDebug != "" {
- sess.Handlers.UnmarshalError.PushFrontNamed(debugAuthFailure)
- }
-
- // This restriction should only be used for Route53 sessions.
- // Other resources that have restrictions should allow the API to fail, rather
- // than Terraform abstracting the region for the user. This can lead to breaking
- // changes if that resource is ever opened up to more regions.
- r53Sess := sess.Copy(&aws.Config{Region: aws.String("us-east-1")})
-
- // Some services have user-configurable endpoints
- awsCfSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.CloudFormationEndpoint)})
- awsCwSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.CloudWatchEndpoint)})
- awsCweSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.CloudWatchEventsEndpoint)})
- awsCwlSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.CloudWatchLogsEndpoint)})
- awsDynamoSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.DynamoDBEndpoint)})
- awsEc2Sess := sess.Copy(&aws.Config{Endpoint: aws.String(c.Ec2Endpoint)})
- awsElbSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.ElbEndpoint)})
- awsIamSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.IamEndpoint)})
- awsKinesisSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.KinesisEndpoint)})
- awsKmsSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.KmsEndpoint)})
- awsRdsSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.RdsEndpoint)})
- awsS3Sess := sess.Copy(&aws.Config{Endpoint: aws.String(c.S3Endpoint)})
- awsSnsSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.SnsEndpoint)})
- awsSqsSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.SqsEndpoint)})
- awsDeviceFarmSess := sess.Copy(&aws.Config{Endpoint: aws.String(c.DeviceFarmEndpoint)})
-
- log.Println("[INFO] Initializing DeviceFarm SDK connection")
- client.devicefarmconn = devicefarm.New(awsDeviceFarmSess)
-
- // These two services need to be set up early so we can check on AccountID
- client.iamconn = iam.New(awsIamSess)
- client.stsconn = sts.New(sess)
-
- if !c.SkipCredsValidation {
- err = c.ValidateCredentials(client.stsconn)
- if err != nil {
- return nil, err
- }
- }
-
- if !c.SkipRequestingAccountId {
- partition, accountId, err := GetAccountInfo(client.iamconn, client.stsconn, cp.ProviderName)
- if err == nil {
- client.partition = partition
- client.accountid = accountId
- }
- }
-
- authErr := c.ValidateAccountId(client.accountid)
- if authErr != nil {
- return nil, authErr
- }
-
- client.ec2conn = ec2.New(awsEc2Sess)
-
- if !c.SkipGetEC2Platforms {
- supportedPlatforms, err := GetSupportedEC2Platforms(client.ec2conn)
- if err != nil {
- // We intentionally fail *silently* because there's a chance
- // user just doesn't have ec2:DescribeAccountAttributes permissions
- log.Printf("[WARN] Unable to get supported EC2 platforms: %s", err)
- } else {
- client.supportedplatforms = supportedPlatforms
- }
- }
-
- client.acmconn = acm.New(sess)
- client.apigateway = apigateway.New(sess)
- client.appautoscalingconn = applicationautoscaling.New(sess)
- client.autoscalingconn = autoscaling.New(sess)
- client.cfconn = cloudformation.New(awsCfSess)
- client.cloudfrontconn = cloudfront.New(sess)
- client.cloudtrailconn = cloudtrail.New(sess)
- client.cloudwatchconn = cloudwatch.New(awsCwSess)
- client.cloudwatcheventsconn = cloudwatchevents.New(awsCweSess)
- client.cloudwatchlogsconn = cloudwatchlogs.New(awsCwlSess)
- client.codecommitconn = codecommit.New(sess)
- client.codebuildconn = codebuild.New(sess)
- client.codedeployconn = codedeploy.New(sess)
- client.configconn = configservice.New(sess)
- client.cognitoconn = cognitoidentity.New(sess)
- client.dmsconn = databasemigrationservice.New(sess)
- client.codepipelineconn = codepipeline.New(sess)
- client.dsconn = directoryservice.New(sess)
- client.dynamodbconn = dynamodb.New(awsDynamoSess)
- client.ecrconn = ecr.New(sess)
- client.ecsconn = ecs.New(sess)
- client.efsconn = efs.New(sess)
- client.elasticacheconn = elasticache.New(sess)
- client.elasticbeanstalkconn = elasticbeanstalk.New(sess)
- client.elastictranscoderconn = elastictranscoder.New(sess)
- client.elbconn = elb.New(awsElbSess)
- client.elbv2conn = elbv2.New(awsElbSess)
- client.emrconn = emr.New(sess)
- client.esconn = elasticsearch.New(sess)
- client.firehoseconn = firehose.New(sess)
- client.inspectorconn = inspector.New(sess)
- client.glacierconn = glacier.New(sess)
- client.kinesisconn = kinesis.New(awsKinesisSess)
- client.kmsconn = kms.New(awsKmsSess)
- client.lambdaconn = lambda.New(sess)
- client.lightsailconn = lightsail.New(sess)
- client.opsworksconn = opsworks.New(sess)
- client.r53conn = route53.New(r53Sess)
- client.rdsconn = rds.New(awsRdsSess)
- client.redshiftconn = redshift.New(sess)
- client.simpledbconn = simpledb.New(sess)
- client.s3conn = s3.New(awsS3Sess)
- client.sesConn = ses.New(sess)
- client.sfnconn = sfn.New(sess)
- client.snsconn = sns.New(awsSnsSess)
- client.sqsconn = sqs.New(awsSqsSess)
- client.ssmconn = ssm.New(sess)
- client.wafconn = waf.New(sess)
- client.wafregionalconn = wafregional.New(sess)
-
- return &client, nil
-}
-
-// ValidateRegion returns an error if the configured region is not a
-// valid aws region and nil otherwise.
-func (c *Config) ValidateRegion() error {
- var regions = []string{
- "ap-northeast-1",
- "ap-northeast-2",
- "ap-south-1",
- "ap-southeast-1",
- "ap-southeast-2",
- "ca-central-1",
- "cn-north-1",
- "eu-central-1",
- "eu-west-1",
- "eu-west-2",
- "sa-east-1",
- "us-east-1",
- "us-east-2",
- "us-gov-west-1",
- "us-west-1",
- "us-west-2",
- }
-
- for _, valid := range regions {
- if c.Region == valid {
- return nil
- }
- }
- return fmt.Errorf("Not a valid region: %s", c.Region)
-}
-
-// Validate credentials early and fail before we do any graph walking.
-func (c *Config) ValidateCredentials(stsconn *sts.STS) error {
- _, err := stsconn.GetCallerIdentity(&sts.GetCallerIdentityInput{})
- return err
-}
-
-// ValidateAccountId returns a context-specific error if the configured account
-// id is explicitly forbidden or not authorised; and nil if it is authorised.
-func (c *Config) ValidateAccountId(accountId string) error {
- if c.AllowedAccountIds == nil && c.ForbiddenAccountIds == nil {
- return nil
- }
-
- log.Println("[INFO] Validating account ID")
-
- if c.ForbiddenAccountIds != nil {
- for _, id := range c.ForbiddenAccountIds {
- if id == accountId {
- return fmt.Errorf("Forbidden account ID (%s)", id)
- }
- }
- }
-
- if c.AllowedAccountIds != nil {
- for _, id := range c.AllowedAccountIds {
- if id == accountId {
- return nil
- }
- }
- return fmt.Errorf("Account ID not allowed (%s)", accountId)
- }
-
- return nil
-}
-
-func GetSupportedEC2Platforms(conn *ec2.EC2) ([]string, error) {
- attrName := "supported-platforms"
-
- input := ec2.DescribeAccountAttributesInput{
- AttributeNames: []*string{aws.String(attrName)},
- }
- attributes, err := conn.DescribeAccountAttributes(&input)
- if err != nil {
- return nil, err
- }
-
- var platforms []string
- for _, attr := range attributes.AccountAttributes {
- if *attr.AttributeName == attrName {
- for _, v := range attr.AttributeValues {
- platforms = append(platforms, *v.AttributeValue)
- }
- break
- }
- }
-
- if len(platforms) == 0 {
- return nil, fmt.Errorf("No EC2 platforms detected")
- }
-
- return platforms, nil
-}
-
-// addTerraformVersionToUserAgent is a named handler that will add Terraform's
-// version information to requests made by the AWS SDK.
-var addTerraformVersionToUserAgent = request.NamedHandler{
- Name: "terraform.TerraformVersionUserAgentHandler",
- Fn: request.MakeAddToUserAgentHandler(
- "APN/1.0 HashiCorp/1.0 Terraform", terraform.VersionString()),
-}
-
-var debugAuthFailure = request.NamedHandler{
- Name: "terraform.AuthFailureAdditionalDebugHandler",
- Fn: func(req *request.Request) {
- if isAWSErr(req.Error, "AuthFailure", "AWS was not able to validate the provided access credentials") {
- log.Printf("[INFO] Additional AuthFailure Debugging Context")
- log.Printf("[INFO] Current system UTC time: %s", time.Now().UTC())
- log.Printf("[INFO] Request object: %s", spew.Sdump(req))
- }
- },
-}
-
-type awsLogger struct{}
-
-func (l awsLogger) Log(args ...interface{}) {
- tokens := make([]string, 0, len(args))
- for _, arg := range args {
- if token, ok := arg.(string); ok {
- tokens = append(tokens, token)
- }
- }
- log.Printf("[DEBUG] [aws-sdk-go] %s", strings.Join(tokens, " "))
-}
diff --git a/builtin/providers/aws/config_test.go b/builtin/providers/aws/config_test.go
deleted file mode 100644
index 50b175c1e..000000000
--- a/builtin/providers/aws/config_test.go
+++ /dev/null
@@ -1,118 +0,0 @@
-package aws
-
-import (
- "bytes"
- "fmt"
- "log"
- "net/http"
- "net/http/httptest"
- "reflect"
- "testing"
- "time"
-
- "github.com/aws/aws-sdk-go/aws"
- awsCredentials "github.com/aws/aws-sdk-go/aws/credentials"
- "github.com/aws/aws-sdk-go/aws/session"
- "github.com/aws/aws-sdk-go/service/ec2"
-)
-
-func TestGetSupportedEC2Platforms(t *testing.T) {
- ec2Endpoints := []*awsMockEndpoint{
- &awsMockEndpoint{
- Request: &awsMockRequest{"POST", "/", "Action=DescribeAccountAttributes&" +
- "AttributeName.1=supported-platforms&Version=2016-11-15"},
- Response: &awsMockResponse{200, test_ec2_describeAccountAttributes_response, "text/xml"},
- },
- }
- closeFunc, sess, err := getMockedAwsApiSession("EC2", ec2Endpoints)
- if err != nil {
- t.Fatal(err)
- }
- defer closeFunc()
- conn := ec2.New(sess)
-
- platforms, err := GetSupportedEC2Platforms(conn)
- if err != nil {
- t.Fatalf("Expected no error, received: %s", err)
- }
- expectedPlatforms := []string{"VPC", "EC2"}
- if !reflect.DeepEqual(platforms, expectedPlatforms) {
- t.Fatalf("Received platforms: %q\nExpected: %q\n", platforms, expectedPlatforms)
- }
-}
-
-// getMockedAwsApiSession establishes a httptest server to simulate behaviour
-// of a real AWS API server
-func getMockedAwsApiSession(svcName string, endpoints []*awsMockEndpoint) (func(), *session.Session, error) {
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- buf := new(bytes.Buffer)
- buf.ReadFrom(r.Body)
- requestBody := buf.String()
-
- log.Printf("[DEBUG] Received %s API %q request to %q: %s",
- svcName, r.Method, r.RequestURI, requestBody)
-
- for _, e := range endpoints {
- if r.Method == e.Request.Method && r.RequestURI == e.Request.Uri && requestBody == e.Request.Body {
- log.Printf("[DEBUG] Mocked %s API responding with %d: %s",
- svcName, e.Response.StatusCode, e.Response.Body)
-
- w.WriteHeader(e.Response.StatusCode)
- w.Header().Set("Content-Type", e.Response.ContentType)
- w.Header().Set("X-Amzn-Requestid", "1b206dd1-f9a8-11e5-becf-051c60f11c4a")
- w.Header().Set("Date", time.Now().Format(time.RFC1123))
-
- fmt.Fprintln(w, e.Response.Body)
- return
- }
- }
-
- w.WriteHeader(400)
- return
- }))
-
- sc := awsCredentials.NewStaticCredentials("accessKey", "secretKey", "")
-
- sess, err := session.NewSession(&aws.Config{
- Credentials: sc,
- Region: aws.String("us-east-1"),
- Endpoint: aws.String(ts.URL),
- CredentialsChainVerboseErrors: aws.Bool(true),
- })
-
- return ts.Close, sess, err
-}
-
-type awsMockEndpoint struct {
- Request *awsMockRequest
- Response *awsMockResponse
-}
-
-type awsMockRequest struct {
- Method string
- Uri string
- Body string
-}
-
-type awsMockResponse struct {
- StatusCode int
- Body string
- ContentType string
-}
-
-var test_ec2_describeAccountAttributes_response = `
- 7a62c49f-347e-4fc4-9331-6e8eEXAMPLE
-
- -
- supported-platforms
-
-
-
- VPC
-
- -
- EC2
-
-
-
-
-`
diff --git a/builtin/providers/aws/core_acceptance_test.go b/builtin/providers/aws/core_acceptance_test.go
deleted file mode 100644
index 796380ad9..000000000
--- a/builtin/providers/aws/core_acceptance_test.go
+++ /dev/null
@@ -1,41 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/aws/aws-sdk-go/service/ec2"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSVPC_coreMismatchedDiffs(t *testing.T) {
- var vpc ec2.Vpc
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckVpcDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testMatchedDiffs,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckVpcExists("aws_vpc.test", &vpc),
- testAccCheckVpcCidr(&vpc, "10.0.0.0/16"),
- resource.TestCheckResourceAttr(
- "aws_vpc.test", "cidr_block", "10.0.0.0/16"),
- ),
- },
- },
- })
-}
-
-const testMatchedDiffs = `resource "aws_vpc" "test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- Name = "Repro GH-4965"
- }
-
- lifecycle {
- ignore_changes = ["tags"]
- }
-}`
diff --git a/builtin/providers/aws/data_source_aws_acm_certificate.go b/builtin/providers/aws/data_source_aws_acm_certificate.go
deleted file mode 100644
index 5b69ed93d..000000000
--- a/builtin/providers/aws/data_source_aws_acm_certificate.go
+++ /dev/null
@@ -1,103 +0,0 @@
-package aws
-
-import (
- "fmt"
- "time"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/acm"
- "github.com/hashicorp/errwrap"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsAcmCertificate() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsAcmCertificateRead,
- Schema: map[string]*schema.Schema{
- "domain": {
- Type: schema.TypeString,
- Required: true,
- },
- "arn": {
- Type: schema.TypeString,
- Computed: true,
- },
- "statuses": {
- Type: schema.TypeList,
- Optional: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
- "types": {
- Type: schema.TypeList,
- Optional: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
- },
- }
-}
-
-func dataSourceAwsAcmCertificateRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).acmconn
- params := &acm.ListCertificatesInput{}
-
- target := d.Get("domain")
-
- statuses, ok := d.GetOk("statuses")
- if ok {
- statusStrings := statuses.([]interface{})
- params.CertificateStatuses = expandStringList(statusStrings)
- } else {
- params.CertificateStatuses = []*string{aws.String("ISSUED")}
- }
-
- var arns []string
- err := conn.ListCertificatesPages(params, func(page *acm.ListCertificatesOutput, lastPage bool) bool {
- for _, cert := range page.CertificateSummaryList {
- if *cert.DomainName == target {
- arns = append(arns, *cert.CertificateArn)
- }
- }
-
- return true
- })
- if err != nil {
- return errwrap.Wrapf("Error describing certificates: {{err}}", err)
- }
-
- // filter based on certificate type (imported or aws-issued)
- types, ok := d.GetOk("types")
- if ok {
- typesStrings := expandStringList(types.([]interface{}))
- var matchedArns []string
- for _, arn := range arns {
- params := &acm.DescribeCertificateInput{}
- params.CertificateArn = &arn
-
- description, err := conn.DescribeCertificate(params)
- if err != nil {
- return errwrap.Wrapf("Error describing certificates: {{err}}", err)
- }
-
- for _, certType := range typesStrings {
- if *description.Certificate.Type == *certType {
- matchedArns = append(matchedArns, arn)
- break
- }
- }
- }
-
- arns = matchedArns
- }
-
- if len(arns) == 0 {
- return fmt.Errorf("No certificate for domain %q found in this region.", target)
- }
- if len(arns) > 1 {
- return fmt.Errorf("Multiple certificates for domain %q found in this region.", target)
- }
-
- d.SetId(time.Now().UTC().String())
- d.Set("arn", arns[0])
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_acm_certificate_test.go b/builtin/providers/aws/data_source_aws_acm_certificate_test.go
deleted file mode 100644
index a862b12e7..000000000
--- a/builtin/providers/aws/data_source_aws_acm_certificate_test.go
+++ /dev/null
@@ -1,59 +0,0 @@
-package aws
-
-import (
- "fmt"
- "regexp"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAwsAcmCertificateDataSource_noMatchReturnsError(t *testing.T) {
- domain := "hashicorp.com"
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsAcmCertificateDataSourceConfig(domain),
- ExpectError: regexp.MustCompile(`No certificate for domain`),
- },
- {
- Config: testAccCheckAwsAcmCertificateDataSourceConfigWithStatus(domain),
- ExpectError: regexp.MustCompile(`No certificate for domain`),
- },
- {
- Config: testAccCheckAwsAcmCertificateDataSourceConfigWithTypes(domain),
- ExpectError: regexp.MustCompile(`No certificate for domain`),
- },
- },
- })
-}
-
-func testAccCheckAwsAcmCertificateDataSourceConfig(domain string) string {
- return fmt.Sprintf(`
-data "aws_acm_certificate" "test" {
- domain = "%s"
-}
-`, domain)
-}
-
-func testAccCheckAwsAcmCertificateDataSourceConfigWithStatus(domain string) string {
- return fmt.Sprintf(`
-data "aws_acm_certificate" "test" {
- domain = "%s"
- statuses = ["ISSUED"]
-}
-`, domain)
-}
-
-func testAccCheckAwsAcmCertificateDataSourceConfigWithTypes(domain string) string {
- return fmt.Sprintf(`
-data "aws_acm_certificate" "test" {
- domain = "%s"
- types = ["IMPORTED"]
-}
-`, domain)
-}
diff --git a/builtin/providers/aws/data_source_aws_alb.go b/builtin/providers/aws/data_source_aws_alb.go
deleted file mode 100644
index d314e0ed7..000000000
--- a/builtin/providers/aws/data_source_aws_alb.go
+++ /dev/null
@@ -1,127 +0,0 @@
-package aws
-
-import (
- "fmt"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/elbv2"
- "github.com/hashicorp/errwrap"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsAlb() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsAlbRead,
- Schema: map[string]*schema.Schema{
- "arn": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
-
- "arn_suffix": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "name": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
-
- "internal": {
- Type: schema.TypeBool,
- Computed: true,
- },
-
- "security_groups": {
- Type: schema.TypeSet,
- Elem: &schema.Schema{Type: schema.TypeString},
- Computed: true,
- Set: schema.HashString,
- },
-
- "subnets": {
- Type: schema.TypeSet,
- Elem: &schema.Schema{Type: schema.TypeString},
- Computed: true,
- Set: schema.HashString,
- },
-
- "access_logs": {
- Type: schema.TypeList,
- Computed: true,
- MaxItems: 1,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "bucket": {
- Type: schema.TypeString,
- Computed: true,
- },
- "prefix": {
- Type: schema.TypeString,
- Computed: true,
- },
- "enabled": {
- Type: schema.TypeBool,
- Computed: true,
- },
- },
- },
- },
-
- "enable_deletion_protection": {
- Type: schema.TypeBool,
- Computed: true,
- },
-
- "idle_timeout": {
- Type: schema.TypeInt,
- Computed: true,
- },
-
- "vpc_id": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "zone_id": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "dns_name": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "tags": tagsSchemaComputed(),
- },
- }
-}
-
-func dataSourceAwsAlbRead(d *schema.ResourceData, meta interface{}) error {
- elbconn := meta.(*AWSClient).elbv2conn
- albArn := d.Get("arn").(string)
- albName := d.Get("name").(string)
-
- describeAlbOpts := &elbv2.DescribeLoadBalancersInput{}
- switch {
- case albArn != "":
- describeAlbOpts.LoadBalancerArns = []*string{aws.String(albArn)}
- case albName != "":
- describeAlbOpts.Names = []*string{aws.String(albName)}
- }
-
- describeResp, err := elbconn.DescribeLoadBalancers(describeAlbOpts)
- if err != nil {
- return errwrap.Wrapf("Error retrieving ALB: {{err}}", err)
- }
- if len(describeResp.LoadBalancers) != 1 {
- return fmt.Errorf("Search returned %d results, please revise so only one is returned", len(describeResp.LoadBalancers))
- }
- d.SetId(*describeResp.LoadBalancers[0].LoadBalancerArn)
-
- return flattenAwsAlbResource(d, meta, describeResp.LoadBalancers[0])
-}
diff --git a/builtin/providers/aws/data_source_aws_alb_listener.go b/builtin/providers/aws/data_source_aws_alb_listener.go
deleted file mode 100644
index 63ec4ed1a..000000000
--- a/builtin/providers/aws/data_source_aws_alb_listener.go
+++ /dev/null
@@ -1,62 +0,0 @@
-package aws
-
-import "github.com/hashicorp/terraform/helper/schema"
-
-func dataSourceAwsAlbListener() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsAlbListenerRead,
-
- 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 dataSourceAwsAlbListenerRead(d *schema.ResourceData, meta interface{}) error {
- d.SetId(d.Get("arn").(string))
- return resourceAwsAlbListenerRead(d, meta)
-}
diff --git a/builtin/providers/aws/data_source_aws_alb_listener_test.go b/builtin/providers/aws/data_source_aws_alb_listener_test.go
deleted file mode 100644
index 5eea80e24..000000000
--- a/builtin/providers/aws/data_source_aws_alb_listener_test.go
+++ /dev/null
@@ -1,326 +0,0 @@
-package aws
-
-import (
- "fmt"
- "math/rand"
- "testing"
- "time"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccDataSourceAWSALBListener_basic(t *testing.T) {
- albName := fmt.Sprintf("testlistener-basic-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum))
- targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAWSALBListenerConfigBasic(albName, targetGroupName),
- Check: resource.ComposeAggregateTestCheckFunc(
- resource.TestCheckResourceAttrSet("data.aws_alb_listener.front_end", "load_balancer_arn"),
- resource.TestCheckResourceAttrSet("data.aws_alb_listener.front_end", "arn"),
- resource.TestCheckResourceAttr("data.aws_alb_listener.front_end", "protocol", "HTTP"),
- resource.TestCheckResourceAttr("data.aws_alb_listener.front_end", "port", "80"),
- resource.TestCheckResourceAttr("data.aws_alb_listener.front_end", "default_action.#", "1"),
- resource.TestCheckResourceAttr("data.aws_alb_listener.front_end", "default_action.0.type", "forward"),
- resource.TestCheckResourceAttrSet("data.aws_alb_listener.front_end", "default_action.0.target_group_arn"),
- ),
- },
- },
- })
-}
-
-func TestAccDataSourceAWSALBListener_https(t *testing.T) {
- albName := fmt.Sprintf("testlistener-https-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum))
- targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAWSALBListenerConfigHTTPS(albName, targetGroupName),
- Check: resource.ComposeAggregateTestCheckFunc(
- resource.TestCheckResourceAttrSet("data.aws_alb_listener.front_end", "load_balancer_arn"),
- resource.TestCheckResourceAttrSet("data.aws_alb_listener.front_end", "arn"),
- resource.TestCheckResourceAttr("data.aws_alb_listener.front_end", "protocol", "HTTPS"),
- resource.TestCheckResourceAttr("data.aws_alb_listener.front_end", "port", "443"),
- resource.TestCheckResourceAttr("data.aws_alb_listener.front_end", "default_action.#", "1"),
- resource.TestCheckResourceAttr("data.aws_alb_listener.front_end", "default_action.0.type", "forward"),
- resource.TestCheckResourceAttrSet("data.aws_alb_listener.front_end", "default_action.0.target_group_arn"),
- resource.TestCheckResourceAttrSet("data.aws_alb_listener.front_end", "certificate_arn"),
- resource.TestCheckResourceAttr("data.aws_alb_listener.front_end", "ssl_policy", "ELBSecurityPolicy-2015-05"),
- ),
- },
- },
- })
-}
-
-func testAccDataSourceAWSALBListenerConfigBasic(albName, targetGroupName string) string {
- return fmt.Sprintf(`resource "aws_alb_listener" "front_end" {
- load_balancer_arn = "${aws_alb.alb_test.id}"
- protocol = "HTTP"
- port = "80"
-
- default_action {
- target_group_arn = "${aws_alb_target_group.test.id}"
- type = "forward"
- }
-}
-
-resource "aws_alb" "alb_test" {
- name = "%s"
- internal = true
- security_groups = ["${aws_security_group.alb_test.id}"]
- subnets = ["${aws_subnet.alb_test.*.id}"]
-
- idle_timeout = 30
- enable_deletion_protection = false
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_alb_target_group" "test" {
- name = "%s"
- port = 8080
- protocol = "HTTP"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- health_check {
- path = "/health"
- interval = 60
- port = 8081
- protocol = "HTTP"
- timeout = 3
- healthy_threshold = 3
- unhealthy_threshold = 3
- matcher = "200-299"
- }
-}
-
-variable "subnets" {
- default = ["10.0.1.0/24", "10.0.2.0/24"]
- type = "list"
-}
-
-data "aws_availability_zones" "available" {}
-
-resource "aws_vpc" "alb_test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_subnet" "alb_test" {
- count = 2
- vpc_id = "${aws_vpc.alb_test.id}"
- cidr_block = "${element(var.subnets, count.index)}"
- map_public_ip_on_launch = true
- availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_security_group" "alb_test" {
- name = "allow_all_alb_test"
- description = "Used for ALB Testing"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- ingress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- egress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-data "aws_alb_listener" "front_end" {
- arn = "${aws_alb_listener.front_end.arn}"
-}`, albName, targetGroupName)
-}
-
-func testAccDataSourceAWSALBListenerConfigHTTPS(albName, targetGroupName string) string {
- return fmt.Sprintf(`resource "aws_alb_listener" "front_end" {
- load_balancer_arn = "${aws_alb.alb_test.id}"
- protocol = "HTTPS"
- port = "443"
- ssl_policy = "ELBSecurityPolicy-2015-05"
- certificate_arn = "${aws_iam_server_certificate.test_cert.arn}"
-
- default_action {
- target_group_arn = "${aws_alb_target_group.test.id}"
- type = "forward"
- }
-}
-
-resource "aws_alb" "alb_test" {
- name = "%s"
- internal = false
- security_groups = ["${aws_security_group.alb_test.id}"]
- subnets = ["${aws_subnet.alb_test.*.id}"]
-
- idle_timeout = 30
- enable_deletion_protection = false
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_alb_target_group" "test" {
- name = "%s"
- port = 8080
- protocol = "HTTP"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- health_check {
- path = "/health"
- interval = 60
- port = 8081
- protocol = "HTTP"
- timeout = 3
- healthy_threshold = 3
- unhealthy_threshold = 3
- matcher = "200-299"
- }
-}
-
-variable "subnets" {
- default = ["10.0.1.0/24", "10.0.2.0/24"]
- type = "list"
-}
-
-data "aws_availability_zones" "available" {}
-
-resource "aws_vpc" "alb_test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_internet_gateway" "gw" {
- vpc_id = "${aws_vpc.alb_test.id}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_subnet" "alb_test" {
- count = 2
- vpc_id = "${aws_vpc.alb_test.id}"
- cidr_block = "${element(var.subnets, count.index)}"
- map_public_ip_on_launch = true
- availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_security_group" "alb_test" {
- name = "allow_all_alb_test"
- description = "Used for ALB Testing"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- ingress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- egress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_iam_server_certificate" "test_cert" {
- name = "terraform-test-cert-%d"
- certificate_body = < 0 {
- params.Owners = o
- }
- }
-
- resp, err := conn.DescribeImages(params)
- if err != nil {
- return err
- }
-
- var filteredImages []*ec2.Image
- if nameRegexOk {
- r := regexp.MustCompile(nameRegex.(string))
- for _, image := range resp.Images {
- // Check for a very rare case where the response would include no
- // image name. No name means nothing to attempt a match against,
- // therefore we are skipping such image.
- if image.Name == nil || *image.Name == "" {
- log.Printf("[WARN] Unable to find AMI name to match against "+
- "for image ID %q owned by %q, nothing to do.",
- *image.ImageId, *image.OwnerId)
- continue
- }
- if r.MatchString(*image.Name) {
- filteredImages = append(filteredImages, image)
- }
- }
- } else {
- filteredImages = resp.Images[:]
- }
-
- var image *ec2.Image
- if len(filteredImages) < 1 {
- return fmt.Errorf("Your query returned no results. Please change your search criteria and try again.")
- }
-
- if len(filteredImages) > 1 {
- recent := d.Get("most_recent").(bool)
- log.Printf("[DEBUG] aws_ami - multiple results found and `most_recent` is set to: %t", recent)
- if recent {
- image = mostRecentAmi(filteredImages)
- } else {
- return fmt.Errorf("Your query returned more than one result. Please try a more " +
- "specific search criteria, or set `most_recent` attribute to true.")
- }
- } else {
- // Query returned single result.
- image = filteredImages[0]
- }
-
- log.Printf("[DEBUG] aws_ami - Single AMI found: %s", *image.ImageId)
- return amiDescriptionAttributes(d, image)
-}
-
-// Returns the most recent AMI out of a slice of images.
-func mostRecentAmi(images []*ec2.Image) *ec2.Image {
- return sortImages(images)[0]
-}
-
-// populate the numerous fields that the image description returns.
-func amiDescriptionAttributes(d *schema.ResourceData, image *ec2.Image) error {
- // Simple attributes first
- d.SetId(*image.ImageId)
- d.Set("architecture", image.Architecture)
- d.Set("creation_date", image.CreationDate)
- if image.Description != nil {
- d.Set("description", image.Description)
- }
- d.Set("hypervisor", image.Hypervisor)
- d.Set("image_id", image.ImageId)
- d.Set("image_location", image.ImageLocation)
- if image.ImageOwnerAlias != nil {
- d.Set("image_owner_alias", image.ImageOwnerAlias)
- }
- d.Set("image_type", image.ImageType)
- if image.KernelId != nil {
- d.Set("kernel_id", image.KernelId)
- }
- d.Set("name", image.Name)
- d.Set("owner_id", image.OwnerId)
- if image.Platform != nil {
- d.Set("platform", image.Platform)
- }
- d.Set("public", image.Public)
- if image.RamdiskId != nil {
- d.Set("ramdisk_id", image.RamdiskId)
- }
- if image.RootDeviceName != nil {
- d.Set("root_device_name", image.RootDeviceName)
- }
- d.Set("root_device_type", image.RootDeviceType)
- if image.SriovNetSupport != nil {
- d.Set("sriov_net_support", image.SriovNetSupport)
- }
- d.Set("state", image.State)
- d.Set("virtualization_type", image.VirtualizationType)
- // Complex types get their own functions
- if err := d.Set("block_device_mappings", amiBlockDeviceMappings(image.BlockDeviceMappings)); err != nil {
- return err
- }
- if err := d.Set("product_codes", amiProductCodes(image.ProductCodes)); err != nil {
- return err
- }
- if err := d.Set("state_reason", amiStateReason(image.StateReason)); err != nil {
- return err
- }
- if err := d.Set("tags", dataSourceTags(image.Tags)); err != nil {
- return err
- }
- return nil
-}
-
-// Returns a set of block device mappings.
-func amiBlockDeviceMappings(m []*ec2.BlockDeviceMapping) *schema.Set {
- s := &schema.Set{
- F: amiBlockDeviceMappingHash,
- }
- for _, v := range m {
- mapping := map[string]interface{}{
- "device_name": *v.DeviceName,
- }
- if v.Ebs != nil {
- ebs := map[string]interface{}{
- "delete_on_termination": fmt.Sprintf("%t", *v.Ebs.DeleteOnTermination),
- "encrypted": fmt.Sprintf("%t", *v.Ebs.Encrypted),
- "volume_size": fmt.Sprintf("%d", *v.Ebs.VolumeSize),
- "volume_type": *v.Ebs.VolumeType,
- }
- // Iops is not always set
- if v.Ebs.Iops != nil {
- ebs["iops"] = fmt.Sprintf("%d", *v.Ebs.Iops)
- } else {
- ebs["iops"] = "0"
- }
- // snapshot id may not be set
- if v.Ebs.SnapshotId != nil {
- ebs["snapshot_id"] = *v.Ebs.SnapshotId
- }
-
- mapping["ebs"] = ebs
- }
- if v.VirtualName != nil {
- mapping["virtual_name"] = *v.VirtualName
- }
- log.Printf("[DEBUG] aws_ami - adding block device mapping: %v", mapping)
- s.Add(mapping)
- }
- return s
-}
-
-// Returns a set of product codes.
-func amiProductCodes(m []*ec2.ProductCode) *schema.Set {
- s := &schema.Set{
- F: amiProductCodesHash,
- }
- for _, v := range m {
- code := map[string]interface{}{
- "product_code_id": *v.ProductCodeId,
- "product_code_type": *v.ProductCodeType,
- }
- s.Add(code)
- }
- return s
-}
-
-// Returns the state reason.
-func amiStateReason(m *ec2.StateReason) map[string]interface{} {
- s := make(map[string]interface{})
- if m != nil {
- s["code"] = *m.Code
- s["message"] = *m.Message
- } else {
- s["code"] = "UNSET"
- s["message"] = "UNSET"
- }
- return s
-}
-
-// Generates a hash for the set hash function used by the block_device_mappings
-// attribute.
-func amiBlockDeviceMappingHash(v interface{}) int {
- var buf bytes.Buffer
- // All keys added in alphabetical order.
- m := v.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%s-", m["device_name"].(string)))
- if d, ok := m["ebs"]; ok {
- if len(d.(map[string]interface{})) > 0 {
- e := d.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%s-", e["delete_on_termination"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", e["encrypted"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", e["iops"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", e["volume_size"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", e["volume_type"].(string)))
- }
- }
- if d, ok := m["no_device"]; ok {
- buf.WriteString(fmt.Sprintf("%s-", d.(string)))
- }
- if d, ok := m["virtual_name"]; ok {
- buf.WriteString(fmt.Sprintf("%s-", d.(string)))
- }
- if d, ok := m["snapshot_id"]; ok {
- buf.WriteString(fmt.Sprintf("%s-", d.(string)))
- }
- return hashcode.String(buf.String())
-}
-
-// Generates a hash for the set hash function used by the product_codes
-// attribute.
-func amiProductCodesHash(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- // All keys added in alphabetical order.
- buf.WriteString(fmt.Sprintf("%s-", m["product_code_id"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["product_code_type"].(string)))
- return hashcode.String(buf.String())
-}
-
-func validateNameRegex(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
-
- if _, err := regexp.Compile(value); err != nil {
- errors = append(errors, fmt.Errorf(
- "%q contains an invalid regular expression: %s",
- k, err))
- }
- return
-}
diff --git a/builtin/providers/aws/data_source_aws_ami_ids.go b/builtin/providers/aws/data_source_aws_ami_ids.go
deleted file mode 100644
index 20df34ac3..000000000
--- a/builtin/providers/aws/data_source_aws_ami_ids.go
+++ /dev/null
@@ -1,111 +0,0 @@
-package aws
-
-import (
- "fmt"
- "log"
- "regexp"
-
- "github.com/aws/aws-sdk-go/service/ec2"
- "github.com/hashicorp/terraform/helper/hashcode"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsAmiIds() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsAmiIdsRead,
-
- Schema: map[string]*schema.Schema{
- "filter": dataSourceFiltersSchema(),
- "executable_users": {
- Type: schema.TypeList,
- Optional: true,
- ForceNew: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
- "name_regex": {
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- ValidateFunc: validateNameRegex,
- },
- "owners": {
- Type: schema.TypeList,
- Optional: true,
- ForceNew: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
- "tags": dataSourceTagsSchema(),
- "ids": &schema.Schema{
- Type: schema.TypeList,
- Computed: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
- },
- }
-}
-
-func dataSourceAwsAmiIdsRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).ec2conn
-
- executableUsers, executableUsersOk := d.GetOk("executable_users")
- filters, filtersOk := d.GetOk("filter")
- nameRegex, nameRegexOk := d.GetOk("name_regex")
- owners, ownersOk := d.GetOk("owners")
-
- if executableUsersOk == false && filtersOk == false && nameRegexOk == false && ownersOk == false {
- return fmt.Errorf("One of executable_users, filters, name_regex, or owners must be assigned")
- }
-
- params := &ec2.DescribeImagesInput{}
-
- if executableUsersOk {
- params.ExecutableUsers = expandStringList(executableUsers.([]interface{}))
- }
- if filtersOk {
- params.Filters = buildAwsDataSourceFilters(filters.(*schema.Set))
- }
- if ownersOk {
- o := expandStringList(owners.([]interface{}))
-
- if len(o) > 0 {
- params.Owners = o
- }
- }
-
- resp, err := conn.DescribeImages(params)
- if err != nil {
- return err
- }
-
- var filteredImages []*ec2.Image
- imageIds := make([]string, 0)
-
- if nameRegexOk {
- r := regexp.MustCompile(nameRegex.(string))
- for _, image := range resp.Images {
- // Check for a very rare case where the response would include no
- // image name. No name means nothing to attempt a match against,
- // therefore we are skipping such image.
- if image.Name == nil || *image.Name == "" {
- log.Printf("[WARN] Unable to find AMI name to match against "+
- "for image ID %q owned by %q, nothing to do.",
- *image.ImageId, *image.OwnerId)
- continue
- }
- if r.MatchString(*image.Name) {
- filteredImages = append(filteredImages, image)
- }
- }
- } else {
- filteredImages = resp.Images[:]
- }
-
- for _, image := range sortImages(filteredImages) {
- imageIds = append(imageIds, *image.ImageId)
- }
-
- d.SetId(fmt.Sprintf("%d", hashcode.String(params.String())))
- d.Set("ids", imageIds)
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_ami_ids_test.go b/builtin/providers/aws/data_source_aws_ami_ids_test.go
deleted file mode 100644
index 52582eaba..000000000
--- a/builtin/providers/aws/data_source_aws_ami_ids_test.go
+++ /dev/null
@@ -1,128 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/satori/uuid"
-)
-
-func TestAccDataSourceAwsAmiIds_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAwsAmiIdsConfig_basic,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsAmiDataSourceID("data.aws_ami_ids.ubuntu"),
- ),
- },
- },
- })
-}
-
-func TestAccDataSourceAwsAmiIds_sorted(t *testing.T) {
- uuid := uuid.NewV4().String()
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAwsAmiIdsConfig_sorted1(uuid),
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttrSet("aws_ami_from_instance.a", "id"),
- resource.TestCheckResourceAttrSet("aws_ami_from_instance.b", "id"),
- ),
- },
- {
- Config: testAccDataSourceAwsAmiIdsConfig_sorted2(uuid),
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsEbsSnapshotDataSourceID("data.aws_ami_ids.test"),
- resource.TestCheckResourceAttr("data.aws_ami_ids.test", "ids.#", "2"),
- resource.TestCheckResourceAttrPair(
- "data.aws_ami_ids.test", "ids.0",
- "aws_ami_from_instance.b", "id"),
- resource.TestCheckResourceAttrPair(
- "data.aws_ami_ids.test", "ids.1",
- "aws_ami_from_instance.a", "id"),
- ),
- },
- },
- })
-}
-
-func TestAccDataSourceAwsAmiIds_empty(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAwsAmiIdsConfig_empty,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsAmiDataSourceID("data.aws_ami_ids.empty"),
- resource.TestCheckResourceAttr("data.aws_ami_ids.empty", "ids.#", "0"),
- ),
- },
- },
- })
-}
-
-const testAccDataSourceAwsAmiIdsConfig_basic = `
-data "aws_ami_ids" "ubuntu" {
- owners = ["099720109477"]
-
- filter {
- name = "name"
- values = ["ubuntu/images/ubuntu-*-*-amd64-server-*"]
- }
-}
-`
-
-func testAccDataSourceAwsAmiIdsConfig_sorted1(uuid string) string {
- return fmt.Sprintf(`
-resource "aws_instance" "test" {
- ami = "ami-efd0428f"
- instance_type = "m3.medium"
-
- count = 2
-}
-
-resource "aws_ami_from_instance" "a" {
- name = "tf-test-%s-a"
- source_instance_id = "${aws_instance.test.*.id[0]}"
- snapshot_without_reboot = true
-}
-
-resource "aws_ami_from_instance" "b" {
- name = "tf-test-%s-b"
- source_instance_id = "${aws_instance.test.*.id[1]}"
- snapshot_without_reboot = true
-
- // We want to ensure that 'aws_ami_from_instance.a.creation_date' is less
- // than 'aws_ami_from_instance.b.creation_date' so that we can ensure that
- // the images are being sorted correctly.
- depends_on = ["aws_ami_from_instance.a"]
-}
-`, uuid, uuid)
-}
-
-func testAccDataSourceAwsAmiIdsConfig_sorted2(uuid string) string {
- return testAccDataSourceAwsAmiIdsConfig_sorted1(uuid) + fmt.Sprintf(`
-data "aws_ami_ids" "test" {
- owners = ["self"]
- name_regex = "^tf-test-%s-"
-}
-`, uuid)
-}
-
-const testAccDataSourceAwsAmiIdsConfig_empty = `
-data "aws_ami_ids" "empty" {
- filter {
- name = "name"
- values = []
- }
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_ami_test.go b/builtin/providers/aws/data_source_aws_ami_test.go
deleted file mode 100644
index 2375e6569..000000000
--- a/builtin/providers/aws/data_source_aws_ami_test.go
+++ /dev/null
@@ -1,350 +0,0 @@
-package aws
-
-import (
- "fmt"
- "regexp"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAWSAmiDataSource_natInstance(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsAmiDataSourceConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsAmiDataSourceID("data.aws_ami.nat_ami"),
- // Check attributes. Some attributes are tough to test - any not contained here should not be considered
- // stable and should not be used in interpolation. Exception to block_device_mappings which should both
- // show up consistently and break if certain references are not available. However modification of the
- // snapshot ID which is bound to happen on the NAT AMIs will cause testing to break consistently, so
- // deep inspection is not included, simply the count is checked.
- // Tags and product codes may need more testing, but I'm having a hard time finding images with
- // these attributes set.
- resource.TestCheckResourceAttr("data.aws_ami.nat_ami", "architecture", "x86_64"),
- resource.TestCheckResourceAttr("data.aws_ami.nat_ami", "block_device_mappings.#", "1"),
- resource.TestMatchResourceAttr("data.aws_ami.nat_ami", "creation_date", regexp.MustCompile("^20[0-9]{2}-")),
- resource.TestMatchResourceAttr("data.aws_ami.nat_ami", "description", regexp.MustCompile("^Amazon Linux AMI")),
- resource.TestCheckResourceAttr("data.aws_ami.nat_ami", "hypervisor", "xen"),
- resource.TestMatchResourceAttr("data.aws_ami.nat_ami", "image_id", regexp.MustCompile("^ami-")),
- resource.TestMatchResourceAttr("data.aws_ami.nat_ami", "image_location", regexp.MustCompile("^amazon/")),
- resource.TestCheckResourceAttr("data.aws_ami.nat_ami", "image_owner_alias", "amazon"),
- resource.TestCheckResourceAttr("data.aws_ami.nat_ami", "image_type", "machine"),
- resource.TestCheckResourceAttr("data.aws_ami.nat_ami", "most_recent", "true"),
- resource.TestMatchResourceAttr("data.aws_ami.nat_ami", "name", regexp.MustCompile("^amzn-ami-vpc-nat")),
- resource.TestCheckResourceAttr("data.aws_ami.nat_ami", "owner_id", "137112412989"),
- resource.TestCheckResourceAttr("data.aws_ami.nat_ami", "public", "true"),
- resource.TestCheckResourceAttr("data.aws_ami.nat_ami", "product_codes.#", "0"),
- resource.TestCheckResourceAttr("data.aws_ami.nat_ami", "root_device_name", "/dev/xvda"),
- resource.TestCheckResourceAttr("data.aws_ami.nat_ami", "root_device_type", "ebs"),
- resource.TestCheckResourceAttr("data.aws_ami.nat_ami", "sriov_net_support", "simple"),
- resource.TestCheckResourceAttr("data.aws_ami.nat_ami", "state", "available"),
- resource.TestCheckResourceAttr("data.aws_ami.nat_ami", "state_reason.code", "UNSET"),
- resource.TestCheckResourceAttr("data.aws_ami.nat_ami", "state_reason.message", "UNSET"),
- resource.TestCheckResourceAttr("data.aws_ami.nat_ami", "tags.#", "0"),
- resource.TestCheckResourceAttr("data.aws_ami.nat_ami", "virtualization_type", "hvm"),
- ),
- },
- },
- })
-}
-func TestAccAWSAmiDataSource_windowsInstance(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsAmiDataSourceWindowsConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsAmiDataSourceID("data.aws_ami.windows_ami"),
- resource.TestCheckResourceAttr("data.aws_ami.windows_ami", "architecture", "x86_64"),
- resource.TestCheckResourceAttr("data.aws_ami.windows_ami", "block_device_mappings.#", "27"),
- resource.TestMatchResourceAttr("data.aws_ami.windows_ami", "creation_date", regexp.MustCompile("^20[0-9]{2}-")),
- resource.TestMatchResourceAttr("data.aws_ami.windows_ami", "description", regexp.MustCompile("^Microsoft Windows Server 2012")),
- resource.TestCheckResourceAttr("data.aws_ami.windows_ami", "hypervisor", "xen"),
- resource.TestMatchResourceAttr("data.aws_ami.windows_ami", "image_id", regexp.MustCompile("^ami-")),
- resource.TestMatchResourceAttr("data.aws_ami.windows_ami", "image_location", regexp.MustCompile("^amazon/")),
- resource.TestCheckResourceAttr("data.aws_ami.windows_ami", "image_owner_alias", "amazon"),
- resource.TestCheckResourceAttr("data.aws_ami.windows_ami", "image_type", "machine"),
- resource.TestCheckResourceAttr("data.aws_ami.windows_ami", "most_recent", "true"),
- resource.TestMatchResourceAttr("data.aws_ami.windows_ami", "name", regexp.MustCompile("^Windows_Server-2012-R2")),
- resource.TestCheckResourceAttr("data.aws_ami.windows_ami", "owner_id", "801119661308"),
- resource.TestCheckResourceAttr("data.aws_ami.windows_ami", "platform", "windows"),
- resource.TestCheckResourceAttr("data.aws_ami.windows_ami", "public", "true"),
- resource.TestCheckResourceAttr("data.aws_ami.windows_ami", "product_codes.#", "0"),
- resource.TestCheckResourceAttr("data.aws_ami.windows_ami", "root_device_name", "/dev/sda1"),
- resource.TestCheckResourceAttr("data.aws_ami.windows_ami", "root_device_type", "ebs"),
- resource.TestCheckResourceAttr("data.aws_ami.windows_ami", "sriov_net_support", "simple"),
- resource.TestCheckResourceAttr("data.aws_ami.windows_ami", "state", "available"),
- resource.TestCheckResourceAttr("data.aws_ami.windows_ami", "state_reason.code", "UNSET"),
- resource.TestCheckResourceAttr("data.aws_ami.windows_ami", "state_reason.message", "UNSET"),
- resource.TestCheckResourceAttr("data.aws_ami.windows_ami", "tags.#", "0"),
- resource.TestCheckResourceAttr("data.aws_ami.windows_ami", "virtualization_type", "hvm"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSAmiDataSource_instanceStore(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsAmiDataSourceInstanceStoreConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsAmiDataSourceID("data.aws_ami.instance_store_ami"),
- resource.TestCheckResourceAttr("data.aws_ami.instance_store_ami", "architecture", "x86_64"),
- resource.TestCheckResourceAttr("data.aws_ami.instance_store_ami", "block_device_mappings.#", "0"),
- resource.TestMatchResourceAttr("data.aws_ami.instance_store_ami", "creation_date", regexp.MustCompile("^20[0-9]{2}-")),
- resource.TestCheckResourceAttr("data.aws_ami.instance_store_ami", "hypervisor", "xen"),
- resource.TestMatchResourceAttr("data.aws_ami.instance_store_ami", "image_id", regexp.MustCompile("^ami-")),
- resource.TestMatchResourceAttr("data.aws_ami.instance_store_ami", "image_location", regexp.MustCompile("images/hvm-instance/ubuntu-trusty-14.04-amd64-server")),
- resource.TestCheckResourceAttr("data.aws_ami.instance_store_ami", "image_type", "machine"),
- resource.TestCheckResourceAttr("data.aws_ami.instance_store_ami", "most_recent", "true"),
- resource.TestMatchResourceAttr("data.aws_ami.instance_store_ami", "name", regexp.MustCompile("^ubuntu/images/hvm-instance/ubuntu-trusty-14.04-amd64-server")),
- resource.TestCheckResourceAttr("data.aws_ami.instance_store_ami", "owner_id", "099720109477"),
- resource.TestCheckResourceAttr("data.aws_ami.instance_store_ami", "public", "true"),
- resource.TestCheckResourceAttr("data.aws_ami.instance_store_ami", "product_codes.#", "0"),
- resource.TestCheckResourceAttr("data.aws_ami.instance_store_ami", "root_device_type", "instance-store"),
- resource.TestCheckResourceAttr("data.aws_ami.instance_store_ami", "sriov_net_support", "simple"),
- resource.TestCheckResourceAttr("data.aws_ami.instance_store_ami", "state", "available"),
- resource.TestCheckResourceAttr("data.aws_ami.instance_store_ami", "state_reason.code", "UNSET"),
- resource.TestCheckResourceAttr("data.aws_ami.instance_store_ami", "state_reason.message", "UNSET"),
- resource.TestCheckResourceAttr("data.aws_ami.instance_store_ami", "tags.#", "0"),
- resource.TestCheckResourceAttr("data.aws_ami.instance_store_ami", "virtualization_type", "hvm"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSAmiDataSource_owners(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsAmiDataSourceOwnersConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsAmiDataSourceID("data.aws_ami.amazon_ami"),
- ),
- },
- },
- })
-}
-
-// Acceptance test for: https://github.com/hashicorp/terraform/issues/10758
-func TestAccAWSAmiDataSource_ownersEmpty(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsAmiDataSourceEmptyOwnersConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsAmiDataSourceID("data.aws_ami.amazon_ami"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSAmiDataSource_localNameFilter(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsAmiDataSourceNameRegexConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsAmiDataSourceID("data.aws_ami.name_regex_filtered_ami"),
- resource.TestMatchResourceAttr("data.aws_ami.name_regex_filtered_ami", "image_id", regexp.MustCompile("^ami-")),
- ),
- },
- },
- })
-}
-
-func TestResourceValidateNameRegex(t *testing.T) {
- type testCases struct {
- Value string
- ErrCount int
- }
-
- invalidCases := []testCases{
- {
- Value: `\`,
- ErrCount: 1,
- },
- {
- Value: `**`,
- ErrCount: 1,
- },
- {
- Value: `(.+`,
- ErrCount: 1,
- },
- }
-
- for _, tc := range invalidCases {
- _, errors := validateNameRegex(tc.Value, "name_regex")
- if len(errors) != tc.ErrCount {
- t.Fatalf("Expected %q to trigger a validation error.", tc.Value)
- }
- }
-
- validCases := []testCases{
- {
- Value: `\/`,
- ErrCount: 0,
- },
- {
- Value: `.*`,
- ErrCount: 0,
- },
- {
- Value: `\b(?:\d{1,3}\.){3}\d{1,3}\b`,
- ErrCount: 0,
- },
- }
-
- for _, tc := range validCases {
- _, errors := validateNameRegex(tc.Value, "name_regex")
- if len(errors) != tc.ErrCount {
- t.Fatalf("Expected %q not to trigger a validation error.", tc.Value)
- }
- }
-}
-
-func testAccCheckAwsAmiDataSourceDestroy(s *terraform.State) error {
- return nil
-}
-
-func testAccCheckAwsAmiDataSourceID(n string) resource.TestCheckFunc {
- // Wait for IAM role
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Can't find AMI data source: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("AMI data source ID not set")
- }
- return nil
- }
-}
-
-// Using NAT AMIs for testing - I would expect with NAT gateways now a thing,
-// that this will possibly be deprecated at some point in time. Other candidates
-// for testing this after that may be Ubuntu's AMI's, or Amazon's regular
-// Amazon Linux AMIs.
-const testAccCheckAwsAmiDataSourceConfig = `
-data "aws_ami" "nat_ami" {
- most_recent = true
- filter {
- name = "owner-alias"
- values = ["amazon"]
- }
- filter {
- name = "name"
- values = ["amzn-ami-vpc-nat*"]
- }
- filter {
- name = "virtualization-type"
- values = ["hvm"]
- }
- filter {
- name = "root-device-type"
- values = ["ebs"]
- }
- filter {
- name = "block-device-mapping.volume-type"
- values = ["standard"]
- }
-}
-`
-
-// Windows image test.
-const testAccCheckAwsAmiDataSourceWindowsConfig = `
-data "aws_ami" "windows_ami" {
- most_recent = true
- filter {
- name = "owner-alias"
- values = ["amazon"]
- }
- filter {
- name = "name"
- values = ["Windows_Server-2012-R2*"]
- }
- filter {
- name = "virtualization-type"
- values = ["hvm"]
- }
- filter {
- name = "root-device-type"
- values = ["ebs"]
- }
- filter {
- name = "block-device-mapping.volume-type"
- values = ["gp2"]
- }
-}
-`
-
-// Instance store test - using Ubuntu images
-const testAccCheckAwsAmiDataSourceInstanceStoreConfig = `
-data "aws_ami" "instance_store_ami" {
- most_recent = true
- filter {
- name = "owner-id"
- values = ["099720109477"]
- }
- filter {
- name = "name"
- values = ["ubuntu/images/hvm-instance/ubuntu-trusty-14.04-amd64-server*"]
- }
- filter {
- name = "virtualization-type"
- values = ["hvm"]
- }
- filter {
- name = "root-device-type"
- values = ["instance-store"]
- }
-}
-`
-
-// Testing owner parameter
-const testAccCheckAwsAmiDataSourceOwnersConfig = `
-data "aws_ami" "amazon_ami" {
- most_recent = true
- owners = ["amazon"]
-}
-`
-
-const testAccCheckAwsAmiDataSourceEmptyOwnersConfig = `
-data "aws_ami" "amazon_ami" {
- most_recent = true
- owners = [""]
-}
-`
-
-// Testing name_regex parameter
-const testAccCheckAwsAmiDataSourceNameRegexConfig = `
-data "aws_ami" "name_regex_filtered_ami" {
- most_recent = true
- owners = ["amazon"]
- filter {
- name = "name"
- values = ["amzn-ami-*"]
- }
- name_regex = "^amzn-ami-\\d{3}[5].*-ecs-optimized"
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_autoscaling_groups.go b/builtin/providers/aws/data_source_aws_autoscaling_groups.go
deleted file mode 100644
index f43f21d4e..000000000
--- a/builtin/providers/aws/data_source_aws_autoscaling_groups.go
+++ /dev/null
@@ -1,102 +0,0 @@
-package aws
-
-import (
- "fmt"
- "log"
- "sort"
- "time"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/autoscaling"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsAutoscalingGroups() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsAutoscalingGroupsRead,
-
- Schema: map[string]*schema.Schema{
- "names": {
- Type: schema.TypeList,
- Computed: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
- "filter": {
- Type: schema.TypeSet,
- Optional: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "name": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
- "values": &schema.Schema{
- Type: schema.TypeSet,
- Required: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- Set: schema.HashString,
- },
- },
- },
- },
- },
- }
-}
-
-func dataSourceAwsAutoscalingGroupsRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).autoscalingconn
-
- log.Printf("[DEBUG] Reading Autoscaling Groups.")
- d.SetId(time.Now().UTC().String())
-
- var raw []string
-
- tf := d.Get("filter").(*schema.Set)
- if tf.Len() > 0 {
- out, err := conn.DescribeTags(&autoscaling.DescribeTagsInput{
- Filters: expandAsgTagFilters(tf.List()),
- })
- if err != nil {
- return err
- }
-
- raw = make([]string, len(out.Tags))
- for i, v := range out.Tags {
- raw[i] = *v.ResourceId
- }
- } else {
-
- resp, err := conn.DescribeAutoScalingGroups(&autoscaling.DescribeAutoScalingGroupsInput{})
- if err != nil {
- return fmt.Errorf("Error fetching Autoscaling Groups: %s", err)
- }
-
- raw = make([]string, len(resp.AutoScalingGroups))
- for i, v := range resp.AutoScalingGroups {
- raw[i] = *v.AutoScalingGroupName
- }
- }
-
- sort.Strings(raw)
-
- if err := d.Set("names", raw); err != nil {
- return fmt.Errorf("[WARN] Error setting Autoscaling Group Names: %s", err)
- }
-
- return nil
-
-}
-
-func expandAsgTagFilters(in []interface{}) []*autoscaling.Filter {
- out := make([]*autoscaling.Filter, len(in), len(in))
- for i, filter := range in {
- m := filter.(map[string]interface{})
- values := expandStringList(m["values"].(*schema.Set).List())
-
- out[i] = &autoscaling.Filter{
- Name: aws.String(m["name"].(string)),
- Values: values,
- }
- }
- return out
-}
diff --git a/builtin/providers/aws/data_source_aws_autoscaling_groups_test.go b/builtin/providers/aws/data_source_aws_autoscaling_groups_test.go
deleted file mode 100644
index 3a6ba7644..000000000
--- a/builtin/providers/aws/data_source_aws_autoscaling_groups_test.go
+++ /dev/null
@@ -1,217 +0,0 @@
-package aws
-
-import (
- "fmt"
- "reflect"
- "sort"
- "strconv"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAWSAutoscalingGroups_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsAutoscalingGroupsConfig(acctest.RandInt(), acctest.RandInt(), acctest.RandInt()),
- },
- {
- Config: testAccCheckAwsAutoscalingGroupsConfigWithDataSource(acctest.RandInt(), acctest.RandInt(), acctest.RandInt()),
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsAutoscalingGroups("data.aws_autoscaling_groups.group_list"),
- resource.TestCheckResourceAttr("data.aws_autoscaling_groups.group_list", "names.#", "3"),
- ),
- },
- },
- })
-}
-
-func testAccCheckAwsAutoscalingGroups(n string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Can't find ASG resource: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("AZ resource ID not set.")
- }
-
- actual, err := testAccCheckAwsAutoscalingGroupsAvailable(rs.Primary.Attributes)
- if err != nil {
- return err
- }
-
- expected := actual
- sort.Strings(expected)
- if reflect.DeepEqual(expected, actual) != true {
- return fmt.Errorf("ASG not sorted - expected %v, got %v", expected, actual)
- }
- return nil
- }
-}
-
-func testAccCheckAwsAutoscalingGroupsAvailable(attrs map[string]string) ([]string, error) {
- v, ok := attrs["names.#"]
- if !ok {
- return nil, fmt.Errorf("Available ASG list is missing.")
- }
- qty, err := strconv.Atoi(v)
- if err != nil {
- return nil, err
- }
- if qty < 1 {
- return nil, fmt.Errorf("No ASG found in region, this is probably a bug.")
- }
- zones := make([]string, qty)
- for n := range zones {
- zone, ok := attrs["names."+strconv.Itoa(n)]
- if !ok {
- return nil, fmt.Errorf("ASG list corrupt, this is definitely a bug.")
- }
- zones[n] = zone
- }
- return zones, nil
-}
-
-func testAccCheckAwsAutoscalingGroupsConfig(rInt1, rInt2, rInt3 int) string {
- return fmt.Sprintf(`
-resource "aws_launch_configuration" "foobar" {
- image_id = "ami-21f78e11"
- instance_type = "t1.micro"
-}
-
-resource "aws_autoscaling_group" "bar" {
- availability_zones = ["us-west-2a"]
- name = "test-asg-%d"
- max_size = 1
- min_size = 0
- health_check_type = "EC2"
- desired_capacity = 0
- force_delete = true
-
- launch_configuration = "${aws_launch_configuration.foobar.name}"
-
- tag {
- key = "Foo"
- value = "foo-bar"
- propagate_at_launch = true
- }
-}
-
-resource "aws_autoscaling_group" "foo" {
- availability_zones = ["us-west-2b"]
- name = "test-asg-%d"
- max_size = 1
- min_size = 0
- health_check_type = "EC2"
- desired_capacity = 0
- force_delete = true
-
- launch_configuration = "${aws_launch_configuration.foobar.name}"
-
- tag {
- key = "Foo"
- value = "foo-bar"
- propagate_at_launch = true
- }
-}
-
-resource "aws_autoscaling_group" "barbaz" {
- availability_zones = ["us-west-2c"]
- name = "test-asg-%d"
- max_size = 1
- min_size = 0
- health_check_type = "EC2"
- desired_capacity = 0
- force_delete = true
-
- launch_configuration = "${aws_launch_configuration.foobar.name}"
-
- tag {
- key = "Foo"
- value = "foo-bar"
- propagate_at_launch = true
- }
-}`, rInt1, rInt2, rInt3)
-}
-
-func testAccCheckAwsAutoscalingGroupsConfigWithDataSource(rInt1, rInt2, rInt3 int) string {
- return fmt.Sprintf(`
-resource "aws_launch_configuration" "foobar" {
- image_id = "ami-21f78e11"
- instance_type = "t1.micro"
-}
-
-resource "aws_autoscaling_group" "bar" {
- availability_zones = ["us-west-2a"]
- name = "test-asg-%d"
- max_size = 1
- min_size = 0
- health_check_type = "EC2"
- desired_capacity = 0
- force_delete = true
-
- launch_configuration = "${aws_launch_configuration.foobar.name}"
-
- tag {
- key = "Foo"
- value = "foo-bar"
- propagate_at_launch = true
- }
-}
-
-resource "aws_autoscaling_group" "foo" {
- availability_zones = ["us-west-2b"]
- name = "test-asg-%d"
- max_size = 1
- min_size = 0
- health_check_type = "EC2"
- desired_capacity = 0
- force_delete = true
-
- launch_configuration = "${aws_launch_configuration.foobar.name}"
-
- tag {
- key = "Foo"
- value = "foo-bar"
- propagate_at_launch = true
- }
-}
-
-resource "aws_autoscaling_group" "barbaz" {
- availability_zones = ["us-west-2c"]
- name = "test-asg-%d"
- max_size = 1
- min_size = 0
- health_check_type = "EC2"
- desired_capacity = 0
- force_delete = true
-
- launch_configuration = "${aws_launch_configuration.foobar.name}"
-
- tag {
- key = "Foo"
- value = "foo-bar"
- propagate_at_launch = true
- }
-}
-
-data "aws_autoscaling_groups" "group_list" {
- filter {
- name = "key"
- values = ["Foo"]
- }
-
- filter {
- name = "value"
- values = ["foo-bar"]
- }
-}
-`, rInt1, rInt2, rInt3)
-}
diff --git a/builtin/providers/aws/data_source_aws_availability_zone.go b/builtin/providers/aws/data_source_aws_availability_zone.go
deleted file mode 100644
index edab7c926..000000000
--- a/builtin/providers/aws/data_source_aws_availability_zone.go
+++ /dev/null
@@ -1,89 +0,0 @@
-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 dataSourceAwsAvailabilityZone() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsAvailabilityZoneRead,
-
- Schema: map[string]*schema.Schema{
- "name": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
-
- "region": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
-
- "name_suffix": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
-
- "state": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- },
- }
-}
-
-func dataSourceAwsAvailabilityZoneRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).ec2conn
-
- req := &ec2.DescribeAvailabilityZonesInput{}
-
- if name := d.Get("name"); name != "" {
- req.ZoneNames = []*string{aws.String(name.(string))}
- }
-
- req.Filters = buildEC2AttributeFilterList(
- map[string]string{
- "state": d.Get("state").(string),
- },
- )
- if len(req.Filters) == 0 {
- // Don't send an empty filters list; the EC2 API won't accept it.
- req.Filters = nil
- }
-
- log.Printf("[DEBUG] DescribeAvailabilityZones %s\n", req)
- resp, err := conn.DescribeAvailabilityZones(req)
- if err != nil {
- return err
- }
- if resp == nil || len(resp.AvailabilityZones) == 0 {
- return fmt.Errorf("no matching AZ found")
- }
- if len(resp.AvailabilityZones) > 1 {
- return fmt.Errorf("multiple AZs matched; use additional constraints to reduce matches to a single AZ")
- }
-
- az := resp.AvailabilityZones[0]
-
- // As a convenience when working with AZs generically, we expose
- // the AZ suffix alone, without the region name.
- // This can be used e.g. to create lookup tables by AZ letter that
- // work regardless of region.
- nameSuffix := (*az.ZoneName)[len(*az.RegionName):]
-
- d.SetId(*az.ZoneName)
- d.Set("id", az.ZoneName)
- d.Set("name", az.ZoneName)
- d.Set("name_suffix", nameSuffix)
- d.Set("region", az.RegionName)
- d.Set("state", az.State)
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_availability_zone_test.go b/builtin/providers/aws/data_source_aws_availability_zone_test.go
deleted file mode 100644
index 8808011db..000000000
--- a/builtin/providers/aws/data_source_aws_availability_zone_test.go
+++ /dev/null
@@ -1,57 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccDataSourceAwsAvailabilityZone(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDataSourceAwsAvailabilityZoneConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccDataSourceAwsAvailabilityZoneCheck("data.aws_availability_zone.by_name"),
- ),
- },
- },
- })
-}
-
-func testAccDataSourceAwsAvailabilityZoneCheck(name string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[name]
- if !ok {
- return fmt.Errorf("root module has no resource called %s", name)
- }
-
- attr := rs.Primary.Attributes
-
- if attr["name"] != "us-west-2a" {
- return fmt.Errorf("bad name %s", attr["name"])
- }
- if attr["name_suffix"] != "a" {
- return fmt.Errorf("bad name_suffix %s", attr["name_suffix"])
- }
- if attr["region"] != "us-west-2" {
- return fmt.Errorf("bad region %s", attr["region"])
- }
-
- return nil
- }
-}
-
-const testAccDataSourceAwsAvailabilityZoneConfig = `
-provider "aws" {
- region = "us-west-2"
-}
-
-data "aws_availability_zone" "by_name" {
- name = "us-west-2a"
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_availability_zones.go b/builtin/providers/aws/data_source_aws_availability_zones.go
deleted file mode 100644
index dcc09438f..000000000
--- a/builtin/providers/aws/data_source_aws_availability_zones.go
+++ /dev/null
@@ -1,87 +0,0 @@
-package aws
-
-import (
- "fmt"
- "log"
- "sort"
- "time"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/ec2"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsAvailabilityZones() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsAvailabilityZonesRead,
-
- Schema: map[string]*schema.Schema{
- "names": {
- Type: schema.TypeList,
- Computed: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
- "state": {
- Type: schema.TypeString,
- Optional: true,
- ValidateFunc: validateStateType,
- },
- },
- }
-}
-
-func dataSourceAwsAvailabilityZonesRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).ec2conn
-
- log.Printf("[DEBUG] Reading Availability Zones.")
- d.SetId(time.Now().UTC().String())
-
- request := &ec2.DescribeAvailabilityZonesInput{}
-
- if v, ok := d.GetOk("state"); ok {
- request.Filters = []*ec2.Filter{
- {
- Name: aws.String("state"),
- Values: []*string{aws.String(v.(string))},
- },
- }
- }
-
- log.Printf("[DEBUG] Availability Zones request options: %#v", *request)
-
- resp, err := conn.DescribeAvailabilityZones(request)
- if err != nil {
- return fmt.Errorf("Error fetching Availability Zones: %s", err)
- }
-
- raw := make([]string, len(resp.AvailabilityZones))
- for i, v := range resp.AvailabilityZones {
- raw[i] = *v.ZoneName
- }
-
- sort.Strings(raw)
-
- if err := d.Set("names", raw); err != nil {
- return fmt.Errorf("[WARN] Error setting Availability Zones: %s", err)
- }
-
- return nil
-}
-
-func validateStateType(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
-
- validState := map[string]bool{
- "available": true,
- "information": true,
- "impaired": true,
- "unavailable": true,
- }
-
- if !validState[value] {
- errors = append(errors, fmt.Errorf(
- "%q contains an invalid Availability Zone state %q. Valid states are: %q, %q, %q and %q.",
- k, value, "available", "information", "impaired", "unavailable"))
- }
- return
-}
diff --git a/builtin/providers/aws/data_source_aws_availability_zones_test.go b/builtin/providers/aws/data_source_aws_availability_zones_test.go
deleted file mode 100644
index a65ec511f..000000000
--- a/builtin/providers/aws/data_source_aws_availability_zones_test.go
+++ /dev/null
@@ -1,151 +0,0 @@
-package aws
-
-import (
- "fmt"
- "reflect"
- "sort"
- "strconv"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAWSAvailabilityZones_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsAvailabilityZonesConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsAvailabilityZonesMeta("data.aws_availability_zones.availability_zones"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSAvailabilityZones_stateFilter(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsAvailabilityZonesStateConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsAvailabilityZoneState("data.aws_availability_zones.state_filter"),
- ),
- },
- },
- })
-}
-
-func TestResourceCheckAwsAvailabilityZones_validateStateType(t *testing.T) {
- _, errors := validateStateType("incorrect", "state")
- if len(errors) == 0 {
- t.Fatalf("Expected to trigger a validation error")
- }
-
- var testCases = []struct {
- Value string
- ErrCount int
- }{
- {
- Value: "available",
- ErrCount: 0,
- },
- {
- Value: "unavailable",
- ErrCount: 0,
- },
- }
-
- for _, tc := range testCases {
- _, errors := validateStateType(tc.Value, "state")
- if len(errors) != tc.ErrCount {
- t.Fatalf("Expected %q not to trigger a validation error.", tc.Value)
- }
- }
-}
-
-func testAccCheckAwsAvailabilityZonesMeta(n string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Can't find AZ resource: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("AZ resource ID not set.")
- }
-
- actual, err := testAccCheckAwsAvailabilityZonesBuildAvailable(rs.Primary.Attributes)
- if err != nil {
- return err
- }
-
- expected := actual
- sort.Strings(expected)
- if reflect.DeepEqual(expected, actual) != true {
- return fmt.Errorf("AZs not sorted - expected %v, got %v", expected, actual)
- }
- return nil
- }
-}
-
-func testAccCheckAwsAvailabilityZoneState(n string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Can't find AZ resource: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("AZ resource ID not set.")
- }
-
- if _, ok := rs.Primary.Attributes["state"]; !ok {
- return fmt.Errorf("AZs state filter is missing, should be set.")
- }
-
- _, err := testAccCheckAwsAvailabilityZonesBuildAvailable(rs.Primary.Attributes)
- if err != nil {
- return err
- }
- return nil
- }
-}
-
-func testAccCheckAwsAvailabilityZonesBuildAvailable(attrs map[string]string) ([]string, error) {
- v, ok := attrs["names.#"]
- if !ok {
- return nil, fmt.Errorf("Available AZ list is missing.")
- }
- qty, err := strconv.Atoi(v)
- if err != nil {
- return nil, err
- }
- if qty < 1 {
- return nil, fmt.Errorf("No AZs found in region, this is probably a bug.")
- }
- zones := make([]string, qty)
- for n := range zones {
- zone, ok := attrs["names."+strconv.Itoa(n)]
- if !ok {
- return nil, fmt.Errorf("AZ list corrupt, this is definitely a bug.")
- }
- zones[n] = zone
- }
- return zones, nil
-}
-
-const testAccCheckAwsAvailabilityZonesConfig = `
-data "aws_availability_zones" "availability_zones" { }
-`
-
-const testAccCheckAwsAvailabilityZonesStateConfig = `
-data "aws_availability_zones" "state_filter" {
- state = "available"
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_billing_service_account.go b/builtin/providers/aws/data_source_aws_billing_service_account.go
deleted file mode 100644
index 23ec40843..000000000
--- a/builtin/providers/aws/data_source_aws_billing_service_account.go
+++ /dev/null
@@ -1,31 +0,0 @@
-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
-}
diff --git a/builtin/providers/aws/data_source_aws_billing_service_account_test.go b/builtin/providers/aws/data_source_aws_billing_service_account_test.go
deleted file mode 100644
index 53f9c2df8..000000000
--- a/builtin/providers/aws/data_source_aws_billing_service_account_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSBillingServiceAccount_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsBillingServiceAccountConfig,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr("data.aws_billing_service_account.main", "id", "386209384616"),
- resource.TestCheckResourceAttr("data.aws_billing_service_account.main", "arn", "arn:aws:iam::386209384616:root"),
- ),
- },
- },
- })
-}
-
-const testAccCheckAwsBillingServiceAccountConfig = `
-data "aws_billing_service_account" "main" { }
-`
diff --git a/builtin/providers/aws/data_source_aws_caller_identity.go b/builtin/providers/aws/data_source_aws_caller_identity.go
deleted file mode 100644
index a2adcef34..000000000
--- a/builtin/providers/aws/data_source_aws_caller_identity.go
+++ /dev/null
@@ -1,50 +0,0 @@
-package aws
-
-import (
- "fmt"
- "log"
- "time"
-
- "github.com/aws/aws-sdk-go/service/sts"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsCallerIdentity() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsCallerIdentityRead,
-
- Schema: map[string]*schema.Schema{
- "account_id": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "arn": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "user_id": {
- Type: schema.TypeString,
- Computed: true,
- },
- },
- }
-}
-
-func dataSourceAwsCallerIdentityRead(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AWSClient).stsconn
-
- res, err := client.GetCallerIdentity(&sts.GetCallerIdentityInput{})
- if err != nil {
- return fmt.Errorf("Error getting Caller Identity: %v", err)
- }
-
- log.Printf("[DEBUG] Received Caller Identity: %s", res)
-
- d.SetId(time.Now().UTC().String())
- d.Set("account_id", res.Account)
- d.Set("arn", res.Arn)
- d.Set("user_id", res.UserId)
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_caller_identity_test.go b/builtin/providers/aws/data_source_aws_caller_identity_test.go
deleted file mode 100644
index 100bb4db8..000000000
--- a/builtin/providers/aws/data_source_aws_caller_identity_test.go
+++ /dev/null
@@ -1,56 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAWSCallerIdentity_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsCallerIdentityConfig_basic,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsCallerIdentityAccountId("data.aws_caller_identity.current"),
- ),
- },
- },
- })
-}
-
-func testAccCheckAwsCallerIdentityAccountId(n string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Can't find AccountID resource: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("Account Id resource ID not set.")
- }
-
- expected := testAccProvider.Meta().(*AWSClient).accountid
- if rs.Primary.Attributes["account_id"] != expected {
- return fmt.Errorf("Incorrect Account ID: expected %q, got %q", expected, rs.Primary.Attributes["account_id"])
- }
-
- if rs.Primary.Attributes["user_id"] == "" {
- return fmt.Errorf("UserID expected to not be nil")
- }
-
- if rs.Primary.Attributes["arn"] == "" {
- return fmt.Errorf("ARN expected to not be nil")
- }
-
- return nil
- }
-}
-
-const testAccCheckAwsCallerIdentityConfig_basic = `
-data "aws_caller_identity" "current" { }
-`
diff --git a/builtin/providers/aws/data_source_aws_canonical_user_id.go b/builtin/providers/aws/data_source_aws_canonical_user_id.go
deleted file mode 100644
index ba6a0b098..000000000
--- a/builtin/providers/aws/data_source_aws_canonical_user_id.go
+++ /dev/null
@@ -1,48 +0,0 @@
-package aws
-
-import (
- "fmt"
- "log"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/s3"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsCanonicalUserId() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsCanonicalUserIdRead,
-
- Schema: map[string]*schema.Schema{
- "id": {
- Type: schema.TypeString,
- Computed: true,
- },
- "display_name": {
- Type: schema.TypeString,
- Computed: true,
- },
- },
- }
-}
-
-func dataSourceAwsCanonicalUserIdRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).s3conn
-
- log.Printf("[DEBUG] Listing S3 buckets.")
-
- req := &s3.ListBucketsInput{}
- resp, err := conn.ListBuckets(req)
- if err != nil {
- return err
- }
- if resp == nil || resp.Owner == nil {
- return fmt.Errorf("no canonical user ID found")
- }
-
- d.SetId(aws.StringValue(resp.Owner.ID))
- d.Set("id", resp.Owner.ID)
- d.Set("display_name", resp.Owner.DisplayName)
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_canonical_user_id_test.go b/builtin/providers/aws/data_source_aws_canonical_user_id_test.go
deleted file mode 100644
index c1bd6e598..000000000
--- a/builtin/providers/aws/data_source_aws_canonical_user_id_test.go
+++ /dev/null
@@ -1,52 +0,0 @@
-// make testacc TEST=./builtin/providers/aws/ TESTARGS='-run=TestAccDataSourceAwsCanonicalUserId_'
-
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccDataSourceAwsCanonicalUserId_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAwsCanonicalUserIdConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccDataSourceAwsCanonicalUserIdCheckExists("data.aws_canonical_user_id.current"),
- ),
- },
- },
- })
-}
-
-func testAccDataSourceAwsCanonicalUserIdCheckExists(name string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[name]
- if !ok {
- return fmt.Errorf("Can't find Canonical User ID resource: %s", name)
- }
-
- if rs.Primary.Attributes["id"] == "" {
- return fmt.Errorf("Missing Canonical User ID")
- }
- if rs.Primary.Attributes["display_name"] == "" {
- return fmt.Errorf("Missing Display Name")
- }
-
- return nil
- }
-}
-
-const testAccDataSourceAwsCanonicalUserIdConfig = `
-provider "aws" {
- region = "us-west-2"
-}
-
-data "aws_canonical_user_id" "current" { }
-`
diff --git a/builtin/providers/aws/data_source_aws_cloudformation_stack.go b/builtin/providers/aws/data_source_aws_cloudformation_stack.go
deleted file mode 100644
index b834e0a29..000000000
--- a/builtin/providers/aws/data_source_aws_cloudformation_stack.go
+++ /dev/null
@@ -1,122 +0,0 @@
-package aws
-
-import (
- "fmt"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/cloudformation"
- "github.com/hashicorp/errwrap"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsCloudFormationStack() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsCloudFormationStackRead,
-
- Schema: map[string]*schema.Schema{
- "name": {
- Type: schema.TypeString,
- Required: true,
- },
- "template_body": {
- Type: schema.TypeString,
- Computed: true,
- StateFunc: func(v interface{}) string {
- template, _ := normalizeCloudFormationTemplate(v)
- return template
- },
- },
- "capabilities": {
- Type: schema.TypeSet,
- Computed: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- Set: schema.HashString,
- },
- "description": {
- Type: schema.TypeString,
- Computed: true,
- },
- "disable_rollback": {
- Type: schema.TypeBool,
- Computed: true,
- },
- "notification_arns": {
- Type: schema.TypeSet,
- Computed: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- Set: schema.HashString,
- },
- "parameters": {
- Type: schema.TypeMap,
- Computed: true,
- },
- "outputs": {
- Type: schema.TypeMap,
- Computed: true,
- },
- "timeout_in_minutes": {
- Type: schema.TypeInt,
- Computed: true,
- },
- "iam_role_arn": {
- Type: schema.TypeString,
- Computed: true,
- },
- "tags": {
- Type: schema.TypeMap,
- Computed: true,
- },
- },
- }
-}
-
-func dataSourceAwsCloudFormationStackRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).cfconn
- name := d.Get("name").(string)
- input := cloudformation.DescribeStacksInput{
- StackName: aws.String(name),
- }
-
- out, err := conn.DescribeStacks(&input)
- if err != nil {
- return fmt.Errorf("Failed describing CloudFormation stack (%s): %s", name, err)
- }
- if l := len(out.Stacks); l != 1 {
- return fmt.Errorf("Expected 1 CloudFormation stack (%s), found %d", name, l)
- }
- stack := out.Stacks[0]
- d.SetId(*stack.StackId)
-
- d.Set("description", stack.Description)
- d.Set("disable_rollback", stack.DisableRollback)
- d.Set("timeout_in_minutes", stack.TimeoutInMinutes)
- d.Set("iam_role_arn", stack.RoleARN)
-
- if len(stack.NotificationARNs) > 0 {
- d.Set("notification_arns", schema.NewSet(schema.HashString, flattenStringList(stack.NotificationARNs)))
- }
-
- d.Set("parameters", flattenAllCloudFormationParameters(stack.Parameters))
- d.Set("tags", flattenCloudFormationTags(stack.Tags))
- d.Set("outputs", flattenCloudFormationOutputs(stack.Outputs))
-
- if len(stack.Capabilities) > 0 {
- d.Set("capabilities", schema.NewSet(schema.HashString, flattenStringList(stack.Capabilities)))
- }
-
- tInput := cloudformation.GetTemplateInput{
- StackName: aws.String(name),
- }
- tOut, err := conn.GetTemplate(&tInput)
- if err != nil {
- return err
- }
-
- template, err := normalizeCloudFormationTemplate(*tOut.TemplateBody)
- if err != nil {
- return errwrap.Wrapf("template body contains an invalid JSON or YAML: {{err}}", err)
- }
- d.Set("template_body", template)
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_cloudformation_stack_test.go b/builtin/providers/aws/data_source_aws_cloudformation_stack_test.go
deleted file mode 100644
index 4a4cde785..000000000
--- a/builtin/providers/aws/data_source_aws_cloudformation_stack_test.go
+++ /dev/null
@@ -1,142 +0,0 @@
-package aws
-
-import (
- "regexp"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSCloudFormationStack_dataSource_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccCheckAwsCloudFormationStackDataSourceConfig_basic,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr("data.aws_cloudformation_stack.network", "outputs.%", "1"),
- resource.TestMatchResourceAttr("data.aws_cloudformation_stack.network", "outputs.VPCId",
- regexp.MustCompile("^vpc-[a-z0-9]{8}$")),
- resource.TestCheckResourceAttr("data.aws_cloudformation_stack.network", "capabilities.#", "0"),
- resource.TestCheckResourceAttr("data.aws_cloudformation_stack.network", "disable_rollback", "false"),
- resource.TestCheckResourceAttr("data.aws_cloudformation_stack.network", "notification_arns.#", "0"),
- resource.TestCheckResourceAttr("data.aws_cloudformation_stack.network", "parameters.%", "1"),
- resource.TestCheckResourceAttr("data.aws_cloudformation_stack.network", "parameters.CIDR", "10.10.10.0/24"),
- resource.TestCheckResourceAttr("data.aws_cloudformation_stack.network", "timeout_in_minutes", "6"),
- resource.TestCheckResourceAttr("data.aws_cloudformation_stack.network", "tags.%", "2"),
- resource.TestCheckResourceAttr("data.aws_cloudformation_stack.network", "tags.Name", "Form the Cloud"),
- resource.TestCheckResourceAttr("data.aws_cloudformation_stack.network", "tags.Second", "meh"),
- ),
- },
- },
- })
-}
-
-const testAccCheckAwsCloudFormationStackDataSourceConfig_basic = `
-resource "aws_cloudformation_stack" "cfs" {
- name = "tf-acc-ds-networking-stack"
- parameters {
- CIDR = "10.10.10.0/24"
- }
- timeout_in_minutes = 6
- template_body = < 1 {
- return fmt.Errorf("Your query returned more than one result. Please try a more specific search criteria.")
- }
-
- dbInstance := *resp.DBInstances[0]
-
- d.SetId(d.Get("db_instance_identifier").(string))
-
- d.Set("allocated_storage", dbInstance.AllocatedStorage)
- d.Set("auto_minor_upgrade_enabled", dbInstance.AutoMinorVersionUpgrade)
- d.Set("availability_zone", dbInstance.AvailabilityZone)
- d.Set("backup_retention_period", dbInstance.BackupRetentionPeriod)
- d.Set("db_cluster_identifier", dbInstance.DBClusterIdentifier)
- d.Set("db_instance_arn", dbInstance.DBClusterIdentifier)
- d.Set("db_instance_class", dbInstance.DBInstanceClass)
- d.Set("db_name", dbInstance.DBName)
-
- var parameterGroups []string
- for _, v := range dbInstance.DBParameterGroups {
- parameterGroups = append(parameterGroups, *v.DBParameterGroupName)
- }
- if err := d.Set("db_parameter_groups", parameterGroups); err != nil {
- return fmt.Errorf("[DEBUG] Error setting db_parameter_groups attribute: %#v, error: %#v", parameterGroups, err)
- }
-
- var dbSecurityGroups []string
- for _, v := range dbInstance.DBSecurityGroups {
- dbSecurityGroups = append(dbSecurityGroups, *v.DBSecurityGroupName)
- }
- if err := d.Set("db_security_groups", dbSecurityGroups); err != nil {
- return fmt.Errorf("[DEBUG] Error setting db_security_groups attribute: %#v, error: %#v", dbSecurityGroups, err)
- }
-
- d.Set("db_subnet_group", dbInstance.DBSubnetGroup)
- d.Set("db_instance_port", dbInstance.DbInstancePort)
- d.Set("engine", dbInstance.Engine)
- d.Set("engine_version", dbInstance.EngineVersion)
- d.Set("iops", dbInstance.Iops)
- d.Set("kms_key_id", dbInstance.KmsKeyId)
- d.Set("license_model", dbInstance.LicenseModel)
- d.Set("master_username", dbInstance.MasterUsername)
- d.Set("monitoring_interval", dbInstance.MonitoringInterval)
- d.Set("monitoring_role_arn", dbInstance.MonitoringRoleArn)
- d.Set("address", dbInstance.Endpoint.Address)
- d.Set("port", dbInstance.Endpoint.Port)
- d.Set("hosted_zone_id", dbInstance.Endpoint.HostedZoneId)
- d.Set("endpoint", fmt.Sprintf("%s:%d", *dbInstance.Endpoint.Address, *dbInstance.Endpoint.Port))
-
- var optionGroups []string
- for _, v := range dbInstance.OptionGroupMemberships {
- optionGroups = append(optionGroups, *v.OptionGroupName)
- }
- if err := d.Set("option_group_memberships", optionGroups); err != nil {
- return fmt.Errorf("[DEBUG] Error setting option_group_memberships attribute: %#v, error: %#v", optionGroups, err)
- }
-
- d.Set("preferred_backup_window", dbInstance.PreferredBackupWindow)
- d.Set("preferred_maintenance_window", dbInstance.PreferredMaintenanceWindow)
- d.Set("publicly_accessible", dbInstance.PubliclyAccessible)
- d.Set("storage_encrypted", dbInstance.StorageEncrypted)
- d.Set("storage_type", dbInstance.StorageType)
- d.Set("timezone", dbInstance.Timezone)
- d.Set("replicate_source_db", dbInstance.ReadReplicaSourceDBInstanceIdentifier)
-
- var vpcSecurityGroups []string
- for _, v := range dbInstance.VpcSecurityGroups {
- vpcSecurityGroups = append(vpcSecurityGroups, *v.VpcSecurityGroupId)
- }
- if err := d.Set("vpc_security_groups", vpcSecurityGroups); err != nil {
- return fmt.Errorf("[DEBUG] Error setting vpc_security_groups attribute: %#v, error: %#v", vpcSecurityGroups, err)
- }
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_db_instance_test.go b/builtin/providers/aws/data_source_aws_db_instance_test.go
deleted file mode 100644
index 5d3a200ec..000000000
--- a/builtin/providers/aws/data_source_aws_db_instance_test.go
+++ /dev/null
@@ -1,71 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSDataDbInstance_basic(t *testing.T) {
- rInt := acctest.RandInt()
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSDBInstanceConfigWithDataSource(rInt),
- Check: resource.ComposeAggregateTestCheckFunc(
- resource.TestCheckResourceAttrSet("data.aws_db_instance.bar", "allocated_storage"),
- resource.TestCheckResourceAttrSet("data.aws_db_instance.bar", "engine"),
- resource.TestCheckResourceAttrSet("data.aws_db_instance.bar", "db_instance_class"),
- resource.TestCheckResourceAttrSet("data.aws_db_instance.bar", "db_name"),
- resource.TestCheckResourceAttrSet("data.aws_db_instance.bar", "master_username"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSDataDbInstance_endpoint(t *testing.T) {
- rInt := acctest.RandInt()
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSDBInstanceConfigWithDataSource(rInt),
- Check: resource.ComposeAggregateTestCheckFunc(
- resource.TestCheckResourceAttrSet("data.aws_db_instance.bar", "address"),
- resource.TestCheckResourceAttrSet("data.aws_db_instance.bar", "port"),
- resource.TestCheckResourceAttrSet("data.aws_db_instance.bar", "hosted_zone_id"),
- resource.TestCheckResourceAttrSet("data.aws_db_instance.bar", "endpoint"),
- ),
- },
- },
- })
-}
-
-func testAccAWSDBInstanceConfigWithDataSource(rInt int) string {
- return fmt.Sprintf(`
-resource "aws_db_instance" "bar" {
- identifier = "datasource-test-terraform-%d"
-
- allocated_storage = 10
- engine = "MySQL"
- instance_class = "db.m1.small"
- name = "baz"
- password = "barbarbarbar"
- username = "foo"
-
- backup_retention_period = 0
- skip_final_snapshot = true
-}
-
-data "aws_db_instance" "bar" {
- db_instance_identifier = "${aws_db_instance.bar.identifier}"
-}
-
-`, rInt)
-}
diff --git a/builtin/providers/aws/data_source_aws_db_snapshot.go b/builtin/providers/aws/data_source_aws_db_snapshot.go
deleted file mode 100644
index 1f381e405..000000000
--- a/builtin/providers/aws/data_source_aws_db_snapshot.go
+++ /dev/null
@@ -1,217 +0,0 @@
-package aws
-
-import (
- "fmt"
- "log"
- "sort"
- "time"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/rds"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsDbSnapshot() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsDbSnapshotRead,
-
- Schema: map[string]*schema.Schema{
- //selection criteria
- "db_instance_identifier": {
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
-
- "db_snapshot_identifier": {
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
-
- "snapshot_type": {
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
-
- "include_shared": {
- Type: schema.TypeBool,
- Optional: true,
- ForceNew: true,
- Default: false,
- },
-
- "include_public": {
- Type: schema.TypeBool,
- Optional: true,
- ForceNew: true,
- Default: false,
- },
- "most_recent": {
- Type: schema.TypeBool,
- Optional: true,
- Default: false,
- ForceNew: true,
- },
-
- //Computed values returned
- "allocated_storage": {
- Type: schema.TypeInt,
- Computed: true,
- },
- "availability_zone": {
- Type: schema.TypeString,
- Computed: true,
- },
- "db_snapshot_arn": {
- Type: schema.TypeString,
- Computed: true,
- },
- "encrypted": {
- Type: schema.TypeBool,
- Computed: true,
- },
- "engine": {
- Type: schema.TypeString,
- Computed: true,
- },
- "engine_version": {
- Type: schema.TypeString,
- Computed: true,
- },
- "iops": {
- Type: schema.TypeInt,
- Computed: true,
- },
- "kms_key_id": {
- Type: schema.TypeString,
- Computed: true,
- },
- "license_model": {
- Type: schema.TypeString,
- Computed: true,
- },
- "option_group_name": {
- Type: schema.TypeString,
- Computed: true,
- },
- "port": {
- Type: schema.TypeInt,
- Computed: true,
- },
- "source_db_snapshot_identifier": {
- Type: schema.TypeString,
- Computed: true,
- },
- "source_region": {
- Type: schema.TypeString,
- Computed: true,
- },
- "snapshot_create_time": {
- Type: schema.TypeString,
- Computed: true,
- },
- "status": {
- Type: schema.TypeString,
- Computed: true,
- },
- "storage_type": {
- Type: schema.TypeString,
- Computed: true,
- },
- "vpc_id": {
- Type: schema.TypeString,
- Computed: true,
- },
- },
- }
-}
-
-func dataSourceAwsDbSnapshotRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).rdsconn
-
- instanceIdentifier, instanceIdentifierOk := d.GetOk("db_instance_identifier")
- snapshotIdentifier, snapshotIdentifierOk := d.GetOk("db_snapshot_identifier")
-
- if !instanceIdentifierOk && !snapshotIdentifierOk {
- return fmt.Errorf("One of db_snapshot_indentifier or db_instance_identifier must be assigned")
- }
-
- params := &rds.DescribeDBSnapshotsInput{
- IncludePublic: aws.Bool(d.Get("include_public").(bool)),
- IncludeShared: aws.Bool(d.Get("include_shared").(bool)),
- }
- if v, ok := d.GetOk("snapshot_type"); ok {
- params.SnapshotType = aws.String(v.(string))
- }
- if instanceIdentifierOk {
- params.DBInstanceIdentifier = aws.String(instanceIdentifier.(string))
- }
- if snapshotIdentifierOk {
- params.DBSnapshotIdentifier = aws.String(snapshotIdentifier.(string))
- }
-
- resp, err := conn.DescribeDBSnapshots(params)
- if err != nil {
- return err
- }
-
- if len(resp.DBSnapshots) < 1 {
- return fmt.Errorf("Your query returned no results. Please change your search criteria and try again.")
- }
-
- var snapshot *rds.DBSnapshot
- if len(resp.DBSnapshots) > 1 {
- recent := d.Get("most_recent").(bool)
- log.Printf("[DEBUG] aws_db_snapshot - multiple results found and `most_recent` is set to: %t", recent)
- if recent {
- snapshot = mostRecentDbSnapshot(resp.DBSnapshots)
- } else {
- return fmt.Errorf("Your query returned more than one result. Please try a more specific search criteria.")
- }
- } else {
- snapshot = resp.DBSnapshots[0]
- }
-
- return dbSnapshotDescriptionAttributes(d, snapshot)
-}
-
-type rdsSnapshotSort []*rds.DBSnapshot
-
-func (a rdsSnapshotSort) Len() int { return len(a) }
-func (a rdsSnapshotSort) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
-func (a rdsSnapshotSort) Less(i, j int) bool {
- return (*a[i].SnapshotCreateTime).Before(*a[j].SnapshotCreateTime)
-}
-
-func mostRecentDbSnapshot(snapshots []*rds.DBSnapshot) *rds.DBSnapshot {
- sortedSnapshots := snapshots
- sort.Sort(rdsSnapshotSort(sortedSnapshots))
- return sortedSnapshots[len(sortedSnapshots)-1]
-}
-
-func dbSnapshotDescriptionAttributes(d *schema.ResourceData, snapshot *rds.DBSnapshot) error {
- d.SetId(*snapshot.DBInstanceIdentifier)
- d.Set("db_instance_identifier", snapshot.DBInstanceIdentifier)
- d.Set("db_snapshot_identifier", snapshot.DBSnapshotIdentifier)
- d.Set("snapshot_type", snapshot.SnapshotType)
- d.Set("allocated_storage", snapshot.AllocatedStorage)
- d.Set("availability_zone", snapshot.AvailabilityZone)
- d.Set("db_snapshot_arn", snapshot.DBSnapshotArn)
- d.Set("encrypted", snapshot.Encrypted)
- d.Set("engine", snapshot.Engine)
- d.Set("engine_version", snapshot.EngineVersion)
- d.Set("iops", snapshot.Iops)
- d.Set("kms_key_id", snapshot.KmsKeyId)
- d.Set("license_model", snapshot.LicenseModel)
- d.Set("option_group_name", snapshot.OptionGroupName)
- d.Set("port", snapshot.Port)
- d.Set("source_db_snapshot_identifier", snapshot.SourceDBSnapshotIdentifier)
- d.Set("source_region", snapshot.SourceRegion)
- d.Set("status", snapshot.Status)
- d.Set("vpc_id", snapshot.VpcId)
- d.Set("snapshot_create_time", snapshot.SnapshotCreateTime.Format(time.RFC3339))
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_db_snapshot_test.go b/builtin/providers/aws/data_source_aws_db_snapshot_test.go
deleted file mode 100644
index c222136cd..000000000
--- a/builtin/providers/aws/data_source_aws_db_snapshot_test.go
+++ /dev/null
@@ -1,74 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAWSDbSnapshotDataSource_basic(t *testing.T) {
- rInt := acctest.RandInt()
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsDbSnapshotDataSourceConfig(rInt),
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsDbSnapshotDataSourceID("data.aws_db_snapshot.snapshot"),
- ),
- },
- },
- })
-}
-
-func testAccCheckAwsDbSnapshotDataSourceID(n string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Can't find Volume data source: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("Snapshot data source ID not set")
- }
- return nil
- }
-}
-
-func testAccCheckAwsDbSnapshotDataSourceConfig(rInt int) string {
- return fmt.Sprintf(`
-resource "aws_db_instance" "bar" {
- allocated_storage = 10
- engine = "MySQL"
- engine_version = "5.6.21"
- instance_class = "db.t1.micro"
- name = "baz"
- password = "barbarbarbar"
- username = "foo"
- skip_final_snapshot = true
-
- # Maintenance Window is stored in lower case in the API, though not strictly
- # documented. Terraform will downcase this to match (as opposed to throw a
- # validation error).
- maintenance_window = "Fri:09:00-Fri:09:30"
-
- backup_retention_period = 0
-
- parameter_group_name = "default.mysql5.6"
-}
-
-data "aws_db_snapshot" "snapshot" {
- most_recent = "true"
- db_snapshot_identifier = "${aws_db_snapshot.test.id}"
-}
-
-
-resource "aws_db_snapshot" "test" {
- db_instance_identifier = "${aws_db_instance.bar.id}"
- db_snapshot_identifier = "testsnapshot%d"
-}`, rInt)
-}
diff --git a/builtin/providers/aws/data_source_aws_ebs_snapshot.go b/builtin/providers/aws/data_source_aws_ebs_snapshot.go
deleted file mode 100644
index c0e386643..000000000
--- a/builtin/providers/aws/data_source_aws_ebs_snapshot.go
+++ /dev/null
@@ -1,162 +0,0 @@
-package aws
-
-import (
- "fmt"
- "log"
-
- "github.com/aws/aws-sdk-go/service/ec2"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsEbsSnapshot() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsEbsSnapshotRead,
-
- Schema: map[string]*schema.Schema{
- //selection criteria
- "filter": dataSourceFiltersSchema(),
- "most_recent": {
- Type: schema.TypeBool,
- Optional: true,
- Default: false,
- ForceNew: true,
- },
- "owners": {
- Type: schema.TypeList,
- Optional: true,
- ForceNew: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
- "snapshot_ids": {
- Type: schema.TypeList,
- Optional: true,
- ForceNew: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
- "restorable_by_user_ids": {
- Type: schema.TypeList,
- Optional: true,
- ForceNew: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
- //Computed values returned
- "snapshot_id": {
- Type: schema.TypeString,
- Computed: true,
- },
- "volume_id": {
- Type: schema.TypeString,
- Computed: true,
- },
- "state": {
- Type: schema.TypeString,
- Computed: true,
- },
- "owner_id": {
- Type: schema.TypeString,
- Computed: true,
- },
- "owner_alias": {
- Type: schema.TypeString,
- Computed: true,
- },
- "encrypted": {
- Type: schema.TypeBool,
- Computed: true,
- },
- "description": {
- Type: schema.TypeString,
- Computed: true,
- },
- "volume_size": {
- Type: schema.TypeInt,
- Computed: true,
- },
- "kms_key_id": {
- Type: schema.TypeString,
- Computed: true,
- },
- "data_encryption_key_id": {
- Type: schema.TypeString,
- Computed: true,
- },
- "tags": dataSourceTagsSchema(),
- },
- }
-}
-
-func dataSourceAwsEbsSnapshotRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).ec2conn
-
- restorableUsers, restorableUsersOk := d.GetOk("restorable_by_user_ids")
- filters, filtersOk := d.GetOk("filter")
- snapshotIds, snapshotIdsOk := d.GetOk("snapshot_ids")
- owners, ownersOk := d.GetOk("owners")
-
- if !restorableUsersOk && !filtersOk && !snapshotIdsOk && !ownersOk {
- return fmt.Errorf("One of snapshot_ids, filters, restorable_by_user_ids, or owners must be assigned")
- }
-
- params := &ec2.DescribeSnapshotsInput{}
- if restorableUsersOk {
- params.RestorableByUserIds = expandStringList(restorableUsers.([]interface{}))
- }
- if filtersOk {
- params.Filters = buildAwsDataSourceFilters(filters.(*schema.Set))
- }
- if ownersOk {
- params.OwnerIds = expandStringList(owners.([]interface{}))
- }
- if snapshotIdsOk {
- params.SnapshotIds = expandStringList(snapshotIds.([]interface{}))
- }
-
- resp, err := conn.DescribeSnapshots(params)
- if err != nil {
- return err
- }
-
- var snapshot *ec2.Snapshot
- if len(resp.Snapshots) < 1 {
- return fmt.Errorf("Your query returned no results. Please change your search criteria and try again.")
- }
-
- if len(resp.Snapshots) > 1 {
- recent := d.Get("most_recent").(bool)
- log.Printf("[DEBUG] aws_ebs_snapshot - multiple results found and `most_recent` is set to: %t", recent)
- if recent {
- snapshot = mostRecentSnapshot(resp.Snapshots)
- } else {
- return fmt.Errorf("Your query returned more than one result. Please try a more specific search criteria.")
- }
- } else {
- snapshot = resp.Snapshots[0]
- }
-
- //Single Snapshot found so set to state
- return snapshotDescriptionAttributes(d, snapshot)
-}
-
-func mostRecentSnapshot(snapshots []*ec2.Snapshot) *ec2.Snapshot {
- return sortSnapshots(snapshots)[0]
-}
-
-func snapshotDescriptionAttributes(d *schema.ResourceData, snapshot *ec2.Snapshot) error {
- d.SetId(*snapshot.SnapshotId)
- d.Set("snapshot_id", snapshot.SnapshotId)
- d.Set("volume_id", snapshot.VolumeId)
- d.Set("data_encryption_key_id", snapshot.DataEncryptionKeyId)
- d.Set("description", snapshot.Description)
- d.Set("encrypted", snapshot.Encrypted)
- d.Set("kms_key_id", snapshot.KmsKeyId)
- d.Set("volume_size", snapshot.VolumeSize)
- d.Set("state", snapshot.State)
- d.Set("owner_id", snapshot.OwnerId)
- d.Set("owner_alias", snapshot.OwnerAlias)
-
- if err := d.Set("tags", dataSourceTags(snapshot.Tags)); err != nil {
- return err
- }
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_ebs_snapshot_ids.go b/builtin/providers/aws/data_source_aws_ebs_snapshot_ids.go
deleted file mode 100644
index bd4f2ad8b..000000000
--- a/builtin/providers/aws/data_source_aws_ebs_snapshot_ids.go
+++ /dev/null
@@ -1,77 +0,0 @@
-package aws
-
-import (
- "fmt"
-
- "github.com/aws/aws-sdk-go/service/ec2"
- "github.com/hashicorp/terraform/helper/hashcode"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsEbsSnapshotIds() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsEbsSnapshotIdsRead,
-
- Schema: map[string]*schema.Schema{
- "filter": dataSourceFiltersSchema(),
- "owners": {
- Type: schema.TypeList,
- Optional: true,
- ForceNew: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
- "restorable_by_user_ids": {
- Type: schema.TypeList,
- Optional: true,
- ForceNew: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
- "tags": dataSourceTagsSchema(),
- "ids": &schema.Schema{
- Type: schema.TypeList,
- Computed: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
- },
- }
-}
-
-func dataSourceAwsEbsSnapshotIdsRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).ec2conn
-
- restorableUsers, restorableUsersOk := d.GetOk("restorable_by_user_ids")
- filters, filtersOk := d.GetOk("filter")
- owners, ownersOk := d.GetOk("owners")
-
- if restorableUsers == false && filtersOk == false && ownersOk == false {
- return fmt.Errorf("One of filters, restorable_by_user_ids, or owners must be assigned")
- }
-
- params := &ec2.DescribeSnapshotsInput{}
-
- if restorableUsersOk {
- params.RestorableByUserIds = expandStringList(restorableUsers.([]interface{}))
- }
- if filtersOk {
- params.Filters = buildAwsDataSourceFilters(filters.(*schema.Set))
- }
- if ownersOk {
- params.OwnerIds = expandStringList(owners.([]interface{}))
- }
-
- resp, err := conn.DescribeSnapshots(params)
- if err != nil {
- return err
- }
-
- snapshotIds := make([]string, 0)
-
- for _, snapshot := range sortSnapshots(resp.Snapshots) {
- snapshotIds = append(snapshotIds, *snapshot.SnapshotId)
- }
-
- d.SetId(fmt.Sprintf("%d", hashcode.String(params.String())))
- d.Set("ids", snapshotIds)
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_ebs_snapshot_ids_test.go b/builtin/providers/aws/data_source_aws_ebs_snapshot_ids_test.go
deleted file mode 100644
index 0c5f3ec4d..000000000
--- a/builtin/providers/aws/data_source_aws_ebs_snapshot_ids_test.go
+++ /dev/null
@@ -1,131 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/satori/uuid"
-)
-
-func TestAccDataSourceAwsEbsSnapshotIds_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAwsEbsSnapshotIdsConfig_basic,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsEbsSnapshotDataSourceID("data.aws_ebs_snapshot_ids.test"),
- ),
- },
- },
- })
-}
-
-func TestAccDataSourceAwsEbsSnapshotIds_sorted(t *testing.T) {
- uuid := uuid.NewV4().String()
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAwsEbsSnapshotIdsConfig_sorted1(uuid),
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttrSet("aws_ebs_snapshot.a", "id"),
- resource.TestCheckResourceAttrSet("aws_ebs_snapshot.b", "id"),
- ),
- },
- {
- Config: testAccDataSourceAwsEbsSnapshotIdsConfig_sorted2(uuid),
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsEbsSnapshotDataSourceID("data.aws_ebs_snapshot_ids.test"),
- resource.TestCheckResourceAttr("data.aws_ebs_snapshot_ids.test", "ids.#", "2"),
- resource.TestCheckResourceAttrPair(
- "data.aws_ebs_snapshot_ids.test", "ids.0",
- "aws_ebs_snapshot.b", "id"),
- resource.TestCheckResourceAttrPair(
- "data.aws_ebs_snapshot_ids.test", "ids.1",
- "aws_ebs_snapshot.a", "id"),
- ),
- },
- },
- })
-}
-
-func TestAccDataSourceAwsEbsSnapshotIds_empty(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAwsEbsSnapshotIdsConfig_empty,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsEbsSnapshotDataSourceID("data.aws_ebs_snapshot_ids.empty"),
- resource.TestCheckResourceAttr("data.aws_ebs_snapshot_ids.empty", "ids.#", "0"),
- ),
- },
- },
- })
-}
-
-const testAccDataSourceAwsEbsSnapshotIdsConfig_basic = `
-resource "aws_ebs_volume" "test" {
- availability_zone = "us-west-2a"
- size = 1
-}
-
-resource "aws_ebs_snapshot" "test" {
- volume_id = "${aws_ebs_volume.test.id}"
-}
-
-data "aws_ebs_snapshot_ids" "test" {
- owners = ["self"]
-}
-`
-
-func testAccDataSourceAwsEbsSnapshotIdsConfig_sorted1(uuid string) string {
- return fmt.Sprintf(`
-resource "aws_ebs_volume" "test" {
- availability_zone = "us-west-2a"
- size = 1
-
- count = 2
-}
-
-resource "aws_ebs_snapshot" "a" {
- volume_id = "${aws_ebs_volume.test.*.id[0]}"
- description = "tf-test-%s"
-}
-
-resource "aws_ebs_snapshot" "b" {
- volume_id = "${aws_ebs_volume.test.*.id[1]}"
- description = "tf-test-%s"
-
- // We want to ensure that 'aws_ebs_snapshot.a.creation_date' is less than
- // 'aws_ebs_snapshot.b.creation_date'/ so that we can ensure that the
- // snapshots are being sorted correctly.
- depends_on = ["aws_ebs_snapshot.a"]
-}
-`, uuid, uuid)
-}
-
-func testAccDataSourceAwsEbsSnapshotIdsConfig_sorted2(uuid string) string {
- return testAccDataSourceAwsEbsSnapshotIdsConfig_sorted1(uuid) + fmt.Sprintf(`
-data "aws_ebs_snapshot_ids" "test" {
- owners = ["self"]
-
- filter {
- name = "description"
- values = ["tf-test-%s"]
- }
-}
-`, uuid)
-}
-
-const testAccDataSourceAwsEbsSnapshotIdsConfig_empty = `
-data "aws_ebs_snapshot_ids" "empty" {
- owners = ["000000000000"]
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_ebs_snapshot_test.go b/builtin/providers/aws/data_source_aws_ebs_snapshot_test.go
deleted file mode 100644
index 58a20165a..000000000
--- a/builtin/providers/aws/data_source_aws_ebs_snapshot_test.go
+++ /dev/null
@@ -1,99 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAWSEbsSnapshotDataSource_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsEbsSnapshotDataSourceConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsEbsSnapshotDataSourceID("data.aws_ebs_snapshot.snapshot"),
- resource.TestCheckResourceAttr("data.aws_ebs_snapshot.snapshot", "volume_size", "40"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSEbsSnapshotDataSource_multipleFilters(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsEbsSnapshotDataSourceConfigWithMultipleFilters,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsEbsSnapshotDataSourceID("data.aws_ebs_snapshot.snapshot"),
- resource.TestCheckResourceAttr("data.aws_ebs_snapshot.snapshot", "volume_size", "10"),
- ),
- },
- },
- })
-}
-
-func testAccCheckAwsEbsSnapshotDataSourceID(n string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Can't find snapshot data source: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("Snapshot data source ID not set")
- }
- return nil
- }
-}
-
-const testAccCheckAwsEbsSnapshotDataSourceConfig = `
-resource "aws_ebs_volume" "example" {
- availability_zone = "us-west-2a"
- type = "gp2"
- size = 40
- tags {
- Name = "External Volume"
- }
-}
-
-resource "aws_ebs_snapshot" "snapshot" {
- volume_id = "${aws_ebs_volume.example.id}"
-}
-
-data "aws_ebs_snapshot" "snapshot" {
- most_recent = true
- snapshot_ids = ["${aws_ebs_snapshot.snapshot.id}"]
-}
-`
-
-const testAccCheckAwsEbsSnapshotDataSourceConfigWithMultipleFilters = `
-resource "aws_ebs_volume" "external1" {
- availability_zone = "us-west-2a"
- type = "gp2"
- size = 10
- tags {
- Name = "External Volume 1"
- }
-}
-
-resource "aws_ebs_snapshot" "snapshot" {
- volume_id = "${aws_ebs_volume.external1.id}"
-}
-
-data "aws_ebs_snapshot" "snapshot" {
- most_recent = true
- snapshot_ids = ["${aws_ebs_snapshot.snapshot.id}"]
- filter {
- name = "volume-size"
- values = ["10"]
- }
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_ebs_volume.go b/builtin/providers/aws/data_source_aws_ebs_volume.go
deleted file mode 100644
index 7794ecf28..000000000
--- a/builtin/providers/aws/data_source_aws_ebs_volume.go
+++ /dev/null
@@ -1,136 +0,0 @@
-package aws
-
-import (
- "fmt"
- "log"
- "sort"
-
- "github.com/aws/aws-sdk-go/service/ec2"
- "github.com/davecgh/go-spew/spew"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsEbsVolume() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsEbsVolumeRead,
-
- Schema: map[string]*schema.Schema{
- "filter": dataSourceFiltersSchema(),
- "most_recent": {
- Type: schema.TypeBool,
- Optional: true,
- Default: false,
- ForceNew: true,
- },
- "availability_zone": {
- Type: schema.TypeString,
- Computed: true,
- },
- "encrypted": {
- Type: schema.TypeBool,
- Computed: true,
- },
- "iops": {
- Type: schema.TypeInt,
- Computed: true,
- },
- "volume_type": {
- Type: schema.TypeString,
- Computed: true,
- },
- "size": {
- Type: schema.TypeInt,
- Computed: true,
- },
- "snapshot_id": {
- Type: schema.TypeString,
- Computed: true,
- },
- "kms_key_id": {
- Type: schema.TypeString,
- Computed: true,
- },
- "volume_id": {
- Type: schema.TypeString,
- Computed: true,
- },
- "tags": dataSourceTagsSchema(),
- },
- }
-}
-
-func dataSourceAwsEbsVolumeRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).ec2conn
-
- filters, filtersOk := d.GetOk("filter")
-
- params := &ec2.DescribeVolumesInput{}
- if filtersOk {
- params.Filters = buildAwsDataSourceFilters(filters.(*schema.Set))
- }
-
- resp, err := conn.DescribeVolumes(params)
- if err != nil {
- return err
- }
-
- log.Printf("Found These Volumes %s", spew.Sdump(resp.Volumes))
-
- filteredVolumes := resp.Volumes[:]
-
- var volume *ec2.Volume
- if len(filteredVolumes) < 1 {
- return fmt.Errorf("Your query returned no results. Please change your search criteria and try again.")
- }
-
- if len(filteredVolumes) > 1 {
- recent := d.Get("most_recent").(bool)
- log.Printf("[DEBUG] aws_ebs_volume - multiple results found and `most_recent` is set to: %t", recent)
- if recent {
- volume = mostRecentVolume(filteredVolumes)
- } else {
- return fmt.Errorf("Your query returned more than one result. Please try a more " +
- "specific search criteria, or set `most_recent` attribute to true.")
- }
- } else {
- // Query returned single result.
- volume = filteredVolumes[0]
- }
-
- log.Printf("[DEBUG] aws_ebs_volume - Single Volume found: %s", *volume.VolumeId)
- return volumeDescriptionAttributes(d, volume)
-}
-
-type volumeSort []*ec2.Volume
-
-func (a volumeSort) Len() int { return len(a) }
-func (a volumeSort) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
-func (a volumeSort) Less(i, j int) bool {
- itime := *a[i].CreateTime
- jtime := *a[j].CreateTime
- return itime.Unix() < jtime.Unix()
-}
-
-func mostRecentVolume(volumes []*ec2.Volume) *ec2.Volume {
- sortedVolumes := volumes
- sort.Sort(volumeSort(sortedVolumes))
- return sortedVolumes[len(sortedVolumes)-1]
-}
-
-func volumeDescriptionAttributes(d *schema.ResourceData, volume *ec2.Volume) error {
- d.SetId(*volume.VolumeId)
- d.Set("volume_id", volume.VolumeId)
- d.Set("availability_zone", volume.AvailabilityZone)
- d.Set("encrypted", volume.Encrypted)
- d.Set("iops", volume.Iops)
- d.Set("kms_key_id", volume.KmsKeyId)
- d.Set("size", volume.Size)
- d.Set("snapshot_id", volume.SnapshotId)
- d.Set("volume_type", volume.VolumeType)
-
- if err := d.Set("tags", dataSourceTags(volume.Tags)); err != nil {
- return err
- }
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_ebs_volume_test.go b/builtin/providers/aws/data_source_aws_ebs_volume_test.go
deleted file mode 100644
index 8be4455fe..000000000
--- a/builtin/providers/aws/data_source_aws_ebs_volume_test.go
+++ /dev/null
@@ -1,106 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAWSEbsVolumeDataSource_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsEbsVolumeDataSourceConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsEbsVolumeDataSourceID("data.aws_ebs_volume.ebs_volume"),
- resource.TestCheckResourceAttr("data.aws_ebs_volume.ebs_volume", "size", "40"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSEbsVolumeDataSource_multipleFilters(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsEbsVolumeDataSourceConfigWithMultipleFilters,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsEbsVolumeDataSourceID("data.aws_ebs_volume.ebs_volume"),
- resource.TestCheckResourceAttr("data.aws_ebs_volume.ebs_volume", "size", "10"),
- resource.TestCheckResourceAttr("data.aws_ebs_volume.ebs_volume", "volume_type", "gp2"),
- ),
- },
- },
- })
-}
-
-func testAccCheckAwsEbsVolumeDataSourceID(n string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Can't find Volume data source: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("Volume data source ID not set")
- }
- return nil
- }
-}
-
-const testAccCheckAwsEbsVolumeDataSourceConfig = `
-resource "aws_ebs_volume" "example" {
- availability_zone = "us-west-2a"
- type = "gp2"
- size = 40
- tags {
- Name = "External Volume"
- }
-}
-
-data "aws_ebs_volume" "ebs_volume" {
- most_recent = true
- filter {
- name = "tag:Name"
- values = ["External Volume"]
- }
- filter {
- name = "volume-type"
- values = ["${aws_ebs_volume.example.type}"]
- }
-}
-`
-
-const testAccCheckAwsEbsVolumeDataSourceConfigWithMultipleFilters = `
-resource "aws_ebs_volume" "external1" {
- availability_zone = "us-west-2a"
- type = "gp2"
- size = 10
- tags {
- Name = "External Volume 1"
- }
-}
-
-data "aws_ebs_volume" "ebs_volume" {
- most_recent = true
- filter {
- name = "tag:Name"
- values = ["External Volume 1"]
- }
- filter {
- name = "size"
- values = ["${aws_ebs_volume.external1.size}"]
- }
- filter {
- name = "volume-type"
- values = ["${aws_ebs_volume.external1.type}"]
- }
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_ecs_cluster.go b/builtin/providers/aws/data_source_aws_ecs_cluster.go
deleted file mode 100644
index 2d8afeeea..000000000
--- a/builtin/providers/aws/data_source_aws_ecs_cluster.go
+++ /dev/null
@@ -1,77 +0,0 @@
-package aws
-
-import (
- "fmt"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/ecs"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsEcsCluster() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsEcsClusterRead,
-
- Schema: map[string]*schema.Schema{
- "cluster_name": {
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
-
- "arn": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "status": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "pending_tasks_count": {
- Type: schema.TypeInt,
- Computed: true,
- },
-
- "running_tasks_count": {
- Type: schema.TypeInt,
- Computed: true,
- },
-
- "registered_container_instances_count": {
- Type: schema.TypeInt,
- Computed: true,
- },
- },
- }
-}
-
-func dataSourceAwsEcsClusterRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).ecsconn
-
- desc, err := conn.DescribeClusters(&ecs.DescribeClustersInput{
- Clusters: []*string{aws.String(d.Get("cluster_name").(string))},
- })
-
- if err != nil {
- return err
- }
-
- for _, cluster := range desc.Clusters {
- if aws.StringValue(cluster.ClusterName) != d.Get("cluster_name").(string) {
- continue
- }
- d.SetId(aws.StringValue(cluster.ClusterArn))
- d.Set("status", cluster.Status)
- d.Set("pending_tasks_count", cluster.PendingTasksCount)
- d.Set("running_tasks_count", cluster.RunningTasksCount)
- d.Set("registered_container_instances_count", cluster.RegisteredContainerInstancesCount)
- }
-
- if d.Id() == "" {
- return fmt.Errorf("cluster with name %q not found", d.Get("cluster_name").(string))
- }
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_ecs_cluster_test.go b/builtin/providers/aws/data_source_aws_ecs_cluster_test.go
deleted file mode 100644
index 131c4656e..000000000
--- a/builtin/providers/aws/data_source_aws_ecs_cluster_test.go
+++ /dev/null
@@ -1,60 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSEcsDataSource_ecsCluster(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsEcsClusterDataSourceConfig,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr("data.aws_ecs_cluster.default", "status", "ACTIVE"),
- resource.TestCheckResourceAttr("data.aws_ecs_cluster.default", "pending_tasks_count", "0"),
- resource.TestCheckResourceAttr("data.aws_ecs_cluster.default", "running_tasks_count", "0"),
- resource.TestCheckResourceAttr("data.aws_ecs_cluster.default", "registered_container_instances_count", "0"),
- ),
- },
- },
- })
-}
-
-var testAccCheckAwsEcsClusterDataSourceConfig = fmt.Sprintf(`
-resource "aws_ecs_cluster" "default" {
- name = "default-%d"
-}
-
-resource "aws_ecs_task_definition" "mongo" {
- family = "mongodb"
- container_definitions = < 1 {
- return fmt.Errorf("multiple Elastic IPs matched; use additional constraints to reduce matches to a single Elastic IP")
- }
-
- eip := resp.Addresses[0]
-
- d.SetId(*eip.AllocationId)
- d.Set("id", eip.AllocationId)
- d.Set("public_ip", eip.PublicIp)
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_eip_test.go b/builtin/providers/aws/data_source_aws_eip_test.go
deleted file mode 100644
index e19db7924..000000000
--- a/builtin/providers/aws/data_source_aws_eip_test.go
+++ /dev/null
@@ -1,77 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccDataSourceAwsEip(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDataSourceAwsEipConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccDataSourceAwsEipCheck("data.aws_eip.by_id"),
- testAccDataSourceAwsEipCheck("data.aws_eip.by_public_ip"),
- ),
- },
- },
- })
-}
-
-func testAccDataSourceAwsEipCheck(name string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[name]
- if !ok {
- return fmt.Errorf("root module has no resource called %s", name)
- }
-
- eipRs, ok := s.RootModule().Resources["aws_eip.test"]
- if !ok {
- return fmt.Errorf("can't find aws_eip.test in state")
- }
-
- attr := rs.Primary.Attributes
-
- if attr["id"] != eipRs.Primary.Attributes["id"] {
- return fmt.Errorf(
- "id is %s; want %s",
- attr["id"],
- eipRs.Primary.Attributes["id"],
- )
- }
-
- if attr["public_ip"] != eipRs.Primary.Attributes["public_ip"] {
- return fmt.Errorf(
- "public_ip is %s; want %s",
- attr["public_ip"],
- eipRs.Primary.Attributes["public_ip"],
- )
- }
-
- return nil
- }
-}
-
-const testAccDataSourceAwsEipConfig = `
-provider "aws" {
- region = "us-west-2"
-}
-
-resource "aws_eip" "wrong1" {}
-resource "aws_eip" "test" {}
-resource "aws_eip" "wrong2" {}
-
-data "aws_eip" "by_id" {
- id = "${aws_eip.test.id}"
-}
-
-data "aws_eip" "by_public_ip" {
- public_ip = "${aws_eip.test.public_ip}"
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_elastic_beanstalk_solution_stack.go b/builtin/providers/aws/data_source_aws_elastic_beanstalk_solution_stack.go
deleted file mode 100644
index f9bec5bce..000000000
--- a/builtin/providers/aws/data_source_aws_elastic_beanstalk_solution_stack.go
+++ /dev/null
@@ -1,105 +0,0 @@
-package aws
-
-import (
- "fmt"
- "log"
- "regexp"
-
- "github.com/aws/aws-sdk-go/service/elasticbeanstalk"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsElasticBeanstalkSolutionStack() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsElasticBeanstalkSolutionStackRead,
-
- Schema: map[string]*schema.Schema{
- "name_regex": {
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- ValidateFunc: validateSolutionStackNameRegex,
- },
- "most_recent": {
- Type: schema.TypeBool,
- Optional: true,
- Default: false,
- ForceNew: true,
- },
- // Computed values.
- "name": {
- Type: schema.TypeString,
- Computed: true,
- },
- },
- }
-}
-
-// dataSourceAwsElasticBeanstalkSolutionStackRead performs the API lookup.
-func dataSourceAwsElasticBeanstalkSolutionStackRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).elasticbeanstalkconn
-
- nameRegex := d.Get("name_regex")
-
- var params *elasticbeanstalk.ListAvailableSolutionStacksInput
-
- resp, err := conn.ListAvailableSolutionStacks(params)
- if err != nil {
- return err
- }
-
- var filteredSolutionStacks []*string
-
- r := regexp.MustCompile(nameRegex.(string))
- for _, solutionStack := range resp.SolutionStacks {
- if r.MatchString(*solutionStack) {
- filteredSolutionStacks = append(filteredSolutionStacks, solutionStack)
- }
- }
-
- var solutionStack *string
- if len(filteredSolutionStacks) < 1 {
- return fmt.Errorf("Your query returned no results. Please change your search criteria and try again.")
- }
-
- if len(filteredSolutionStacks) == 1 {
- // Query returned single result.
- solutionStack = filteredSolutionStacks[0]
- } else {
- recent := d.Get("most_recent").(bool)
- log.Printf("[DEBUG] aws_elastic_beanstalk_solution_stack - multiple results found and `most_recent` is set to: %t", recent)
- if recent {
- solutionStack = mostRecentSolutionStack(filteredSolutionStacks)
- } else {
- return fmt.Errorf("Your query returned more than one result. Please try a more " +
- "specific search criteria, or set `most_recent` attribute to true.")
- }
- }
-
- log.Printf("[DEBUG] aws_elastic_beanstalk_solution_stack - Single solution stack found: %s", *solutionStack)
- return solutionStackDescriptionAttributes(d, solutionStack)
-}
-
-// Returns the most recent solution stack out of a slice of stacks.
-func mostRecentSolutionStack(solutionStacks []*string) *string {
- return solutionStacks[0]
-}
-
-// populate the numerous fields that the image description returns.
-func solutionStackDescriptionAttributes(d *schema.ResourceData, solutionStack *string) error {
- // Simple attributes first
- d.SetId(*solutionStack)
- d.Set("name", solutionStack)
- return nil
-}
-
-func validateSolutionStackNameRegex(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
-
- if _, err := regexp.Compile(value); err != nil {
- errors = append(errors, fmt.Errorf(
- "%q contains an invalid regular expression: %s",
- k, err))
- }
- return
-}
diff --git a/builtin/providers/aws/data_source_aws_elastic_beanstalk_solution_stack_test.go b/builtin/providers/aws/data_source_aws_elastic_beanstalk_solution_stack_test.go
deleted file mode 100644
index 99ca8f7c8..000000000
--- a/builtin/providers/aws/data_source_aws_elastic_beanstalk_solution_stack_test.go
+++ /dev/null
@@ -1,103 +0,0 @@
-package aws
-
-import (
- "fmt"
- "regexp"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAWSElasticBeanstalkSolutionStackDataSource(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsElasticBeanstalkSolutionStackDataSourceConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsElasticBeanstalkSolutionStackDataSourceID("data.aws_elastic_beanstalk_solution_stack.multi_docker"),
- resource.TestMatchResourceAttr("data.aws_elastic_beanstalk_solution_stack.multi_docker", "name", regexp.MustCompile("^64bit Amazon Linux (.*) Multi-container Docker (.*)$")),
- ),
- },
- },
- })
-}
-
-func TestResourceValidateSolutionStackNameRegex(t *testing.T) {
- type testCases struct {
- Value string
- ErrCount int
- }
-
- invalidCases := []testCases{
- {
- Value: `\`,
- ErrCount: 1,
- },
- {
- Value: `**`,
- ErrCount: 1,
- },
- {
- Value: `(.+`,
- ErrCount: 1,
- },
- }
-
- for _, tc := range invalidCases {
- _, errors := validateSolutionStackNameRegex(tc.Value, "name_regex")
- if len(errors) != tc.ErrCount {
- t.Fatalf("Expected %q to trigger a validation error.", tc.Value)
- }
- }
-
- validCases := []testCases{
- {
- Value: `\/`,
- ErrCount: 0,
- },
- {
- Value: `.*`,
- ErrCount: 0,
- },
- {
- Value: `\b(?:\d{1,3}\.){3}\d{1,3}\b`,
- ErrCount: 0,
- },
- }
-
- for _, tc := range validCases {
- _, errors := validateSolutionStackNameRegex(tc.Value, "name_regex")
- if len(errors) != tc.ErrCount {
- t.Fatalf("Expected %q not to trigger a validation error.", tc.Value)
- }
- }
-}
-
-func testAccCheckAwsElasticBeanstalkSolutionStackDataSourceDestroy(s *terraform.State) error {
- return nil
-}
-
-func testAccCheckAwsElasticBeanstalkSolutionStackDataSourceID(n string) resource.TestCheckFunc {
- // Wait for solution stacks
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Can't find solution stack data source: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("Solution stack data source ID not set")
- }
- return nil
- }
-}
-
-const testAccCheckAwsElasticBeanstalkSolutionStackDataSourceConfig = `
-data "aws_elastic_beanstalk_solution_stack" "multi_docker" {
- most_recent = true
- name_regex = "^64bit Amazon Linux (.*) Multi-container Docker (.*)$"
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_elasticache_cluster.go b/builtin/providers/aws/data_source_aws_elasticache_cluster.go
deleted file mode 100644
index eaa539d3a..000000000
--- a/builtin/providers/aws/data_source_aws_elasticache_cluster.go
+++ /dev/null
@@ -1,236 +0,0 @@
-package aws
-
-import (
- "fmt"
- "log"
- "strings"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/elasticache"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsElastiCacheCluster() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsElastiCacheClusterRead,
-
- Schema: map[string]*schema.Schema{
- "cluster_id": {
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- StateFunc: func(v interface{}) string {
- value := v.(string)
- return strings.ToLower(value)
- },
- },
-
- "node_type": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "num_cache_nodes": {
- Type: schema.TypeInt,
- Computed: true,
- },
-
- "subnet_group_name": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "engine": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "engine_version": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "parameter_group_name": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "replication_group_id": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "security_group_names": {
- Type: schema.TypeSet,
- Computed: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- Set: schema.HashString,
- },
-
- "security_group_ids": {
- Type: schema.TypeSet,
- Computed: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- Set: schema.HashString,
- },
-
- "maintenance_window": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "snapshot_window": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "snapshot_retention_limit": {
- Type: schema.TypeInt,
- Computed: true,
- },
-
- "availability_zone": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "notification_topic_arn": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "port": {
- Type: schema.TypeInt,
- Computed: true,
- },
-
- "configuration_endpoint": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "cluster_address": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "arn": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "cache_nodes": {
- Type: schema.TypeList,
- Computed: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "id": {
- Type: schema.TypeString,
- Computed: true,
- },
- "address": {
- Type: schema.TypeString,
- Computed: true,
- },
- "port": {
- Type: schema.TypeInt,
- Computed: true,
- },
- "availability_zone": {
- Type: schema.TypeString,
- Computed: true,
- },
- },
- },
- },
-
- "tags": tagsSchemaComputed(),
- },
- }
-}
-
-func dataSourceAwsElastiCacheClusterRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).elasticacheconn
-
- req := &elasticache.DescribeCacheClustersInput{
- CacheClusterId: aws.String(d.Get("cluster_id").(string)),
- ShowCacheNodeInfo: aws.Bool(true),
- }
-
- resp, err := conn.DescribeCacheClusters(req)
- if err != nil {
- return err
- }
-
- if len(resp.CacheClusters) < 1 {
- return fmt.Errorf("Your query returned no results. Please change your search criteria and try again.")
- }
- if len(resp.CacheClusters) > 1 {
- return fmt.Errorf("Your query returned more than one result. Please try a more specific search criteria.")
- }
-
- cluster := resp.CacheClusters[0]
-
- d.SetId(*cluster.CacheClusterId)
-
- d.Set("cluster_id", cluster.CacheClusterId)
- d.Set("node_type", cluster.CacheNodeType)
- d.Set("num_cache_nodes", cluster.NumCacheNodes)
- d.Set("subnet_group_name", cluster.CacheSubnetGroupName)
- d.Set("engine", cluster.Engine)
- d.Set("engine_version", cluster.EngineVersion)
- d.Set("security_group_names", flattenElastiCacheSecurityGroupNames(cluster.CacheSecurityGroups))
- d.Set("security_group_ids", flattenElastiCacheSecurityGroupIds(cluster.SecurityGroups))
-
- if cluster.CacheParameterGroup != nil {
- d.Set("parameter_group_name", cluster.CacheParameterGroup.CacheParameterGroupName)
- }
-
- if cluster.ReplicationGroupId != nil {
- d.Set("replication_group_id", cluster.ReplicationGroupId)
- }
-
- d.Set("maintenance_window", cluster.PreferredMaintenanceWindow)
- d.Set("snapshot_window", cluster.SnapshotWindow)
- d.Set("snapshot_retention_limit", cluster.SnapshotRetentionLimit)
- d.Set("availability_zone", cluster.PreferredAvailabilityZone)
-
- if cluster.NotificationConfiguration != nil {
- if *cluster.NotificationConfiguration.TopicStatus == "active" {
- d.Set("notification_topic_arn", cluster.NotificationConfiguration.TopicArn)
- }
- }
-
- if cluster.ConfigurationEndpoint != nil {
- d.Set("port", cluster.ConfigurationEndpoint.Port)
- d.Set("configuration_endpoint", aws.String(fmt.Sprintf("%s:%d", *cluster.ConfigurationEndpoint.Address, *cluster.ConfigurationEndpoint.Port)))
- d.Set("cluster_address", aws.String(fmt.Sprintf("%s", *cluster.ConfigurationEndpoint.Address)))
- }
-
- if err := setCacheNodeData(d, cluster); err != nil {
- return err
- }
-
- arn, err := buildECARN(d.Id(), meta.(*AWSClient).partition, meta.(*AWSClient).accountid, meta.(*AWSClient).region)
- if err != nil {
- log.Printf("[DEBUG] Error building ARN for ElastiCache Cluster %s", *cluster.CacheClusterId)
- }
- d.Set("arn", arn)
-
- tagResp, err := conn.ListTagsForResource(&elasticache.ListTagsForResourceInput{
- ResourceName: aws.String(arn),
- })
-
- if err != nil {
- log.Printf("[DEBUG] Error retrieving tags for ARN: %s", arn)
- }
-
- var et []*elasticache.Tag
- if len(tagResp.TagList) > 0 {
- et = tagResp.TagList
- }
- d.Set("tags", tagsToMapEC(et))
-
- return nil
-
-}
diff --git a/builtin/providers/aws/data_source_aws_elasticache_cluster_test.go b/builtin/providers/aws/data_source_aws_elasticache_cluster_test.go
deleted file mode 100644
index 57791cf05..000000000
--- a/builtin/providers/aws/data_source_aws_elasticache_cluster_test.go
+++ /dev/null
@@ -1,72 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSDataElasticacheCluster_basic(t *testing.T) {
- rInt := acctest.RandInt()
- rString := acctest.RandString(10)
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSElastiCacheClusterConfigWithDataSource(rString, rInt),
- Check: resource.ComposeAggregateTestCheckFunc(
- resource.TestCheckResourceAttr("data.aws_elasticache_cluster.bar", "engine", "memcached"),
- resource.TestCheckResourceAttr("data.aws_elasticache_cluster.bar", "node_type", "cache.m1.small"),
- resource.TestCheckResourceAttr("data.aws_elasticache_cluster.bar", "port", "11211"),
- resource.TestCheckResourceAttr("data.aws_elasticache_cluster.bar", "num_cache_nodes", "1"),
- resource.TestCheckResourceAttrSet("data.aws_elasticache_cluster.bar", "configuration_endpoint"),
- resource.TestCheckResourceAttrSet("data.aws_elasticache_cluster.bar", "cluster_address"),
- resource.TestCheckResourceAttrSet("data.aws_elasticache_cluster.bar", "availability_zone"),
- ),
- },
- },
- })
-}
-
-func testAccAWSElastiCacheClusterConfigWithDataSource(rString string, rInt int) string {
- return fmt.Sprintf(`
-provider "aws" {
- region = "us-east-1"
-}
-
-resource "aws_security_group" "bar" {
- name = "tf-test-security-group-%d"
- description = "tf-test-security-group-descr"
- ingress {
- from_port = -1
- to_port = -1
- protocol = "icmp"
- cidr_blocks = ["0.0.0.0/0"]
- }
-}
-
-resource "aws_elasticache_security_group" "bar" {
- name = "tf-test-security-group-%d"
- description = "tf-test-security-group-descr"
- security_group_names = ["${aws_security_group.bar.name}"]
-}
-
-resource "aws_elasticache_cluster" "bar" {
- cluster_id = "tf-%s"
- engine = "memcached"
- node_type = "cache.m1.small"
- num_cache_nodes = 1
- port = 11211
- parameter_group_name = "default.memcached1.4"
- security_group_names = ["${aws_elasticache_security_group.bar.name}"]
-}
-
-data "aws_elasticache_cluster" "bar" {
- cluster_id = "${aws_elasticache_cluster.bar.cluster_id}"
-}
-
-`, rInt, rInt, rString)
-}
diff --git a/builtin/providers/aws/data_source_aws_elb_hosted_zone_id.go b/builtin/providers/aws/data_source_aws_elb_hosted_zone_id.go
deleted file mode 100644
index ee75a27bf..000000000
--- a/builtin/providers/aws/data_source_aws_elb_hosted_zone_id.go
+++ /dev/null
@@ -1,56 +0,0 @@
-package aws
-
-import (
- "fmt"
-
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-// See https://github.com/fog/fog-aws/pull/332/files
-// This list isn't exposed by AWS - it's been found through
-// trouble solving
-var elbHostedZoneIdPerRegionMap = map[string]string{
- "ap-northeast-1": "Z14GRHDCWA56QT",
- "ap-northeast-2": "ZWKZPGTI48KDX",
- "ap-south-1": "ZP97RAFLXTNZK",
- "ap-southeast-1": "Z1LMS91P8CMLE5",
- "ap-southeast-2": "Z1GM3OXH4ZPM65",
- "ca-central-1": "ZQSVJUPU6J1EY",
- "eu-central-1": "Z215JYRZR1TBD5",
- "eu-west-1": "Z32O12XQLNTSW2",
- "eu-west-2": "ZHURV8PSTC4K8",
- "us-east-1": "Z35SXDOTRQ7X7K",
- "us-east-2": "Z3AADJGX6KTTL2",
- "us-west-1": "Z368ELLRRE2KJ0",
- "us-west-2": "Z1H1FL5HABSF5",
- "sa-east-1": "Z2P70J7HTTTPLU",
- "us-gov-west-1": "048591011584",
- "cn-north-1": "638102146993",
-}
-
-func dataSourceAwsElbHostedZoneId() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsElbHostedZoneIdRead,
-
- Schema: map[string]*schema.Schema{
- "region": {
- Type: schema.TypeString,
- Optional: true,
- },
- },
- }
-}
-
-func dataSourceAwsElbHostedZoneIdRead(d *schema.ResourceData, meta interface{}) error {
- region := meta.(*AWSClient).region
- if v, ok := d.GetOk("region"); ok {
- region = v.(string)
- }
-
- if zoneId, ok := elbHostedZoneIdPerRegionMap[region]; ok {
- d.SetId(zoneId)
- return nil
- }
-
- return fmt.Errorf("Unknown region (%q)", region)
-}
diff --git a/builtin/providers/aws/data_source_aws_elb_hosted_zone_id_test.go b/builtin/providers/aws/data_source_aws_elb_hosted_zone_id_test.go
deleted file mode 100644
index e7fe326a0..000000000
--- a/builtin/providers/aws/data_source_aws_elb_hosted_zone_id_test.go
+++ /dev/null
@@ -1,38 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSElbHostedZoneId_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsElbHostedZoneIdConfig,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr("data.aws_elb_hosted_zone_id.main", "id", "Z1H1FL5HABSF5"),
- ),
- },
- {
- Config: testAccCheckAwsElbHostedZoneIdExplicitRegionConfig,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr("data.aws_elb_hosted_zone_id.regional", "id", "Z32O12XQLNTSW2"),
- ),
- },
- },
- })
-}
-
-const testAccCheckAwsElbHostedZoneIdConfig = `
-data "aws_elb_hosted_zone_id" "main" { }
-`
-
-const testAccCheckAwsElbHostedZoneIdExplicitRegionConfig = `
-data "aws_elb_hosted_zone_id" "regional" {
- region = "eu-west-1"
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_elb_service_account.go b/builtin/providers/aws/data_source_aws_elb_service_account.go
deleted file mode 100644
index a3d6cdd71..000000000
--- a/builtin/providers/aws/data_source_aws_elb_service_account.go
+++ /dev/null
@@ -1,61 +0,0 @@
-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",
- "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)
-}
diff --git a/builtin/providers/aws/data_source_aws_elb_service_account_test.go b/builtin/providers/aws/data_source_aws_elb_service_account_test.go
deleted file mode 100644
index 551d7df46..000000000
--- a/builtin/providers/aws/data_source_aws_elb_service_account_test.go
+++ /dev/null
@@ -1,40 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSElbServiceAccount_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsElbServiceAccountConfig,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr("data.aws_elb_service_account.main", "id", "797873946194"),
- resource.TestCheckResourceAttr("data.aws_elb_service_account.main", "arn", "arn:aws:iam::797873946194:root"),
- ),
- },
- {
- Config: testAccCheckAwsElbServiceAccountExplicitRegionConfig,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr("data.aws_elb_service_account.regional", "id", "156460612806"),
- resource.TestCheckResourceAttr("data.aws_elb_service_account.regional", "arn", "arn:aws:iam::156460612806:root"),
- ),
- },
- },
- })
-}
-
-const testAccCheckAwsElbServiceAccountConfig = `
-data "aws_elb_service_account" "main" { }
-`
-
-const testAccCheckAwsElbServiceAccountExplicitRegionConfig = `
-data "aws_elb_service_account" "regional" {
- region = "eu-west-1"
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_iam_account_alias.go b/builtin/providers/aws/data_source_aws_iam_account_alias.go
deleted file mode 100644
index f93897373..000000000
--- a/builtin/providers/aws/data_source_aws_iam_account_alias.go
+++ /dev/null
@@ -1,48 +0,0 @@
-package aws
-
-import (
- "fmt"
- "log"
- "time"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/iam"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsIamAccountAlias() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsIamAccountAliasRead,
-
- Schema: map[string]*schema.Schema{
- "account_alias": {
- Type: schema.TypeString,
- Computed: true,
- },
- },
- }
-}
-
-func dataSourceAwsIamAccountAliasRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).iamconn
-
- log.Printf("[DEBUG] Reading IAM Account Aliases.")
- d.SetId(time.Now().UTC().String())
-
- req := &iam.ListAccountAliasesInput{}
- resp, err := conn.ListAccountAliases(req)
- if err != nil {
- return err
- }
-
- // 'AccountAliases': [] if there is no alias.
- if resp == nil || len(resp.AccountAliases) == 0 {
- return fmt.Errorf("no IAM account alias found")
- }
-
- alias := aws.StringValue(resp.AccountAliases[0])
- log.Printf("[DEBUG] Setting AWS IAM Account Alias to %s.", alias)
- d.Set("account_alias", alias)
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_iam_policy_document.go b/builtin/providers/aws/data_source_aws_iam_policy_document.go
deleted file mode 100644
index 2366ae4bc..000000000
--- a/builtin/providers/aws/data_source_aws_iam_policy_document.go
+++ /dev/null
@@ -1,232 +0,0 @@
-package aws
-
-import (
- "fmt"
-
- "encoding/json"
- "strings"
-
- "github.com/hashicorp/terraform/helper/hashcode"
- "github.com/hashicorp/terraform/helper/schema"
- "strconv"
-)
-
-var dataSourceAwsIamPolicyDocumentVarReplacer = strings.NewReplacer("&{", "${")
-
-func dataSourceAwsIamPolicyDocument() *schema.Resource {
- setOfString := &schema.Schema{
- Type: schema.TypeSet,
- Optional: true,
- Elem: &schema.Schema{
- Type: schema.TypeString,
- },
- }
-
- return &schema.Resource{
- Read: dataSourceAwsIamPolicyDocumentRead,
-
- Schema: map[string]*schema.Schema{
- "policy_id": {
- Type: schema.TypeString,
- Optional: true,
- },
- "statement": {
- Type: schema.TypeList,
- Required: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "sid": {
- Type: schema.TypeString,
- Optional: true,
- },
- "effect": {
- Type: schema.TypeString,
- Optional: true,
- Default: "Allow",
- ValidateFunc: func(v interface{}, k string) (ws []string, es []error) {
- switch v.(string) {
- case "Allow", "Deny":
- return
- default:
- es = append(es, fmt.Errorf("%q must be either \"Allow\" or \"Deny\"", k))
- return
- }
- },
- },
- "actions": setOfString,
- "not_actions": setOfString,
- "resources": setOfString,
- "not_resources": setOfString,
- "principals": dataSourceAwsIamPolicyPrincipalSchema(),
- "not_principals": dataSourceAwsIamPolicyPrincipalSchema(),
- "condition": {
- Type: schema.TypeSet,
- Optional: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "test": {
- Type: schema.TypeString,
- Required: true,
- },
- "variable": {
- Type: schema.TypeString,
- Required: true,
- },
- "values": {
- Type: schema.TypeSet,
- Required: true,
- Elem: &schema.Schema{
- Type: schema.TypeString,
- },
- },
- },
- },
- },
- },
- },
- },
- "json": {
- Type: schema.TypeString,
- Computed: true,
- },
- },
- }
-}
-
-func dataSourceAwsIamPolicyDocumentRead(d *schema.ResourceData, meta interface{}) error {
- doc := &IAMPolicyDoc{
- Version: "2012-10-17",
- }
-
- if policyId, hasPolicyId := d.GetOk("policy_id"); hasPolicyId {
- doc.Id = policyId.(string)
- }
-
- var cfgStmts = d.Get("statement").([]interface{})
- stmts := make([]*IAMPolicyStatement, len(cfgStmts))
- doc.Statements = stmts
- for i, stmtI := range cfgStmts {
- cfgStmt := stmtI.(map[string]interface{})
- stmt := &IAMPolicyStatement{
- Effect: cfgStmt["effect"].(string),
- }
-
- if sid, ok := cfgStmt["sid"]; ok {
- stmt.Sid = sid.(string)
- }
-
- if actions := cfgStmt["actions"].(*schema.Set).List(); len(actions) > 0 {
- stmt.Actions = iamPolicyDecodeConfigStringList(actions)
- }
- if actions := cfgStmt["not_actions"].(*schema.Set).List(); len(actions) > 0 {
- stmt.NotActions = iamPolicyDecodeConfigStringList(actions)
- }
-
- if resources := cfgStmt["resources"].(*schema.Set).List(); len(resources) > 0 {
- stmt.Resources = dataSourceAwsIamPolicyDocumentReplaceVarsInList(
- iamPolicyDecodeConfigStringList(resources),
- )
- }
- if resources := cfgStmt["not_resources"].(*schema.Set).List(); len(resources) > 0 {
- stmt.NotResources = dataSourceAwsIamPolicyDocumentReplaceVarsInList(
- iamPolicyDecodeConfigStringList(resources),
- )
- }
-
- if principals := cfgStmt["principals"].(*schema.Set).List(); len(principals) > 0 {
- stmt.Principals = dataSourceAwsIamPolicyDocumentMakePrincipals(principals)
- }
-
- if principals := cfgStmt["not_principals"].(*schema.Set).List(); len(principals) > 0 {
- stmt.NotPrincipals = dataSourceAwsIamPolicyDocumentMakePrincipals(principals)
- }
-
- if conditions := cfgStmt["condition"].(*schema.Set).List(); len(conditions) > 0 {
- stmt.Conditions = dataSourceAwsIamPolicyDocumentMakeConditions(conditions)
- }
-
- stmts[i] = stmt
- }
-
- jsonDoc, err := json.MarshalIndent(doc, "", " ")
- if err != nil {
- // should never happen if the above code is correct
- return err
- }
- jsonString := string(jsonDoc)
-
- d.Set("json", jsonString)
- d.SetId(strconv.Itoa(hashcode.String(jsonString)))
-
- return nil
-}
-
-func dataSourceAwsIamPolicyDocumentReplaceVarsInList(in interface{}) interface{} {
- switch v := in.(type) {
- case string:
- return dataSourceAwsIamPolicyDocumentVarReplacer.Replace(v)
- case []string:
- out := make([]string, len(v))
- for i, item := range v {
- out[i] = dataSourceAwsIamPolicyDocumentVarReplacer.Replace(item)
- }
- return out
- default:
- panic("dataSourceAwsIamPolicyDocumentReplaceVarsInList: input not string nor []string")
- }
-}
-
-func dataSourceAwsIamPolicyDocumentMakeConditions(in []interface{}) IAMPolicyStatementConditionSet {
- out := make([]IAMPolicyStatementCondition, len(in))
- for i, itemI := range in {
- item := itemI.(map[string]interface{})
- out[i] = IAMPolicyStatementCondition{
- Test: item["test"].(string),
- Variable: item["variable"].(string),
- Values: dataSourceAwsIamPolicyDocumentReplaceVarsInList(
- iamPolicyDecodeConfigStringList(
- item["values"].(*schema.Set).List(),
- ),
- ),
- }
- }
- return IAMPolicyStatementConditionSet(out)
-}
-
-func dataSourceAwsIamPolicyDocumentMakePrincipals(in []interface{}) IAMPolicyStatementPrincipalSet {
- out := make([]IAMPolicyStatementPrincipal, len(in))
- for i, itemI := range in {
- item := itemI.(map[string]interface{})
- out[i] = IAMPolicyStatementPrincipal{
- Type: item["type"].(string),
- Identifiers: dataSourceAwsIamPolicyDocumentReplaceVarsInList(
- iamPolicyDecodeConfigStringList(
- item["identifiers"].(*schema.Set).List(),
- ),
- ),
- }
- }
- return IAMPolicyStatementPrincipalSet(out)
-}
-
-func dataSourceAwsIamPolicyPrincipalSchema() *schema.Schema {
- return &schema.Schema{
- Type: schema.TypeSet,
- Optional: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "type": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
- "identifiers": &schema.Schema{
- Type: schema.TypeSet,
- Required: true,
- Elem: &schema.Schema{
- Type: schema.TypeString,
- },
- },
- },
- },
- }
-}
diff --git a/builtin/providers/aws/data_source_aws_iam_policy_document_test.go b/builtin/providers/aws/data_source_aws_iam_policy_document_test.go
deleted file mode 100644
index a720d181a..000000000
--- a/builtin/providers/aws/data_source_aws_iam_policy_document_test.go
+++ /dev/null
@@ -1,191 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "fmt"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAWSIAMPolicyDocument(t *testing.T) {
- // This really ought to be able to be a unit test rather than an
- // acceptance test, but just instantiating the AWS provider requires
- // some AWS API calls, and so this needs valid AWS credentials to work.
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSIAMPolicyDocumentConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckStateValue(
- "data.aws_iam_policy_document.test",
- "json",
- testAccAWSIAMPolicyDocumentExpectedJSON,
- ),
- ),
- },
- },
- })
-}
-
-func testAccCheckStateValue(id, name, value string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[id]
- if !ok {
- return fmt.Errorf("Not found: %s", id)
- }
- if rs.Primary.ID == "" {
- return fmt.Errorf("No ID is set")
- }
-
- v := rs.Primary.Attributes[name]
- if v != value {
- return fmt.Errorf(
- "Value for %s is %s, not %s", name, v, value)
- }
-
- return nil
- }
-}
-
-var testAccAWSIAMPolicyDocumentConfig = `
-data "aws_iam_policy_document" "test" {
- policy_id = "policy_id"
- statement {
- sid = "1"
- actions = [
- "s3:ListAllMyBuckets",
- "s3:GetBucketLocation",
- ]
- resources = [
- "arn:aws:s3:::*",
- ]
- }
-
- statement {
- actions = [
- "s3:ListBucket",
- ]
- resources = [
- "arn:aws:s3:::foo",
- ]
- condition {
- test = "StringLike"
- variable = "s3:prefix"
- values = [
- "home/",
- "home/&{aws:username}/",
- ]
- }
-
- not_principals {
- type = "AWS"
- identifiers = ["arn:blahblah:example"]
- }
- }
-
- statement {
- actions = [
- "s3:*",
- ]
- resources = [
- "arn:aws:s3:::foo/home/&{aws:username}",
- "arn:aws:s3:::foo/home/&{aws:username}/*",
- ]
- principals {
- type = "AWS"
- identifiers = ["arn:blahblah:example"]
- }
- }
-
- statement {
- effect = "Deny"
- not_actions = ["s3:*"]
- not_resources = ["arn:aws:s3:::*"]
- }
-
- # Normalization of wildcard principals
- statement {
- effect = "Allow"
- actions = ["kinesis:*"]
- principals {
- type = "AWS"
- identifiers = ["*"]
- }
- }
- statement {
- effect = "Allow"
- actions = ["firehose:*"]
- principals {
- type = "*"
- identifiers = ["*"]
- }
- }
-
-}
-`
-
-var testAccAWSIAMPolicyDocumentExpectedJSON = `{
- "Version": "2012-10-17",
- "Id": "policy_id",
- "Statement": [
- {
- "Sid": "1",
- "Effect": "Allow",
- "Action": [
- "s3:ListAllMyBuckets",
- "s3:GetBucketLocation"
- ],
- "Resource": "arn:aws:s3:::*"
- },
- {
- "Sid": "",
- "Effect": "Allow",
- "Action": "s3:ListBucket",
- "Resource": "arn:aws:s3:::foo",
- "NotPrincipal": {
- "AWS": "arn:blahblah:example"
- },
- "Condition": {
- "StringLike": {
- "s3:prefix": [
- "home/${aws:username}/",
- "home/"
- ]
- }
- }
- },
- {
- "Sid": "",
- "Effect": "Allow",
- "Action": "s3:*",
- "Resource": [
- "arn:aws:s3:::foo/home/${aws:username}/*",
- "arn:aws:s3:::foo/home/${aws:username}"
- ],
- "Principal": {
- "AWS": "arn:blahblah:example"
- }
- },
- {
- "Sid": "",
- "Effect": "Deny",
- "NotAction": "s3:*",
- "NotResource": "arn:aws:s3:::*"
- },
- {
- "Sid": "",
- "Effect": "Allow",
- "Action": "kinesis:*",
- "Principal": "*"
- },
- {
- "Sid": "",
- "Effect": "Allow",
- "Action": "firehose:*",
- "Principal": "*"
- }
- ]
-}`
diff --git a/builtin/providers/aws/data_source_aws_iam_role.go b/builtin/providers/aws/data_source_aws_iam_role.go
deleted file mode 100644
index f681268b9..000000000
--- a/builtin/providers/aws/data_source_aws_iam_role.go
+++ /dev/null
@@ -1,67 +0,0 @@
-package aws
-
-import (
- "fmt"
-
- "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 dataSourceAwsIAMRole() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsIAMRoleRead,
-
- Schema: map[string]*schema.Schema{
- "arn": {
- Type: schema.TypeString,
- Computed: true,
- },
- "assume_role_policy_document": {
- Type: schema.TypeString,
- Computed: true,
- },
- "path": {
- Type: schema.TypeString,
- Computed: true,
- },
- "role_id": {
- Type: schema.TypeString,
- Computed: true,
- },
- "role_name": {
- Type: schema.TypeString,
- Required: true,
- },
- },
- }
-}
-
-func dataSourceAwsIAMRoleRead(d *schema.ResourceData, meta interface{}) error {
- iamconn := meta.(*AWSClient).iamconn
-
- roleName := d.Get("role_name").(string)
-
- req := &iam.GetRoleInput{
- RoleName: aws.String(roleName),
- }
-
- resp, err := iamconn.GetRole(req)
- if err != nil {
- return errwrap.Wrapf("Error getting roles: {{err}}", err)
- }
- if resp == nil {
- return fmt.Errorf("no IAM role found")
- }
-
- role := resp.Role
-
- d.SetId(*role.RoleId)
- d.Set("arn", role.Arn)
- d.Set("assume_role_policy_document", role.AssumeRolePolicyDocument)
- d.Set("path", role.Path)
- d.Set("role_id", role.RoleId)
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_iam_role_test.go b/builtin/providers/aws/data_source_aws_iam_role_test.go
deleted file mode 100644
index 160e5d49b..000000000
--- a/builtin/providers/aws/data_source_aws_iam_role_test.go
+++ /dev/null
@@ -1,59 +0,0 @@
-package aws
-
-import (
- "regexp"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSDataSourceIAMRole_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccAwsIAMRoleConfig,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttrSet("data.aws_iam_role.test", "role_id"),
- resource.TestCheckResourceAttr("data.aws_iam_role.test", "assume_role_policy_document", "%7B%22Version%22%3A%222012-10-17%22%2C%22Statement%22%3A%5B%7B%22Sid%22%3A%22%22%2C%22Effect%22%3A%22Allow%22%2C%22Principal%22%3A%7B%22Service%22%3A%22ec2.amazonaws.com%22%7D%2C%22Action%22%3A%22sts%3AAssumeRole%22%7D%5D%7D"),
- resource.TestCheckResourceAttr("data.aws_iam_role.test", "path", "/testpath/"),
- resource.TestCheckResourceAttr("data.aws_iam_role.test", "role_name", "TestRole"),
- resource.TestMatchResourceAttr("data.aws_iam_role.test", "arn", regexp.MustCompile("^arn:aws:iam::[0-9]{12}:role/testpath/TestRole$")),
- ),
- },
- },
- })
-}
-
-const testAccAwsIAMRoleConfig = `
-provider "aws" {
- region = "us-east-1"
-}
-
-resource "aws_iam_role" "test_role" {
- name = "TestRole"
-
- assume_role_policy = < 128 {
- errors = append(errors, fmt.Errorf(
- "%q cannot be longer than 128 characters", k))
- }
- return
- },
- },
-
- "name_prefix": {
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
- if len(value) > 30 {
- errors = append(errors, fmt.Errorf(
- "%q cannot be longer than 30 characters, name is limited to 128", k))
- }
- return
- },
- },
-
- "latest": {
- Type: schema.TypeBool,
- Optional: true,
- ForceNew: true,
- Default: false,
- },
-
- "arn": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "id": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "path": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "expiration_date": {
- Type: schema.TypeString,
- Computed: true,
- },
- },
- }
-}
-
-type certificateByExpiration []*iam.ServerCertificateMetadata
-
-func (m certificateByExpiration) Len() int {
- return len(m)
-}
-
-func (m certificateByExpiration) Swap(i, j int) {
- m[i], m[j] = m[j], m[i]
-}
-
-func (m certificateByExpiration) Less(i, j int) bool {
- return m[i].Expiration.After(*m[j].Expiration)
-}
-
-func dataSourceAwsIAMServerCertificateRead(d *schema.ResourceData, meta interface{}) error {
- iamconn := meta.(*AWSClient).iamconn
-
- var matcher = func(cert *iam.ServerCertificateMetadata) bool {
- return strings.HasPrefix(aws.StringValue(cert.ServerCertificateName), d.Get("name_prefix").(string))
- }
- if v, ok := d.GetOk("name"); ok {
- matcher = func(cert *iam.ServerCertificateMetadata) bool {
- return aws.StringValue(cert.ServerCertificateName) == v.(string)
- }
- }
-
- var metadatas = []*iam.ServerCertificateMetadata{}
- err := iamconn.ListServerCertificatesPages(&iam.ListServerCertificatesInput{}, func(p *iam.ListServerCertificatesOutput, lastPage bool) bool {
- for _, cert := range p.ServerCertificateMetadataList {
- if matcher(cert) {
- metadatas = append(metadatas, cert)
- }
- }
- return true
- })
- if err != nil {
- return errwrap.Wrapf("Error describing certificates: {{err}}", err)
- }
-
- if len(metadatas) == 0 {
- return fmt.Errorf("Search for AWS IAM server certificate returned no results")
- }
- if len(metadatas) > 1 {
- if !d.Get("latest").(bool) {
- return fmt.Errorf("Search for AWS IAM server certificate returned too many results")
- }
-
- sort.Sort(certificateByExpiration(metadatas))
- }
-
- metadata := metadatas[0]
- d.SetId(*metadata.ServerCertificateId)
- d.Set("arn", *metadata.Arn)
- d.Set("path", *metadata.Path)
- d.Set("id", *metadata.ServerCertificateId)
- d.Set("name", *metadata.ServerCertificateName)
- if metadata.Expiration != nil {
- d.Set("expiration_date", metadata.Expiration.Format("2006-01-02T15:04:05"))
- }
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_iam_server_certificate_test.go b/builtin/providers/aws/data_source_aws_iam_server_certificate_test.go
deleted file mode 100644
index b840ac115..000000000
--- a/builtin/providers/aws/data_source_aws_iam_server_certificate_test.go
+++ /dev/null
@@ -1,96 +0,0 @@
-package aws
-
-import (
- "fmt"
- "regexp"
- "sort"
- "testing"
- "time"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/iam"
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func timePtr(t time.Time) *time.Time {
- return &t
-}
-
-func TestResourceSortByExpirationDate(t *testing.T) {
- certs := []*iam.ServerCertificateMetadata{
- {
- ServerCertificateName: aws.String("oldest"),
- Expiration: timePtr(time.Now()),
- },
- {
- ServerCertificateName: aws.String("latest"),
- Expiration: timePtr(time.Now().Add(3 * time.Hour)),
- },
- {
- ServerCertificateName: aws.String("in between"),
- Expiration: timePtr(time.Now().Add(2 * time.Hour)),
- },
- }
- sort.Sort(certificateByExpiration(certs))
- if *certs[0].ServerCertificateName != "latest" {
- t.Fatalf("Expected first item to be %q, but was %q", "latest", *certs[0].ServerCertificateName)
- }
-}
-
-func TestAccAWSDataSourceIAMServerCertificate_basic(t *testing.T) {
- rInt := acctest.RandInt()
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckIAMServerCertificateDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccIAMServerCertConfig(rInt),
- },
- {
- Config: testAccAwsDataIAMServerCertConfig(rInt),
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttrSet("aws_iam_server_certificate.test_cert", "arn"),
- resource.TestCheckResourceAttrSet("data.aws_iam_server_certificate.test", "arn"),
- resource.TestCheckResourceAttrSet("data.aws_iam_server_certificate.test", "id"),
- resource.TestCheckResourceAttrSet("data.aws_iam_server_certificate.test", "name"),
- resource.TestCheckResourceAttrSet("data.aws_iam_server_certificate.test", "path"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSDataSourceIAMServerCertificate_matchNamePrefix(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckIAMServerCertificateDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAwsDataIAMServerCertConfigMatchNamePrefix,
- ExpectError: regexp.MustCompile(`Search for AWS IAM server certificate returned no results`),
- },
- },
- })
-}
-
-func testAccAwsDataIAMServerCertConfig(rInt int) string {
- return fmt.Sprintf(`
-%s
-
-data "aws_iam_server_certificate" "test" {
- name = "${aws_iam_server_certificate.test_cert.name}"
- latest = true
-}
-`, testAccIAMServerCertConfig(rInt))
-}
-
-var testAccAwsDataIAMServerCertConfigMatchNamePrefix = `
-data "aws_iam_server_certificate" "test" {
- name_prefix = "MyCert"
- latest = true
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_instance.go b/builtin/providers/aws/data_source_aws_instance.go
deleted file mode 100644
index 617a5c257..000000000
--- a/builtin/providers/aws/data_source_aws_instance.go
+++ /dev/null
@@ -1,356 +0,0 @@
-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 dataSourceAwsInstance() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsInstanceRead,
-
- Schema: map[string]*schema.Schema{
- "filter": dataSourceFiltersSchema(),
- "tags": dataSourceTagsSchema(),
- "instance_tags": tagsSchemaComputed(),
- "instance_id": {
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- },
- "ami": {
- Type: schema.TypeString,
- Computed: true,
- },
- "instance_type": {
- Type: schema.TypeString,
- Computed: true,
- },
- "instance_state": {
- Type: schema.TypeString,
- Computed: true,
- },
- "availability_zone": {
- Type: schema.TypeString,
- Computed: true,
- },
- "tenancy": {
- Type: schema.TypeString,
- Computed: true,
- },
- "key_name": {
- Type: schema.TypeString,
- Computed: true,
- },
- "public_dns": {
- Type: schema.TypeString,
- Computed: true,
- },
- "public_ip": {
- Type: schema.TypeString,
- Computed: true,
- },
- "private_dns": {
- Type: schema.TypeString,
- Computed: true,
- },
- "private_ip": {
- Type: schema.TypeString,
- Computed: true,
- },
- "iam_instance_profile": {
- Type: schema.TypeString,
- Computed: true,
- },
- "subnet_id": {
- Type: schema.TypeString,
- Computed: true,
- },
- "network_interface_id": {
- Type: schema.TypeString,
- Computed: true,
- },
- "associate_public_ip_address": {
- Type: schema.TypeBool,
- Computed: true,
- },
- "ebs_optimized": {
- Type: schema.TypeBool,
- Computed: true,
- },
- "source_dest_check": {
- Type: schema.TypeBool,
- Computed: true,
- },
- "monitoring": {
- Type: schema.TypeBool,
- Computed: true,
- },
- "user_data": {
- Type: schema.TypeString,
- Computed: true,
- },
- "security_groups": {
- Type: schema.TypeSet,
- Computed: true,
- Elem: &schema.Schema{
- Type: schema.TypeString,
- },
- },
- "vpc_security_group_ids": {
- Type: schema.TypeSet,
- Computed: true,
- Elem: &schema.Schema{
- Type: schema.TypeString,
- },
- },
- "ephemeral_block_device": {
- Type: schema.TypeSet,
- Computed: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "device_name": {
- Type: schema.TypeString,
- Required: true,
- },
-
- "virtual_name": {
- Type: schema.TypeString,
- Optional: true,
- },
-
- "no_device": {
- Type: schema.TypeBool,
- Optional: true,
- },
- },
- },
- },
- "ebs_block_device": {
- Type: schema.TypeSet,
- Computed: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "delete_on_termination": {
- Type: schema.TypeBool,
- Computed: true,
- },
-
- "device_name": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "encrypted": {
- Type: schema.TypeBool,
- Computed: true,
- },
-
- "iops": {
- Type: schema.TypeInt,
- Computed: true,
- },
-
- "snapshot_id": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "volume_size": {
- Type: schema.TypeInt,
- Computed: true,
- },
-
- "volume_type": {
- Type: schema.TypeString,
- Computed: true,
- },
- },
- },
- },
- "root_block_device": {
- Type: schema.TypeSet,
- Computed: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "delete_on_termination": {
- Type: schema.TypeBool,
- Computed: true,
- },
-
- "iops": {
- Type: schema.TypeInt,
- Computed: true,
- },
-
- "volume_size": {
- Type: schema.TypeInt,
- Computed: true,
- },
-
- "volume_type": {
- Type: schema.TypeString,
- Computed: true,
- },
- },
- },
- },
- },
- }
-}
-
-// dataSourceAwsInstanceRead performs the instanceID lookup
-func dataSourceAwsInstanceRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).ec2conn
-
- filters, filtersOk := d.GetOk("filter")
- instanceID, instanceIDOk := d.GetOk("instance_id")
- tags, tagsOk := d.GetOk("instance_tags")
-
- if filtersOk == false && instanceIDOk == false && tagsOk == false {
- return fmt.Errorf("One of filters, instance_tags, or instance_id must be assigned")
- }
-
- // Build up search parameters
- params := &ec2.DescribeInstancesInput{}
- if filtersOk {
- params.Filters = buildAwsDataSourceFilters(filters.(*schema.Set))
- }
- if instanceIDOk {
- params.InstanceIds = []*string{aws.String(instanceID.(string))}
- }
- if tagsOk {
- params.Filters = append(params.Filters, buildEC2TagFilterList(
- tagsFromMap(tags.(map[string]interface{})),
- )...)
- }
-
- // Perform the lookup
- resp, err := conn.DescribeInstances(params)
- if err != nil {
- return err
- }
-
- // If no instances were returned, return
- if len(resp.Reservations) == 0 {
- return fmt.Errorf("Your query returned no results. Please change your search criteria and try again.")
- }
-
- var filteredInstances []*ec2.Instance
-
- // loop through reservations, and remove terminated instances, populate instance slice
- for _, res := range resp.Reservations {
- for _, instance := range res.Instances {
- if instance.State != nil && *instance.State.Name != "terminated" {
- filteredInstances = append(filteredInstances, instance)
- }
- }
- }
-
- var instance *ec2.Instance
- if len(filteredInstances) < 1 {
- return fmt.Errorf("Your query returned no results. Please change your search criteria and try again.")
- }
-
- // (TODO: Support a list of instances to be returned)
- // Possibly with a different data source that returns a list of individual instance data sources
- if len(filteredInstances) > 1 {
- return fmt.Errorf("Your query returned more than one result. Please try a more " +
- "specific search criteria.")
- } else {
- instance = filteredInstances[0]
- }
-
- log.Printf("[DEBUG] aws_instance - Single Instance ID found: %s", *instance.InstanceId)
- return instanceDescriptionAttributes(d, instance, conn)
-}
-
-// Populate instance attribute fields with the returned instance
-func instanceDescriptionAttributes(d *schema.ResourceData, instance *ec2.Instance, conn *ec2.EC2) error {
- d.SetId(*instance.InstanceId)
- // Set the easy attributes
- d.Set("instance_state", instance.State.Name)
- if instance.Placement != nil {
- d.Set("availability_zone", instance.Placement.AvailabilityZone)
- }
- if instance.Placement.Tenancy != nil {
- d.Set("tenancy", instance.Placement.Tenancy)
- }
- d.Set("ami", instance.ImageId)
- d.Set("instance_type", instance.InstanceType)
- d.Set("key_name", instance.KeyName)
- d.Set("public_dns", instance.PublicDnsName)
- d.Set("public_ip", instance.PublicIpAddress)
- d.Set("private_dns", instance.PrivateDnsName)
- d.Set("private_ip", instance.PrivateIpAddress)
- d.Set("iam_instance_profile", iamInstanceProfileArnToName(instance.IamInstanceProfile))
-
- // iterate through network interfaces, and set subnet, network_interface, public_addr
- if len(instance.NetworkInterfaces) > 0 {
- for _, ni := range instance.NetworkInterfaces {
- if *ni.Attachment.DeviceIndex == 0 {
- d.Set("subnet_id", ni.SubnetId)
- d.Set("network_interface_id", ni.NetworkInterfaceId)
- d.Set("associate_public_ip_address", ni.Association != nil)
- }
- }
- } else {
- d.Set("subnet_id", instance.SubnetId)
- d.Set("network_interface_id", "")
- }
-
- d.Set("ebs_optimized", instance.EbsOptimized)
- if instance.SubnetId != nil && *instance.SubnetId != "" {
- d.Set("source_dest_check", instance.SourceDestCheck)
- }
-
- if instance.Monitoring != nil && instance.Monitoring.State != nil {
- monitoringState := *instance.Monitoring.State
- d.Set("monitoring", monitoringState == "enabled" || monitoringState == "pending")
- }
-
- d.Set("tags", dataSourceTags(instance.Tags))
-
- // Security Groups
- if err := readSecurityGroups(d, instance); err != nil {
- return err
- }
-
- // Block devices
- if err := readBlockDevices(d, instance, conn); err != nil {
- return err
- }
- if _, ok := d.GetOk("ephemeral_block_device"); !ok {
- d.Set("ephemeral_block_device", []interface{}{})
- }
-
- // Lookup and Set Instance Attributes
- {
- attr, err := conn.DescribeInstanceAttribute(&ec2.DescribeInstanceAttributeInput{
- Attribute: aws.String("disableApiTermination"),
- InstanceId: aws.String(d.Id()),
- })
- if err != nil {
- return err
- }
- d.Set("disable_api_termination", attr.DisableApiTermination.Value)
- }
- {
- attr, err := conn.DescribeInstanceAttribute(&ec2.DescribeInstanceAttributeInput{
- Attribute: aws.String(ec2.InstanceAttributeNameUserData),
- InstanceId: aws.String(d.Id()),
- })
- if err != nil {
- return err
- }
- if attr.UserData.Value != nil {
- d.Set("user_data", userDataHashSum(*attr.UserData.Value))
- }
- }
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_instance_test.go b/builtin/providers/aws/data_source_aws_instance_test.go
deleted file mode 100644
index 04eee4bed..000000000
--- a/builtin/providers/aws/data_source_aws_instance_test.go
+++ /dev/null
@@ -1,554 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "fmt"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSInstanceDataSource_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccInstanceDataSourceConfig,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr(
- "data.aws_instance.web-instance", "ami", "ami-4fccb37f"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.web-instance", "tags.#", "1"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.web-instance", "instance_type", "m1.small"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSInstanceDataSource_tags(t *testing.T) {
- rInt := acctest.RandInt()
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccInstanceDataSourceConfig_Tags(rInt),
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr(
- "data.aws_instance.web-instance", "ami", "ami-4fccb37f"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.web-instance", "tags.#", "2"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.web-instance", "instance_type", "m1.small"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSInstanceDataSource_AzUserData(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccInstanceDataSourceConfig_AzUserData,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "ami", "ami-4fccb37f"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "tags.#", "1"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "instance_type", "m1.small"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "availability_zone", "us-west-2a"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "user_data", "3dc39dda39be1205215e776bad998da361a5955d"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSInstanceDataSource_gp2IopsDevice(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccInstanceDataSourceConfig_gp2IopsDevice,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "ami", "ami-55a7ea65"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "instance_type", "m3.medium"),
- resource.TestCheckResourceAttr(
- "aws_instance.foo", "root_block_device.#", "1"),
- resource.TestCheckResourceAttr(
- "aws_instance.foo", "root_block_device.0.volume_size", "11"),
- resource.TestCheckResourceAttr(
- "aws_instance.foo", "root_block_device.0.volume_type", "gp2"),
- resource.TestCheckResourceAttr(
- "aws_instance.foo", "root_block_device.0.iops", "100"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSInstanceDataSource_blockDevices(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccInstanceDataSourceConfig_blockDevices,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "ami", "ami-55a7ea65"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "instance_type", "m3.medium"),
- resource.TestCheckResourceAttr(
- "aws_instance.foo", "root_block_device.#", "1"),
- resource.TestCheckResourceAttr(
- "aws_instance.foo", "root_block_device.0.volume_size", "11"),
- resource.TestCheckResourceAttr(
- "aws_instance.foo", "root_block_device.0.volume_type", "gp2"),
- resource.TestCheckResourceAttr(
- "aws_instance.foo", "ebs_block_device.#", "3"),
- resource.TestCheckResourceAttr(
- "aws_instance.foo", "ephemeral_block_device.#", "1"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSInstanceDataSource_rootInstanceStore(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccInstanceDataSourceConfig_rootInstanceStore,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "ami", "ami-44c36524"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "instance_type", "m3.medium"),
- resource.TestCheckResourceAttr(
- "aws_instance.foo", "ebs_block_device.#", "0"),
- resource.TestCheckResourceAttr(
- "aws_instance.foo", "ebs_optimized", "false"),
- resource.TestCheckResourceAttr(
- "aws_instance.foo", "root_block_device.#", "0"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSInstanceDataSource_privateIP(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccInstanceDataSourceConfig_privateIP,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "ami", "ami-c5eabbf5"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "instance_type", "t2.micro"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "private_ip", "10.1.1.42"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSInstanceDataSource_keyPair(t *testing.T) {
- rName := fmt.Sprintf("tf-test-key-%d", acctest.RandInt())
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccInstanceDataSourceConfig_keyPair(rName),
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "ami", "ami-408c7f28"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "instance_type", "t1.micro"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "tags.#", "1"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "key_name", rName),
- ),
- },
- },
- })
-}
-
-func TestAccAWSInstanceDataSource_VPC(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccInstanceDataSourceConfig_VPC,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "ami", "ami-4fccb37f"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "instance_type", "m1.small"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "user_data", "562a3e32810edf6ff09994f050f12e799452379d"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "associate_public_ip_address", "true"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "tenancy", "dedicated"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSInstanceDataSource_SecurityGroups(t *testing.T) {
- rInt := acctest.RandInt()
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccInstanceDataSourceConfig_SecurityGroups(rInt),
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "ami", "ami-408c7f28"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "instance_type", "m1.small"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "vpc_security_group_ids.#", "0"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "security_groups.#", "1"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "user_data", "3dc39dda39be1205215e776bad998da361a5955d"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSInstanceDataSource_VPCSecurityGroups(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccInstanceDataSourceConfig_VPCSecurityGroups,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "ami", "ami-21f78e11"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "instance_type", "t1.micro"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "security_groups.#", "0"),
- resource.TestCheckResourceAttr(
- "data.aws_instance.foo", "vpc_security_group_ids.#", "1"),
- ),
- },
- },
- })
-}
-
-// Lookup based on InstanceID
-const testAccInstanceDataSourceConfig = `
-resource "aws_instance" "web" {
- # us-west-2
- ami = "ami-4fccb37f"
- instance_type = "m1.small"
- tags {
- Name = "HelloWorld"
- }
-}
-
-data "aws_instance" "web-instance" {
- filter {
- name = "instance-id"
- values = ["${aws_instance.web.id}"]
- }
-}
-`
-
-// Use the tags attribute to filter
-func testAccInstanceDataSourceConfig_Tags(rInt int) string {
- return fmt.Sprintf(`
-resource "aws_instance" "web" {
- # us-west-2
- ami = "ami-4fccb37f"
- instance_type = "m1.small"
- tags {
- Name = "HelloWorld"
- TestSeed = "%d"
- }
-}
-
-data "aws_instance" "web-instance" {
- instance_tags {
- Name = "${aws_instance.web.tags["Name"]}"
- TestSeed = "%d"
- }
-}
-`, rInt, rInt)
-}
-
-// filter on tag, populate more attributes
-const testAccInstanceDataSourceConfig_AzUserData = `
-resource "aws_instance" "foo" {
- # us-west-2
- ami = "ami-4fccb37f"
- availability_zone = "us-west-2a"
-
- instance_type = "m1.small"
- user_data = "foo:-with-character's"
- tags {
- TFAccTest = "YesThisIsATest"
- }
-}
-
-data "aws_instance" "foo" {
- instance_id = "${aws_instance.foo.id}"
-}
-`
-
-// GP2IopsDevice
-const testAccInstanceDataSourceConfig_gp2IopsDevice = `
-resource "aws_instance" "foo" {
- # us-west-2
- ami = "ami-55a7ea65"
- instance_type = "m3.medium"
- root_block_device {
- volume_type = "gp2"
- volume_size = 11
- }
-}
-
-data "aws_instance" "foo" {
- instance_id = "${aws_instance.foo.id}"
-}
-`
-
-// Block Device
-const testAccInstanceDataSourceConfig_blockDevices = `
-resource "aws_instance" "foo" {
- # us-west-2
- ami = "ami-55a7ea65"
- instance_type = "m3.medium"
-
- root_block_device {
- volume_type = "gp2"
- volume_size = 11
- }
- ebs_block_device {
- device_name = "/dev/sdb"
- volume_size = 9
- }
- ebs_block_device {
- device_name = "/dev/sdc"
- volume_size = 10
- volume_type = "io1"
- iops = 100
- }
-
- # Encrypted ebs block device
- ebs_block_device {
- device_name = "/dev/sdd"
- volume_size = 12
- encrypted = true
- }
-
- ephemeral_block_device {
- device_name = "/dev/sde"
- virtual_name = "ephemeral0"
- }
-}
-
-data "aws_instance" "foo" {
- instance_id = "${aws_instance.foo.id}"
-}
-`
-
-const testAccInstanceDataSourceConfig_rootInstanceStore = `
-resource "aws_instance" "foo" {
- ami = "ami-44c36524"
- instance_type = "m3.medium"
-}
-data "aws_instance" "foo" {
- instance_id = "${aws_instance.foo.id}"
-}
-`
-
-const testAccInstanceDataSourceConfig_privateIP = `
-resource "aws_vpc" "foo" {
- cidr_block = "10.1.0.0/16"
- tags {
- Name = "testAccInstanceDataSourceConfig_privateIP"
- }
-}
-
-resource "aws_subnet" "foo" {
- cidr_block = "10.1.1.0/24"
- vpc_id = "${aws_vpc.foo.id}"
-}
-
-resource "aws_instance" "foo" {
- ami = "ami-c5eabbf5"
- instance_type = "t2.micro"
- subnet_id = "${aws_subnet.foo.id}"
- private_ip = "10.1.1.42"
-}
-
-data "aws_instance" "foo" {
- instance_id = "${aws_instance.foo.id}"
-}
-`
-
-func testAccInstanceDataSourceConfig_keyPair(rName string) string {
- return fmt.Sprintf(`
-provider "aws" {
- region = "us-east-1"
-}
-
-resource "aws_key_pair" "debugging" {
- key_name = "%s"
- public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD3F6tyPEFEzV0LX3X8BsXdMsQz1x2cEikKDEY0aIj41qgxMCP/iteneqXSIFZBp5vizPvaoIR3Um9xK7PGoW8giupGn+EPuxIA4cDM4vzOqOkiMPhz5XK0whEjkVzTo4+S0puvDZuwIsdiW9mxhJc7tgBNL0cYlWSYVkz4G/fslNfRPW5mYAM49f4fhtxPb5ok4Q2Lg9dPKVHO/Bgeu5woMc7RY0p1ej6D4CKFE6lymSDJpW0YHX/wqE9+cfEauh7xZcG0q9t2ta6F6fmX0agvpFyZo8aFbXeUBr7osSCJNgvavWbM/06niWrOvYX2xwWdhXmXSrbX8ZbabVohBK41 phodgson@thoughtworks.com"
-}
-
-resource "aws_instance" "foo" {
- ami = "ami-408c7f28"
- instance_type = "t1.micro"
- key_name = "${aws_key_pair.debugging.key_name}"
- tags {
- Name = "testAccInstanceDataSourceConfigKeyPair_TestAMI"
- }
-}
-
-data "aws_instance" "foo" {
- filter {
- name = "tag:Name"
- values = ["testAccInstanceDataSourceConfigKeyPair_TestAMI"]
- }
- filter {
- name = "key-name"
- values = ["${aws_instance.foo.key_name}"]
- }
-}`, rName)
-}
-
-const testAccInstanceDataSourceConfig_VPC = `
-resource "aws_vpc" "foo" {
- cidr_block = "10.1.0.0/16"
- tags {
- Name = "testAccInstanceDataSourceConfig_VPC"
- }
-}
-
-resource "aws_subnet" "foo" {
- cidr_block = "10.1.1.0/24"
- vpc_id = "${aws_vpc.foo.id}"
-}
-
-resource "aws_instance" "foo" {
- # us-west-2
- ami = "ami-4fccb37f"
- instance_type = "m1.small"
- subnet_id = "${aws_subnet.foo.id}"
- associate_public_ip_address = true
- tenancy = "dedicated"
- # pre-encoded base64 data
- user_data = "3dc39dda39be1205215e776bad998da361a5955d"
-}
-
-data "aws_instance" "foo" {
- instance_id = "${aws_instance.foo.id}"
-}
-`
-
-func testAccInstanceDataSourceConfig_SecurityGroups(rInt int) string {
- return fmt.Sprintf(`
-provider "aws" {
- region = "us-east-1"
-}
-
-resource "aws_security_group" "tf_test_foo" {
- name = "tf_test_foo-%d"
- description = "foo"
-
- ingress {
- protocol = "icmp"
- from_port = -1
- to_port = -1
- cidr_blocks = ["0.0.0.0/0"]
- }
-}
-
-resource "aws_instance" "foo" {
- ami = "ami-408c7f28"
- instance_type = "m1.small"
- security_groups = ["${aws_security_group.tf_test_foo.name}"]
- user_data = "foo:-with-character's"
-}
-
-data "aws_instance" "foo" {
- instance_id = "${aws_instance.foo.id}"
-}
-`, rInt)
-}
-
-const testAccInstanceDataSourceConfig_VPCSecurityGroups = `
-resource "aws_internet_gateway" "gw" {
- vpc_id = "${aws_vpc.foo.id}"
-}
-
-resource "aws_vpc" "foo" {
- cidr_block = "10.1.0.0/16"
- tags {
- Name = "tf-network-test"
- }
-}
-
-resource "aws_security_group" "tf_test_foo" {
- name = "tf_test_foo"
- description = "foo"
- vpc_id="${aws_vpc.foo.id}"
-
- ingress {
- protocol = "icmp"
- from_port = -1
- to_port = -1
- cidr_blocks = ["0.0.0.0/0"]
- }
-}
-
-resource "aws_subnet" "foo" {
- cidr_block = "10.1.1.0/24"
- vpc_id = "${aws_vpc.foo.id}"
-}
-
-resource "aws_instance" "foo_instance" {
- ami = "ami-21f78e11"
- instance_type = "t1.micro"
- vpc_security_group_ids = ["${aws_security_group.tf_test_foo.id}"]
- subnet_id = "${aws_subnet.foo.id}"
- depends_on = ["aws_internet_gateway.gw"]
-}
-
-data "aws_instance" "foo" {
- instance_id = "${aws_instance.foo_instance.id}"
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_ip_ranges.go b/builtin/providers/aws/data_source_aws_ip_ranges.go
deleted file mode 100644
index 32e9d8988..000000000
--- a/builtin/providers/aws/data_source_aws_ip_ranges.go
+++ /dev/null
@@ -1,151 +0,0 @@
-package aws
-
-import (
- "encoding/json"
- "fmt"
- "io/ioutil"
- "log"
- "sort"
- "strconv"
- "strings"
-
- "github.com/hashicorp/go-cleanhttp"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-type dataSourceAwsIPRangesResult struct {
- CreateDate string
- Prefixes []dataSourceAwsIPRangesPrefix
- SyncToken string
-}
-
-type dataSourceAwsIPRangesPrefix struct {
- IpPrefix string `json:"ip_prefix"`
- Region string
- Service string
-}
-
-func dataSourceAwsIPRanges() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsIPRangesRead,
-
- Schema: map[string]*schema.Schema{
- "cidr_blocks": &schema.Schema{
- Type: schema.TypeList,
- Computed: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
- "create_date": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- "regions": &schema.Schema{
- Type: schema.TypeSet,
- Elem: &schema.Schema{Type: schema.TypeString},
- Optional: true,
- },
- "services": &schema.Schema{
- Type: schema.TypeSet,
- Required: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
- "sync_token": &schema.Schema{
- Type: schema.TypeInt,
- Computed: true,
- },
- },
- }
-}
-
-func dataSourceAwsIPRangesRead(d *schema.ResourceData, meta interface{}) error {
-
- conn := cleanhttp.DefaultClient()
-
- log.Printf("[DEBUG] Reading IP ranges")
-
- res, err := conn.Get("https://ip-ranges.amazonaws.com/ip-ranges.json")
-
- if err != nil {
- return fmt.Errorf("Error listing IP ranges: %s", err)
- }
-
- defer res.Body.Close()
-
- data, err := ioutil.ReadAll(res.Body)
-
- if err != nil {
- return fmt.Errorf("Error reading response body: %s", err)
- }
-
- result := new(dataSourceAwsIPRangesResult)
-
- if err := json.Unmarshal(data, result); err != nil {
- return fmt.Errorf("Error parsing result: %s", err)
- }
-
- if err := d.Set("create_date", result.CreateDate); err != nil {
- return fmt.Errorf("Error setting create date: %s", err)
- }
-
- syncToken, err := strconv.Atoi(result.SyncToken)
-
- if err != nil {
- return fmt.Errorf("Error while converting sync token: %s", err)
- }
-
- d.SetId(result.SyncToken)
-
- if err := d.Set("sync_token", syncToken); err != nil {
- return fmt.Errorf("Error setting sync token: %s", err)
- }
-
- get := func(key string) *schema.Set {
-
- set := d.Get(key).(*schema.Set)
-
- for _, e := range set.List() {
-
- s := e.(string)
-
- set.Remove(s)
- set.Add(strings.ToLower(s))
-
- }
-
- return set
-
- }
-
- var (
- regions = get("regions")
- services = get("services")
- noRegionFilter = regions.Len() == 0
- prefixes []string
- )
-
- for _, e := range result.Prefixes {
-
- var (
- matchRegion = noRegionFilter || regions.Contains(strings.ToLower(e.Region))
- matchService = services.Contains(strings.ToLower(e.Service))
- )
-
- if matchRegion && matchService {
- prefixes = append(prefixes, e.IpPrefix)
- }
-
- }
-
- if len(prefixes) == 0 {
- return fmt.Errorf(" No IP ranges result from filters")
- }
-
- sort.Strings(prefixes)
-
- if err := d.Set("cidr_blocks", prefixes); err != nil {
- return fmt.Errorf("Error setting ip ranges: %s", err)
- }
-
- return nil
-
-}
diff --git a/builtin/providers/aws/data_source_aws_ip_ranges_test.go b/builtin/providers/aws/data_source_aws_ip_ranges_test.go
deleted file mode 100644
index 5e8f4b13d..000000000
--- a/builtin/providers/aws/data_source_aws_ip_ranges_test.go
+++ /dev/null
@@ -1,128 +0,0 @@
-package aws
-
-import (
- "fmt"
- "net"
- "regexp"
- "sort"
- "strconv"
- "testing"
- "time"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAWSIPRanges(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSIPRangesConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccAWSIPRanges("data.aws_ip_ranges.some"),
- ),
- },
- },
- })
-}
-
-func testAccAWSIPRanges(n string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
-
- r := s.RootModule().Resources[n]
- a := r.Primary.Attributes
-
- var (
- cidrBlockSize int
- createDate time.Time
- err error
- syncToken int
- )
-
- if cidrBlockSize, err = strconv.Atoi(a["cidr_blocks.#"]); err != nil {
- return err
- }
-
- if cidrBlockSize < 10 {
- return fmt.Errorf("cidr_blocks for eu-west-1 seem suspiciously low: %d", cidrBlockSize)
- }
-
- if createDate, err = time.Parse("2006-01-02-15-04-05", a["create_date"]); err != nil {
- return err
- }
-
- if syncToken, err = strconv.Atoi(a["sync_token"]); err != nil {
- return err
- }
-
- if syncToken != int(createDate.Unix()) {
- return fmt.Errorf("sync_token %d does not match create_date %s", syncToken, createDate)
- }
-
- var cidrBlocks sort.StringSlice = make([]string, cidrBlockSize)
-
- for i := range make([]string, cidrBlockSize) {
-
- block := a[fmt.Sprintf("cidr_blocks.%d", i)]
-
- if _, _, err := net.ParseCIDR(block); err != nil {
- return fmt.Errorf("malformed CIDR block %s: %s", block, err)
- }
-
- cidrBlocks[i] = block
-
- }
-
- if !sort.IsSorted(cidrBlocks) {
- return fmt.Errorf("unexpected order of cidr_blocks: %s", cidrBlocks)
- }
-
- var (
- regionMember = regexp.MustCompile(`regions\.\d+`)
- regions, services int
- serviceMember = regexp.MustCompile(`services\.\d+`)
- )
-
- for k, v := range a {
-
- if regionMember.MatchString(k) {
-
- if !(v == "eu-west-1" || v == "EU-central-1") {
- return fmt.Errorf("unexpected region %s", v)
- }
-
- regions = regions + 1
-
- }
-
- if serviceMember.MatchString(k) {
-
- if v != "EC2" {
- return fmt.Errorf("unexpected service %s", v)
- }
-
- services = services + 1
- }
-
- }
-
- if regions != 2 {
- return fmt.Errorf("unexpected number of regions: %d", regions)
- }
-
- if services != 1 {
- return fmt.Errorf("unexpected number of services: %d", services)
- }
-
- return nil
- }
-}
-
-const testAccAWSIPRangesConfig = `
-data "aws_ip_ranges" "some" {
- regions = [ "eu-west-1", "EU-central-1" ]
- services = [ "EC2" ]
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_kinesis_stream.go b/builtin/providers/aws/data_source_aws_kinesis_stream.go
deleted file mode 100644
index ebc843d11..000000000
--- a/builtin/providers/aws/data_source_aws_kinesis_stream.go
+++ /dev/null
@@ -1,95 +0,0 @@
-package aws
-
-import (
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/kinesis"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsKinesisStream() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsKinesisStreamRead,
-
- Schema: map[string]*schema.Schema{
- "name": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
-
- "arn": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
-
- "creation_timestamp": &schema.Schema{
- Type: schema.TypeInt,
- Computed: true,
- },
-
- "status": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
-
- "retention_period": &schema.Schema{
- Type: schema.TypeInt,
- Computed: true,
- },
-
- "open_shards": &schema.Schema{
- Type: schema.TypeSet,
- Computed: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- Set: schema.HashString,
- },
-
- "closed_shards": &schema.Schema{
- Type: schema.TypeSet,
- Computed: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- Set: schema.HashString,
- },
-
- "shard_level_metrics": &schema.Schema{
- Type: schema.TypeSet,
- Computed: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- Set: schema.HashString,
- },
-
- "tags": &schema.Schema{
- Type: schema.TypeMap,
- Computed: true,
- },
- },
- }
-}
-
-func dataSourceAwsKinesisStreamRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).kinesisconn
- sn := d.Get("name").(string)
-
- state, err := readKinesisStreamState(conn, sn)
- if err != nil {
- return err
- }
- d.SetId(state.arn)
- d.Set("arn", state.arn)
- d.Set("name", sn)
- d.Set("open_shards", state.openShards)
- d.Set("closed_shards", state.closedShards)
- d.Set("status", state.status)
- d.Set("creation_timestamp", state.creationTimestamp)
- d.Set("retention_period", state.retentionPeriod)
- d.Set("shard_level_metrics", state.shardLevelMetrics)
-
- tags, err := conn.ListTagsForStream(&kinesis.ListTagsForStreamInput{
- StreamName: aws.String(sn),
- })
- if err != nil {
- return err
- }
- d.Set("tags", tagsToMapKinesis(tags.Tags))
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_kinesis_stream_test.go b/builtin/providers/aws/data_source_aws_kinesis_stream_test.go
deleted file mode 100644
index 815724ae8..000000000
--- a/builtin/providers/aws/data_source_aws_kinesis_stream_test.go
+++ /dev/null
@@ -1,94 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/kinesis"
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSKinesisStreamDataSource(t *testing.T) {
- var stream kinesis.StreamDescription
-
- sn := fmt.Sprintf("terraform-kinesis-test-%d", acctest.RandInt())
- config := fmt.Sprintf(testAccCheckAwsKinesisStreamDataSourceConfig, sn)
-
- updateShardCount := func() {
- conn := testAccProvider.Meta().(*AWSClient).kinesisconn
- _, err := conn.UpdateShardCount(&kinesis.UpdateShardCountInput{
- ScalingType: aws.String(kinesis.ScalingTypeUniformScaling),
- StreamName: aws.String(sn),
- TargetShardCount: aws.Int64(3),
- })
- if err != nil {
- t.Fatalf("Error calling UpdateShardCount: %s", err)
- }
- if err := waitForKinesisToBeActive(conn, sn); err != nil {
- t.Fatal(err)
- }
- }
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckKinesisStreamDestroy,
- Steps: []resource.TestStep{
- {
- Config: config,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckKinesisStreamExists("aws_kinesis_stream.test_stream", &stream),
- resource.TestCheckResourceAttrSet("data.aws_kinesis_stream.test_stream", "arn"),
- resource.TestCheckResourceAttr("data.aws_kinesis_stream.test_stream", "name", sn),
- resource.TestCheckResourceAttr("data.aws_kinesis_stream.test_stream", "status", "ACTIVE"),
- resource.TestCheckResourceAttr("data.aws_kinesis_stream.test_stream", "open_shards.#", "2"),
- resource.TestCheckResourceAttr("data.aws_kinesis_stream.test_stream", "closed_shards.#", "0"),
- resource.TestCheckResourceAttr("data.aws_kinesis_stream.test_stream", "shard_level_metrics.#", "2"),
- resource.TestCheckResourceAttr("data.aws_kinesis_stream.test_stream", "retention_period", "72"),
- resource.TestCheckResourceAttrSet("data.aws_kinesis_stream.test_stream", "creation_timestamp"),
- resource.TestCheckResourceAttr("data.aws_kinesis_stream.test_stream", "tags.Name", "tf-test"),
- ),
- },
- {
- Config: config,
- PreConfig: updateShardCount,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckKinesisStreamExists("aws_kinesis_stream.test_stream", &stream),
- resource.TestCheckResourceAttrSet("data.aws_kinesis_stream.test_stream", "arn"),
- resource.TestCheckResourceAttr("data.aws_kinesis_stream.test_stream", "name", sn),
- resource.TestCheckResourceAttr("data.aws_kinesis_stream.test_stream", "status", "ACTIVE"),
- resource.TestCheckResourceAttr("data.aws_kinesis_stream.test_stream", "open_shards.#", "3"),
- resource.TestCheckResourceAttr("data.aws_kinesis_stream.test_stream", "closed_shards.#", "4"),
- resource.TestCheckResourceAttr("data.aws_kinesis_stream.test_stream", "shard_level_metrics.#", "2"),
- resource.TestCheckResourceAttr("data.aws_kinesis_stream.test_stream", "retention_period", "72"),
- resource.TestCheckResourceAttrSet("data.aws_kinesis_stream.test_stream", "creation_timestamp"),
- resource.TestCheckResourceAttr("data.aws_kinesis_stream.test_stream", "tags.Name", "tf-test"),
- ),
- },
- },
- })
-}
-
-var testAccCheckAwsKinesisStreamDataSourceConfig = `
-resource "aws_kinesis_stream" "test_stream" {
- name = "%s"
- shard_count = 2
- retention_period = 72
- tags {
- Name = "tf-test"
- }
- shard_level_metrics = [
- "IncomingBytes",
- "OutgoingBytes"
- ]
- lifecycle {
- ignore_changes = ["shard_count"]
- }
-}
-
-data "aws_kinesis_stream" "test_stream" {
- name = "${aws_kinesis_stream.test_stream.name}"
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_kms_alias.go b/builtin/providers/aws/data_source_aws_kms_alias.go
deleted file mode 100644
index 41c33b680..000000000
--- a/builtin/providers/aws/data_source_aws_kms_alias.go
+++ /dev/null
@@ -1,62 +0,0 @@
-package aws
-
-import (
- "fmt"
- "time"
-
- "github.com/aws/aws-sdk-go/service/kms"
- "github.com/hashicorp/errwrap"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsKmsAlias() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsKmsAliasRead,
- Schema: map[string]*schema.Schema{
- "name": {
- Type: schema.TypeString,
- Required: true,
- ValidateFunc: validateAwsKmsName,
- },
- "arn": {
- Type: schema.TypeString,
- Computed: true,
- },
- "target_key_id": {
- Type: schema.TypeString,
- Computed: true,
- },
- },
- }
-}
-
-func dataSourceAwsKmsAliasRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).kmsconn
- params := &kms.ListAliasesInput{}
-
- target := d.Get("name")
- var alias *kms.AliasListEntry
- err := conn.ListAliasesPages(params, func(page *kms.ListAliasesOutput, lastPage bool) bool {
- for _, entity := range page.Aliases {
- if *entity.AliasName == target {
- alias = entity
- return false
- }
- }
-
- return true
- })
- if err != nil {
- return errwrap.Wrapf("Error fetch KMS alias list: {{err}}", err)
- }
-
- if alias == nil {
- return fmt.Errorf("No alias with name %q found in this region.", target)
- }
-
- d.SetId(time.Now().UTC().String())
- d.Set("arn", alias.AliasArn)
- d.Set("target_key_id", alias.TargetKeyId)
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_kms_alias_test.go b/builtin/providers/aws/data_source_aws_kms_alias_test.go
deleted file mode 100644
index c498d5168..000000000
--- a/builtin/providers/aws/data_source_aws_kms_alias_test.go
+++ /dev/null
@@ -1,77 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccDataSourceAwsKmsAlias(t *testing.T) {
- rInt := acctest.RandInt()
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDataSourceAwsKmsAlias(rInt),
- Check: resource.ComposeTestCheckFunc(
- testAccDataSourceAwsKmsAliasCheck("data.aws_kms_alias.by_name"),
- ),
- },
- },
- })
-}
-
-func testAccDataSourceAwsKmsAliasCheck(name string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[name]
- if !ok {
- return fmt.Errorf("root module has no resource called %s", name)
- }
-
- kmsKeyRs, ok := s.RootModule().Resources["aws_kms_alias.single"]
- if !ok {
- return fmt.Errorf("can't find aws_kms_alias.single in state")
- }
-
- attr := rs.Primary.Attributes
-
- if attr["arn"] != kmsKeyRs.Primary.Attributes["arn"] {
- return fmt.Errorf(
- "arn is %s; want %s",
- attr["arn"],
- kmsKeyRs.Primary.Attributes["arn"],
- )
- }
-
- if attr["target_key_id"] != kmsKeyRs.Primary.Attributes["target_key_id"] {
- return fmt.Errorf(
- "target_key_id is %s; want %s",
- attr["target_key_id"],
- kmsKeyRs.Primary.Attributes["target_key_id"],
- )
- }
-
- return nil
- }
-}
-
-func testAccDataSourceAwsKmsAlias(rInt int) string {
- return fmt.Sprintf(`
-resource "aws_kms_key" "one" {
- description = "Terraform acc test"
- deletion_window_in_days = 7
-}
-
-resource "aws_kms_alias" "single" {
- name = "alias/tf-acc-key-alias-%d"
- target_key_id = "${aws_kms_key.one.key_id}"
-}
-
-data "aws_kms_alias" "by_name" {
- name = "${aws_kms_alias.single.name}"
-}`, rInt)
-}
diff --git a/builtin/providers/aws/data_source_aws_kms_ciphertext.go b/builtin/providers/aws/data_source_aws_kms_ciphertext.go
deleted file mode 100644
index 3f15965ca..000000000
--- a/builtin/providers/aws/data_source_aws_kms_ciphertext.go
+++ /dev/null
@@ -1,66 +0,0 @@
-package aws
-
-import (
- "encoding/base64"
- "log"
- "time"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/kms"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsKmsCiphetext() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsKmsCiphetextRead,
-
- Schema: map[string]*schema.Schema{
- "plaintext": {
- Type: schema.TypeString,
- Required: true,
- },
-
- "key_id": {
- Type: schema.TypeString,
- Required: true,
- },
-
- "context": &schema.Schema{
- Type: schema.TypeMap,
- Optional: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
-
- "ciphertext_blob": {
- Type: schema.TypeString,
- Computed: true,
- },
- },
- }
-}
-
-func dataSourceAwsKmsCiphetextRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).kmsconn
-
- d.SetId(time.Now().UTC().String())
-
- req := &kms.EncryptInput{
- KeyId: aws.String(d.Get("key_id").(string)),
- Plaintext: []byte(d.Get("plaintext").(string)),
- }
-
- if ec := d.Get("context"); ec != nil {
- req.EncryptionContext = stringMapToPointers(ec.(map[string]interface{}))
- }
-
- log.Printf("[DEBUG] KMS encrypt for key: %s", d.Get("key_id").(string))
-
- resp, err := conn.Encrypt(req)
- if err != nil {
- return err
- }
-
- d.Set("ciphertext_blob", base64.StdEncoding.EncodeToString(resp.CiphertextBlob))
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_kms_ciphertext_test.go b/builtin/providers/aws/data_source_aws_kms_ciphertext_test.go
deleted file mode 100644
index f871acc03..000000000
--- a/builtin/providers/aws/data_source_aws_kms_ciphertext_test.go
+++ /dev/null
@@ -1,136 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccDataSourceAwsKmsCiphertext_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAwsKmsCiphertextConfig_basic,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttrSet(
- "data.aws_kms_ciphertext.foo", "ciphertext_blob"),
- ),
- },
- },
- })
-}
-
-func TestAccDataSourceAwsKmsCiphertext_validate(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAwsKmsCiphertextConfig_validate,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttrSet(
- "data.aws_kms_ciphertext.foo", "ciphertext_blob"),
- resource.TestCheckResourceAttrSet(
- "data.aws_kms_secret.foo", "plaintext"),
- resource.TestCheckResourceAttr(
- "data.aws_kms_secret.foo", "plaintext", "Super secret data"),
- ),
- },
- },
- })
-}
-
-func TestAccDataSourceAwsKmsCiphertext_validate_withContext(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAwsKmsCiphertextConfig_validate_withContext,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttrSet(
- "data.aws_kms_ciphertext.foo", "ciphertext_blob"),
- resource.TestCheckResourceAttrSet(
- "data.aws_kms_secret.foo", "plaintext"),
- resource.TestCheckResourceAttr(
- "data.aws_kms_secret.foo", "plaintext", "Super secret data"),
- ),
- },
- },
- })
-}
-
-const testAccDataSourceAwsKmsCiphertextConfig_basic = `
-provider "aws" {
- region = "us-west-2"
-}
-
-resource "aws_kms_key" "foo" {
- description = "tf-test-acc-data-source-aws-kms-ciphertext-basic"
- is_enabled = true
-}
-
-data "aws_kms_ciphertext" "foo" {
- key_id = "${aws_kms_key.foo.key_id}"
-
- plaintext = "Super secret data"
-}
-`
-
-const testAccDataSourceAwsKmsCiphertextConfig_validate = `
-provider "aws" {
- region = "us-west-2"
-}
-
-resource "aws_kms_key" "foo" {
- description = "tf-test-acc-data-source-aws-kms-ciphertext-validate"
- is_enabled = true
-}
-
-data "aws_kms_ciphertext" "foo" {
- key_id = "${aws_kms_key.foo.key_id}"
-
- plaintext = "Super secret data"
-}
-
-data "aws_kms_secret" "foo" {
- secret {
- name = "plaintext"
- payload = "${data.aws_kms_ciphertext.foo.ciphertext_blob}"
- }
-}
-`
-
-const testAccDataSourceAwsKmsCiphertextConfig_validate_withContext = `
-provider "aws" {
- region = "us-west-2"
-}
-
-resource "aws_kms_key" "foo" {
- description = "tf-test-acc-data-source-aws-kms-ciphertext-validate-with-context"
- is_enabled = true
-}
-
-data "aws_kms_ciphertext" "foo" {
- key_id = "${aws_kms_key.foo.key_id}"
-
- plaintext = "Super secret data"
-
- context {
- name = "value"
- }
-}
-
-data "aws_kms_secret" "foo" {
- secret {
- name = "plaintext"
- payload = "${data.aws_kms_ciphertext.foo.ciphertext_blob}"
-
- context {
- name = "value"
- }
- }
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_kms_secret.go b/builtin/providers/aws/data_source_aws_kms_secret.go
deleted file mode 100644
index 92d5134fd..000000000
--- a/builtin/providers/aws/data_source_aws_kms_secret.go
+++ /dev/null
@@ -1,99 +0,0 @@
-package aws
-
-import (
- "encoding/base64"
- "fmt"
- "log"
- "time"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/kms"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsKmsSecret() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsKmsSecretRead,
-
- Schema: map[string]*schema.Schema{
- "secret": &schema.Schema{
- Type: schema.TypeSet,
- Required: true,
- ForceNew: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "name": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
- "payload": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
- "context": &schema.Schema{
- Type: schema.TypeMap,
- Optional: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
- "grant_tokens": &schema.Schema{
- Type: schema.TypeList,
- Optional: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
- },
- },
- },
- "__has_dynamic_attributes": {
- Type: schema.TypeString,
- Optional: true,
- },
- },
- }
-}
-
-// dataSourceAwsKmsSecretRead decrypts the specified secrets
-func dataSourceAwsKmsSecretRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).kmsconn
- secrets := d.Get("secret").(*schema.Set)
-
- d.SetId(time.Now().UTC().String())
-
- for _, v := range secrets.List() {
- secret := v.(map[string]interface{})
-
- // base64 decode the payload
- payload, err := base64.StdEncoding.DecodeString(secret["payload"].(string))
- if err != nil {
- return fmt.Errorf("Invalid base64 value for secret '%s': %v", secret["name"].(string), err)
- }
-
- // build the kms decrypt params
- params := &kms.DecryptInput{
- CiphertextBlob: []byte(payload),
- }
- if context, exists := secret["context"]; exists {
- params.EncryptionContext = make(map[string]*string)
- for k, v := range context.(map[string]interface{}) {
- params.EncryptionContext[k] = aws.String(v.(string))
- }
- }
- if grant_tokens, exists := secret["grant_tokens"]; exists {
- params.GrantTokens = make([]*string, 0)
- for _, v := range grant_tokens.([]interface{}) {
- params.GrantTokens = append(params.GrantTokens, aws.String(v.(string)))
- }
- }
-
- // decrypt
- resp, err := conn.Decrypt(params)
- if err != nil {
- return fmt.Errorf("Failed to decrypt '%s': %s", secret["name"].(string), err)
- }
-
- // Set the secret via the name
- log.Printf("[DEBUG] aws_kms_secret - successfully decrypted secret: %s", secret["name"].(string))
- d.UnsafeSetFieldRaw(secret["name"].(string), string(resp.Plaintext))
- }
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_kms_secret_test.go b/builtin/providers/aws/data_source_aws_kms_secret_test.go
deleted file mode 100644
index 4d0bf139e..000000000
--- a/builtin/providers/aws/data_source_aws_kms_secret_test.go
+++ /dev/null
@@ -1,96 +0,0 @@
-package aws
-
-import (
- "encoding/base64"
- "fmt"
- "testing"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/kms"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAWSKmsSecretDataSource_basic(t *testing.T) {
- // Run a resource test to setup our KMS key
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsKmsSecretDataSourceKey,
- Check: func(s *terraform.State) error {
- encryptedPayload, err := testAccCheckAwsKmsSecretDataSourceCheckKeySetup(s)
- if err != nil {
- return err
- }
-
- // We run the actual test on our data source nested in the
- // Check function of the KMS key so we can access the
- // encrypted output, above, and so that the key will be
- // deleted at the end of the test
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: fmt.Sprintf(testAccCheckAwsKmsSecretDataSourceSecret, encryptedPayload),
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr("data.aws_kms_secret.testing", "secret_name", "PAYLOAD"),
- ),
- },
- },
- })
-
- return nil
- },
- },
- },
- })
-
-}
-
-func testAccCheckAwsKmsSecretDataSourceCheckKeySetup(s *terraform.State) (string, error) {
- rs, ok := s.RootModule().Resources["aws_kms_key.terraform_data_source_testing"]
- if !ok {
- return "", fmt.Errorf("Failed to setup a KMS key for data source testing!")
- }
-
- // Now that the key is setup encrypt a string using it
- // XXX TODO: Set up and test with grants
- params := &kms.EncryptInput{
- KeyId: aws.String(rs.Primary.Attributes["arn"]),
- Plaintext: []byte("PAYLOAD"),
- EncryptionContext: map[string]*string{
- "name": aws.String("value"),
- },
- }
-
- kmsconn := testAccProvider.Meta().(*AWSClient).kmsconn
- resp, err := kmsconn.Encrypt(params)
- if err != nil {
- return "", fmt.Errorf("Failed encrypting string with KMS for data source testing: %s", err)
- }
-
- return base64.StdEncoding.EncodeToString(resp.CiphertextBlob), nil
-}
-
-const testAccCheckAwsKmsSecretDataSourceKey = `
-resource "aws_kms_key" "terraform_data_source_testing" {
- description = "Testing the Terraform AWS KMS Secret data_source"
-}
-`
-
-const testAccCheckAwsKmsSecretDataSourceSecret = `
-data "aws_kms_secret" "testing" {
- secret {
- name = "secret_name"
- payload = "%s"
-
- context {
- name = "value"
- }
- }
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_partition.go b/builtin/providers/aws/data_source_aws_partition.go
deleted file mode 100644
index d52f7ee47..000000000
--- a/builtin/providers/aws/data_source_aws_partition.go
+++ /dev/null
@@ -1,33 +0,0 @@
-package aws
-
-import (
- "log"
- "time"
-
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsPartition() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsPartitionRead,
-
- Schema: map[string]*schema.Schema{
- "partition": {
- Type: schema.TypeString,
- Computed: true,
- },
- },
- }
-}
-
-func dataSourceAwsPartitionRead(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AWSClient)
-
- log.Printf("[DEBUG] Reading Partition.")
- d.SetId(time.Now().UTC().String())
-
- log.Printf("[DEBUG] Setting AWS Partition to %s.", client.partition)
- d.Set("partition", meta.(*AWSClient).partition)
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_partition_test.go b/builtin/providers/aws/data_source_aws_partition_test.go
deleted file mode 100644
index 5610a0b96..000000000
--- a/builtin/providers/aws/data_source_aws_partition_test.go
+++ /dev/null
@@ -1,44 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAWSPartition_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsPartitionConfig_basic,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsPartition("data.aws_partition.current"),
- ),
- },
- },
- })
-}
-
-func testAccCheckAwsPartition(n string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Can't find resource: %s", n)
- }
-
- expected := testAccProvider.Meta().(*AWSClient).partition
- if rs.Primary.Attributes["partition"] != expected {
- return fmt.Errorf("Incorrect Partition: expected %q, got %q", expected, rs.Primary.Attributes["partition"])
- }
-
- return nil
- }
-}
-
-const testAccCheckAwsPartitionConfig_basic = `
-data "aws_partition" "current" { }
-`
diff --git a/builtin/providers/aws/data_source_aws_prefix_list.go b/builtin/providers/aws/data_source_aws_prefix_list.go
deleted file mode 100644
index 8bed85506..000000000
--- a/builtin/providers/aws/data_source_aws_prefix_list.go
+++ /dev/null
@@ -1,76 +0,0 @@
-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 dataSourceAwsPrefixList() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsPrefixListRead,
-
- Schema: map[string]*schema.Schema{
- "prefix_list_id": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- },
- "name": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- // Computed values.
- "id": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- "cidr_blocks": &schema.Schema{
- Type: schema.TypeList,
- Computed: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
- },
- }
-}
-
-func dataSourceAwsPrefixListRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).ec2conn
-
- req := &ec2.DescribePrefixListsInput{}
-
- if prefixListID := d.Get("prefix_list_id"); prefixListID != "" {
- req.PrefixListIds = aws.StringSlice([]string{prefixListID.(string)})
- }
- req.Filters = buildEC2AttributeFilterList(
- map[string]string{
- "prefix-list-name": d.Get("name").(string),
- },
- )
-
- log.Printf("[DEBUG] DescribePrefixLists %s\n", req)
- resp, err := conn.DescribePrefixLists(req)
- if err != nil {
- return err
- }
- if resp == nil || len(resp.PrefixLists) == 0 {
- return fmt.Errorf("no matching prefix list found; the prefix list ID or name may be invalid or not exist in the current region")
- }
-
- pl := resp.PrefixLists[0]
-
- d.SetId(*pl.PrefixListId)
- d.Set("id", pl.PrefixListId)
- d.Set("name", pl.PrefixListName)
-
- cidrs := make([]string, len(pl.Cidrs))
- for i, v := range pl.Cidrs {
- cidrs[i] = *v
- }
- d.Set("cidr_blocks", cidrs)
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_prefix_list_test.go b/builtin/providers/aws/data_source_aws_prefix_list_test.go
deleted file mode 100644
index c9ad308d0..000000000
--- a/builtin/providers/aws/data_source_aws_prefix_list_test.go
+++ /dev/null
@@ -1,72 +0,0 @@
-package aws
-
-import (
- "fmt"
- "strconv"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccDataSourceAwsPrefixList(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDataSourceAwsPrefixListConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccDataSourceAwsPrefixListCheck("data.aws_prefix_list.s3_by_id"),
- testAccDataSourceAwsPrefixListCheck("data.aws_prefix_list.s3_by_name"),
- ),
- },
- },
- })
-}
-
-func testAccDataSourceAwsPrefixListCheck(name string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[name]
- if !ok {
- return fmt.Errorf("root module has no resource called %s", name)
- }
-
- attr := rs.Primary.Attributes
-
- if attr["name"] != "com.amazonaws.us-west-2.s3" {
- return fmt.Errorf("bad name %s", attr["name"])
- }
- if attr["id"] != "pl-68a54001" {
- return fmt.Errorf("bad id %s", attr["id"])
- }
-
- var (
- cidrBlockSize int
- err error
- )
-
- if cidrBlockSize, err = strconv.Atoi(attr["cidr_blocks.#"]); err != nil {
- return err
- }
- if cidrBlockSize < 1 {
- return fmt.Errorf("cidr_blocks seem suspiciously low: %d", cidrBlockSize)
- }
-
- return nil
- }
-}
-
-const testAccDataSourceAwsPrefixListConfig = `
-provider "aws" {
- region = "us-west-2"
-}
-
-data "aws_prefix_list" "s3_by_id" {
- prefix_list_id = "pl-68a54001"
-}
-
-data "aws_prefix_list" "s3_by_name" {
- name = "com.amazonaws.us-west-2.s3"
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_redshift_service_account.go b/builtin/providers/aws/data_source_aws_redshift_service_account.go
deleted file mode 100644
index faa210fff..000000000
--- a/builtin/providers/aws/data_source_aws_redshift_service_account.go
+++ /dev/null
@@ -1,50 +0,0 @@
-package aws
-
-import (
- "fmt"
-
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-// See http://docs.aws.amazon.com/redshift/latest/mgmt/db-auditing.html#db-auditing-enable-logging
-var redshiftServiceAccountPerRegionMap = map[string]string{
- "us-east-1": "193672423079",
- "us-east-2": "391106570357",
- "us-west-1": "262260360010",
- "us-west-2": "902366379725",
- "ap-south-1": "865932855811",
- "ap-northeast-2": "760740231472",
- "ap-southeast-1": "361669875840",
- "ap-southeast-2": "762762565011",
- "ap-northeast-1": "404641285394",
- "ca-central-1": "907379612154",
- "eu-central-1": "053454850223",
- "eu-west-1": "210876761215",
-}
-
-func dataSourceAwsRedshiftServiceAccount() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsRedshiftServiceAccountRead,
-
- Schema: map[string]*schema.Schema{
- "region": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- },
- },
- }
-}
-
-func dataSourceAwsRedshiftServiceAccountRead(d *schema.ResourceData, meta interface{}) error {
- region := meta.(*AWSClient).region
- if v, ok := d.GetOk("region"); ok {
- region = v.(string)
- }
-
- if accid, ok := redshiftServiceAccountPerRegionMap[region]; ok {
- d.SetId(accid)
- return nil
- }
-
- return fmt.Errorf("Unknown region (%q)", region)
-}
diff --git a/builtin/providers/aws/data_source_aws_redshift_service_account_test.go b/builtin/providers/aws/data_source_aws_redshift_service_account_test.go
deleted file mode 100644
index 347de6814..000000000
--- a/builtin/providers/aws/data_source_aws_redshift_service_account_test.go
+++ /dev/null
@@ -1,38 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSRedshiftServiceAccount_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccCheckAwsRedshiftServiceAccountConfig,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr("data.aws_redshift_service_account.main", "id", "902366379725"),
- ),
- },
- resource.TestStep{
- Config: testAccCheckAwsRedshiftServiceAccountExplicitRegionConfig,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr("data.aws_redshift_service_account.regional", "id", "210876761215"),
- ),
- },
- },
- })
-}
-
-const testAccCheckAwsRedshiftServiceAccountConfig = `
-data "aws_redshift_service_account" "main" { }
-`
-
-const testAccCheckAwsRedshiftServiceAccountExplicitRegionConfig = `
-data "aws_redshift_service_account" "regional" {
- region = "eu-west-1"
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_region.go b/builtin/providers/aws/data_source_aws_region.go
deleted file mode 100644
index ed75f7056..000000000
--- a/builtin/providers/aws/data_source_aws_region.go
+++ /dev/null
@@ -1,84 +0,0 @@
-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 dataSourceAwsRegion() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsRegionRead,
-
- Schema: map[string]*schema.Schema{
- "name": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
-
- "current": &schema.Schema{
- Type: schema.TypeBool,
- Optional: true,
- Computed: true,
- },
-
- "endpoint": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- },
- }
-}
-
-func dataSourceAwsRegionRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).ec2conn
- currentRegion := meta.(*AWSClient).region
-
- req := &ec2.DescribeRegionsInput{}
-
- req.RegionNames = make([]*string, 0, 2)
- if name := d.Get("name").(string); name != "" {
- req.RegionNames = append(req.RegionNames, aws.String(name))
- }
-
- if d.Get("current").(bool) {
- req.RegionNames = append(req.RegionNames, aws.String(currentRegion))
- }
-
- req.Filters = buildEC2AttributeFilterList(
- map[string]string{
- "endpoint": d.Get("endpoint").(string),
- },
- )
- if len(req.Filters) == 0 {
- // Don't send an empty filters list; the EC2 API won't accept it.
- req.Filters = nil
- }
-
- log.Printf("[DEBUG] DescribeRegions %s\n", req)
- resp, err := conn.DescribeRegions(req)
- if err != nil {
- return err
- }
- if resp == nil || len(resp.Regions) == 0 {
- return fmt.Errorf("no matching regions found")
- }
- if len(resp.Regions) > 1 {
- return fmt.Errorf("multiple regions matched; use additional constraints to reduce matches to a single region")
- }
-
- region := resp.Regions[0]
-
- d.SetId(*region.RegionName)
- d.Set("id", region.RegionName)
- d.Set("name", region.RegionName)
- d.Set("endpoint", region.Endpoint)
- d.Set("current", *region.RegionName == currentRegion)
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_region_test.go b/builtin/providers/aws/data_source_aws_region_test.go
deleted file mode 100644
index 370c4b2b0..000000000
--- a/builtin/providers/aws/data_source_aws_region_test.go
+++ /dev/null
@@ -1,64 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccDataSourceAwsRegion(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDataSourceAwsRegionConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccDataSourceAwsRegionCheck("data.aws_region.by_name_current", "us-west-2", "true"),
- testAccDataSourceAwsRegionCheck("data.aws_region.by_name_other", "us-west-1", "false"),
- testAccDataSourceAwsRegionCheck("data.aws_region.by_current", "us-west-2", "true"),
- ),
- },
- },
- })
-}
-
-func testAccDataSourceAwsRegionCheck(name, region, current string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[name]
- if !ok {
- return fmt.Errorf("root module has no resource called %s", name)
- }
-
- attr := rs.Primary.Attributes
-
- if attr["name"] != region {
- return fmt.Errorf("bad name %s", attr["name"])
- }
- if attr["current"] != current {
- return fmt.Errorf("bad current %s; want %s", attr["current"], current)
- }
-
- return nil
- }
-}
-
-const testAccDataSourceAwsRegionConfig = `
-provider "aws" {
- region = "us-west-2"
-}
-
-data "aws_region" "by_name_current" {
- name = "us-west-2"
-}
-
-data "aws_region" "by_name_other" {
- name = "us-west-1"
-}
-
-data "aws_region" "by_current" {
- current = true
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_route53_zone.go b/builtin/providers/aws/data_source_aws_route53_zone.go
deleted file mode 100644
index b3de4eed4..000000000
--- a/builtin/providers/aws/data_source_aws_route53_zone.go
+++ /dev/null
@@ -1,176 +0,0 @@
-package aws
-
-import (
- "fmt"
- "strings"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/route53"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsRoute53Zone() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsRoute53ZoneRead,
-
- Schema: map[string]*schema.Schema{
- "zone_id": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "name": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "private_zone": {
- Type: schema.TypeBool,
- Optional: true,
- Default: false,
- },
- "comment": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "caller_reference": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "vpc_id": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "tags": tagsSchemaComputed(),
- "resource_record_set_count": {
- Type: schema.TypeInt,
- Optional: true,
- Computed: true,
- },
- },
- }
-}
-
-func dataSourceAwsRoute53ZoneRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).r53conn
- name, nameExists := d.GetOk("name")
- name = hostedZoneName(name.(string))
- id, idExists := d.GetOk("zone_id")
- vpcId, vpcIdExists := d.GetOk("vpc_id")
- tags := tagsFromMap(d.Get("tags").(map[string]interface{}))
- if nameExists && idExists {
- return fmt.Errorf("zone_id and name arguments can't be used together")
- } else if !nameExists && !idExists {
- return fmt.Errorf("Either name or zone_id must be set")
- }
-
- var nextMarker *string
-
- var hostedZoneFound *route53.HostedZone
- // We loop through all hostedzone
- for allHostedZoneListed := false; !allHostedZoneListed; {
- req := &route53.ListHostedZonesInput{}
- if nextMarker != nil {
- req.Marker = nextMarker
- }
- resp, err := conn.ListHostedZones(req)
-
- if err != nil {
- return fmt.Errorf("Error finding Route 53 Hosted Zone: %v", err)
- }
- for _, hostedZone := range resp.HostedZones {
- hostedZoneId := cleanZoneID(*hostedZone.Id)
- if idExists && hostedZoneId == id.(string) {
- hostedZoneFound = hostedZone
- break
- // we check if the name is the same as requested and if private zone field is the same as requested or if there is a vpc_id
- } else if *hostedZone.Name == name && (*hostedZone.Config.PrivateZone == d.Get("private_zone").(bool) || (*hostedZone.Config.PrivateZone == true && vpcIdExists)) {
- matchingVPC := false
- if vpcIdExists {
- reqHostedZone := &route53.GetHostedZoneInput{}
- reqHostedZone.Id = aws.String(hostedZoneId)
-
- respHostedZone, errHostedZone := conn.GetHostedZone(reqHostedZone)
- if errHostedZone != nil {
- return fmt.Errorf("Error finding Route 53 Hosted Zone: %v", errHostedZone)
- }
- // we go through all VPCs
- for _, vpc := range respHostedZone.VPCs {
- if *vpc.VPCId == vpcId.(string) {
- matchingVPC = true
- break
- }
- }
- } else {
- matchingVPC = true
- }
- // we check if tags match
- matchingTags := true
- if len(tags) > 0 {
- reqListTags := &route53.ListTagsForResourceInput{}
- reqListTags.ResourceId = aws.String(hostedZoneId)
- reqListTags.ResourceType = aws.String("hostedzone")
- respListTags, errListTags := conn.ListTagsForResource(reqListTags)
-
- if errListTags != nil {
- return fmt.Errorf("Error finding Route 53 Hosted Zone: %v", errListTags)
- }
- for _, tag := range tags {
- found := false
- for _, tagRequested := range respListTags.ResourceTagSet.Tags {
- if *tag.Key == *tagRequested.Key && *tag.Value == *tagRequested.Value {
- found = true
- }
- }
-
- if !found {
- matchingTags = false
- break
- }
- }
-
- }
-
- if matchingTags && matchingVPC {
- if hostedZoneFound != nil {
- return fmt.Errorf("multiple Route53Zone found please use vpc_id option to filter")
- } else {
- hostedZoneFound = hostedZone
- }
- }
- }
-
- }
- if *resp.IsTruncated {
-
- nextMarker = resp.NextMarker
- } else {
- allHostedZoneListed = true
- }
- }
- if hostedZoneFound == nil {
- return fmt.Errorf("no matching Route53Zone found")
- }
-
- idHostedZone := cleanZoneID(*hostedZoneFound.Id)
- d.SetId(idHostedZone)
- d.Set("zone_id", idHostedZone)
- d.Set("name", hostedZoneFound.Name)
- d.Set("comment", hostedZoneFound.Config.Comment)
- d.Set("private_zone", hostedZoneFound.Config.PrivateZone)
- d.Set("caller_reference", hostedZoneFound.CallerReference)
- d.Set("resource_record_set_count", hostedZoneFound.ResourceRecordSetCount)
- return nil
-}
-
-// used to manage trailing .
-func hostedZoneName(name string) string {
- if strings.HasSuffix(name, ".") {
- return name
- } else {
- return name + "."
- }
-}
diff --git a/builtin/providers/aws/data_source_aws_route53_zone_test.go b/builtin/providers/aws/data_source_aws_route53_zone_test.go
deleted file mode 100644
index 4be9cae42..000000000
--- a/builtin/providers/aws/data_source_aws_route53_zone_test.go
+++ /dev/null
@@ -1,117 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccDataSourceAwsRoute53Zone(t *testing.T) {
- rInt := acctest.RandInt()
- publicResourceName := "aws_route53_zone.test"
- publicDomain := fmt.Sprintf("terraformtestacchz-%d.com.", rInt)
- privateResourceName := "aws_route53_zone.test_private"
- privateDomain := fmt.Sprintf("test.acc-%d.", rInt)
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAwsRoute53ZoneConfig(rInt),
- Check: resource.ComposeTestCheckFunc(
- testAccDataSourceAwsRoute53ZoneCheck(
- publicResourceName, "data.aws_route53_zone.by_zone_id", publicDomain),
- testAccDataSourceAwsRoute53ZoneCheck(
- publicResourceName, "data.aws_route53_zone.by_name", publicDomain),
- testAccDataSourceAwsRoute53ZoneCheck(
- privateResourceName, "data.aws_route53_zone.by_vpc", privateDomain),
- testAccDataSourceAwsRoute53ZoneCheck(
- privateResourceName, "data.aws_route53_zone.by_tag", privateDomain),
- ),
- },
- },
- })
-}
-
-// rsName for the name of the created resource
-// dsName for the name of the created data source
-// zName for the name of the domain
-func testAccDataSourceAwsRoute53ZoneCheck(rsName, dsName, zName string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[rsName]
- if !ok {
- return fmt.Errorf("root module has no resource called %s", rsName)
- }
-
- hostedZone, ok := s.RootModule().Resources[dsName]
- if !ok {
- return fmt.Errorf("can't find zone %q in state", dsName)
- }
-
- attr := rs.Primary.Attributes
- if attr["id"] != hostedZone.Primary.Attributes["id"] {
- return fmt.Errorf(
- "id is %s; want %s",
- attr["id"],
- hostedZone.Primary.Attributes["id"],
- )
- }
-
- if attr["name"] != zName {
- return fmt.Errorf("Route53 Zone name is %q; want %q", attr["name"], zName)
- }
-
- return nil
- }
-}
-
-func testAccDataSourceAwsRoute53ZoneConfig(rInt int) string {
- return fmt.Sprintf(`
- provider "aws" {
- region = "us-east-1"
- }
-
- resource "aws_vpc" "test" {
- cidr_block = "172.16.0.0/16"
- tags {
- Name = "testAccDataSourceAwsRoute53ZoneConfig"
- }
- }
-
- resource "aws_route53_zone" "test_private" {
- name = "test.acc-%d."
- vpc_id = "${aws_vpc.test.id}"
- tags {
- Environment = "dev-%d"
- }
- }
-
- data "aws_route53_zone" "by_vpc" {
- name = "${aws_route53_zone.test_private.name}"
- vpc_id = "${aws_vpc.test.id}"
- }
-
- data "aws_route53_zone" "by_tag" {
- name = "${aws_route53_zone.test_private.name}"
- private_zone = true
- tags {
- Environment = "dev-%d"
- }
- }
-
- resource "aws_route53_zone" "test" {
- name = "terraformtestacchz-%d.com."
- }
-
- data "aws_route53_zone" "by_zone_id" {
- zone_id = "${aws_route53_zone.test.zone_id}"
- }
-
- data "aws_route53_zone" "by_name" {
- name = "${data.aws_route53_zone.by_zone_id.name}"
- }`, rInt, rInt, rInt, rInt)
-}
diff --git a/builtin/providers/aws/data_source_aws_route_table.go b/builtin/providers/aws/data_source_aws_route_table.go
deleted file mode 100644
index c332bdd91..000000000
--- a/builtin/providers/aws/data_source_aws_route_table.go
+++ /dev/null
@@ -1,233 +0,0 @@
-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 dataSourceAwsRouteTable() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsRouteTableRead,
-
- Schema: map[string]*schema.Schema{
- "subnet_id": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "route_table_id": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "vpc_id": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "filter": ec2CustomFiltersSchema(),
- "tags": tagsSchemaComputed(),
- "routes": {
- Type: schema.TypeList,
- Computed: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "cidr_block": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "ipv6_cidr_block": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "egress_only_gateway_id": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "gateway_id": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "instance_id": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "nat_gateway_id": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "vpc_peering_connection_id": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "network_interface_id": {
- Type: schema.TypeString,
- Computed: true,
- },
- },
- },
- },
- "associations": {
- Type: schema.TypeList,
- Computed: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "route_table_association_id": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "route_table_id": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "subnet_id": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "main": {
- Type: schema.TypeBool,
- Computed: true,
- },
- },
- },
- },
- },
- }
-}
-
-func dataSourceAwsRouteTableRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).ec2conn
- req := &ec2.DescribeRouteTablesInput{}
- vpcId, vpcIdOk := d.GetOk("vpc_id")
- subnetId, subnetIdOk := d.GetOk("subnet_id")
- rtbId, rtbOk := d.GetOk("route_table_id")
- tags, tagsOk := d.GetOk("tags")
- filter, filterOk := d.GetOk("filter")
-
- if !vpcIdOk && !subnetIdOk && !tagsOk && !filterOk && !rtbOk {
- return fmt.Errorf("One of route_table_id, vpc_id, subnet_id, filters, or tags must be assigned")
- }
- req.Filters = buildEC2AttributeFilterList(
- map[string]string{
- "route-table-id": rtbId.(string),
- "vpc-id": vpcId.(string),
- "association.subnet-id": subnetId.(string),
- },
- )
- req.Filters = append(req.Filters, buildEC2TagFilterList(
- tagsFromMap(tags.(map[string]interface{})),
- )...)
- req.Filters = append(req.Filters, buildEC2CustomFilterList(
- filter.(*schema.Set),
- )...)
-
- log.Printf("[DEBUG] Describe Route Tables %v\n", req)
- resp, err := conn.DescribeRouteTables(req)
- if err != nil {
- return err
- }
- if resp == nil || len(resp.RouteTables) == 0 {
- return fmt.Errorf("Your query returned no results. Please change your search criteria and try again.")
- }
- if len(resp.RouteTables) > 1 {
- return fmt.Errorf("Multiple Route Table matched; use additional constraints to reduce matches to a single Route Table")
- }
-
- rt := resp.RouteTables[0]
-
- d.SetId(aws.StringValue(rt.RouteTableId))
- d.Set("route_table_id", rt.RouteTableId)
- d.Set("vpc_id", rt.VpcId)
- d.Set("tags", tagsToMap(rt.Tags))
- if err := d.Set("routes", dataSourceRoutesRead(rt.Routes)); err != nil {
- return err
- }
-
- if err := d.Set("associations", dataSourceAssociationsRead(rt.Associations)); err != nil {
- return err
- }
-
- return nil
-}
-
-func dataSourceRoutesRead(ec2Routes []*ec2.Route) []map[string]interface{} {
- routes := make([]map[string]interface{}, 0, len(ec2Routes))
- // Loop through the routes and add them to the set
- for _, r := range ec2Routes {
- if r.GatewayId != nil && *r.GatewayId == "local" {
- continue
- }
-
- if r.Origin != nil && *r.Origin == "EnableVgwRoutePropagation" {
- continue
- }
-
- if r.DestinationPrefixListId != nil {
- // Skipping because VPC endpoint routes are handled separately
- // See aws_vpc_endpoint
- continue
- }
-
- m := make(map[string]interface{})
-
- if r.DestinationCidrBlock != nil {
- m["cidr_block"] = *r.DestinationCidrBlock
- }
- if r.DestinationIpv6CidrBlock != nil {
- m["ipv6_cidr_block"] = *r.DestinationIpv6CidrBlock
- }
- if r.EgressOnlyInternetGatewayId != nil {
- m["egress_only_gateway_id"] = *r.EgressOnlyInternetGatewayId
- }
- if r.GatewayId != nil {
- m["gateway_id"] = *r.GatewayId
- }
- if r.NatGatewayId != nil {
- m["nat_gateway_id"] = *r.NatGatewayId
- }
- if r.InstanceId != nil {
- m["instance_id"] = *r.InstanceId
- }
- if r.VpcPeeringConnectionId != nil {
- m["vpc_peering_connection_id"] = *r.VpcPeeringConnectionId
- }
- if r.NetworkInterfaceId != nil {
- m["network_interface_id"] = *r.NetworkInterfaceId
- }
-
- routes = append(routes, m)
- }
- return routes
-}
-
-func dataSourceAssociationsRead(ec2Assocations []*ec2.RouteTableAssociation) []map[string]interface{} {
- associations := make([]map[string]interface{}, 0, len(ec2Assocations))
- // Loop through the routes and add them to the set
- for _, a := range ec2Assocations {
-
- m := make(map[string]interface{})
- m["route_table_id"] = *a.RouteTableId
- m["route_table_association_id"] = *a.RouteTableAssociationId
- // GH[11134]
- if a.SubnetId != nil {
- m["subnet_id"] = *a.SubnetId
- }
- m["main"] = *a.Main
- associations = append(associations, m)
- }
- return associations
-}
diff --git a/builtin/providers/aws/data_source_aws_route_table_test.go b/builtin/providers/aws/data_source_aws_route_table_test.go
deleted file mode 100644
index 71957541f..000000000
--- a/builtin/providers/aws/data_source_aws_route_table_test.go
+++ /dev/null
@@ -1,215 +0,0 @@
-// make testacc TEST=./builtin/providers/aws/ TESTARGS='-run=TestAccDataSourceAwsRouteTable_'
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccDataSourceAwsRouteTable_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAwsRouteTableGroupConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccDataSourceAwsRouteTableCheck("data.aws_route_table.by_tag"),
- testAccDataSourceAwsRouteTableCheck("data.aws_route_table.by_filter"),
- testAccDataSourceAwsRouteTableCheck("data.aws_route_table.by_subnet"),
- testAccDataSourceAwsRouteTableCheck("data.aws_route_table.by_id"),
- ),
- ExpectNonEmptyPlan: true,
- },
- },
- })
-}
-
-func TestAccDataSourceAwsRouteTable_main(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAwsRouteTableMainRoute,
- Check: resource.ComposeTestCheckFunc(
- testAccDataSourceAwsRouteTableCheckMain("data.aws_route_table.by_filter"),
- ),
- },
- },
- })
-}
-
-func testAccDataSourceAwsRouteTableCheck(name string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[name]
-
- if !ok {
- return fmt.Errorf("root module has no resource called %s", name)
- }
-
- rts, ok := s.RootModule().Resources["aws_route_table.test"]
- if !ok {
- return fmt.Errorf("can't find aws_route_table.test in state")
- }
- vpcRs, ok := s.RootModule().Resources["aws_vpc.test"]
- if !ok {
- return fmt.Errorf("can't find aws_vpc.test in state")
- }
- subnetRs, ok := s.RootModule().Resources["aws_subnet.test"]
- if !ok {
- return fmt.Errorf("can't find aws_subnet.test in state")
- }
- attr := rs.Primary.Attributes
-
- if attr["id"] != rts.Primary.Attributes["id"] {
- return fmt.Errorf(
- "id is %s; want %s",
- attr["id"],
- rts.Primary.Attributes["id"],
- )
- }
-
- if attr["route_table_id"] != rts.Primary.Attributes["id"] {
- return fmt.Errorf(
- "route_table_id is %s; want %s",
- attr["route_table_id"],
- rts.Primary.Attributes["id"],
- )
- }
-
- if attr["vpc_id"] != vpcRs.Primary.Attributes["id"] {
- return fmt.Errorf(
- "vpc_id is %s; want %s",
- attr["vpc_id"],
- vpcRs.Primary.Attributes["id"],
- )
- }
-
- if attr["tags.Name"] != "terraform-testacc-routetable-data-source" {
- return fmt.Errorf("bad Name tag %s", attr["tags.Name"])
- }
- if attr["associations.0.subnet_id"] != subnetRs.Primary.Attributes["id"] {
- return fmt.Errorf(
- "subnet_id is %v; want %s",
- attr["associations.0.subnet_id"],
- subnetRs.Primary.Attributes["id"],
- )
- }
-
- return nil
- }
-}
-
-func testAccDataSourceAwsRouteTableCheckMain(name string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[name]
-
- if !ok {
- return fmt.Errorf("root module has no resource called %s", name)
- }
-
- attr := rs.Primary.Attributes
-
- // Verify attributes are set
- if _, ok := attr["id"]; !ok {
- return fmt.Errorf("id not set for main route table")
- }
- if _, ok := attr["vpc_id"]; !ok {
- return fmt.Errorf("vpc_id not set for main route table")
- }
- // Verify it's actually the main route table that's returned
- if attr["associations.0.main"] != "true" {
- return fmt.Errorf("main route table not found")
- }
-
- return nil
- }
-}
-
-const testAccDataSourceAwsRouteTableGroupConfig = `
-provider "aws" {
- region = "eu-central-1"
-}
-resource "aws_vpc" "test" {
- cidr_block = "172.16.0.0/16"
-
- tags {
- Name = "terraform-testacc-data-source"
- }
-}
-
-resource "aws_subnet" "test" {
- cidr_block = "172.16.0.0/24"
- vpc_id = "${aws_vpc.test.id}"
- tags {
- Name = "terraform-testacc-data-source"
- }
-}
-
-resource "aws_route_table" "test" {
- vpc_id = "${aws_vpc.test.id}"
- tags {
- Name = "terraform-testacc-routetable-data-source"
- }
-}
-
-resource "aws_route_table_association" "a" {
- subnet_id = "${aws_subnet.test.id}"
- route_table_id = "${aws_route_table.test.id}"
-}
-
-data "aws_route_table" "by_filter" {
- filter {
- name = "association.route-table-association-id"
- values = ["${aws_route_table_association.a.id}"]
- }
- depends_on = ["aws_route_table_association.a"]
-}
-
-data "aws_route_table" "by_tag" {
- tags {
- Name = "${aws_route_table.test.tags["Name"]}"
- }
- depends_on = ["aws_route_table_association.a"]
-}
-
-data "aws_route_table" "by_subnet" {
- subnet_id = "${aws_subnet.test.id}"
- depends_on = ["aws_route_table_association.a"]
-}
-
-data "aws_route_table" "by_id" {
- route_table_id = "${aws_route_table.test.id}"
- depends_on = ["aws_route_table_association.a"]
-}
-`
-
-// Uses us-east-2, as region only has a single main route table
-const testAccDataSourceAwsRouteTableMainRoute = `
-provider "aws" {
- region = "us-east-2"
-}
-
-resource "aws_vpc" "test" {
- cidr_block = "172.16.0.0/16"
-
- tags {
- Name = "terraform-testacc-data-source"
- }
-}
-
-data "aws_route_table" "by_filter" {
- filter {
- name = "association.main"
- values = ["true"]
- }
- filter {
- name = "vpc-id"
- values = ["${aws_vpc.test.id}"]
- }
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_s3_bucket_object.go b/builtin/providers/aws/data_source_aws_s3_bucket_object.go
deleted file mode 100644
index 2eff5e6da..000000000
--- a/builtin/providers/aws/data_source_aws_s3_bucket_object.go
+++ /dev/null
@@ -1,239 +0,0 @@
-package aws
-
-import (
- "bytes"
- "fmt"
- "log"
- "regexp"
- "strings"
- "time"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/s3"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsS3BucketObject() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsS3BucketObjectRead,
-
- Schema: map[string]*schema.Schema{
- "body": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- "bucket": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
- "cache_control": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- "content_disposition": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- "content_encoding": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- "content_language": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- "content_length": &schema.Schema{
- Type: schema.TypeInt,
- Computed: true,
- },
- "content_type": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- "etag": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- "expiration": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- "expires": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- "key": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
- "last_modified": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- "metadata": &schema.Schema{
- Type: schema.TypeMap,
- Computed: true,
- },
- "range": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- },
- "server_side_encryption": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- "sse_kms_key_id": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- "storage_class": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
- "version_id": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "website_redirect_location": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
-
- "tags": tagsSchemaComputed(),
- },
- }
-}
-
-func dataSourceAwsS3BucketObjectRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).s3conn
-
- bucket := d.Get("bucket").(string)
- key := d.Get("key").(string)
-
- input := s3.HeadObjectInput{
- Bucket: aws.String(bucket),
- Key: aws.String(key),
- }
- if v, ok := d.GetOk("range"); ok {
- input.Range = aws.String(v.(string))
- }
- if v, ok := d.GetOk("version_id"); ok {
- input.VersionId = aws.String(v.(string))
- }
-
- versionText := ""
- uniqueId := bucket + "/" + key
- if v, ok := d.GetOk("version_id"); ok {
- versionText = fmt.Sprintf(" of version %q", v.(string))
- uniqueId += "@" + v.(string)
- }
-
- log.Printf("[DEBUG] Reading S3 object: %s", input)
- out, err := conn.HeadObject(&input)
- if err != nil {
- return fmt.Errorf("Failed getting S3 object: %s Bucket: %q Object: %q", err, bucket, key)
- }
- if out.DeleteMarker != nil && *out.DeleteMarker == true {
- return fmt.Errorf("Requested S3 object %q%s has been deleted",
- bucket+key, versionText)
- }
-
- log.Printf("[DEBUG] Received S3 object: %s", out)
-
- d.SetId(uniqueId)
-
- d.Set("cache_control", out.CacheControl)
- d.Set("content_disposition", out.ContentDisposition)
- d.Set("content_encoding", out.ContentEncoding)
- d.Set("content_language", out.ContentLanguage)
- d.Set("content_length", out.ContentLength)
- d.Set("content_type", out.ContentType)
- // See https://forums.aws.amazon.com/thread.jspa?threadID=44003
- d.Set("etag", strings.Trim(*out.ETag, `"`))
- d.Set("expiration", out.Expiration)
- d.Set("expires", out.Expires)
- d.Set("last_modified", out.LastModified.Format(time.RFC1123))
- d.Set("metadata", pointersMapToStringList(out.Metadata))
- d.Set("server_side_encryption", out.ServerSideEncryption)
- d.Set("sse_kms_key_id", out.SSEKMSKeyId)
- d.Set("version_id", out.VersionId)
- d.Set("website_redirect_location", out.WebsiteRedirectLocation)
-
- // The "STANDARD" (which is also the default) storage
- // class when set would not be included in the results.
- d.Set("storage_class", s3.StorageClassStandard)
- if out.StorageClass != nil {
- d.Set("storage_class", out.StorageClass)
- }
-
- if isContentTypeAllowed(out.ContentType) {
- input := s3.GetObjectInput{
- Bucket: aws.String(bucket),
- Key: aws.String(key),
- }
- if v, ok := d.GetOk("range"); ok {
- input.Range = aws.String(v.(string))
- }
- if out.VersionId != nil {
- input.VersionId = out.VersionId
- }
- out, err := conn.GetObject(&input)
- if err != nil {
- return fmt.Errorf("Failed getting S3 object: %s", err)
- }
-
- buf := new(bytes.Buffer)
- bytesRead, err := buf.ReadFrom(out.Body)
- if err != nil {
- return fmt.Errorf("Failed reading content of S3 object (%s): %s",
- uniqueId, err)
- }
- log.Printf("[INFO] Saving %d bytes from S3 object %s", bytesRead, uniqueId)
- d.Set("body", buf.String())
- } else {
- contentType := ""
- if out.ContentType == nil {
- contentType = ""
- } else {
- contentType = *out.ContentType
- }
-
- log.Printf("[INFO] Ignoring body of S3 object %s with Content-Type %q",
- uniqueId, contentType)
- }
-
- tagResp, err := conn.GetObjectTagging(
- &s3.GetObjectTaggingInput{
- Bucket: aws.String(bucket),
- Key: aws.String(key),
- })
- if err != nil {
- return err
- }
- d.Set("tags", tagsToMapS3(tagResp.TagSet))
-
- return nil
-}
-
-// This is to prevent potential issues w/ binary files
-// and generally unprintable characters
-// See https://github.com/hashicorp/terraform/pull/3858#issuecomment-156856738
-func isContentTypeAllowed(contentType *string) bool {
- if contentType == nil {
- return false
- }
-
- allowedContentTypes := []*regexp.Regexp{
- regexp.MustCompile("^text/.+"),
- regexp.MustCompile("^application/json$"),
- }
-
- for _, r := range allowedContentTypes {
- if r.MatchString(*contentType) {
- return true
- }
- }
-
- return false
-}
diff --git a/builtin/providers/aws/data_source_aws_s3_bucket_object_test.go b/builtin/providers/aws/data_source_aws_s3_bucket_object_test.go
deleted file mode 100644
index b4693da54..000000000
--- a/builtin/providers/aws/data_source_aws_s3_bucket_object_test.go
+++ /dev/null
@@ -1,302 +0,0 @@
-// make testacc TEST=./builtin/providers/aws/ TESTARGS='-run=TestAccDataSourceAWSS3BucketObject_'
-package aws
-
-import (
- "fmt"
- "regexp"
- "testing"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/s3"
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccDataSourceAWSS3BucketObject_basic(t *testing.T) {
- rInt := acctest.RandInt()
- resourceOnlyConf, conf := testAccAWSDataSourceS3ObjectConfig_basic(rInt)
-
- var rObj s3.GetObjectOutput
- var dsObj s3.GetObjectOutput
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- PreventPostDestroyRefresh: true,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: resourceOnlyConf,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAWSS3BucketObjectExists("aws_s3_bucket_object.object", &rObj),
- ),
- },
- resource.TestStep{
- Config: conf,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsS3ObjectDataSourceExists("data.aws_s3_bucket_object.obj", &dsObj),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_length", "11"),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_type", "binary/octet-stream"),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "etag", "b10a8db164e0754105b7a99be72e3fe5"),
- resource.TestMatchResourceAttr("data.aws_s3_bucket_object.obj", "last_modified",
- regexp.MustCompile("^[a-zA-Z]{3}, [0-9]+ [a-zA-Z]+ [0-9]{4} [0-9:]+ [A-Z]+$")),
- resource.TestCheckNoResourceAttr("data.aws_s3_bucket_object.obj", "body"),
- ),
- },
- },
- })
-}
-
-func TestAccDataSourceAWSS3BucketObject_readableBody(t *testing.T) {
- rInt := acctest.RandInt()
- resourceOnlyConf, conf := testAccAWSDataSourceS3ObjectConfig_readableBody(rInt)
-
- var rObj s3.GetObjectOutput
- var dsObj s3.GetObjectOutput
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- PreventPostDestroyRefresh: true,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: resourceOnlyConf,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAWSS3BucketObjectExists("aws_s3_bucket_object.object", &rObj),
- ),
- },
- resource.TestStep{
- Config: conf,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsS3ObjectDataSourceExists("data.aws_s3_bucket_object.obj", &dsObj),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_length", "3"),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_type", "text/plain"),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "etag", "a6105c0a611b41b08f1209506350279e"),
- resource.TestMatchResourceAttr("data.aws_s3_bucket_object.obj", "last_modified",
- regexp.MustCompile("^[a-zA-Z]{3}, [0-9]+ [a-zA-Z]+ [0-9]{4} [0-9:]+ [A-Z]+$")),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "body", "yes"),
- ),
- },
- },
- })
-}
-
-func TestAccDataSourceAWSS3BucketObject_kmsEncrypted(t *testing.T) {
- rInt := acctest.RandInt()
- resourceOnlyConf, conf := testAccAWSDataSourceS3ObjectConfig_kmsEncrypted(rInt)
-
- var rObj s3.GetObjectOutput
- var dsObj s3.GetObjectOutput
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- PreventPostDestroyRefresh: true,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: resourceOnlyConf,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAWSS3BucketObjectExists("aws_s3_bucket_object.object", &rObj),
- ),
- },
- resource.TestStep{
- Config: conf,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsS3ObjectDataSourceExists("data.aws_s3_bucket_object.obj", &dsObj),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_length", "22"),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_type", "text/plain"),
- resource.TestMatchResourceAttr("data.aws_s3_bucket_object.obj", "etag", regexp.MustCompile("^[a-f0-9]{32}$")),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "server_side_encryption", "aws:kms"),
- resource.TestMatchResourceAttr("data.aws_s3_bucket_object.obj", "sse_kms_key_id",
- regexp.MustCompile("^arn:aws:kms:[a-z]{2}-[a-z]+-\\d{1}:[0-9]{12}:key/[a-z0-9-]{36}$")),
- resource.TestMatchResourceAttr("data.aws_s3_bucket_object.obj", "last_modified",
- regexp.MustCompile("^[a-zA-Z]{3}, [0-9]+ [a-zA-Z]+ [0-9]{4} [0-9:]+ [A-Z]+$")),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "body", "Keep Calm and Carry On"),
- ),
- },
- },
- })
-}
-
-func TestAccDataSourceAWSS3BucketObject_allParams(t *testing.T) {
- rInt := acctest.RandInt()
- resourceOnlyConf, conf := testAccAWSDataSourceS3ObjectConfig_allParams(rInt)
-
- var rObj s3.GetObjectOutput
- var dsObj s3.GetObjectOutput
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- PreventPostDestroyRefresh: true,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: resourceOnlyConf,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAWSS3BucketObjectExists("aws_s3_bucket_object.object", &rObj),
- ),
- },
- resource.TestStep{
- Config: conf,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAwsS3ObjectDataSourceExists("data.aws_s3_bucket_object.obj", &dsObj),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_length", "21"),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_type", "application/unknown"),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "etag", "723f7a6ac0c57b445790914668f98640"),
- resource.TestMatchResourceAttr("data.aws_s3_bucket_object.obj", "last_modified",
- regexp.MustCompile("^[a-zA-Z]{3}, [0-9]+ [a-zA-Z]+ [0-9]{4} [0-9:]+ [A-Z]+$")),
- resource.TestMatchResourceAttr("data.aws_s3_bucket_object.obj", "version_id", regexp.MustCompile("^.{32}$")),
- resource.TestCheckNoResourceAttr("data.aws_s3_bucket_object.obj", "body"),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "cache_control", "no-cache"),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_disposition", "attachment"),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_encoding", "identity"),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_language", "en-GB"),
- // Encryption is off
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "server_side_encryption", ""),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "sse_kms_key_id", ""),
- // Supported, but difficult to reproduce in short testing time
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "storage_class", "STANDARD"),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "expiration", ""),
- // Currently unsupported in aws_s3_bucket_object resource
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "expires", ""),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "website_redirect_location", ""),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "metadata.%", "0"),
- resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "tags.%", "1"),
- ),
- },
- },
- })
-}
-
-func testAccCheckAwsS3ObjectDataSourceExists(n string, obj *s3.GetObjectOutput) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Can't find S3 object data source: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("S3 object data source ID not set")
- }
-
- s3conn := testAccProvider.Meta().(*AWSClient).s3conn
- out, err := s3conn.GetObject(
- &s3.GetObjectInput{
- Bucket: aws.String(rs.Primary.Attributes["bucket"]),
- Key: aws.String(rs.Primary.Attributes["key"]),
- })
- if err != nil {
- return fmt.Errorf("Failed getting S3 Object from %s: %s",
- rs.Primary.Attributes["bucket"]+"/"+rs.Primary.Attributes["key"], err)
- }
-
- *obj = *out
-
- return nil
- }
-}
-
-func testAccAWSDataSourceS3ObjectConfig_basic(randInt int) (string, string) {
- resources := fmt.Sprintf(`
-resource "aws_s3_bucket" "object_bucket" {
- bucket = "tf-object-test-bucket-%d"
-}
-resource "aws_s3_bucket_object" "object" {
- bucket = "${aws_s3_bucket.object_bucket.bucket}"
- key = "tf-testing-obj-%d"
- content = "Hello World"
-}
-`, randInt, randInt)
-
- both := fmt.Sprintf(`%s
-data "aws_s3_bucket_object" "obj" {
- bucket = "tf-object-test-bucket-%d"
- key = "tf-testing-obj-%d"
-}`, resources, randInt, randInt)
-
- return resources, both
-}
-
-func testAccAWSDataSourceS3ObjectConfig_readableBody(randInt int) (string, string) {
- resources := fmt.Sprintf(`
-resource "aws_s3_bucket" "object_bucket" {
- bucket = "tf-object-test-bucket-%d"
-}
-resource "aws_s3_bucket_object" "object" {
- bucket = "${aws_s3_bucket.object_bucket.bucket}"
- key = "tf-testing-obj-%d-readable"
- content = "yes"
- content_type = "text/plain"
-}
-`, randInt, randInt)
-
- both := fmt.Sprintf(`%s
-data "aws_s3_bucket_object" "obj" {
- bucket = "tf-object-test-bucket-%d"
- key = "tf-testing-obj-%d-readable"
-}`, resources, randInt, randInt)
-
- return resources, both
-}
-
-func testAccAWSDataSourceS3ObjectConfig_kmsEncrypted(randInt int) (string, string) {
- resources := fmt.Sprintf(`
-resource "aws_s3_bucket" "object_bucket" {
- bucket = "tf-object-test-bucket-%d"
-}
-resource "aws_kms_key" "example" {
- description = "TF Acceptance Test KMS key"
- deletion_window_in_days = 7
-}
-resource "aws_s3_bucket_object" "object" {
- bucket = "${aws_s3_bucket.object_bucket.bucket}"
- key = "tf-testing-obj-%d-encrypted"
- content = "Keep Calm and Carry On"
- content_type = "text/plain"
- kms_key_id = "${aws_kms_key.example.arn}"
-}
-`, randInt, randInt)
-
- both := fmt.Sprintf(`%s
-data "aws_s3_bucket_object" "obj" {
- bucket = "tf-object-test-bucket-%d"
- key = "tf-testing-obj-%d-encrypted"
-}`, resources, randInt, randInt)
-
- return resources, both
-}
-
-func testAccAWSDataSourceS3ObjectConfig_allParams(randInt int) (string, string) {
- resources := fmt.Sprintf(`
-resource "aws_s3_bucket" "object_bucket" {
- bucket = "tf-object-test-bucket-%d"
- versioning {
- enabled = true
- }
-}
-
-resource "aws_s3_bucket_object" "object" {
- bucket = "${aws_s3_bucket.object_bucket.bucket}"
- key = "tf-testing-obj-%d-all-params"
- content = < 1 {
- return fmt.Errorf("multiple Security Groups matched; use additional constraints to reduce matches to a single Security Group")
- }
-
- sg := resp.SecurityGroups[0]
-
- d.SetId(*sg.GroupId)
- d.Set("id", sg.VpcId)
- d.Set("name", sg.GroupName)
- d.Set("description", sg.Description)
- d.Set("vpc_id", sg.VpcId)
- d.Set("tags", tagsToMap(sg.Tags))
- d.Set("arn", fmt.Sprintf("arn:%s:ec2:%s:%s/security-group/%s",
- meta.(*AWSClient).partition, meta.(*AWSClient).region, *sg.OwnerId, *sg.GroupId))
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_security_group_test.go b/builtin/providers/aws/data_source_aws_security_group_test.go
deleted file mode 100644
index 6e1f1664a..000000000
--- a/builtin/providers/aws/data_source_aws_security_group_test.go
+++ /dev/null
@@ -1,151 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "strings"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccDataSourceAwsSecurityGroup(t *testing.T) {
- rInt := acctest.RandInt()
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAwsSecurityGroupConfig(rInt),
- Check: resource.ComposeTestCheckFunc(
- testAccDataSourceAwsSecurityGroupCheck("data.aws_security_group.by_id"),
- testAccDataSourceAwsSecurityGroupCheck("data.aws_security_group.by_tag"),
- testAccDataSourceAwsSecurityGroupCheck("data.aws_security_group.by_filter"),
- testAccDataSourceAwsSecurityGroupCheck("data.aws_security_group.by_name"),
- testAccDataSourceAwsSecurityGroupCheckDefault("data.aws_security_group.default_by_name"),
- ),
- },
- },
- })
-}
-
-func testAccDataSourceAwsSecurityGroupCheck(name string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[name]
- if !ok {
- return fmt.Errorf("root module has no resource called %s", name)
- }
-
- SGRs, ok := s.RootModule().Resources["aws_security_group.test"]
- if !ok {
- return fmt.Errorf("can't find aws_security_group.test in state")
- }
- vpcRs, ok := s.RootModule().Resources["aws_vpc.test"]
- if !ok {
- return fmt.Errorf("can't find aws_vpc.test in state")
- }
- attr := rs.Primary.Attributes
-
- if attr["id"] != SGRs.Primary.Attributes["id"] {
- return fmt.Errorf(
- "id is %s; want %s",
- attr["id"],
- SGRs.Primary.Attributes["id"],
- )
- }
-
- if attr["vpc_id"] != vpcRs.Primary.Attributes["id"] {
- return fmt.Errorf(
- "vpc_id is %s; want %s",
- attr["vpc_id"],
- vpcRs.Primary.Attributes["id"],
- )
- }
-
- if attr["tags.Name"] != "tf-acctest" {
- return fmt.Errorf("bad Name tag %s", attr["tags.Name"])
- }
-
- if !strings.Contains(attr["arn"], attr["id"]) {
- return fmt.Errorf("bad ARN %s", attr["arn"])
- }
-
- return nil
- }
-}
-
-func testAccDataSourceAwsSecurityGroupCheckDefault(name string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[name]
- if !ok {
- return fmt.Errorf("root module has no resource called %s", name)
- }
-
- vpcRs, ok := s.RootModule().Resources["aws_vpc.test"]
- if !ok {
- return fmt.Errorf("can't find aws_vpc.test in state")
- }
- attr := rs.Primary.Attributes
-
- if attr["id"] != vpcRs.Primary.Attributes["default_security_group_id"] {
- return fmt.Errorf(
- "id is %s; want %s",
- attr["id"],
- vpcRs.Primary.Attributes["default_security_group_id"],
- )
- }
-
- return nil
- }
-}
-
-func testAccDataSourceAwsSecurityGroupConfig(rInt int) string {
- return fmt.Sprintf(`
- provider "aws" {
- region = "eu-west-1"
- }
- resource "aws_vpc" "test" {
- cidr_block = "172.16.0.0/16"
-
- tags {
- Name = "terraform-testacc-subnet-data-source"
- }
- }
-
- resource "aws_security_group" "test" {
- vpc_id = "${aws_vpc.test.id}"
- name = "test-%d"
- tags {
- Name = "tf-acctest"
- Seed = "%d"
- }
- }
-
- data "aws_security_group" "by_id" {
- id = "${aws_security_group.test.id}"
- }
-
- data "aws_security_group" "by_name" {
- name = "${aws_security_group.test.name}"
- }
-
- data "aws_security_group" "default_by_name" {
- vpc_id = "${aws_vpc.test.id}"
- name = "default"
- }
-
- data "aws_security_group" "by_tag" {
- tags {
- Seed = "${aws_security_group.test.tags["Seed"]}"
- }
- }
-
- data "aws_security_group" "by_filter" {
- filter {
- name = "group-name"
- values = ["${aws_security_group.test.name}"]
- }
- }`, rInt, rInt)
-}
diff --git a/builtin/providers/aws/data_source_aws_sns.go b/builtin/providers/aws/data_source_aws_sns.go
deleted file mode 100644
index c02ec328a..000000000
--- a/builtin/providers/aws/data_source_aws_sns.go
+++ /dev/null
@@ -1,71 +0,0 @@
-package aws
-
-import (
- "fmt"
- "regexp"
- "time"
-
- "github.com/aws/aws-sdk-go/service/sns"
- "github.com/hashicorp/errwrap"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsSnsTopic() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsSnsTopicsRead,
- Schema: map[string]*schema.Schema{
- "name": {
- Type: schema.TypeString,
- Required: true,
- ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
- validNamePattern := "^[A-Za-z0-9_-]+$"
- validName, nameMatchErr := regexp.MatchString(validNamePattern, value)
- if !validName || nameMatchErr != nil {
- errors = append(errors, fmt.Errorf(
- "%q must match regex '%v'", k, validNamePattern))
- }
- return
- },
- },
- "arn": {
- Type: schema.TypeString,
- Computed: true,
- },
- },
- }
-}
-
-func dataSourceAwsSnsTopicsRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).snsconn
- params := &sns.ListTopicsInput{}
-
- target := d.Get("name")
- var arns []string
- err := conn.ListTopicsPages(params, func(page *sns.ListTopicsOutput, lastPage bool) bool {
- for _, topic := range page.Topics {
- topicPattern := fmt.Sprintf(".*:%v$", target)
- matched, regexpErr := regexp.MatchString(topicPattern, *topic.TopicArn)
- if matched && regexpErr == nil {
- arns = append(arns, *topic.TopicArn)
- }
- }
-
- return true
- })
- if err != nil {
- return errwrap.Wrapf("Error describing topics: {{err}}", err)
- }
-
- if len(arns) == 0 {
- return fmt.Errorf("No topic with name %q found in this region.", target)
- }
- if len(arns) > 1 {
- return fmt.Errorf("Multiple topics with name %q found in this region.", target)
- }
-
- d.SetId(time.Now().UTC().String())
- d.Set("arn", arns[0])
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_sns_test.go b/builtin/providers/aws/data_source_aws_sns_test.go
deleted file mode 100644
index f4742dcb7..000000000
--- a/builtin/providers/aws/data_source_aws_sns_test.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccDataSourceAwsSnsTopic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDataSourceAwsSnsTopicConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccDataSourceAwsSnsTopicCheck("data.aws_sns_topic.by_name"),
- ),
- },
- },
- })
-}
-
-func testAccDataSourceAwsSnsTopicCheck(name string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[name]
- if !ok {
- return fmt.Errorf("root module has no resource called %s", name)
- }
-
- snsTopicRs, ok := s.RootModule().Resources["aws_sns_topic.tf_test"]
- if !ok {
- return fmt.Errorf("can't find aws_sns_topic.tf_test in state")
- }
-
- attr := rs.Primary.Attributes
-
- if attr["name"] != snsTopicRs.Primary.Attributes["name"] {
- return fmt.Errorf(
- "name is %s; want %s",
- attr["name"],
- snsTopicRs.Primary.Attributes["name"],
- )
- }
-
- return nil
- }
-}
-
-const testAccDataSourceAwsSnsTopicConfig = `
-provider "aws" {
- region = "us-west-2"
-}
-
-resource "aws_sns_topic" "tf_wrong1" {
- name = "wrong1"
-}
-resource "aws_sns_topic" "tf_test" {
- name = "tf_test"
-}
-resource "aws_sns_topic" "tf_wrong2" {
- name = "wrong2"
-}
-
-data "aws_sns_topic" "by_name" {
- name = "${aws_sns_topic.tf_test.name}"
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_ssm_parameter.go b/builtin/providers/aws/data_source_aws_ssm_parameter.go
deleted file mode 100644
index 388366686..000000000
--- a/builtin/providers/aws/data_source_aws_ssm_parameter.go
+++ /dev/null
@@ -1,63 +0,0 @@
-package aws
-
-import (
- "fmt"
- "log"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/ssm"
- "github.com/hashicorp/errwrap"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsSsmParameter() *schema.Resource {
- return &schema.Resource{
- Read: dataAwsSsmParameterRead,
- Schema: map[string]*schema.Schema{
- "name": {
- Type: schema.TypeString,
- Required: true,
- },
- "type": {
- Type: schema.TypeString,
- Computed: true,
- },
- "value": {
- Type: schema.TypeString,
- Computed: true,
- Sensitive: true,
- },
- },
- }
-}
-
-func dataAwsSsmParameterRead(d *schema.ResourceData, meta interface{}) error {
- ssmconn := meta.(*AWSClient).ssmconn
-
- log.Printf("[DEBUG] Reading SSM Parameter: %s", d.Id())
-
- paramInput := &ssm.GetParametersInput{
- Names: []*string{
- aws.String(d.Get("name").(string)),
- },
- WithDecryption: aws.Bool(true),
- }
-
- resp, err := ssmconn.GetParameters(paramInput)
-
- if err != nil {
- return errwrap.Wrapf("[ERROR] Error describing SSM parameter: {{err}}", err)
- }
-
- if len(resp.InvalidParameters) > 0 {
- return fmt.Errorf("[ERROR] SSM Parameter %s is invalid", d.Get("name").(string))
- }
-
- param := resp.Parameters[0]
- d.SetId(*param.Name)
- d.Set("name", param.Name)
- d.Set("type", param.Type)
- d.Set("value", param.Value)
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_ssm_parameter_test.go b/builtin/providers/aws/data_source_aws_ssm_parameter_test.go
deleted file mode 100644
index 3b9c0d0f4..000000000
--- a/builtin/providers/aws/data_source_aws_ssm_parameter_test.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAwsSsmParameterDataSource_basic(t *testing.T) {
- name := "test.parameter"
- resource.Test(t, resource.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccCheckAwsSsmParameterDataSourceConfig(name),
- Check: resource.ComposeAggregateTestCheckFunc(
- resource.TestCheckResourceAttr("data.aws_ssm_parameter.test", "name", name),
- resource.TestCheckResourceAttr("data.aws_ssm_parameter.test", "type", "String"),
- resource.TestCheckResourceAttr("data.aws_ssm_parameter.test", "value", "TestValue"),
- ),
- },
- },
- })
-}
-
-func testAccCheckAwsSsmParameterDataSourceConfig(name string) string {
- return fmt.Sprintf(`
-resource "aws_ssm_parameter" "test" {
- name = "%s"
- type = "String"
- value = "TestValue"
-}
-
-data "aws_ssm_parameter" "test" {
- name = "${aws_ssm_parameter.test.name}"
-}
-`, name)
-}
diff --git a/builtin/providers/aws/data_source_aws_subnet.go b/builtin/providers/aws/data_source_aws_subnet.go
deleted file mode 100644
index 188a09dd2..000000000
--- a/builtin/providers/aws/data_source_aws_subnet.go
+++ /dev/null
@@ -1,160 +0,0 @@
-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 dataSourceAwsSubnet() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsSubnetRead,
-
- Schema: map[string]*schema.Schema{
- "availability_zone": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
-
- "cidr_block": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
-
- "ipv6_cidr_block": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
-
- "default_for_az": {
- Type: schema.TypeBool,
- Optional: true,
- Computed: true,
- },
-
- "filter": ec2CustomFiltersSchema(),
-
- "id": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
-
- "state": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
-
- "tags": tagsSchemaComputed(),
-
- "vpc_id": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
-
- "assign_ipv6_address_on_creation": {
- Type: schema.TypeBool,
- Computed: true,
- },
-
- "map_public_ip_on_launch": {
- Type: schema.TypeBool,
- Computed: true,
- },
-
- "ipv6_cidr_block_association_id": {
- Type: schema.TypeString,
- Computed: true,
- },
- },
- }
-}
-
-func dataSourceAwsSubnetRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).ec2conn
-
- req := &ec2.DescribeSubnetsInput{}
-
- if id := d.Get("id"); id != "" {
- req.SubnetIds = []*string{aws.String(id.(string))}
- }
-
- // We specify default_for_az as boolean, but EC2 filters want
- // it to be serialized as a string. Note that setting it to
- // "false" here does not actually filter by it *not* being
- // the default, because Terraform can't distinguish between
- // "false" and "not set".
- defaultForAzStr := ""
- if d.Get("default_for_az").(bool) {
- defaultForAzStr = "true"
- }
-
- filters := map[string]string{
- "availabilityZone": d.Get("availability_zone").(string),
- "defaultForAz": defaultForAzStr,
- "state": d.Get("state").(string),
- "vpc-id": d.Get("vpc_id").(string),
- }
-
- if v, ok := d.GetOk("cidr_block"); ok {
- filters["cidrBlock"] = v.(string)
- }
-
- if v, ok := d.GetOk("ipv6_cidr_block"); ok {
- filters["ipv6-cidr-block-association.ipv6-cidr-block"] = v.(string)
- }
-
- req.Filters = buildEC2AttributeFilterList(filters)
- req.Filters = append(req.Filters, buildEC2TagFilterList(
- tagsFromMap(d.Get("tags").(map[string]interface{})),
- )...)
- req.Filters = append(req.Filters, buildEC2CustomFilterList(
- d.Get("filter").(*schema.Set),
- )...)
- if len(req.Filters) == 0 {
- // Don't send an empty filters list; the EC2 API won't accept it.
- req.Filters = nil
- }
-
- log.Printf("[DEBUG] DescribeSubnets %s\n", req)
- resp, err := conn.DescribeSubnets(req)
- if err != nil {
- return err
- }
- if resp == nil || len(resp.Subnets) == 0 {
- return fmt.Errorf("no matching subnet found")
- }
- if len(resp.Subnets) > 1 {
- return fmt.Errorf("multiple subnets matched; use additional constraints to reduce matches to a single subnet")
- }
-
- subnet := resp.Subnets[0]
-
- d.SetId(*subnet.SubnetId)
- d.Set("id", subnet.SubnetId)
- d.Set("vpc_id", subnet.VpcId)
- d.Set("availability_zone", subnet.AvailabilityZone)
- d.Set("cidr_block", subnet.CidrBlock)
- d.Set("default_for_az", subnet.DefaultForAz)
- d.Set("state", subnet.State)
- d.Set("tags", tagsToMap(subnet.Tags))
- d.Set("assign_ipv6_address_on_creation", subnet.AssignIpv6AddressOnCreation)
- d.Set("map_public_ip_on_launch", subnet.MapPublicIpOnLaunch)
-
- for _, a := range subnet.Ipv6CidrBlockAssociationSet {
- if *a.Ipv6CidrBlockState.State == "associated" { //we can only ever have 1 IPv6 block associated at once
- d.Set("ipv6_cidr_block_association_id", a.AssociationId)
- d.Set("ipv6_cidr_block", a.Ipv6CidrBlock)
- }
- }
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_subnet_ids.go b/builtin/providers/aws/data_source_aws_subnet_ids.go
deleted file mode 100644
index c1a495aa1..000000000
--- a/builtin/providers/aws/data_source_aws_subnet_ids.go
+++ /dev/null
@@ -1,68 +0,0 @@
-package aws
-
-import (
- "fmt"
- "log"
-
- "github.com/aws/aws-sdk-go/service/ec2"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsSubnetIDs() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsSubnetIDsRead,
- Schema: map[string]*schema.Schema{
-
- "tags": tagsSchemaComputed(),
-
- "vpc_id": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
-
- "ids": &schema.Schema{
- Type: schema.TypeSet,
- Computed: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- Set: schema.HashString,
- },
- },
- }
-}
-
-func dataSourceAwsSubnetIDsRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).ec2conn
-
- req := &ec2.DescribeSubnetsInput{}
-
- req.Filters = buildEC2AttributeFilterList(
- map[string]string{
- "vpc-id": d.Get("vpc_id").(string),
- },
- )
-
- req.Filters = append(req.Filters, buildEC2TagFilterList(
- tagsFromMap(d.Get("tags").(map[string]interface{})),
- )...)
-
- log.Printf("[DEBUG] DescribeSubnets %s\n", req)
- resp, err := conn.DescribeSubnets(req)
- if err != nil {
- return err
- }
-
- if resp == nil || len(resp.Subnets) == 0 {
- return fmt.Errorf("no matching subnet found for vpc with id %s", d.Get("vpc_id").(string))
- }
-
- subnets := make([]string, 0)
-
- for _, subnet := range resp.Subnets {
- subnets = append(subnets, *subnet.SubnetId)
- }
-
- d.SetId(d.Get("vpc_id").(string))
- d.Set("ids", subnets)
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_subnet_ids_test.go b/builtin/providers/aws/data_source_aws_subnet_ids_test.go
deleted file mode 100644
index 5d752a25e..000000000
--- a/builtin/providers/aws/data_source_aws_subnet_ids_test.go
+++ /dev/null
@@ -1,132 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccDataSourceAwsSubnetIDs(t *testing.T) {
- rInt := acctest.RandIntRange(0, 256)
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckVpcDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAwsSubnetIDsConfig(rInt),
- },
- {
- Config: testAccDataSourceAwsSubnetIDsConfigWithDataSource(rInt),
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr("data.aws_subnet_ids.selected", "ids.#", "3"),
- resource.TestCheckResourceAttr("data.aws_subnet_ids.private", "ids.#", "2"),
- ),
- },
- },
- })
-}
-
-func testAccDataSourceAwsSubnetIDsConfigWithDataSource(rInt int) string {
- return fmt.Sprintf(
- `
- resource "aws_vpc" "test" {
- cidr_block = "172.%d.0.0/16"
-
- tags {
- Name = "terraform-testacc-subnet-ids-data-source"
- }
- }
-
- resource "aws_subnet" "test_public_a" {
- vpc_id = "${aws_vpc.test.id}"
- cidr_block = "172.%d.123.0/24"
- availability_zone = "us-west-2a"
-
- tags {
- Name = "terraform-testacc-subnet-ids-data-source-public-a"
- Tier = "Public"
- }
- }
-
- resource "aws_subnet" "test_private_a" {
- vpc_id = "${aws_vpc.test.id}"
- cidr_block = "172.%d.125.0/24"
- availability_zone = "us-west-2a"
-
- tags {
- Name = "terraform-testacc-subnet-ids-data-source-private-a"
- Tier = "Private"
- }
- }
-
- resource "aws_subnet" "test_private_b" {
- vpc_id = "${aws_vpc.test.id}"
- cidr_block = "172.%d.126.0/24"
- availability_zone = "us-west-2b"
-
- tags {
- Name = "terraform-testacc-subnet-ids-data-source-private-b"
- Tier = "Private"
- }
- }
-
- data "aws_subnet_ids" "selected" {
- vpc_id = "${aws_vpc.test.id}"
- }
-
- data "aws_subnet_ids" "private" {
- vpc_id = "${aws_vpc.test.id}"
- tags {
- Tier = "Private"
- }
- }
- `, rInt, rInt, rInt, rInt)
-}
-
-func testAccDataSourceAwsSubnetIDsConfig(rInt int) string {
- return fmt.Sprintf(`
- resource "aws_vpc" "test" {
- cidr_block = "172.%d.0.0/16"
-
- tags {
- Name = "terraform-testacc-subnet-ids-data-source"
- }
- }
-
- resource "aws_subnet" "test_public_a" {
- vpc_id = "${aws_vpc.test.id}"
- cidr_block = "172.%d.123.0/24"
- availability_zone = "us-west-2a"
-
- tags {
- Name = "terraform-testacc-subnet-ids-data-source-public-a"
- Tier = "Public"
- }
- }
-
- resource "aws_subnet" "test_private_a" {
- vpc_id = "${aws_vpc.test.id}"
- cidr_block = "172.%d.125.0/24"
- availability_zone = "us-west-2a"
-
- tags {
- Name = "terraform-testacc-subnet-ids-data-source-private-a"
- Tier = "Private"
- }
- }
-
- resource "aws_subnet" "test_private_b" {
- vpc_id = "${aws_vpc.test.id}"
- cidr_block = "172.%d.126.0/24"
- availability_zone = "us-west-2b"
-
- tags {
- Name = "terraform-testacc-subnet-ids-data-source-private-b"
- Tier = "Private"
- }
- }
- `, rInt, rInt, rInt, rInt)
-}
diff --git a/builtin/providers/aws/data_source_aws_subnet_test.go b/builtin/providers/aws/data_source_aws_subnet_test.go
deleted file mode 100644
index 3c9c5ed6f..000000000
--- a/builtin/providers/aws/data_source_aws_subnet_test.go
+++ /dev/null
@@ -1,257 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccDataSourceAwsSubnet(t *testing.T) {
- rInt := acctest.RandIntRange(0, 256)
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckVpcDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAwsSubnetConfig(rInt),
- Check: resource.ComposeTestCheckFunc(
- testAccDataSourceAwsSubnetCheck("data.aws_subnet.by_id", rInt),
- testAccDataSourceAwsSubnetCheck("data.aws_subnet.by_cidr", rInt),
- testAccDataSourceAwsSubnetCheck("data.aws_subnet.by_tag", rInt),
- testAccDataSourceAwsSubnetCheck("data.aws_subnet.by_vpc", rInt),
- testAccDataSourceAwsSubnetCheck("data.aws_subnet.by_filter", rInt),
- ),
- },
- },
- })
-}
-
-func TestAccDataSourceAwsSubnetIpv6ByIpv6Filter(t *testing.T) {
- rInt := acctest.RandIntRange(0, 256)
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAwsSubnetConfigIpv6(rInt),
- },
- {
- Config: testAccDataSourceAwsSubnetConfigIpv6WithDataSourceFilter(rInt),
- Check: resource.ComposeAggregateTestCheckFunc(
- resource.TestCheckResourceAttrSet(
- "data.aws_subnet.by_ipv6_cidr", "ipv6_cidr_block_association_id"),
- resource.TestCheckResourceAttrSet(
- "data.aws_subnet.by_ipv6_cidr", "ipv6_cidr_block"),
- ),
- },
- },
- })
-}
-
-func TestAccDataSourceAwsSubnetIpv6ByIpv6CidrBlock(t *testing.T) {
- rInt := acctest.RandIntRange(0, 256)
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAwsSubnetConfigIpv6(rInt),
- },
- {
- Config: testAccDataSourceAwsSubnetConfigIpv6WithDataSourceIpv6CidrBlock(rInt),
- Check: resource.ComposeAggregateTestCheckFunc(
- resource.TestCheckResourceAttrSet(
- "data.aws_subnet.by_ipv6_cidr", "ipv6_cidr_block_association_id"),
- ),
- },
- },
- })
-}
-
-func testAccDataSourceAwsSubnetCheck(name string, rInt int) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[name]
- if !ok {
- return fmt.Errorf("root module has no resource called %s", name)
- }
-
- vpcRs, ok := s.RootModule().Resources["aws_vpc.test"]
- if !ok {
- return fmt.Errorf("can't find aws_vpc.test in state")
- }
- subnetRs, ok := s.RootModule().Resources["aws_subnet.test"]
- if !ok {
- return fmt.Errorf("can't find aws_subnet.test in state")
- }
-
- attr := rs.Primary.Attributes
-
- if attr["id"] != subnetRs.Primary.Attributes["id"] {
- return fmt.Errorf(
- "id is %s; want %s",
- attr["id"],
- subnetRs.Primary.Attributes["id"],
- )
- }
-
- if attr["vpc_id"] != vpcRs.Primary.Attributes["id"] {
- return fmt.Errorf(
- "vpc_id is %s; want %s",
- attr["vpc_id"],
- vpcRs.Primary.Attributes["id"],
- )
- }
-
- if attr["cidr_block"] != fmt.Sprintf("172.%d.123.0/24", rInt) {
- return fmt.Errorf("bad cidr_block %s", attr["cidr_block"])
- }
- if attr["availability_zone"] != "us-west-2a" {
- return fmt.Errorf("bad availability_zone %s", attr["availability_zone"])
- }
- if attr["tags.Name"] != fmt.Sprintf("terraform-testacc-subnet-data-source-%d", rInt) {
- return fmt.Errorf("bad Name tag %s", attr["tags.Name"])
- }
-
- return nil
- }
-}
-
-func testAccDataSourceAwsSubnetConfig(rInt int) string {
- return fmt.Sprintf(`
- provider "aws" {
- region = "us-west-2"
- }
-
- resource "aws_vpc" "test" {
- cidr_block = "172.%d.0.0/16"
-
- tags {
- Name = "terraform-testacc-subnet-data-source"
- }
- }
-
- resource "aws_subnet" "test" {
- vpc_id = "${aws_vpc.test.id}"
- cidr_block = "172.%d.123.0/24"
- availability_zone = "us-west-2a"
-
- tags {
- Name = "terraform-testacc-subnet-data-source-%d"
- }
- }
-
-
- data "aws_subnet" "by_id" {
- id = "${aws_subnet.test.id}"
- }
-
- data "aws_subnet" "by_cidr" {
- cidr_block = "${aws_subnet.test.cidr_block}"
- }
-
- data "aws_subnet" "by_tag" {
- tags {
- Name = "${aws_subnet.test.tags["Name"]}"
- }
- }
-
- data "aws_subnet" "by_vpc" {
- vpc_id = "${aws_subnet.test.vpc_id}"
- }
-
- data "aws_subnet" "by_filter" {
- filter {
- name = "vpc-id"
- values = ["${aws_subnet.test.vpc_id}"]
- }
- }
- `, rInt, rInt, rInt)
-}
-
-func testAccDataSourceAwsSubnetConfigIpv6(rInt int) string {
- return fmt.Sprintf(`
-resource "aws_vpc" "test" {
- cidr_block = "172.%d.0.0/16"
- assign_generated_ipv6_cidr_block = true
-
- tags {
- Name = "terraform-testacc-subnet-data-source-ipv6"
- }
-}
-
-resource "aws_subnet" "test" {
- vpc_id = "${aws_vpc.test.id}"
- cidr_block = "172.%d.123.0/24"
- availability_zone = "us-west-2a"
- ipv6_cidr_block = "${cidrsubnet(aws_vpc.test.ipv6_cidr_block, 8, 1)}"
-
- tags {
- Name = "terraform-testacc-subnet-data-sourceipv6-%d"
- }
-}
-`, rInt, rInt, rInt)
-}
-
-func testAccDataSourceAwsSubnetConfigIpv6WithDataSourceFilter(rInt int) string {
- return fmt.Sprintf(`
-resource "aws_vpc" "test" {
- cidr_block = "172.%d.0.0/16"
- assign_generated_ipv6_cidr_block = true
-
- tags {
- Name = "terraform-testacc-subnet-data-source-ipv6"
- }
-}
-
-resource "aws_subnet" "test" {
- vpc_id = "${aws_vpc.test.id}"
- cidr_block = "172.%d.123.0/24"
- availability_zone = "us-west-2a"
- ipv6_cidr_block = "${cidrsubnet(aws_vpc.test.ipv6_cidr_block, 8, 1)}"
-
- tags {
- Name = "terraform-testacc-subnet-data-sourceipv6-%d"
- }
-}
-
-data "aws_subnet" "by_ipv6_cidr" {
- filter {
- name = "ipv6-cidr-block-association.ipv6-cidr-block"
- values = ["${aws_subnet.test.ipv6_cidr_block}"]
- }
-}
-`, rInt, rInt, rInt)
-}
-
-func testAccDataSourceAwsSubnetConfigIpv6WithDataSourceIpv6CidrBlock(rInt int) string {
- return fmt.Sprintf(`
-resource "aws_vpc" "test" {
- cidr_block = "172.%d.0.0/16"
- assign_generated_ipv6_cidr_block = true
-
- tags {
- Name = "terraform-testacc-subnet-data-source-ipv6"
- }
-}
-
-resource "aws_subnet" "test" {
- vpc_id = "${aws_vpc.test.id}"
- cidr_block = "172.%d.123.0/24"
- availability_zone = "us-west-2a"
- ipv6_cidr_block = "${cidrsubnet(aws_vpc.test.ipv6_cidr_block, 8, 1)}"
-
- tags {
- Name = "terraform-testacc-subnet-data-sourceipv6-%d"
- }
-}
-
-data "aws_subnet" "by_ipv6_cidr" {
- ipv6_cidr_block = "${aws_subnet.test.ipv6_cidr_block}"
-}
-`, rInt, rInt, rInt)
-}
diff --git a/builtin/providers/aws/data_source_aws_vpc.go b/builtin/providers/aws/data_source_aws_vpc.go
deleted file mode 100644
index 6e09e971d..000000000
--- a/builtin/providers/aws/data_source_aws_vpc.go
+++ /dev/null
@@ -1,136 +0,0 @@
-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 dataSourceAwsVpc() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsVpcRead,
-
- Schema: map[string]*schema.Schema{
- "cidr_block": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
-
- "dhcp_options_id": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
-
- "default": {
- Type: schema.TypeBool,
- Optional: true,
- Computed: true,
- },
-
- "filter": ec2CustomFiltersSchema(),
-
- "id": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
-
- "instance_tenancy": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "ipv6_cidr_block": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "ipv6_association_id": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "state": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
-
- "tags": tagsSchemaComputed(),
- },
- }
-}
-
-func dataSourceAwsVpcRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).ec2conn
-
- req := &ec2.DescribeVpcsInput{}
-
- if id := d.Get("id"); id != "" {
- req.VpcIds = []*string{aws.String(id.(string))}
- }
-
- // We specify "default" as boolean, but EC2 filters want
- // it to be serialized as a string. Note that setting it to
- // "false" here does not actually filter by it *not* being
- // the default, because Terraform can't distinguish between
- // "false" and "not set".
- isDefaultStr := ""
- if d.Get("default").(bool) {
- isDefaultStr = "true"
- }
-
- req.Filters = buildEC2AttributeFilterList(
- map[string]string{
- "cidr": d.Get("cidr_block").(string),
- "dhcp-options-id": d.Get("dhcp_options_id").(string),
- "isDefault": isDefaultStr,
- "state": d.Get("state").(string),
- },
- )
- req.Filters = append(req.Filters, buildEC2TagFilterList(
- tagsFromMap(d.Get("tags").(map[string]interface{})),
- )...)
- req.Filters = append(req.Filters, buildEC2CustomFilterList(
- d.Get("filter").(*schema.Set),
- )...)
- if len(req.Filters) == 0 {
- // Don't send an empty filters list; the EC2 API won't accept it.
- req.Filters = nil
- }
-
- log.Printf("[DEBUG] DescribeVpcs %s\n", req)
- resp, err := conn.DescribeVpcs(req)
- if err != nil {
- return err
- }
- if resp == nil || len(resp.Vpcs) == 0 {
- return fmt.Errorf("no matching VPC found")
- }
- if len(resp.Vpcs) > 1 {
- return fmt.Errorf("multiple VPCs matched; use additional constraints to reduce matches to a single VPC")
- }
-
- vpc := resp.Vpcs[0]
-
- d.SetId(*vpc.VpcId)
- d.Set("id", vpc.VpcId)
- d.Set("cidr_block", vpc.CidrBlock)
- d.Set("dhcp_options_id", vpc.DhcpOptionsId)
- d.Set("instance_tenancy", vpc.InstanceTenancy)
- d.Set("default", vpc.IsDefault)
- d.Set("state", vpc.State)
- d.Set("tags", tagsToMap(vpc.Tags))
-
- if vpc.Ipv6CidrBlockAssociationSet != nil {
- d.Set("ipv6_association_id", vpc.Ipv6CidrBlockAssociationSet[0].AssociationId)
- d.Set("ipv6_cidr_block", vpc.Ipv6CidrBlockAssociationSet[0].Ipv6CidrBlock)
- }
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_vpc_endpoint.go b/builtin/providers/aws/data_source_aws_vpc_endpoint.go
deleted file mode 100644
index c15933129..000000000
--- a/builtin/providers/aws/data_source_aws_vpc_endpoint.go
+++ /dev/null
@@ -1,103 +0,0 @@
-package aws
-
-import (
- "fmt"
- "log"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/ec2"
- "github.com/hashicorp/errwrap"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsVpcEndpoint() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsVpcEndpointRead,
-
- Schema: map[string]*schema.Schema{
- "id": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "state": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "vpc_id": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "service_name": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "policy": {
- Type: schema.TypeString,
- Computed: true,
- },
- "route_table_ids": &schema.Schema{
- Type: schema.TypeSet,
- Computed: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- Set: schema.HashString,
- },
- },
- }
-}
-
-func dataSourceAwsVpcEndpointRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).ec2conn
-
- log.Printf("[DEBUG] Reading VPC Endpoints.")
-
- req := &ec2.DescribeVpcEndpointsInput{}
-
- if id, ok := d.GetOk("id"); ok {
- req.VpcEndpointIds = aws.StringSlice([]string{id.(string)})
- }
-
- req.Filters = buildEC2AttributeFilterList(
- map[string]string{
- "vpc-endpoint-state": d.Get("state").(string),
- "vpc-id": d.Get("vpc_id").(string),
- "service-name": d.Get("service_name").(string),
- },
- )
- if len(req.Filters) == 0 {
- // Don't send an empty filters list; the EC2 API won't accept it.
- req.Filters = nil
- }
-
- resp, err := conn.DescribeVpcEndpoints(req)
- if err != nil {
- return err
- }
- if resp == nil || len(resp.VpcEndpoints) == 0 {
- return fmt.Errorf("no matching VPC endpoint found")
- }
- if len(resp.VpcEndpoints) > 1 {
- return fmt.Errorf("multiple VPC endpoints matched; use additional constraints to reduce matches to a single VPC endpoint")
- }
-
- vpce := resp.VpcEndpoints[0]
- policy, err := normalizeJsonString(*vpce.PolicyDocument)
- if err != nil {
- return errwrap.Wrapf("policy contains an invalid JSON: {{err}}", err)
- }
-
- d.SetId(aws.StringValue(vpce.VpcEndpointId))
- d.Set("id", vpce.VpcEndpointId)
- d.Set("state", vpce.State)
- d.Set("vpc_id", vpce.VpcId)
- d.Set("service_name", vpce.ServiceName)
- d.Set("policy", policy)
- if err := d.Set("route_table_ids", aws.StringValueSlice(vpce.RouteTableIds)); err != nil {
- return err
- }
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_vpc_endpoint_service.go b/builtin/providers/aws/data_source_aws_vpc_endpoint_service.go
deleted file mode 100644
index 8860b39a7..000000000
--- a/builtin/providers/aws/data_source_aws_vpc_endpoint_service.go
+++ /dev/null
@@ -1,56 +0,0 @@
-package aws
-
-import (
- "fmt"
- "log"
- "strconv"
- "strings"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/ec2"
- "github.com/hashicorp/terraform/helper/hashcode"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func dataSourceAwsVpcEndpointService() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsVpcEndpointServiceRead,
-
- Schema: map[string]*schema.Schema{
- "service": {
- Type: schema.TypeString,
- Required: true,
- },
- "service_name": {
- Type: schema.TypeString,
- Computed: true,
- },
- },
- }
-}
-
-func dataSourceAwsVpcEndpointServiceRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).ec2conn
-
- service := d.Get("service").(string)
-
- log.Printf("[DEBUG] Reading VPC Endpoint Services.")
-
- request := &ec2.DescribeVpcEndpointServicesInput{}
-
- resp, err := conn.DescribeVpcEndpointServices(request)
- if err != nil {
- return fmt.Errorf("Error fetching VPC Endpoint Services: %s", err)
- }
-
- names := aws.StringValueSlice(resp.ServiceNames)
- for _, name := range names {
- if strings.HasSuffix(name, "."+service) {
- d.SetId(strconv.Itoa(hashcode.String(name)))
- d.Set("service_name", name)
- return nil
- }
- }
-
- return fmt.Errorf("VPC Endpoint Service (%s) not found", service)
-}
diff --git a/builtin/providers/aws/data_source_aws_vpc_endpoint_service_test.go b/builtin/providers/aws/data_source_aws_vpc_endpoint_service_test.go
deleted file mode 100644
index ce82b8e2d..000000000
--- a/builtin/providers/aws/data_source_aws_vpc_endpoint_service_test.go
+++ /dev/null
@@ -1,52 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccDataSourceAwsVpcEndpointService(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDataSourceAwsVpcEndpointServiceConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccDataSourceAwsVpcEndpointServiceCheck("data.aws_vpc_endpoint_service.s3"),
- ),
- },
- },
- })
-}
-
-func testAccDataSourceAwsVpcEndpointServiceCheck(name string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[name]
- if !ok {
- return fmt.Errorf("root module has no resource called %s", name)
- }
-
- attr := rs.Primary.Attributes
-
- name := attr["service_name"]
- if name != "com.amazonaws.us-west-2.s3" {
- return fmt.Errorf("bad service name %s", name)
- }
-
- return nil
- }
-}
-
-const testAccDataSourceAwsVpcEndpointServiceConfig = `
-provider "aws" {
- region = "us-west-2"
-}
-
-data "aws_vpc_endpoint_service" "s3" {
- service = "s3"
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_vpc_endpoint_test.go b/builtin/providers/aws/data_source_aws_vpc_endpoint_test.go
deleted file mode 100644
index e73d0be56..000000000
--- a/builtin/providers/aws/data_source_aws_vpc_endpoint_test.go
+++ /dev/null
@@ -1,129 +0,0 @@
-// make testacc TEST=./builtin/providers/aws/ TESTARGS='-run=TestAccDataSourceAwsVpcEndpoint_'
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccDataSourceAwsVpcEndpoint_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDataSourceAwsVpcEndpointConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccDataSourceAwsVpcEndpointCheckExists("data.aws_vpc_endpoint.s3"),
- ),
- ExpectNonEmptyPlan: true,
- },
- },
- })
-}
-
-func TestAccDataSourceAwsVpcEndpoint_withRouteTable(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDataSourceAwsVpcEndpointWithRouteTableConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccDataSourceAwsVpcEndpointCheckExists("data.aws_vpc_endpoint.s3"),
- resource.TestCheckResourceAttr(
- "data.aws_vpc_endpoint.s3", "route_table_ids.#", "1"),
- ),
- ExpectNonEmptyPlan: true,
- },
- },
- })
-}
-
-func testAccDataSourceAwsVpcEndpointCheckExists(name string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[name]
- if !ok {
- return fmt.Errorf("root module has no resource called %s", name)
- }
-
- vpceRs, ok := s.RootModule().Resources["aws_vpc_endpoint.s3"]
- if !ok {
- return fmt.Errorf("can't find aws_vpc_endpoint.s3 in state")
- }
-
- attr := rs.Primary.Attributes
-
- if attr["id"] != vpceRs.Primary.Attributes["id"] {
- return fmt.Errorf(
- "id is %s; want %s",
- attr["id"],
- vpceRs.Primary.Attributes["id"],
- )
- }
-
- return nil
- }
-}
-
-const testAccDataSourceAwsVpcEndpointConfig = `
-provider "aws" {
- region = "us-west-2"
-}
-
-resource "aws_vpc" "foo" {
- cidr_block = "10.1.0.0/16"
-
- tags {
- Name = "terraform-testacc-vpc-endpoint-data-source-foo"
- }
-}
-
-resource "aws_vpc_endpoint" "s3" {
- vpc_id = "${aws_vpc.foo.id}"
- service_name = "com.amazonaws.us-west-2.s3"
-}
-
-data "aws_vpc_endpoint" "s3" {
- vpc_id = "${aws_vpc.foo.id}"
- service_name = "com.amazonaws.us-west-2.s3"
- state = "available"
-
- depends_on = ["aws_vpc_endpoint.s3"]
-}
-`
-
-const testAccDataSourceAwsVpcEndpointWithRouteTableConfig = `
-provider "aws" {
- region = "us-west-2"
-}
-
-resource "aws_vpc" "foo" {
- cidr_block = "10.1.0.0/16"
-
- tags {
- Name = "terraform-testacc-vpc-endpoint-data-source-foo"
- }
-}
-
-resource "aws_route_table" "rt" {
- vpc_id = "${aws_vpc.foo.id}"
-}
-
-resource "aws_vpc_endpoint" "s3" {
- vpc_id = "${aws_vpc.foo.id}"
- service_name = "com.amazonaws.us-west-2.s3"
- route_table_ids = ["${aws_route_table.rt.id}"]
-}
-
-data "aws_vpc_endpoint" "s3" {
- vpc_id = "${aws_vpc.foo.id}"
- service_name = "com.amazonaws.us-west-2.s3"
- state = "available"
-
- depends_on = ["aws_vpc_endpoint.s3"]
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_vpc_peering_connection.go b/builtin/providers/aws/data_source_aws_vpc_peering_connection.go
deleted file mode 100644
index 8d800751f..000000000
--- a/builtin/providers/aws/data_source_aws_vpc_peering_connection.go
+++ /dev/null
@@ -1,143 +0,0 @@
-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 dataSourceAwsVpcPeeringConnection() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsVpcPeeringConnectionRead,
-
- Schema: map[string]*schema.Schema{
- "id": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "status": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "vpc_id": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "owner_id": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "cidr_block": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "peer_vpc_id": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "peer_owner_id": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "peer_cidr_block": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "accepter": {
- Type: schema.TypeMap,
- Computed: true,
- Elem: schema.TypeBool,
- },
- "requester": {
- Type: schema.TypeMap,
- Computed: true,
- Elem: schema.TypeBool,
- },
- "filter": ec2CustomFiltersSchema(),
- "tags": tagsSchemaComputed(),
- },
- }
-}
-
-func dataSourceAwsVpcPeeringConnectionRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).ec2conn
-
- log.Printf("[DEBUG] Reading VPC Peering Connections.")
-
- req := &ec2.DescribeVpcPeeringConnectionsInput{}
-
- if id, ok := d.GetOk("id"); ok {
- req.VpcPeeringConnectionIds = aws.StringSlice([]string{id.(string)})
- }
-
- req.Filters = buildEC2AttributeFilterList(
- map[string]string{
- "status-code": d.Get("status").(string),
- "requester-vpc-info.vpc-id": d.Get("vpc_id").(string),
- "requester-vpc-info.owner-id": d.Get("owner_id").(string),
- "requester-vpc-info.cidr-block": d.Get("cidr_block").(string),
- "accepter-vpc-info.vpc-id": d.Get("peer_vpc_id").(string),
- "accepter-vpc-info.owner-id": d.Get("peer_owner_id").(string),
- "accepter-vpc-info.cidr-block": d.Get("peer_cidr_block").(string),
- },
- )
- req.Filters = append(req.Filters, buildEC2TagFilterList(
- tagsFromMap(d.Get("tags").(map[string]interface{})),
- )...)
- req.Filters = append(req.Filters, buildEC2CustomFilterList(
- d.Get("filter").(*schema.Set),
- )...)
- if len(req.Filters) == 0 {
- // Don't send an empty filters list; the EC2 API won't accept it.
- req.Filters = nil
- }
-
- resp, err := conn.DescribeVpcPeeringConnections(req)
- if err != nil {
- return err
- }
- if resp == nil || len(resp.VpcPeeringConnections) == 0 {
- return fmt.Errorf("no matching VPC peering connection found")
- }
- if len(resp.VpcPeeringConnections) > 1 {
- return fmt.Errorf("multiple VPC peering connections matched; use additional constraints to reduce matches to a single VPC peering connection")
- }
-
- pcx := resp.VpcPeeringConnections[0]
-
- d.SetId(aws.StringValue(pcx.VpcPeeringConnectionId))
- d.Set("id", pcx.VpcPeeringConnectionId)
- d.Set("status", pcx.Status.Code)
- d.Set("vpc_id", pcx.RequesterVpcInfo.VpcId)
- d.Set("owner_id", pcx.RequesterVpcInfo.OwnerId)
- d.Set("cidr_block", pcx.RequesterVpcInfo.CidrBlock)
- d.Set("peer_vpc_id", pcx.AccepterVpcInfo.VpcId)
- d.Set("peer_owner_id", pcx.AccepterVpcInfo.OwnerId)
- d.Set("peer_cidr_block", pcx.AccepterVpcInfo.CidrBlock)
- d.Set("tags", tagsToMap(pcx.Tags))
-
- if pcx.AccepterVpcInfo.PeeringOptions != nil {
- if err := d.Set("accepter", flattenPeeringOptions(pcx.AccepterVpcInfo.PeeringOptions)[0]); err != nil {
- return err
- }
- }
-
- if pcx.RequesterVpcInfo.PeeringOptions != nil {
- if err := d.Set("requester", flattenPeeringOptions(pcx.RequesterVpcInfo.PeeringOptions)[0]); err != nil {
- return err
- }
- }
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_vpc_peering_connection_test.go b/builtin/providers/aws/data_source_aws_vpc_peering_connection_test.go
deleted file mode 100644
index 366921a72..000000000
--- a/builtin/providers/aws/data_source_aws_vpc_peering_connection_test.go
+++ /dev/null
@@ -1,129 +0,0 @@
-// make testacc TEST=./builtin/providers/aws/ TESTARGS='-run=TestAccDataSourceAwsVpcPeeringConnection_'
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccDataSourceAwsVpcPeeringConnection_basic(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDataSourceAwsVpcPeeringConnectionConfig,
- Check: resource.ComposeTestCheckFunc(
- testAccDataSourceAwsVpcPeeringConnectionCheck("data.aws_vpc_peering_connection.test_by_id"),
- testAccDataSourceAwsVpcPeeringConnectionCheck("data.aws_vpc_peering_connection.test_by_requester_vpc_id"),
- testAccDataSourceAwsVpcPeeringConnectionCheck("data.aws_vpc_peering_connection.test_by_accepter_vpc_id"),
- testAccDataSourceAwsVpcPeeringConnectionCheck("data.aws_vpc_peering_connection.test_by_requester_cidr_block"),
- testAccDataSourceAwsVpcPeeringConnectionCheck("data.aws_vpc_peering_connection.test_by_accepter_cidr_block"),
- testAccDataSourceAwsVpcPeeringConnectionCheck("data.aws_vpc_peering_connection.test_by_owner_ids"),
- ),
- ExpectNonEmptyPlan: true,
- },
- },
- })
-}
-
-func testAccDataSourceAwsVpcPeeringConnectionCheck(name string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[name]
- if !ok {
- return fmt.Errorf("root module has no resource called %s", name)
- }
-
- pcxRs, ok := s.RootModule().Resources["aws_vpc_peering_connection.test"]
- if !ok {
- return fmt.Errorf("can't find aws_vpc_peering_connection.test in state")
- }
-
- attr := rs.Primary.Attributes
-
- if attr["id"] != pcxRs.Primary.Attributes["id"] {
- return fmt.Errorf(
- "id is %s; want %s",
- attr["id"],
- pcxRs.Primary.Attributes["id"],
- )
- }
-
- return nil
- }
-}
-
-const testAccDataSourceAwsVpcPeeringConnectionConfig = `
-provider "aws" {
- region = "us-west-2"
-}
-
-resource "aws_vpc" "foo" {
- cidr_block = "10.1.0.0/16"
-
- tags {
- Name = "terraform-testacc-vpc-peering-connection-data-source-foo"
- }
-}
-
-resource "aws_vpc" "bar" {
- cidr_block = "10.2.0.0/16"
-
- tags {
- Name = "terraform-testacc-vpc-peering-connection-data-source-bar"
- }
-}
-
-resource "aws_vpc_peering_connection" "test" {
- vpc_id = "${aws_vpc.foo.id}"
- peer_vpc_id = "${aws_vpc.bar.id}"
- auto_accept = true
-
- tags {
- Name = "terraform-testacc-vpc-peering-connection-data-source-foo-to-bar"
- }
-}
-
-data "aws_caller_identity" "current" {}
-
-data "aws_vpc_peering_connection" "test_by_id" {
- id = "${aws_vpc_peering_connection.test.id}"
-}
-
-data "aws_vpc_peering_connection" "test_by_requester_vpc_id" {
- vpc_id = "${aws_vpc.foo.id}"
-
- depends_on = ["aws_vpc_peering_connection.test"]
-}
-
-data "aws_vpc_peering_connection" "test_by_accepter_vpc_id" {
- peer_vpc_id = "${aws_vpc.bar.id}"
-
- depends_on = ["aws_vpc_peering_connection.test"]
-}
-
-data "aws_vpc_peering_connection" "test_by_requester_cidr_block" {
- cidr_block = "10.1.0.0/16"
- status = "active"
-
- depends_on = ["aws_vpc_peering_connection.test"]
-}
-
-data "aws_vpc_peering_connection" "test_by_accepter_cidr_block" {
- peer_cidr_block = "10.2.0.0/16"
- status = "active"
-
- depends_on = ["aws_vpc_peering_connection.test"]
-}
-
-data "aws_vpc_peering_connection" "test_by_owner_ids" {
- owner_id = "${data.aws_caller_identity.current.account_id}"
- peer_owner_id = "${data.aws_caller_identity.current.account_id}"
- status = "active"
-
- depends_on = ["aws_vpc_peering_connection.test"]
-}
-`
diff --git a/builtin/providers/aws/data_source_aws_vpc_test.go b/builtin/providers/aws/data_source_aws_vpc_test.go
deleted file mode 100644
index e8344db98..000000000
--- a/builtin/providers/aws/data_source_aws_vpc_test.go
+++ /dev/null
@@ -1,145 +0,0 @@
-package aws
-
-import (
- "fmt"
- "math/rand"
- "testing"
- "time"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccDataSourceAwsVpc_basic(t *testing.T) {
- rand.Seed(time.Now().UTC().UnixNano())
- rInt := rand.Intn(16)
- cidr := fmt.Sprintf("172.%d.0.0/16", rInt)
- tag := fmt.Sprintf("terraform-testacc-vpc-data-source-%d", rInt)
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAwsVpcConfig(cidr, tag),
- Check: resource.ComposeTestCheckFunc(
- testAccDataSourceAwsVpcCheck("data.aws_vpc.by_id", cidr, tag),
- testAccDataSourceAwsVpcCheck("data.aws_vpc.by_cidr", cidr, tag),
- testAccDataSourceAwsVpcCheck("data.aws_vpc.by_tag", cidr, tag),
- testAccDataSourceAwsVpcCheck("data.aws_vpc.by_filter", cidr, tag),
- ),
- },
- },
- })
-}
-
-func TestAccDataSourceAwsVpc_ipv6Associated(t *testing.T) {
- rand.Seed(time.Now().UTC().UnixNano())
- rInt := rand.Intn(16)
- cidr := fmt.Sprintf("172.%d.0.0/16", rInt)
- tag := fmt.Sprintf("terraform-testacc-vpc-data-source-%d", rInt)
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccDataSourceAwsVpcConfigIpv6(cidr, tag),
- Check: resource.ComposeTestCheckFunc(
- testAccDataSourceAwsVpcCheck("data.aws_vpc.by_id", cidr, tag),
- resource.TestCheckResourceAttrSet(
- "data.aws_vpc.by_id", "ipv6_association_id"),
- resource.TestCheckResourceAttrSet(
- "data.aws_vpc.by_id", "ipv6_cidr_block"),
- ),
- },
- },
- })
-}
-
-func testAccDataSourceAwsVpcCheck(name, cidr, tag string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[name]
- if !ok {
- return fmt.Errorf("root module has no resource called %s", name)
- }
-
- vpcRs, ok := s.RootModule().Resources["aws_vpc.test"]
- if !ok {
- return fmt.Errorf("can't find aws_vpc.test in state")
- }
-
- attr := rs.Primary.Attributes
-
- if attr["id"] != vpcRs.Primary.Attributes["id"] {
- return fmt.Errorf(
- "id is %s; want %s",
- attr["id"],
- vpcRs.Primary.Attributes["id"],
- )
- }
-
- if attr["cidr_block"] != cidr {
- return fmt.Errorf("bad cidr_block %s, expected: %s", attr["cidr_block"], cidr)
- }
- if attr["tags.Name"] != tag {
- return fmt.Errorf("bad Name tag %s", attr["tags.Name"])
- }
-
- return nil
- }
-}
-
-func testAccDataSourceAwsVpcConfigIpv6(cidr, tag string) string {
- return fmt.Sprintf(`
-provider "aws" {
- region = "us-west-2"
-}
-
-resource "aws_vpc" "test" {
- cidr_block = "%s"
- assign_generated_ipv6_cidr_block = true
-
- tags {
- Name = "%s"
- }
-}
-
-data "aws_vpc" "by_id" {
- id = "${aws_vpc.test.id}"
-}`, cidr, tag)
-}
-
-func testAccDataSourceAwsVpcConfig(cidr, tag string) string {
- return fmt.Sprintf(`
-provider "aws" {
- region = "us-west-2"
-}
-
-resource "aws_vpc" "test" {
- cidr_block = "%s"
-
- tags {
- Name = "%s"
- }
-}
-
-data "aws_vpc" "by_id" {
- id = "${aws_vpc.test.id}"
-}
-
-data "aws_vpc" "by_cidr" {
- cidr_block = "${aws_vpc.test.cidr_block}"
-}
-
-data "aws_vpc" "by_tag" {
- tags {
- Name = "${aws_vpc.test.tags["Name"]}"
- }
-}
-
-data "aws_vpc" "by_filter" {
- filter {
- name = "cidr"
- values = ["${aws_vpc.test.cidr_block}"]
- }
-}`, cidr, tag)
-}
diff --git a/builtin/providers/aws/data_source_aws_vpn_gateway.go b/builtin/providers/aws/data_source_aws_vpn_gateway.go
deleted file mode 100644
index 5d088e548..000000000
--- a/builtin/providers/aws/data_source_aws_vpn_gateway.go
+++ /dev/null
@@ -1,105 +0,0 @@
-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 dataSourceAwsVpnGateway() *schema.Resource {
- return &schema.Resource{
- Read: dataSourceAwsVpnGatewayRead,
-
- Schema: map[string]*schema.Schema{
- "id": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "state": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "attached_vpc_id": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "availability_zone": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
- "filter": ec2CustomFiltersSchema(),
- "tags": tagsSchemaComputed(),
- },
- }
-}
-
-func dataSourceAwsVpnGatewayRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).ec2conn
-
- log.Printf("[DEBUG] Reading VPN Gateways.")
-
- req := &ec2.DescribeVpnGatewaysInput{}
-
- if id, ok := d.GetOk("id"); ok {
- req.VpnGatewayIds = aws.StringSlice([]string{id.(string)})
- }
-
- req.Filters = buildEC2AttributeFilterList(
- map[string]string{
- "state": d.Get("state").(string),
- "availability-zone": d.Get("availability_zone").(string),
- },
- )
- if id, ok := d.GetOk("attached_vpc_id"); ok {
- req.Filters = append(req.Filters, buildEC2AttributeFilterList(
- map[string]string{
- "attachment.state": "attached",
- "attachment.vpc-id": id.(string),
- },
- )...)
- }
- req.Filters = append(req.Filters, buildEC2TagFilterList(
- tagsFromMap(d.Get("tags").(map[string]interface{})),
- )...)
- req.Filters = append(req.Filters, buildEC2CustomFilterList(
- d.Get("filter").(*schema.Set),
- )...)
- if len(req.Filters) == 0 {
- // Don't send an empty filters list; the EC2 API won't accept it.
- req.Filters = nil
- }
-
- resp, err := conn.DescribeVpnGateways(req)
- if err != nil {
- return err
- }
- if resp == nil || len(resp.VpnGateways) == 0 {
- return fmt.Errorf("no matching VPN gateway found: %#v", req)
- }
- if len(resp.VpnGateways) > 1 {
- return fmt.Errorf("multiple VPN gateways matched; use additional constraints to reduce matches to a single VPN gateway")
- }
-
- vgw := resp.VpnGateways[0]
-
- d.SetId(aws.StringValue(vgw.VpnGatewayId))
- d.Set("state", vgw.State)
- d.Set("availability_zone", vgw.AvailabilityZone)
- d.Set("tags", tagsToMap(vgw.Tags))
-
- for _, attachment := range vgw.VpcAttachments {
- if *attachment.State == "attached" {
- d.Set("attached_vpc_id", attachment.VpcId)
- break
- }
- }
-
- return nil
-}
diff --git a/builtin/providers/aws/data_source_aws_vpn_gateway_test.go b/builtin/providers/aws/data_source_aws_vpn_gateway_test.go
deleted file mode 100644
index e082e844e..000000000
--- a/builtin/providers/aws/data_source_aws_vpn_gateway_test.go
+++ /dev/null
@@ -1,114 +0,0 @@
-// make testacc TEST=./builtin/providers/aws/ TESTARGS='-run=TestAccDataSourceAwsVpnGateway_'
-package aws
-
-import (
- "fmt"
- "regexp"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccDataSourceAwsVpnGateway_unattached(t *testing.T) {
- rInt := acctest.RandInt()
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDataSourceAwsVpnGatewayUnattachedConfig(rInt),
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttrPair(
- "data.aws_vpn_gateway.test_by_id", "id",
- "aws_vpn_gateway.unattached", "id"),
- resource.TestCheckResourceAttrPair(
- "data.aws_vpn_gateway.test_by_tags", "id",
- "aws_vpn_gateway.unattached", "id"),
- resource.TestCheckResourceAttrSet("data.aws_vpn_gateway.test_by_id", "state"),
- resource.TestCheckResourceAttr("data.aws_vpn_gateway.test_by_tags", "tags.%", "3"),
- resource.TestCheckNoResourceAttr("data.aws_vpn_gateway.test_by_id", "attached_vpc_id"),
- ),
- },
- },
- })
-}
-
-func TestAccDataSourceAwsVpnGateway_attached(t *testing.T) {
- rInt := acctest.RandInt()
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDataSourceAwsVpnGatewayAttachedConfig(rInt),
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttrPair(
- "data.aws_vpn_gateway.test_by_attached_vpc_id", "id",
- "aws_vpn_gateway.attached", "id"),
- resource.TestCheckResourceAttrPair(
- "data.aws_vpn_gateway.test_by_attached_vpc_id", "attached_vpc_id",
- "aws_vpc.foo", "id"),
- resource.TestMatchResourceAttr("data.aws_vpn_gateway.test_by_attached_vpc_id", "state", regexp.MustCompile("(?i)available")),
- ),
- },
- },
- })
-}
-
-func testAccDataSourceAwsVpnGatewayUnattachedConfig(rInt int) string {
- return fmt.Sprintf(`
-provider "aws" {
- region = "us-west-2"
-}
-
-resource "aws_vpn_gateway" "unattached" {
- tags {
- Name = "terraform-testacc-vpn-gateway-data-source-unattached-%d"
- ABC = "testacc-%d"
- XYZ = "testacc-%d"
- }
-}
-
-data "aws_vpn_gateway" "test_by_id" {
- id = "${aws_vpn_gateway.unattached.id}"
-}
-
-data "aws_vpn_gateway" "test_by_tags" {
- tags = "${aws_vpn_gateway.unattached.tags}"
-}
-`, rInt, rInt+1, rInt-1)
-}
-
-func testAccDataSourceAwsVpnGatewayAttachedConfig(rInt int) string {
- return fmt.Sprintf(`
-provider "aws" {
- region = "us-west-2"
-}
-
-resource "aws_vpc" "foo" {
- cidr_block = "10.1.0.0/16"
-
- tags {
- Name = "terraform-testacc-vpn-gateway-data-source-foo-%d"
- }
-}
-
-resource "aws_vpn_gateway" "attached" {
- tags {
- Name = "terraform-testacc-vpn-gateway-data-source-attached-%d"
- }
-}
-
-resource "aws_vpn_gateway_attachment" "vpn_attachment" {
- vpc_id = "${aws_vpc.foo.id}"
- vpn_gateway_id = "${aws_vpn_gateway.attached.id}"
-}
-
-data "aws_vpn_gateway" "test_by_attached_vpc_id" {
- attached_vpc_id = "${aws_vpn_gateway_attachment.vpn_attachment.vpc_id}"
-}
-`, rInt, rInt)
-}
diff --git a/builtin/providers/aws/diff_aws_policy_test.go b/builtin/providers/aws/diff_aws_policy_test.go
deleted file mode 100644
index ae06c26aa..000000000
--- a/builtin/providers/aws/diff_aws_policy_test.go
+++ /dev/null
@@ -1,38 +0,0 @@
-package aws
-
-import (
- "fmt"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
- "github.com/jen20/awspolicyequivalence"
-)
-
-func testAccCheckAwsPolicyMatch(resource, attr, expectedPolicy string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[resource]
- if !ok {
- return fmt.Errorf("Not found: %s", resource)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No ID is set")
- }
-
- given, ok := rs.Primary.Attributes[attr]
- if !ok {
- return fmt.Errorf("Attribute %q not found for %q", attr, resource)
- }
-
- areEquivalent, err := awspolicy.PoliciesAreEquivalent(given, expectedPolicy)
- if err != nil {
- return fmt.Errorf("Comparing AWS Policies failed: %s", err)
- }
-
- if !areEquivalent {
- return fmt.Errorf("AWS policies differ.\nGiven: %s\nExpected: %s", given, expectedPolicy)
- }
-
- return nil
- }
-}
diff --git a/builtin/providers/aws/diff_suppress_funcs.go b/builtin/providers/aws/diff_suppress_funcs.go
deleted file mode 100644
index e8c58b813..000000000
--- a/builtin/providers/aws/diff_suppress_funcs.go
+++ /dev/null
@@ -1,77 +0,0 @@
-package aws
-
-import (
- "bytes"
- "encoding/json"
- "log"
- "net/url"
- "strings"
-
- "github.com/hashicorp/terraform/helper/schema"
- "github.com/jen20/awspolicyequivalence"
-)
-
-func suppressEquivalentAwsPolicyDiffs(k, old, new string, d *schema.ResourceData) bool {
- equivalent, err := awspolicy.PoliciesAreEquivalent(old, new)
- if err != nil {
- return false
- }
-
- return equivalent
-}
-
-// Suppresses minor version changes to the db_instance engine_version attribute
-func suppressAwsDbEngineVersionDiffs(k, old, new string, d *schema.ResourceData) bool {
- // First check if the old/new values are nil.
- // If both are nil, we have no state to compare the values with, so register a diff.
- // This populates the attribute field during a plan/apply with fresh state, allowing
- // the attribute to still be used in future resources.
- // See https://github.com/hashicorp/terraform/issues/11881
- if old == "" && new == "" {
- return false
- }
-
- if v, ok := d.GetOk("auto_minor_version_upgrade"); ok {
- if v.(bool) {
- // If we're set to auto upgrade minor versions
- // ignore a minor version diff between versions
- if strings.HasPrefix(old, new) {
- log.Printf("[DEBUG] Ignoring minor version diff")
- return true
- }
- }
- }
-
- // Throw a diff by default
- return false
-}
-
-func suppressEquivalentJsonDiffs(k, old, new string, d *schema.ResourceData) bool {
- ob := bytes.NewBufferString("")
- if err := json.Compact(ob, []byte(old)); err != nil {
- return false
- }
-
- nb := bytes.NewBufferString("")
- if err := json.Compact(nb, []byte(new)); err != nil {
- return false
- }
-
- return jsonBytesEqual(ob.Bytes(), nb.Bytes())
-}
-
-func suppressOpenIdURL(k, old, new string, d *schema.ResourceData) bool {
- oldUrl, err := url.Parse(old)
- if err != nil {
- return false
- }
-
- newUrl, err := url.Parse(new)
- if err != nil {
- return false
- }
-
- oldUrl.Scheme = "https"
-
- return oldUrl.String() == newUrl.String()
-}
diff --git a/builtin/providers/aws/diff_suppress_funcs_test.go b/builtin/providers/aws/diff_suppress_funcs_test.go
deleted file mode 100644
index 0727a1042..000000000
--- a/builtin/providers/aws/diff_suppress_funcs_test.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func TestSuppressEquivalentJsonDiffsWhitespaceAndNoWhitespace(t *testing.T) {
- d := new(schema.ResourceData)
-
- noWhitespace := `{"test":"test"}`
- whitespace := `
-{
- "test": "test"
-}`
-
- if !suppressEquivalentJsonDiffs("", noWhitespace, whitespace, d) {
- t.Errorf("Expected suppressEquivalentJsonDiffs to return true for %s == %s", noWhitespace, whitespace)
- }
-
- noWhitespaceDiff := `{"test":"test"}`
- whitespaceDiff := `
-{
- "test": "tested"
-}`
-
- if suppressEquivalentJsonDiffs("", noWhitespaceDiff, whitespaceDiff, d) {
- t.Errorf("Expected suppressEquivalentJsonDiffs to return false for %s == %s", noWhitespaceDiff, whitespaceDiff)
- }
-}
diff --git a/builtin/providers/aws/ec2_filters.go b/builtin/providers/aws/ec2_filters.go
deleted file mode 100644
index 743d28224..000000000
--- a/builtin/providers/aws/ec2_filters.go
+++ /dev/null
@@ -1,163 +0,0 @@
-package aws
-
-import (
- "fmt"
- "sort"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/ec2"
-
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-// buildEC2AttributeFilterList takes a flat map of scalar attributes (most
-// likely values extracted from a *schema.ResourceData on an EC2-querying
-// data source) and produces a []*ec2.Filter representing an exact match
-// for each of the given non-empty attributes.
-//
-// The keys of the given attributes map are the attribute names expected
-// by the EC2 API, which are usually either in camelcase or with dash-separated
-// words. We conventionally map these to underscore-separated identifiers
-// with the same words when presenting these as data source query attributes
-// in Terraform.
-//
-// It's the callers responsibility to transform any non-string values into
-// the appropriate string serialization required by the AWS API when
-// encoding the given filter. Any attributes given with empty string values
-// are ignored, assuming that the user wishes to leave that attribute
-// unconstrained while filtering.
-//
-// The purpose of this function is to create values to pass in
-// for the "Filters" attribute on most of the "Describe..." API functions in
-// the EC2 API, to aid in the implementation of Terraform data sources that
-// retrieve data about EC2 objects.
-func buildEC2AttributeFilterList(attrs map[string]string) []*ec2.Filter {
- var filters []*ec2.Filter
-
- // sort the filters by name to make the output deterministic
- var names []string
- for filterName := range attrs {
- names = append(names, filterName)
- }
-
- sort.Strings(names)
-
- for _, filterName := range names {
- value := attrs[filterName]
- if value == "" {
- continue
- }
-
- filters = append(filters, &ec2.Filter{
- Name: aws.String(filterName),
- Values: []*string{aws.String(value)},
- })
- }
-
- return filters
-}
-
-// buildEC2TagFilterList takes a []*ec2.Tag and produces a []*ec2.Filter that
-// represents exact matches for all of the tag key/value pairs given in
-// the tag set.
-//
-// The purpose of this function is to create values to pass in for
-// the "Filters" attribute on most of the "Describe..." API functions
-// in the EC2 API, to implement filtering by tag values e.g. in Terraform
-// data sources that retrieve data about EC2 objects.
-//
-// It is conventional for an EC2 data source to include an attribute called
-// "tags" which conforms to the schema returned by the tagsSchema() function.
-// The value of this can then be converted to a tags slice using tagsFromMap,
-// and the result finally passed in to this function.
-//
-// In Terraform configuration this would then look like this, to constrain
-// results by name:
-//
-// tags {
-// Name = "my-awesome-subnet"
-// }
-func buildEC2TagFilterList(tags []*ec2.Tag) []*ec2.Filter {
- filters := make([]*ec2.Filter, len(tags))
-
- for i, tag := range tags {
- filters[i] = &ec2.Filter{
- Name: aws.String(fmt.Sprintf("tag:%s", *tag.Key)),
- Values: []*string{tag.Value},
- }
- }
-
- return filters
-}
-
-// ec2CustomFiltersSchema returns a *schema.Schema that represents
-// a set of custom filtering criteria that a user can specify as input
-// to a data source that wraps one of the many "Describe..." API calls
-// in the EC2 API.
-//
-// It is conventional for an attribute of this type to be included
-// as a top-level attribute called "filter". This is the "catch all" for
-// filter combinations that are not possible to express using scalar
-// attributes or tags. In Terraform configuration, the custom filter blocks
-// then look like this:
-//
-// filter {
-// name = "availabilityZone"
-// values = ["us-west-2a", "us-west-2b"]
-// }
-func ec2CustomFiltersSchema() *schema.Schema {
- return &schema.Schema{
- Type: schema.TypeSet,
- Optional: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "name": {
- Type: schema.TypeString,
- Required: true,
- },
- "values": {
- Type: schema.TypeSet,
- Required: true,
- Elem: &schema.Schema{
- Type: schema.TypeString,
- },
- },
- },
- },
- }
-}
-
-// buildEC2CustomFilterList takes the set value extracted from a schema
-// attribute conforming to the schema returned by ec2CustomFiltersSchema,
-// and transforms it into a []*ec2.Filter representing the same filter
-// expressions which is ready to pass into the "Filters" attribute on most
-// of the "Describe..." functions in the EC2 API.
-//
-// This function is intended only to be used in conjunction with
-// ec2CustomFitlersSchema. See the docs on that function for more details
-// on the configuration pattern this is intended to support.
-func buildEC2CustomFilterList(filterSet *schema.Set) []*ec2.Filter {
- if filterSet == nil {
- return []*ec2.Filter{}
- }
-
- customFilters := filterSet.List()
- filters := make([]*ec2.Filter, len(customFilters))
-
- for filterIdx, customFilterI := range customFilters {
- customFilterMapI := customFilterI.(map[string]interface{})
- name := customFilterMapI["name"].(string)
- valuesI := customFilterMapI["values"].(*schema.Set).List()
- values := make([]*string, len(valuesI))
- for valueIdx, valueI := range valuesI {
- values[valueIdx] = aws.String(valueI.(string))
- }
-
- filters[filterIdx] = &ec2.Filter{
- Name: &name,
- Values: values,
- }
- }
-
- return filters
-}
diff --git a/builtin/providers/aws/ec2_filters_test.go b/builtin/providers/aws/ec2_filters_test.go
deleted file mode 100644
index 267faa957..000000000
--- a/builtin/providers/aws/ec2_filters_test.go
+++ /dev/null
@@ -1,158 +0,0 @@
-package aws
-
-import (
- "reflect"
- "testing"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/ec2"
-
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func TestBuildEC2AttributeFilterList(t *testing.T) {
- type TestCase struct {
- Attrs map[string]string
- Expected []*ec2.Filter
- }
- testCases := []TestCase{
- {
- map[string]string{
- "foo": "bar",
- "baz": "boo",
- },
- []*ec2.Filter{
- {
- Name: aws.String("baz"),
- Values: []*string{aws.String("boo")},
- },
- {
- Name: aws.String("foo"),
- Values: []*string{aws.String("bar")},
- },
- },
- },
- {
- map[string]string{
- "foo": "bar",
- "baz": "",
- },
- []*ec2.Filter{
- {
- Name: aws.String("foo"),
- Values: []*string{aws.String("bar")},
- },
- },
- },
- }
-
- for i, testCase := range testCases {
- result := buildEC2AttributeFilterList(testCase.Attrs)
-
- if !reflect.DeepEqual(result, testCase.Expected) {
- t.Errorf(
- "test case %d: got %#v, but want %#v",
- i, result, testCase.Expected,
- )
- }
- }
-}
-
-func TestBuildEC2TagFilterList(t *testing.T) {
- type TestCase struct {
- Tags []*ec2.Tag
- Expected []*ec2.Filter
- }
- testCases := []TestCase{
- {
- []*ec2.Tag{
- {
- Key: aws.String("foo"),
- Value: aws.String("bar"),
- },
- {
- Key: aws.String("baz"),
- Value: aws.String("boo"),
- },
- },
- []*ec2.Filter{
- {
- Name: aws.String("tag:foo"),
- Values: []*string{aws.String("bar")},
- },
- {
- Name: aws.String("tag:baz"),
- Values: []*string{aws.String("boo")},
- },
- },
- },
- }
-
- for i, testCase := range testCases {
- result := buildEC2TagFilterList(testCase.Tags)
-
- if !reflect.DeepEqual(result, testCase.Expected) {
- t.Errorf(
- "test case %d: got %#v, but want %#v",
- i, result, testCase.Expected,
- )
- }
- }
-}
-
-func TestBuildEC2CustomFilterList(t *testing.T) {
-
- // We need to get a set with the appropriate hash function,
- // so we'll use the schema to help us produce what would
- // be produced in the normal case.
- filtersSchema := ec2CustomFiltersSchema()
-
- // The zero value of this schema will be an interface{}
- // referring to a new, empty *schema.Set with the
- // appropriate hash function configured.
- filters := filtersSchema.ZeroValue().(*schema.Set)
-
- // We also need an appropriately-configured set for
- // the list of values.
- valuesSchema := filtersSchema.Elem.(*schema.Resource).Schema["values"]
- valuesSet := func(vals ...string) *schema.Set {
- ret := valuesSchema.ZeroValue().(*schema.Set)
- for _, val := range vals {
- ret.Add(val)
- }
- return ret
- }
-
- filters.Add(map[string]interface{}{
- "name": "foo",
- "values": valuesSet("bar", "baz"),
- })
- filters.Add(map[string]interface{}{
- "name": "pizza",
- "values": valuesSet("cheese"),
- })
-
- expected := []*ec2.Filter{
- // These are produced in the deterministic order guaranteed
- // by schema.Set.List(), which happens to produce them in
- // the following order for our current input. If this test
- // evolves with different input data in future then they
- // will likely be emitted in a different order, which is fine.
- {
- Name: aws.String("pizza"),
- Values: []*string{aws.String("cheese")},
- },
- {
- Name: aws.String("foo"),
- Values: []*string{aws.String("bar"), aws.String("baz")},
- },
- }
- result := buildEC2CustomFilterList(filters)
-
- if !reflect.DeepEqual(result, expected) {
- t.Errorf(
- "got %#v, but want %#v",
- result, expected,
- )
- }
-}
diff --git a/builtin/providers/aws/hosted_zones.go b/builtin/providers/aws/hosted_zones.go
deleted file mode 100644
index 131f03ebd..000000000
--- a/builtin/providers/aws/hosted_zones.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package aws
-
-// This list is copied from
-// http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_website_region_endpoints
-// It currently cannot be generated from the API json.
-var hostedZoneIDsMap = map[string]string{
- "us-east-1": "Z3AQBSTGFYJSTF",
- "us-east-2": "Z2O1EMRO9K5GLX",
- "us-west-2": "Z3BJ6K6RIION7M",
- "us-west-1": "Z2F56UZL2M1ACD",
- "eu-west-1": "Z1BKCTXD74EZPE",
- "eu-west-2": "Z3GKZC51ZF0DB4",
- "eu-central-1": "Z21DNDUVLTQW6Q",
- "ap-south-1": "Z11RGJOFQNVJUP",
- "ap-southeast-1": "Z3O0J2DXBE1FTB",
- "ap-southeast-2": "Z1WCIGYICN2BYD",
- "ap-northeast-1": "Z2M4EHUR26P7ZW",
- "ap-northeast-2": "Z3W03O7B5YMIYP",
- "ca-central-1": "Z1QDHH18159H29",
- "sa-east-1": "Z7KQH4QJS55SO",
- "us-gov-west-1": "Z31GFT0UA1I2HV",
-}
-
-// Returns the hosted zone ID for an S3 website endpoint region. This can be
-// used as input to the aws_route53_record resource's zone_id argument.
-func HostedZoneIDForRegion(region string) string {
- return hostedZoneIDsMap[region]
-}
diff --git a/builtin/providers/aws/hosted_zones_test.go b/builtin/providers/aws/hosted_zones_test.go
deleted file mode 100644
index d331a7b8f..000000000
--- a/builtin/providers/aws/hosted_zones_test.go
+++ /dev/null
@@ -1,19 +0,0 @@
-package aws
-
-import (
- "testing"
-)
-
-func TestHostedZoneIDForRegion(t *testing.T) {
- if r := HostedZoneIDForRegion("us-east-1"); r != "Z3AQBSTGFYJSTF" {
- t.Fatalf("bad: %s", r)
- }
- if r := HostedZoneIDForRegion("ap-southeast-2"); r != "Z1WCIGYICN2BYD" {
- t.Fatalf("bad: %s", r)
- }
-
- // Bad input should be empty string
- if r := HostedZoneIDForRegion("not-a-region"); r != "" {
- t.Fatalf("bad: %s", r)
- }
-}
diff --git a/builtin/providers/aws/iam_policy_model.go b/builtin/providers/aws/iam_policy_model.go
deleted file mode 100644
index 81306971d..000000000
--- a/builtin/providers/aws/iam_policy_model.go
+++ /dev/null
@@ -1,112 +0,0 @@
-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
-}
diff --git a/builtin/providers/aws/import_aws_api_gateway_account_test.go b/builtin/providers/aws/import_aws_api_gateway_account_test.go
deleted file mode 100644
index cb60a4929..000000000
--- a/builtin/providers/aws/import_aws_api_gateway_account_test.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSAPIGatewayAccount_importBasic(t *testing.T) {
- resourceName := "aws_api_gateway_account.test"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSAPIGatewayAccountDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSAPIGatewayAccountConfig_empty,
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_api_gateway_key_test.go b/builtin/providers/aws/import_aws_api_gateway_key_test.go
deleted file mode 100644
index 2fd3d4cef..000000000
--- a/builtin/providers/aws/import_aws_api_gateway_key_test.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSAPIGatewayApiKey_importBasic(t *testing.T) {
- resourceName := "aws_api_gateway_api_key.test"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSAPIGatewayApiKeyDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSAPIGatewayApiKeyConfig,
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_api_gateway_usage_plan_test.go b/builtin/providers/aws/import_aws_api_gateway_usage_plan_test.go
deleted file mode 100644
index 76a58e0c5..000000000
--- a/builtin/providers/aws/import_aws_api_gateway_usage_plan_test.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSAPIGatewayUsagePlan_importBasic(t *testing.T) {
- resourceName := "aws_api_gateway_usage_plan.main"
- rName := acctest.RandString(10)
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSAPIGatewayUsagePlanDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSApiGatewayUsagePlanBasicConfig(rName),
- },
-
- {
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_autoscaling_group_test.go b/builtin/providers/aws/import_aws_autoscaling_group_test.go
deleted file mode 100644
index 666563b50..000000000
--- a/builtin/providers/aws/import_aws_autoscaling_group_test.go
+++ /dev/null
@@ -1,33 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSAutoScalingGroup_importBasic(t *testing.T) {
- resourceName := "aws_autoscaling_group.bar"
- randName := fmt.Sprintf("terraform-test-%s", acctest.RandString(10))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSAutoScalingGroupImport(randName),
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- ImportStateVerifyIgnore: []string{
- "force_delete", "metrics_granularity", "wait_for_capacity_timeout"},
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_cloudfront_distribution.go b/builtin/providers/aws/import_aws_cloudfront_distribution.go
deleted file mode 100644
index acfc836dc..000000000
--- a/builtin/providers/aws/import_aws_cloudfront_distribution.go
+++ /dev/null
@@ -1,32 +0,0 @@
-package aws
-
-import (
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/cloudfront"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func resourceAwsCloudFrontDistributionImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
- // This is a non API attribute
- // We are merely setting this to the same value as the Default setting in the schema
- d.Set("retain_on_delete", false)
-
- conn := meta.(*AWSClient).cloudfrontconn
- id := d.Id()
- resp, err := conn.GetDistributionConfig(&cloudfront.GetDistributionConfigInput{
- Id: aws.String(id),
- })
-
- if err != nil {
- return nil, err
- }
-
- distConfig := resp.DistributionConfig
- results := make([]*schema.ResourceData, 1)
- err = flattenDistributionConfig(d, distConfig)
- if err != nil {
- return nil, err
- }
- results[0] = d
- return results, nil
-}
diff --git a/builtin/providers/aws/import_aws_cloudfront_distribution_test.go b/builtin/providers/aws/import_aws_cloudfront_distribution_test.go
deleted file mode 100644
index 787d913a5..000000000
--- a/builtin/providers/aws/import_aws_cloudfront_distribution_test.go
+++ /dev/null
@@ -1,32 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSCloudFrontDistribution_importBasic(t *testing.T) {
- ri := acctest.RandInt()
- testConfig := fmt.Sprintf(testAccAWSCloudFrontDistributionS3Config, ri, originBucket, logBucket, testAccAWSCloudFrontDistributionRetainConfig())
-
- resourceName := "aws_cloudfront_distribution.s3_distribution"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckCloudFrontDistributionDestroy,
- Steps: []resource.TestStep{
- {
- Config: testConfig,
- },
- {
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_cloudfront_origin_access_identity_test.go b/builtin/providers/aws/import_aws_cloudfront_origin_access_identity_test.go
deleted file mode 100644
index dd45cc786..000000000
--- a/builtin/providers/aws/import_aws_cloudfront_origin_access_identity_test.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSCloudFrontOriginAccessIdentity_importBasic(t *testing.T) {
- resourceName := "aws_cloudfront_origin_access_identity.origin_access_identity"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckCloudFrontOriginAccessIdentityDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSCloudFrontOriginAccessIdentityConfig,
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_cloudtrail_test.go b/builtin/providers/aws/import_aws_cloudtrail_test.go
deleted file mode 100644
index b5b3aba3b..000000000
--- a/builtin/providers/aws/import_aws_cloudtrail_test.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSCloudTrail_importBasic(t *testing.T) {
- resourceName := "aws_cloudtrail.foobar"
- cloudTrailRandInt := acctest.RandInt()
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSCloudTrailDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSCloudTrailConfig(cloudTrailRandInt),
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- ImportStateVerifyIgnore: []string{"enable_log_file_validation", "is_multi_region_trail", "include_global_service_events", "enable_logging"},
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_cloudwatch_event_rule_test.go b/builtin/providers/aws/import_aws_cloudwatch_event_rule_test.go
deleted file mode 100644
index ac200dddf..000000000
--- a/builtin/providers/aws/import_aws_cloudwatch_event_rule_test.go
+++ /dev/null
@@ -1,29 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSCloudWatchEventRule_importBasic(t *testing.T) {
- resourceName := "aws_cloudwatch_event_rule.foo"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSCloudWatchEventRuleDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSCloudWatchEventRuleConfig,
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- ImportStateVerifyIgnore: []string{"is_enabled"}, //this has a default value
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_cloudwatch_log_destination_policy_test.go b/builtin/providers/aws/import_aws_cloudwatch_log_destination_policy_test.go
deleted file mode 100644
index f7c4a7f35..000000000
--- a/builtin/providers/aws/import_aws_cloudwatch_log_destination_policy_test.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSCloudwatchLogDestinationPolicy_importBasic(t *testing.T) {
- resourceName := "aws_cloudwatch_log_destination_policy.test"
-
- rstring := acctest.RandString(5)
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSCloudwatchLogDestinationPolicyDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSCloudwatchLogDestinationPolicyConfig(rstring),
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_cloudwatch_log_destination_test.go b/builtin/providers/aws/import_aws_cloudwatch_log_destination_test.go
deleted file mode 100644
index b0c1d2535..000000000
--- a/builtin/providers/aws/import_aws_cloudwatch_log_destination_test.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSCloudwatchLogDestination_importBasic(t *testing.T) {
- resourceName := "aws_cloudwatch_log_destination.test"
-
- rstring := acctest.RandString(5)
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSCloudwatchLogDestinationDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSCloudwatchLogDestinationConfig(rstring),
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_cloudwatch_log_group_test.go b/builtin/providers/aws/import_aws_cloudwatch_log_group_test.go
deleted file mode 100644
index b218ab286..000000000
--- a/builtin/providers/aws/import_aws_cloudwatch_log_group_test.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSCloudWatchLogGroup_importBasic(t *testing.T) {
- resourceName := "aws_cloudwatch_log_group.foobar"
- rInt := acctest.RandInt()
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSCloudWatchLogGroupDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSCloudWatchLogGroupConfig(rInt),
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- ImportStateVerifyIgnore: []string{"retention_in_days"}, //this has a default value
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_cloudwatch_metric_alarm_test.go b/builtin/providers/aws/import_aws_cloudwatch_metric_alarm_test.go
deleted file mode 100644
index 1cb30254c..000000000
--- a/builtin/providers/aws/import_aws_cloudwatch_metric_alarm_test.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSCloudWatchMetricAlarm_importBasic(t *testing.T) {
- rInt := acctest.RandInt()
- resourceName := "aws_cloudwatch_metric_alarm.foobar"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSCloudWatchMetricAlarmDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSCloudWatchMetricAlarmConfig(rInt),
- },
-
- {
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_codecommit_repository_test.go b/builtin/providers/aws/import_aws_codecommit_repository_test.go
deleted file mode 100644
index ea203c9c1..000000000
--- a/builtin/providers/aws/import_aws_codecommit_repository_test.go
+++ /dev/null
@@ -1,29 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSCodeCommitRepository_importBasic(t *testing.T) {
- resName := "aws_codecommit_repository.test"
- rInt := acctest.RandInt()
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckCodeCommitRepositoryDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccCodeCommitRepository_basic(rInt),
- },
- {
- ResourceName: resName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_codepipeline_test.go b/builtin/providers/aws/import_aws_codepipeline_test.go
deleted file mode 100644
index 5025fcddc..000000000
--- a/builtin/providers/aws/import_aws_codepipeline_test.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package aws
-
-import (
- "os"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSCodePipeline_Import_basic(t *testing.T) {
- if os.Getenv("GITHUB_TOKEN") == "" {
- t.Skip("Environment variable GITHUB_TOKEN is not set")
- }
-
- name := acctest.RandString(10)
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSCodePipelineDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSCodePipelineConfig_basic(name),
- },
-
- resource.TestStep{
- ResourceName: "aws_codepipeline.bar",
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_cognito_identity_pool_test.go b/builtin/providers/aws/import_aws_cognito_identity_pool_test.go
deleted file mode 100644
index bdd2caec8..000000000
--- a/builtin/providers/aws/import_aws_cognito_identity_pool_test.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSCognitoIdentityPool_importBasic(t *testing.T) {
- resourceName := "aws_cognito_identity_pool.main"
- rName := acctest.RandString(10)
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSAPIGatewayAccountDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSCognitoIdentityPoolConfig_basic(rName),
- },
-
- {
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_customer_gateway_test.go b/builtin/providers/aws/import_aws_customer_gateway_test.go
deleted file mode 100644
index 96e791ce8..000000000
--- a/builtin/providers/aws/import_aws_customer_gateway_test.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSCustomerGateway_importBasic(t *testing.T) {
- resourceName := "aws_customer_gateway.foo"
- rInt := acctest.RandInt()
- rBgpAsn := acctest.RandIntRange(64512, 65534)
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckCustomerGatewayDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccCustomerGatewayConfig(rInt, rBgpAsn),
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_db_event_subscription.go b/builtin/providers/aws/import_aws_db_event_subscription.go
deleted file mode 100644
index 82e5317ea..000000000
--- a/builtin/providers/aws/import_aws_db_event_subscription.go
+++ /dev/null
@@ -1,17 +0,0 @@
-package aws
-
-import "github.com/hashicorp/terraform/helper/schema"
-
-func resourceAwsDbEventSubscriptionImport(
- d *schema.ResourceData,
- meta interface{}) ([]*schema.ResourceData, error) {
-
- // The db event subscription Read function only needs the "name" of the event subscription
- // in order to populate the necessary values. This takes the "id" from the supplied StateFunc
- // and sets it as the "name" attribute, as described in the import documentation. This allows
- // the Read function to actually succeed and set the ID of the resource
- results := make([]*schema.ResourceData, 1, 1)
- d.Set("name", d.Id())
- results[0] = d
- return results, nil
-}
diff --git a/builtin/providers/aws/import_aws_db_event_subscription_test.go b/builtin/providers/aws/import_aws_db_event_subscription_test.go
deleted file mode 100644
index 2aa85073f..000000000
--- a/builtin/providers/aws/import_aws_db_event_subscription_test.go
+++ /dev/null
@@ -1,33 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSDBEventSubscription_importBasic(t *testing.T) {
- resourceName := "aws_db_event_subscription.bar"
- rInt := acctest.RandInt()
- subscriptionName := fmt.Sprintf("tf-acc-test-rds-event-subs-%d", rInt)
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSDBEventSubscriptionDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSDBEventSubscriptionConfig(rInt),
- },
-
- {
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- ImportStateId: subscriptionName,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_db_instance_test.go b/builtin/providers/aws/import_aws_db_instance_test.go
deleted file mode 100644
index 5fea3c2e0..000000000
--- a/builtin/providers/aws/import_aws_db_instance_test.go
+++ /dev/null
@@ -1,33 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSDBInstance_importBasic(t *testing.T) {
- resourceName := "aws_db_instance.bar"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSDBInstanceDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSDBInstanceConfig,
- },
-
- {
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- ImportStateVerifyIgnore: []string{
- "password",
- "skip_final_snapshot",
- "final_snapshot_identifier",
- },
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_db_option_group_test.go b/builtin/providers/aws/import_aws_db_option_group_test.go
deleted file mode 100644
index 3025ff9e8..000000000
--- a/builtin/providers/aws/import_aws_db_option_group_test.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSDBOptionGroup_importBasic(t *testing.T) {
- resourceName := "aws_db_option_group.bar"
- rName := fmt.Sprintf("option-group-test-terraform-%s", acctest.RandString(5))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSDBOptionGroupDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSDBOptionGroupBasicConfig(rName),
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_db_parameter_group_group_test.go b/builtin/providers/aws/import_aws_db_parameter_group_group_test.go
deleted file mode 100644
index d9806e5cf..000000000
--- a/builtin/providers/aws/import_aws_db_parameter_group_group_test.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSDBParameterGroup_importBasic(t *testing.T) {
- resourceName := "aws_db_parameter_group.bar"
- groupName := fmt.Sprintf("parameter-group-test-terraform-%d", acctest.RandInt())
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSDBParameterGroupDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSDBParameterGroupConfig(groupName),
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_db_security_group_test.go b/builtin/providers/aws/import_aws_db_security_group_test.go
deleted file mode 100644
index 57447c5a5..000000000
--- a/builtin/providers/aws/import_aws_db_security_group_test.go
+++ /dev/null
@@ -1,33 +0,0 @@
-package aws
-
-import (
- "os"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSDBSecurityGroup_importBasic(t *testing.T) {
- oldvar := os.Getenv("AWS_DEFAULT_REGION")
- os.Setenv("AWS_DEFAULT_REGION", "us-east-1")
- defer os.Setenv("AWS_DEFAULT_REGION", oldvar)
-
- resourceName := "aws_db_security_group.bar"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSDBSecurityGroupDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSDBSecurityGroupConfig,
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_db_subnet_group_test.go b/builtin/providers/aws/import_aws_db_subnet_group_test.go
deleted file mode 100644
index e9ab51b82..000000000
--- a/builtin/providers/aws/import_aws_db_subnet_group_test.go
+++ /dev/null
@@ -1,33 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSDBSubnetGroup_importBasic(t *testing.T) {
- resourceName := "aws_db_subnet_group.foo"
-
- rName := fmt.Sprintf("tf-test-%d", acctest.RandInt())
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckDBSubnetGroupDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDBSubnetGroupConfig(rName),
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- ImportStateVerifyIgnore: []string{
- "description"},
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_dynamodb_table_test.go b/builtin/providers/aws/import_aws_dynamodb_table_test.go
deleted file mode 100644
index 00fa2169d..000000000
--- a/builtin/providers/aws/import_aws_dynamodb_table_test.go
+++ /dev/null
@@ -1,51 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSDynamoDbTable_importBasic(t *testing.T) {
- resourceName := "aws_dynamodb_table.basic-dynamodb-table"
-
- rName := acctest.RandomWithPrefix("TerraformTestTable-")
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSDynamoDbTableDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSDynamoDbConfigInitialState(rName),
- },
-
- {
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
-
-func TestAccAWSDynamoDbTable_importTags(t *testing.T) {
- resourceName := "aws_dynamodb_table.basic-dynamodb-table"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSDynamoDbTableDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSDynamoDbConfigTags(),
- },
-
- {
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_ebs_volume_test.go b/builtin/providers/aws/import_aws_ebs_volume_test.go
deleted file mode 100644
index fd15bc241..000000000
--- a/builtin/providers/aws/import_aws_ebs_volume_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSEBSVolume_importBasic(t *testing.T) {
- resourceName := "aws_ebs_volume.test"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAwsEbsVolumeConfig,
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_ecr_repository_test.go b/builtin/providers/aws/import_aws_ecr_repository_test.go
deleted file mode 100644
index cd7b14439..000000000
--- a/builtin/providers/aws/import_aws_ecr_repository_test.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSEcrRepository_importBasic(t *testing.T) {
- resourceName := "aws_ecr_repository.default"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSEcrRepositoryDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSEcrRepository,
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_efs_file_system_test.go b/builtin/providers/aws/import_aws_efs_file_system_test.go
deleted file mode 100644
index 885ee9ddd..000000000
--- a/builtin/providers/aws/import_aws_efs_file_system_test.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSEFSFileSystem_importBasic(t *testing.T) {
- resourceName := "aws_efs_file_system.foo-with-tags"
- rInt := acctest.RandInt()
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckEfsFileSystemDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSEFSFileSystemConfigWithTags(rInt),
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- ImportStateVerifyIgnore: []string{"reference_name", "creation_token"},
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_efs_mount_target_test.go b/builtin/providers/aws/import_aws_efs_mount_target_test.go
deleted file mode 100644
index 607938e43..000000000
--- a/builtin/providers/aws/import_aws_efs_mount_target_test.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSEFSMountTarget_importBasic(t *testing.T) {
- resourceName := "aws_efs_mount_target.alpha"
-
- ct := fmt.Sprintf("createtoken-%d", acctest.RandInt())
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckEfsMountTargetDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSEFSMountTargetConfig(ct),
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_elastic_beanstalk_application_test.go b/builtin/providers/aws/import_aws_elastic_beanstalk_application_test.go
deleted file mode 100644
index 8d322abb4..000000000
--- a/builtin/providers/aws/import_aws_elastic_beanstalk_application_test.go
+++ /dev/null
@@ -1,38 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAWSElasticBeanstalkApplication_importBasic(t *testing.T) {
- resourceName := "aws_elastic_beanstalk_application.tftest"
- config := fmt.Sprintf("tf-test-name-%d", acctest.RandInt())
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckBeanstalkAppDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccBeanstalkAppImportConfig(config),
- },
-
- {
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
-
-func testAccBeanstalkAppImportConfig(name string) string {
- return fmt.Sprintf(`resource "aws_elastic_beanstalk_application" "tftest" {
- name = "%s"
- description = "tf-test-desc"
- }`, name)
-}
diff --git a/builtin/providers/aws/import_aws_elastic_beanstalk_environment_test.go b/builtin/providers/aws/import_aws_elastic_beanstalk_environment_test.go
deleted file mode 100644
index 559df2e3e..000000000
--- a/builtin/providers/aws/import_aws_elastic_beanstalk_environment_test.go
+++ /dev/null
@@ -1,46 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAWSElasticBeanstalkEnvironment_importBasic(t *testing.T) {
- resourceName := "aws_elastic_beanstalk_application.tftest"
-
- applicationName := fmt.Sprintf("tf-test-name-%d", acctest.RandInt())
- environmentName := fmt.Sprintf("tf-test-env-name-%d", acctest.RandInt())
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckBeanstalkAppDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccBeanstalkEnvImportConfig(applicationName, environmentName),
- },
-
- {
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
-
-func testAccBeanstalkEnvImportConfig(appName, envName string) string {
- return fmt.Sprintf(`resource "aws_elastic_beanstalk_application" "tftest" {
- name = "%s"
- description = "tf-test-desc"
- }
-
- resource "aws_elastic_beanstalk_environment" "tfenvtest" {
- name = "%s"
- application = "${aws_elastic_beanstalk_application.tftest.name}"
- solution_stack_name = "64bit Amazon Linux running Python"
- }`, appName, envName)
-}
diff --git a/builtin/providers/aws/import_aws_elasticache_cluster_test.go b/builtin/providers/aws/import_aws_elasticache_cluster_test.go
deleted file mode 100644
index 6128ddf95..000000000
--- a/builtin/providers/aws/import_aws_elasticache_cluster_test.go
+++ /dev/null
@@ -1,36 +0,0 @@
-package aws
-
-import (
- "os"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSElasticacheCluster_importBasic(t *testing.T) {
- oldvar := os.Getenv("AWS_DEFAULT_REGION")
- os.Setenv("AWS_DEFAULT_REGION", "us-east-1")
- defer os.Setenv("AWS_DEFAULT_REGION", oldvar)
-
- name := acctest.RandString(10)
-
- resourceName := "aws_elasticache_cluster.bar"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSElasticacheClusterDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSElasticacheClusterConfigBasic(name),
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_elasticache_parameter_group_test.go b/builtin/providers/aws/import_aws_elasticache_parameter_group_test.go
deleted file mode 100644
index 11c9334ed..000000000
--- a/builtin/providers/aws/import_aws_elasticache_parameter_group_test.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSElasticacheParameterGroup_importBasic(t *testing.T) {
- resourceName := "aws_elasticache_parameter_group.bar"
- rName := fmt.Sprintf("parameter-group-test-terraform-%d", acctest.RandInt())
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSElasticacheParameterGroupDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSElasticacheParameterGroupConfig(rName),
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_elasticache_replication_group_test.go b/builtin/providers/aws/import_aws_elasticache_replication_group_test.go
deleted file mode 100644
index 372eff849..000000000
--- a/builtin/providers/aws/import_aws_elasticache_replication_group_test.go
+++ /dev/null
@@ -1,37 +0,0 @@
-package aws
-
-import (
- "os"
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSElasticacheReplicationGroup_importBasic(t *testing.T) {
- oldvar := os.Getenv("AWS_DEFAULT_REGION")
- os.Setenv("AWS_DEFAULT_REGION", "us-east-1")
- defer os.Setenv("AWS_DEFAULT_REGION", oldvar)
-
- name := acctest.RandString(10)
-
- resourceName := "aws_elasticache_replication_group.bar"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSElasticacheReplicationDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSElasticacheReplicationGroupConfig(name),
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- ImportStateVerifyIgnore: []string{"apply_immediately"}, //not in the API
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_elasticache_subnet_group_test.go b/builtin/providers/aws/import_aws_elasticache_subnet_group_test.go
deleted file mode 100644
index 2ce156110..000000000
--- a/builtin/providers/aws/import_aws_elasticache_subnet_group_test.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "fmt"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSElasticacheSubnetGroup_importBasic(t *testing.T) {
- resourceName := "aws_elasticache_subnet_group.bar"
- config := fmt.Sprintf(testAccAWSElasticacheSubnetGroupConfig, acctest.RandInt())
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSElasticacheSubnetGroupDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: config,
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- ImportStateVerifyIgnore: []string{
- "description"},
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_elb_test.go b/builtin/providers/aws/import_aws_elb_test.go
deleted file mode 100644
index f4d90dcef..000000000
--- a/builtin/providers/aws/import_aws_elb_test.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSELB_importBasic(t *testing.T) {
- resourceName := "aws_elb.bar"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSELBDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSELBConfig,
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_emr_security_configuration_test.go b/builtin/providers/aws/import_aws_emr_security_configuration_test.go
deleted file mode 100644
index 72ddddf51..000000000
--- a/builtin/providers/aws/import_aws_emr_security_configuration_test.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSEmrSecurityConfiguration_importBasic(t *testing.T) {
- resourceName := "aws_emr_security_configuration.foo"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckEmrSecurityConfigurationDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccEmrSecurityConfigurationConfig,
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_flow_log_test.go b/builtin/providers/aws/import_aws_flow_log_test.go
deleted file mode 100644
index 97ccebb68..000000000
--- a/builtin/providers/aws/import_aws_flow_log_test.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSFlowLog_importBasic(t *testing.T) {
- resourceName := "aws_flow_log.test_flow_log"
-
- rInt := acctest.RandInt()
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckFlowLogDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccFlowLogConfig_basic(rInt),
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_glacier_vault_test.go b/builtin/providers/aws/import_aws_glacier_vault_test.go
deleted file mode 100644
index f7c20666e..000000000
--- a/builtin/providers/aws/import_aws_glacier_vault_test.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSGlacierVault_importBasic(t *testing.T) {
- resourceName := "aws_glacier_vault.full"
- rInt := acctest.RandInt()
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckGlacierVaultDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccGlacierVault_full(rInt),
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_iam_account_alias_test.go b/builtin/providers/aws/import_aws_iam_account_alias_test.go
deleted file mode 100644
index 28829a419..000000000
--- a/builtin/providers/aws/import_aws_iam_account_alias_test.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func testAccAWSIAMAccountAlias_importBasic(t *testing.T) {
- resourceName := "aws_iam_account_alias.test"
-
- rstring := acctest.RandString(5)
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSIAMAccountAliasDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSIAMAccountAliasConfig(rstring),
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_iam_account_password_policy_test.go b/builtin/providers/aws/import_aws_iam_account_password_policy_test.go
deleted file mode 100644
index b5fec9eca..000000000
--- a/builtin/providers/aws/import_aws_iam_account_password_policy_test.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSIAMAccountPasswordPolicy_importBasic(t *testing.T) {
- resourceName := "aws_iam_account_password_policy.default"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSIAMAccountPasswordPolicyDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSIAMAccountPasswordPolicy,
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_iam_group_test.go b/builtin/providers/aws/import_aws_iam_group_test.go
deleted file mode 100644
index 7e94f116f..000000000
--- a/builtin/providers/aws/import_aws_iam_group_test.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSIAMGroup_importBasic(t *testing.T) {
- rInt := acctest.RandInt()
- resourceName := "aws_iam_group.group"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSGroupDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSGroupConfig(rInt),
- },
-
- {
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_iam_policy_test.go b/builtin/providers/aws/import_aws_iam_policy_test.go
deleted file mode 100644
index d40145b58..000000000
--- a/builtin/providers/aws/import_aws_iam_policy_test.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "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/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func testAccAwsIamPolicyConfig(suffix string) string {
- return fmt.Sprintf(`
-resource "aws_iam_policy" "test_%[1]s" {
- name = "test_policy_%[1]s"
- path = "/"
- description = "My test policy"
- policy = < 0 {
- for _, pair := range perm.UserIdGroupPairs {
- p := &ec2.IpPermission{
- FromPort: perm.FromPort,
- IpProtocol: perm.IpProtocol,
- PrefixListIds: perm.PrefixListIds,
- ToPort: perm.ToPort,
- UserIdGroupPairs: []*ec2.UserIdGroupPair{pair},
- }
-
- r, err := resourceAwsSecurityGroupImportStatePermPair(sg, ruleType, p)
- if err != nil {
- return nil, err
- }
- result = append(result, r)
- }
- }
-
- if len(result) == 0 && len(perm.PrefixListIds) > 0 {
- p := &ec2.IpPermission{
- FromPort: perm.FromPort,
- IpProtocol: perm.IpProtocol,
- PrefixListIds: perm.PrefixListIds,
- ToPort: perm.ToPort,
- }
-
- r, err := resourceAwsSecurityGroupImportStatePermPair(sg, ruleType, p)
- if err != nil {
- return nil, err
- }
- result = append(result, r)
- }
-
- return result, nil
-}
-
-func resourceAwsSecurityGroupImportStatePermPair(sg *ec2.SecurityGroup, ruleType string, perm *ec2.IpPermission) (*schema.ResourceData, error) {
- // Construct the rule. We do this by populating the absolute
- // minimum necessary for Refresh on the rule to work. This
- // happens to be a lot of fields since they're almost all needed
- // for de-dupping.
- sgId := sg.GroupId
- id := ipPermissionIDHash(*sgId, ruleType, perm)
- ruleResource := resourceAwsSecurityGroupRule()
- d := ruleResource.Data(nil)
- d.SetId(id)
- d.SetType("aws_security_group_rule")
- d.Set("security_group_id", sgId)
- d.Set("type", ruleType)
-
- // 'self' is false by default. Below, we range over the group ids and set true
- // if the parent sg id is found
- d.Set("self", false)
-
- if len(perm.UserIdGroupPairs) > 0 {
- s := perm.UserIdGroupPairs[0]
-
- // Check for Pair that is the same as the Security Group, to denote self.
- // Otherwise, mark the group id in source_security_group_id
- isVPC := sg.VpcId != nil && *sg.VpcId != ""
- if isVPC {
- if *s.GroupId == *sg.GroupId {
- d.Set("self", true)
- // prune the self reference from the UserIdGroupPairs, so we don't
- // have duplicate sg ids (both self and in source_security_group_id)
- perm.UserIdGroupPairs = append(perm.UserIdGroupPairs[:0], perm.UserIdGroupPairs[0+1:]...)
- }
- } else {
- if *s.GroupName == *sg.GroupName {
- d.Set("self", true)
- // prune the self reference from the UserIdGroupPairs, so we don't
- // have duplicate sg ids (both self and in source_security_group_id)
- perm.UserIdGroupPairs = append(perm.UserIdGroupPairs[:0], perm.UserIdGroupPairs[0+1:]...)
- }
- }
- }
-
- if err := setFromIPPerm(d, sg, perm); err != nil {
- return nil, errwrap.Wrapf("Error importing AWS Security Group: {{err}}", err)
- }
-
- return d, nil
-}
diff --git a/builtin/providers/aws/import_aws_security_group_test.go b/builtin/providers/aws/import_aws_security_group_test.go
deleted file mode 100644
index a57313ae5..000000000
--- a/builtin/providers/aws/import_aws_security_group_test.go
+++ /dev/null
@@ -1,187 +0,0 @@
-package aws
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAWSSecurityGroup_importBasic(t *testing.T) {
- checkFn := func(s []*terraform.InstanceState) error {
- // Expect 3: group, 2 rules
- if len(s) != 3 {
- return fmt.Errorf("expected 3 states: %#v", s)
- }
-
- return nil
- }
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSSecurityGroupDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSSecurityGroupConfig,
- },
-
- {
- ResourceName: "aws_security_group.web",
- ImportState: true,
- ImportStateCheck: checkFn,
- },
- },
- })
-}
-
-func TestAccAWSSecurityGroup_importIpv6(t *testing.T) {
- checkFn := func(s []*terraform.InstanceState) error {
- // Expect 3: group, 2 rules
- if len(s) != 3 {
- return fmt.Errorf("expected 3 states: %#v", s)
- }
-
- return nil
- }
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSSecurityGroupDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSSecurityGroupConfigIpv6,
- },
-
- {
- ResourceName: "aws_security_group.web",
- ImportState: true,
- ImportStateCheck: checkFn,
- },
- },
- })
-}
-
-func TestAccAWSSecurityGroup_importSelf(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSSecurityGroupDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSSecurityGroupConfig_importSelf,
- },
-
- {
- ResourceName: "aws_security_group.allow_all",
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
-
-func TestAccAWSSecurityGroup_importSourceSecurityGroup(t *testing.T) {
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSSecurityGroupDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSSecurityGroupConfig_importSourceSecurityGroup,
- },
-
- {
- ResourceName: "aws_security_group.test_group_1",
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
-
-func TestAccAWSSecurityGroup_importIPRangeAndSecurityGroupWithSameRules(t *testing.T) {
- checkFn := func(s []*terraform.InstanceState) error {
- // Expect 4: group, 3 rules
- if len(s) != 4 {
- return fmt.Errorf("expected 4 states: %#v", s)
- }
-
- return nil
- }
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSSecurityGroupDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSSecurityGroupConfig_importIPRangeAndSecurityGroupWithSameRules,
- },
-
- {
- ResourceName: "aws_security_group.test_group_1",
- ImportState: true,
- ImportStateCheck: checkFn,
- },
- },
- })
-}
-
-func TestAccAWSSecurityGroup_importIPRangesWithSameRules(t *testing.T) {
- checkFn := func(s []*terraform.InstanceState) error {
- // Expect 4: group, 2 rules
- if len(s) != 3 {
- return fmt.Errorf("expected 3 states: %#v", s)
- }
-
- return nil
- }
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSSecurityGroupDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSSecurityGroupConfig_importIPRangesWithSameRules,
- },
-
- {
- ResourceName: "aws_security_group.test_group_1",
- ImportState: true,
- ImportStateCheck: checkFn,
- },
- },
- })
-}
-
-func TestAccAWSSecurityGroup_importPrefixList(t *testing.T) {
- checkFn := func(s []*terraform.InstanceState) error {
- // Expect 2: group, 1 rule
- if len(s) != 2 {
- return fmt.Errorf("expected 2 states: %#v", s)
- }
-
- return nil
- }
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSSecurityGroupDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSSecurityGroupConfigPrefixListEgress,
- },
-
- {
- ResourceName: "aws_security_group.egress",
- ImportState: true,
- ImportStateCheck: checkFn,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_ses_receipt_filter_test.go b/builtin/providers/aws/import_aws_ses_receipt_filter_test.go
deleted file mode 100644
index ecc962b85..000000000
--- a/builtin/providers/aws/import_aws_ses_receipt_filter_test.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSSESReceiptFilter_importBasic(t *testing.T) {
- resourceName := "aws_ses_receipt_filter.test"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckSESReceiptFilterDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSSESReceiptFilterConfig,
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_ses_receipt_rule_set_test.go b/builtin/providers/aws/import_aws_ses_receipt_rule_set_test.go
deleted file mode 100644
index c5294bcb4..000000000
--- a/builtin/providers/aws/import_aws_ses_receipt_rule_set_test.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSSESReceiptRuleSet_importBasic(t *testing.T) {
- resourceName := "aws_ses_receipt_rule_set.test"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckSESReceiptRuleSetDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSSESReceiptRuleSetConfig,
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_sfn_activity_test.go b/builtin/providers/aws/import_aws_sfn_activity_test.go
deleted file mode 100644
index 01a91143e..000000000
--- a/builtin/providers/aws/import_aws_sfn_activity_test.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSSfnActivity_importBasic(t *testing.T) {
- resourceName := "aws_sfn_activity.foo"
- rName := acctest.RandString(10)
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSSfnActivityDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSSfnActivityBasicConfig(rName),
- },
-
- {
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_simpledb_domain_test.go b/builtin/providers/aws/import_aws_simpledb_domain_test.go
deleted file mode 100644
index d79de8925..000000000
--- a/builtin/providers/aws/import_aws_simpledb_domain_test.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSSimpleDBDomain_importBasic(t *testing.T) {
- resourceName := "aws_simpledb_domain.test_domain"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSSimpleDBDomainDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSSimpleDBDomainConfig,
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_sns_topic_subscription_test.go b/builtin/providers/aws/import_aws_sns_topic_subscription_test.go
deleted file mode 100644
index 9a0b60bbc..000000000
--- a/builtin/providers/aws/import_aws_sns_topic_subscription_test.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSSNSTopicSubscription_importBasic(t *testing.T) {
- resourceName := "aws_sns_topic.test_topic"
- ri := acctest.RandInt()
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSSNSTopicSubscriptionDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSSNSTopicSubscriptionConfig(ri),
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_sns_topic_test.go b/builtin/providers/aws/import_aws_sns_topic_test.go
deleted file mode 100644
index 593610330..000000000
--- a/builtin/providers/aws/import_aws_sns_topic_test.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSSNSTopic_importBasic(t *testing.T) {
- resourceName := "aws_sns_topic.test_topic"
- rName := acctest.RandString(10)
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSSNSTopicDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSSNSTopicConfig(rName),
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_spot_datafeed_subscription_test.go b/builtin/providers/aws/import_aws_spot_datafeed_subscription_test.go
deleted file mode 100644
index 24c7acc59..000000000
--- a/builtin/providers/aws/import_aws_spot_datafeed_subscription_test.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func testAccAWSSpotDatafeedSubscription_importBasic(t *testing.T) {
- resourceName := "aws_spot_datafeed_subscription.default"
- ri := acctest.RandInt()
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSSpotDatafeedSubscriptionDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSSpotDatafeedSubscription(ri),
- },
-
- {
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_sqs_queue_test.go b/builtin/providers/aws/import_aws_sqs_queue_test.go
deleted file mode 100644
index 437b949e8..000000000
--- a/builtin/providers/aws/import_aws_sqs_queue_test.go
+++ /dev/null
@@ -1,58 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "fmt"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSSQSQueue_importBasic(t *testing.T) {
- resourceName := "aws_sqs_queue.queue"
- queueName := fmt.Sprintf("sqs-queue-%s", acctest.RandString(5))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSSQSQueueDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSSQSConfigWithDefaults(queueName),
- },
- {
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr("aws_sqs_queue.queue", "fifo_queue", "false"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSSQSQueue_importFifo(t *testing.T) {
- resourceName := "aws_sqs_queue.queue"
- queueName := fmt.Sprintf("sqs-queue-%s", acctest.RandString(5))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSSQSQueueDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSSQSFifoConfigWithDefaults(queueName),
- },
- {
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- Check: resource.ComposeTestCheckFunc(
- resource.TestCheckResourceAttr("aws_sqs_queue.queue", "fifo_queue", "true"),
- ),
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_subnet_test.go b/builtin/providers/aws/import_aws_subnet_test.go
deleted file mode 100644
index c08e4f7ed..000000000
--- a/builtin/providers/aws/import_aws_subnet_test.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSSubnet_importBasic(t *testing.T) {
- resourceName := "aws_subnet.foo"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckSubnetDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccSubnetConfig,
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_vpc_dhcp_options_test.go b/builtin/providers/aws/import_aws_vpc_dhcp_options_test.go
deleted file mode 100644
index e0f605f28..000000000
--- a/builtin/providers/aws/import_aws_vpc_dhcp_options_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSDHCPOptions_importBasic(t *testing.T) {
- resourceName := "aws_vpc_dhcp_options.foo"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccDHCPOptionsConfig,
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_vpc_endpoint_test.go b/builtin/providers/aws/import_aws_vpc_endpoint_test.go
deleted file mode 100644
index d44c35493..000000000
--- a/builtin/providers/aws/import_aws_vpc_endpoint_test.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSVpcEndpoint_importBasic(t *testing.T) {
- resourceName := "aws_vpc_endpoint.second-private-s3"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckVpcEndpointDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccVpcEndpointWithRouteTableAndPolicyConfig,
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_vpc_peering_connection_test.go b/builtin/providers/aws/import_aws_vpc_peering_connection_test.go
deleted file mode 100644
index c64f84a36..000000000
--- a/builtin/providers/aws/import_aws_vpc_peering_connection_test.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSVPCPeeringConnection_importBasic(t *testing.T) {
- resourceName := "aws_vpc_peering_connection.foo"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSVpcPeeringConnectionDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccVpcPeeringConfig,
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- ImportStateVerifyIgnore: []string{
- "auto_accept"},
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_vpc_test.go b/builtin/providers/aws/import_aws_vpc_test.go
deleted file mode 100644
index e940b3ddc..000000000
--- a/builtin/providers/aws/import_aws_vpc_test.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSVpc_importBasic(t *testing.T) {
- resourceName := "aws_vpc.foo"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckVpcDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccVpcConfig,
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_vpn_connection_test.go b/builtin/providers/aws/import_aws_vpn_connection_test.go
deleted file mode 100644
index a7297a220..000000000
--- a/builtin/providers/aws/import_aws_vpn_connection_test.go
+++ /dev/null
@@ -1,29 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSVpnConnection_importBasic(t *testing.T) {
- resourceName := "aws_vpn_connection.foo"
- rBgpAsn := acctest.RandIntRange(64512, 65534)
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccAwsVpnConnectionDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAwsVpnConnectionConfig(rBgpAsn),
- },
- {
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/import_aws_vpn_gateway_test.go b/builtin/providers/aws/import_aws_vpn_gateway_test.go
deleted file mode 100644
index e911ff1ab..000000000
--- a/builtin/providers/aws/import_aws_vpn_gateway_test.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package aws
-
-import (
- "testing"
-
- "github.com/hashicorp/terraform/helper/resource"
-)
-
-func TestAccAWSVpnGateway_importBasic(t *testing.T) {
- resourceName := "aws_vpn_gateway.foo"
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckVpnGatewayDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccVpnGatewayConfig,
- },
-
- resource.TestStep{
- ResourceName: resourceName,
- ImportState: true,
- ImportStateVerify: true,
- },
- },
- })
-}
diff --git a/builtin/providers/aws/network_acl_entry.go b/builtin/providers/aws/network_acl_entry.go
deleted file mode 100644
index c57f82222..000000000
--- a/builtin/providers/aws/network_acl_entry.go
+++ /dev/null
@@ -1,141 +0,0 @@
-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
-}
diff --git a/builtin/providers/aws/network_acl_entry_test.go b/builtin/providers/aws/network_acl_entry_test.go
deleted file mode 100644
index 46b288e4c..000000000
--- a/builtin/providers/aws/network_acl_entry_test.go
+++ /dev/null
@@ -1,174 +0,0 @@
-package aws
-
-import (
- "reflect"
- "testing"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/ec2"
-)
-
-func Test_expandNetworkACLEntry(t *testing.T) {
- input := []interface{}{
- map[string]interface{}{
- "protocol": "tcp",
- "from_port": 22,
- "to_port": 22,
- "cidr_block": "0.0.0.0/0",
- "action": "deny",
- "rule_no": 1,
- },
- map[string]interface{}{
- "protocol": "tcp",
- "from_port": 443,
- "to_port": 443,
- "cidr_block": "0.0.0.0/0",
- "action": "deny",
- "rule_no": 2,
- },
- map[string]interface{}{
- "protocol": "-1",
- "from_port": 443,
- "to_port": 443,
- "cidr_block": "0.0.0.0/0",
- "action": "deny",
- "rule_no": 2,
- },
- }
- expanded, _ := expandNetworkAclEntries(input, "egress")
-
- expected := []*ec2.NetworkAclEntry{
- &ec2.NetworkAclEntry{
- Protocol: aws.String("6"),
- PortRange: &ec2.PortRange{
- From: aws.Int64(22),
- To: aws.Int64(22),
- },
- RuleAction: aws.String("deny"),
- RuleNumber: aws.Int64(1),
- CidrBlock: aws.String("0.0.0.0/0"),
- Egress: aws.Bool(true),
- },
- &ec2.NetworkAclEntry{
- Protocol: aws.String("6"),
- PortRange: &ec2.PortRange{
- From: aws.Int64(443),
- To: aws.Int64(443),
- },
- RuleAction: aws.String("deny"),
- RuleNumber: aws.Int64(2),
- CidrBlock: aws.String("0.0.0.0/0"),
- Egress: aws.Bool(true),
- },
- &ec2.NetworkAclEntry{
- Protocol: aws.String("-1"),
- PortRange: &ec2.PortRange{
- From: aws.Int64(443),
- To: aws.Int64(443),
- },
- RuleAction: aws.String("deny"),
- RuleNumber: aws.Int64(2),
- CidrBlock: aws.String("0.0.0.0/0"),
- Egress: aws.Bool(true),
- },
- }
-
- if !reflect.DeepEqual(expanded, expected) {
- t.Fatalf(
- "Got:\n\n%#v\n\nExpected:\n\n%#v\n",
- expanded,
- expected)
- }
-
-}
-
-func Test_flattenNetworkACLEntry(t *testing.T) {
-
- apiInput := []*ec2.NetworkAclEntry{
- &ec2.NetworkAclEntry{
- Protocol: aws.String("tcp"),
- PortRange: &ec2.PortRange{
- From: aws.Int64(22),
- To: aws.Int64(22),
- },
- RuleAction: aws.String("deny"),
- RuleNumber: aws.Int64(1),
- CidrBlock: aws.String("0.0.0.0/0"),
- },
- &ec2.NetworkAclEntry{
- Protocol: aws.String("tcp"),
- PortRange: &ec2.PortRange{
- From: aws.Int64(443),
- To: aws.Int64(443),
- },
- RuleAction: aws.String("deny"),
- RuleNumber: aws.Int64(2),
- CidrBlock: aws.String("0.0.0.0/0"),
- },
- }
- flattened := flattenNetworkAclEntries(apiInput)
-
- expected := []map[string]interface{}{
- map[string]interface{}{
- "protocol": "tcp",
- "from_port": int64(22),
- "to_port": int64(22),
- "cidr_block": "0.0.0.0/0",
- "action": "deny",
- "rule_no": int64(1),
- },
- map[string]interface{}{
- "protocol": "tcp",
- "from_port": int64(443),
- "to_port": int64(443),
- "cidr_block": "0.0.0.0/0",
- "action": "deny",
- "rule_no": int64(2),
- },
- }
-
- if !reflect.DeepEqual(flattened, expected) {
- t.Fatalf(
- "Got:\n\n%#v\n\nExpected:\n\n%#v\n",
- flattened,
- expected)
- }
-
-}
-
-func Test_validatePorts(t *testing.T) {
- for _, ts := range []struct {
- to int64
- from int64
- expected *expectedPortPair
- wanted bool
- }{
- {0, 0, &expectedPortPair{0, 0}, true},
- {0, 1, &expectedPortPair{0, 0}, false},
- } {
- got := validatePorts(ts.to, ts.from, *ts.expected)
- if got != ts.wanted {
- t.Fatalf("Got: %t; Expected: %t\n", got, ts.wanted)
- }
- }
-}
-
-func Test_validateCIDRBlock(t *testing.T) {
- for _, ts := range []struct {
- cidr string
- shouldErr bool
- }{
- {"10.2.2.0/24", false},
- {"10.2.2.0/1234", true},
- {"10/24", true},
- {"10.2.2.2/24", true},
- } {
- err := validateCIDRBlock(ts.cidr)
- if ts.shouldErr && err == nil {
- t.Fatalf("Input '%s' should error but didn't!", ts.cidr)
- }
- if !ts.shouldErr && err != nil {
- t.Fatalf("Got unexpected error for '%s' input: %s", ts.cidr, err)
- }
- }
-}
diff --git a/builtin/providers/aws/opsworks_layers.go b/builtin/providers/aws/opsworks_layers.go
deleted file mode 100644
index c4bfeb6b2..000000000
--- a/builtin/providers/aws/opsworks_layers.go
+++ /dev/null
@@ -1,645 +0,0 @@
-package aws
-
-import (
- "fmt"
- "log"
- "strconv"
-
- "github.com/hashicorp/terraform/helper/hashcode"
- "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/opsworks"
-)
-
-// OpsWorks has a single concept of "layer" which represents several different
-// layer types. The differences between these are in some extra properties that
-// get packed into an "Attributes" map, but in the OpsWorks UI these are presented
-// as first-class options, and so Terraform prefers to expose them this way and
-// hide the implementation detail that they are all packed into a single type
-// in the underlying API.
-//
-// This file contains utilities that are shared between all of the concrete
-// layer resource types, which have names matching aws_opsworks_*_layer .
-
-type opsworksLayerTypeAttribute struct {
- AttrName string
- Type schema.ValueType
- Default interface{}
- Required bool
- WriteOnly bool
-}
-
-type opsworksLayerType struct {
- TypeName string
- DefaultLayerName string
- Attributes map[string]*opsworksLayerTypeAttribute
- CustomShortName bool
-}
-
-var (
- opsworksTrueString = "true"
- opsworksFalseString = "false"
-)
-
-func (lt *opsworksLayerType) SchemaResource() *schema.Resource {
- resourceSchema := map[string]*schema.Schema{
- "id": &schema.Schema{
- Type: schema.TypeString,
- Computed: true,
- },
-
- "auto_assign_elastic_ips": &schema.Schema{
- Type: schema.TypeBool,
- Optional: true,
- Default: false,
- },
-
- "auto_assign_public_ips": &schema.Schema{
- Type: schema.TypeBool,
- Optional: true,
- Default: false,
- },
-
- "custom_instance_profile_arn": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- },
-
- "elastic_load_balancer": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- },
-
- "custom_setup_recipes": &schema.Schema{
- Type: schema.TypeList,
- Optional: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
-
- "custom_configure_recipes": &schema.Schema{
- Type: schema.TypeList,
- Optional: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
-
- "custom_deploy_recipes": &schema.Schema{
- Type: schema.TypeList,
- Optional: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
-
- "custom_undeploy_recipes": &schema.Schema{
- Type: schema.TypeList,
- Optional: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
-
- "custom_shutdown_recipes": &schema.Schema{
- Type: schema.TypeList,
- Optional: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- },
-
- "custom_security_group_ids": &schema.Schema{
- Type: schema.TypeSet,
- Optional: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- Set: schema.HashString,
- },
-
- "custom_json": &schema.Schema{
- Type: schema.TypeString,
- StateFunc: normalizeJson,
- Optional: true,
- },
-
- "auto_healing": &schema.Schema{
- Type: schema.TypeBool,
- Optional: true,
- Default: true,
- },
-
- "install_updates_on_boot": &schema.Schema{
- Type: schema.TypeBool,
- Optional: true,
- Default: true,
- },
-
- "instance_shutdown_timeout": &schema.Schema{
- Type: schema.TypeInt,
- Optional: true,
- Default: 120,
- },
-
- "drain_elb_on_shutdown": &schema.Schema{
- Type: schema.TypeBool,
- Optional: true,
- Default: true,
- },
-
- "system_packages": &schema.Schema{
- Type: schema.TypeSet,
- Optional: true,
- Elem: &schema.Schema{Type: schema.TypeString},
- Set: schema.HashString,
- },
-
- "stack_id": &schema.Schema{
- Type: schema.TypeString,
- ForceNew: true,
- Required: true,
- },
-
- "use_ebs_optimized_instances": &schema.Schema{
- Type: schema.TypeBool,
- Optional: true,
- Default: false,
- },
-
- "ebs_volume": &schema.Schema{
- Type: schema.TypeSet,
- Optional: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
-
- "iops": &schema.Schema{
- Type: schema.TypeInt,
- Optional: true,
- Default: 0,
- },
-
- "mount_point": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- },
-
- "number_of_disks": &schema.Schema{
- Type: schema.TypeInt,
- Required: true,
- },
-
- "raid_level": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- },
-
- "size": &schema.Schema{
- Type: schema.TypeInt,
- Required: true,
- },
-
- "type": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Default: "standard",
- },
- },
- },
- Set: func(v interface{}) int {
- m := v.(map[string]interface{})
- return hashcode.String(m["mount_point"].(string))
- },
- },
- }
-
- if lt.CustomShortName {
- resourceSchema["short_name"] = &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- }
- }
-
- if lt.DefaultLayerName != "" {
- resourceSchema["name"] = &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Default: lt.DefaultLayerName,
- }
- } else {
- resourceSchema["name"] = &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- }
- }
-
- for key, def := range lt.Attributes {
- resourceSchema[key] = &schema.Schema{
- Type: def.Type,
- Default: def.Default,
- Required: def.Required,
- Optional: !def.Required,
- }
- }
-
- return &schema.Resource{
- Read: func(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AWSClient).opsworksconn
- return lt.Read(d, client)
- },
- Create: func(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AWSClient).opsworksconn
- return lt.Create(d, client)
- },
- Update: func(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AWSClient).opsworksconn
- return lt.Update(d, client)
- },
- Delete: func(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AWSClient).opsworksconn
- return lt.Delete(d, client)
- },
- Importer: &schema.ResourceImporter{
- State: schema.ImportStatePassthrough,
- },
-
- Schema: resourceSchema,
- }
-}
-
-func (lt *opsworksLayerType) Read(d *schema.ResourceData, client *opsworks.OpsWorks) error {
-
- req := &opsworks.DescribeLayersInput{
- LayerIds: []*string{
- aws.String(d.Id()),
- },
- }
-
- log.Printf("[DEBUG] Reading OpsWorks layer: %s", d.Id())
-
- resp, err := client.DescribeLayers(req)
- if err != nil {
- if awserr, ok := err.(awserr.Error); ok {
- if awserr.Code() == "ResourceNotFoundException" {
- d.SetId("")
- return nil
- }
- }
- return err
- }
-
- layer := resp.Layers[0]
- d.Set("id", layer.LayerId)
- d.Set("auto_assign_elastic_ips", layer.AutoAssignElasticIps)
- d.Set("auto_assign_public_ips", layer.AutoAssignPublicIps)
- d.Set("custom_instance_profile_arn", layer.CustomInstanceProfileArn)
- d.Set("custom_security_group_ids", flattenStringList(layer.CustomSecurityGroupIds))
- d.Set("auto_healing", layer.EnableAutoHealing)
- d.Set("install_updates_on_boot", layer.InstallUpdatesOnBoot)
- d.Set("name", layer.Name)
- d.Set("system_packages", flattenStringList(layer.Packages))
- d.Set("stack_id", layer.StackId)
- d.Set("use_ebs_optimized_instances", layer.UseEbsOptimizedInstances)
-
- if lt.CustomShortName {
- d.Set("short_name", layer.Shortname)
- }
-
- if v := layer.CustomJson; v == nil {
- if err := d.Set("custom_json", ""); err != nil {
- return err
- }
- } else if err := d.Set("custom_json", normalizeJson(*v)); err != nil {
- return err
- }
-
- lt.SetAttributeMap(d, layer.Attributes)
- lt.SetLifecycleEventConfiguration(d, layer.LifecycleEventConfiguration)
- lt.SetCustomRecipes(d, layer.CustomRecipes)
- lt.SetVolumeConfigurations(d, layer.VolumeConfigurations)
-
- /* get ELB */
- ebsRequest := &opsworks.DescribeElasticLoadBalancersInput{
- LayerIds: []*string{
- aws.String(d.Id()),
- },
- }
- loadBalancers, err := client.DescribeElasticLoadBalancers(ebsRequest)
- if err != nil {
- return err
- }
-
- if loadBalancers.ElasticLoadBalancers == nil || len(loadBalancers.ElasticLoadBalancers) == 0 {
- d.Set("elastic_load_balancer", "")
- } else {
- loadBalancer := loadBalancers.ElasticLoadBalancers[0]
- if loadBalancer != nil {
- d.Set("elastic_load_balancer", loadBalancer.ElasticLoadBalancerName)
- }
- }
-
- return nil
-}
-
-func (lt *opsworksLayerType) Create(d *schema.ResourceData, client *opsworks.OpsWorks) error {
-
- req := &opsworks.CreateLayerInput{
- AutoAssignElasticIps: aws.Bool(d.Get("auto_assign_elastic_ips").(bool)),
- AutoAssignPublicIps: aws.Bool(d.Get("auto_assign_public_ips").(bool)),
- CustomInstanceProfileArn: aws.String(d.Get("custom_instance_profile_arn").(string)),
- CustomRecipes: lt.CustomRecipes(d),
- CustomSecurityGroupIds: expandStringSet(d.Get("custom_security_group_ids").(*schema.Set)),
- EnableAutoHealing: aws.Bool(d.Get("auto_healing").(bool)),
- InstallUpdatesOnBoot: aws.Bool(d.Get("install_updates_on_boot").(bool)),
- LifecycleEventConfiguration: lt.LifecycleEventConfiguration(d),
- Name: aws.String(d.Get("name").(string)),
- Packages: expandStringSet(d.Get("system_packages").(*schema.Set)),
- Type: aws.String(lt.TypeName),
- StackId: aws.String(d.Get("stack_id").(string)),
- UseEbsOptimizedInstances: aws.Bool(d.Get("use_ebs_optimized_instances").(bool)),
- Attributes: lt.AttributeMap(d),
- VolumeConfigurations: lt.VolumeConfigurations(d),
- }
-
- if lt.CustomShortName {
- req.Shortname = aws.String(d.Get("short_name").(string))
- } else {
- req.Shortname = aws.String(lt.TypeName)
- }
-
- req.CustomJson = aws.String(d.Get("custom_json").(string))
-
- log.Printf("[DEBUG] Creating OpsWorks layer: %s", d.Id())
-
- resp, err := client.CreateLayer(req)
- if err != nil {
- return err
- }
-
- layerId := *resp.LayerId
- d.SetId(layerId)
- d.Set("id", layerId)
-
- loadBalancer := aws.String(d.Get("elastic_load_balancer").(string))
- if loadBalancer != nil && *loadBalancer != "" {
- log.Printf("[DEBUG] Attaching load balancer: %s", *loadBalancer)
- _, err := client.AttachElasticLoadBalancer(&opsworks.AttachElasticLoadBalancerInput{
- ElasticLoadBalancerName: loadBalancer,
- LayerId: &layerId,
- })
- if err != nil {
- return err
- }
- }
-
- return lt.Read(d, client)
-}
-
-func (lt *opsworksLayerType) Update(d *schema.ResourceData, client *opsworks.OpsWorks) error {
-
- req := &opsworks.UpdateLayerInput{
- LayerId: aws.String(d.Id()),
- AutoAssignElasticIps: aws.Bool(d.Get("auto_assign_elastic_ips").(bool)),
- AutoAssignPublicIps: aws.Bool(d.Get("auto_assign_public_ips").(bool)),
- CustomInstanceProfileArn: aws.String(d.Get("custom_instance_profile_arn").(string)),
- CustomRecipes: lt.CustomRecipes(d),
- CustomSecurityGroupIds: expandStringSet(d.Get("custom_security_group_ids").(*schema.Set)),
- EnableAutoHealing: aws.Bool(d.Get("auto_healing").(bool)),
- InstallUpdatesOnBoot: aws.Bool(d.Get("install_updates_on_boot").(bool)),
- LifecycleEventConfiguration: lt.LifecycleEventConfiguration(d),
- Name: aws.String(d.Get("name").(string)),
- Packages: expandStringSet(d.Get("system_packages").(*schema.Set)),
- UseEbsOptimizedInstances: aws.Bool(d.Get("use_ebs_optimized_instances").(bool)),
- Attributes: lt.AttributeMap(d),
- VolumeConfigurations: lt.VolumeConfigurations(d),
- }
-
- if lt.CustomShortName {
- req.Shortname = aws.String(d.Get("short_name").(string))
- } else {
- req.Shortname = aws.String(lt.TypeName)
- }
-
- req.CustomJson = aws.String(d.Get("custom_json").(string))
-
- log.Printf("[DEBUG] Updating OpsWorks layer: %s", d.Id())
-
- if d.HasChange("elastic_load_balancer") {
- lbo, lbn := d.GetChange("elastic_load_balancer")
-
- loadBalancerOld := aws.String(lbo.(string))
- loadBalancerNew := aws.String(lbn.(string))
-
- if loadBalancerOld != nil && *loadBalancerOld != "" {
- log.Printf("[DEBUG] Dettaching load balancer: %s", *loadBalancerOld)
- _, err := client.DetachElasticLoadBalancer(&opsworks.DetachElasticLoadBalancerInput{
- ElasticLoadBalancerName: loadBalancerOld,
- LayerId: aws.String(d.Id()),
- })
- if err != nil {
- return err
- }
- }
-
- if loadBalancerNew != nil && *loadBalancerNew != "" {
- log.Printf("[DEBUG] Attaching load balancer: %s", *loadBalancerNew)
- _, err := client.AttachElasticLoadBalancer(&opsworks.AttachElasticLoadBalancerInput{
- ElasticLoadBalancerName: loadBalancerNew,
- LayerId: aws.String(d.Id()),
- })
- if err != nil {
- return err
- }
- }
- }
-
- _, err := client.UpdateLayer(req)
- if err != nil {
- return err
- }
-
- return lt.Read(d, client)
-}
-
-func (lt *opsworksLayerType) Delete(d *schema.ResourceData, client *opsworks.OpsWorks) error {
- req := &opsworks.DeleteLayerInput{
- LayerId: aws.String(d.Id()),
- }
-
- log.Printf("[DEBUG] Deleting OpsWorks layer: %s", d.Id())
-
- _, err := client.DeleteLayer(req)
- return err
-}
-
-func (lt *opsworksLayerType) AttributeMap(d *schema.ResourceData) map[string]*string {
- attrs := map[string]*string{}
-
- for key, def := range lt.Attributes {
- value := d.Get(key)
- switch def.Type {
- case schema.TypeString:
- strValue := value.(string)
- attrs[def.AttrName] = &strValue
- case schema.TypeInt:
- intValue := value.(int)
- strValue := strconv.Itoa(intValue)
- attrs[def.AttrName] = &strValue
- case schema.TypeBool:
- boolValue := value.(bool)
- if boolValue {
- attrs[def.AttrName] = &opsworksTrueString
- } else {
- attrs[def.AttrName] = &opsworksFalseString
- }
- default:
- // should never happen
- panic(fmt.Errorf("Unsupported OpsWorks layer attribute type"))
- }
- }
-
- return attrs
-}
-
-func (lt *opsworksLayerType) SetAttributeMap(d *schema.ResourceData, attrs map[string]*string) {
- for key, def := range lt.Attributes {
- // Ignore write-only attributes; we'll just keep what we already have stored.
- // (The AWS API returns garbage placeholder values for these.)
- if def.WriteOnly {
- continue
- }
-
- if strPtr, ok := attrs[def.AttrName]; ok && strPtr != nil {
- strValue := *strPtr
-
- switch def.Type {
- case schema.TypeString:
- d.Set(key, strValue)
- case schema.TypeInt:
- intValue, err := strconv.Atoi(strValue)
- if err == nil {
- d.Set(key, intValue)
- } else {
- // Got garbage from the AWS API
- d.Set(key, nil)
- }
- case schema.TypeBool:
- boolValue := true
- if strValue == opsworksFalseString {
- boolValue = false
- }
- d.Set(key, boolValue)
- default:
- // should never happen
- panic(fmt.Errorf("Unsupported OpsWorks layer attribute type"))
- }
- return
-
- } else {
- d.Set(key, nil)
- }
- }
-}
-
-func (lt *opsworksLayerType) LifecycleEventConfiguration(d *schema.ResourceData) *opsworks.LifecycleEventConfiguration {
- return &opsworks.LifecycleEventConfiguration{
- Shutdown: &opsworks.ShutdownEventConfiguration{
- DelayUntilElbConnectionsDrained: aws.Bool(d.Get("drain_elb_on_shutdown").(bool)),
- ExecutionTimeout: aws.Int64(int64(d.Get("instance_shutdown_timeout").(int))),
- },
- }
-}
-
-func (lt *opsworksLayerType) SetLifecycleEventConfiguration(d *schema.ResourceData, v *opsworks.LifecycleEventConfiguration) {
- if v == nil || v.Shutdown == nil {
- d.Set("drain_elb_on_shutdown", nil)
- d.Set("instance_shutdown_timeout", nil)
- } else {
- d.Set("drain_elb_on_shutdown", v.Shutdown.DelayUntilElbConnectionsDrained)
- d.Set("instance_shutdown_timeout", v.Shutdown.ExecutionTimeout)
- }
-}
-
-func (lt *opsworksLayerType) CustomRecipes(d *schema.ResourceData) *opsworks.Recipes {
- return &opsworks.Recipes{
- Configure: expandStringList(d.Get("custom_configure_recipes").([]interface{})),
- Deploy: expandStringList(d.Get("custom_deploy_recipes").([]interface{})),
- Setup: expandStringList(d.Get("custom_setup_recipes").([]interface{})),
- Shutdown: expandStringList(d.Get("custom_shutdown_recipes").([]interface{})),
- Undeploy: expandStringList(d.Get("custom_undeploy_recipes").([]interface{})),
- }
-}
-
-func (lt *opsworksLayerType) SetCustomRecipes(d *schema.ResourceData, v *opsworks.Recipes) {
- // Null out everything first, and then we'll consider what to put back.
- d.Set("custom_configure_recipes", nil)
- d.Set("custom_deploy_recipes", nil)
- d.Set("custom_setup_recipes", nil)
- d.Set("custom_shutdown_recipes", nil)
- d.Set("custom_undeploy_recipes", nil)
-
- if v == nil {
- return
- }
-
- d.Set("custom_configure_recipes", flattenStringList(v.Configure))
- d.Set("custom_deploy_recipes", flattenStringList(v.Deploy))
- d.Set("custom_setup_recipes", flattenStringList(v.Setup))
- d.Set("custom_shutdown_recipes", flattenStringList(v.Shutdown))
- d.Set("custom_undeploy_recipes", flattenStringList(v.Undeploy))
-}
-
-func (lt *opsworksLayerType) VolumeConfigurations(d *schema.ResourceData) []*opsworks.VolumeConfiguration {
- configuredVolumes := d.Get("ebs_volume").(*schema.Set).List()
- result := make([]*opsworks.VolumeConfiguration, len(configuredVolumes))
-
- for i := 0; i < len(configuredVolumes); i++ {
- volumeData := configuredVolumes[i].(map[string]interface{})
-
- result[i] = &opsworks.VolumeConfiguration{
- MountPoint: aws.String(volumeData["mount_point"].(string)),
- NumberOfDisks: aws.Int64(int64(volumeData["number_of_disks"].(int))),
- Size: aws.Int64(int64(volumeData["size"].(int))),
- VolumeType: aws.String(volumeData["type"].(string)),
- }
- iops := int64(volumeData["iops"].(int))
- if iops != 0 {
- result[i].Iops = aws.Int64(iops)
- }
-
- raidLevelStr := volumeData["raid_level"].(string)
- if raidLevelStr != "" {
- raidLevel, err := strconv.Atoi(raidLevelStr)
- if err == nil {
- result[i].RaidLevel = aws.Int64(int64(raidLevel))
- }
- }
- }
-
- return result
-}
-
-func (lt *opsworksLayerType) SetVolumeConfigurations(d *schema.ResourceData, v []*opsworks.VolumeConfiguration) {
- newValue := make([]*map[string]interface{}, len(v))
-
- for i := 0; i < len(v); i++ {
- config := v[i]
- data := make(map[string]interface{})
- newValue[i] = &data
-
- if config.Iops != nil {
- data["iops"] = int(*config.Iops)
- } else {
- data["iops"] = 0
- }
- if config.MountPoint != nil {
- data["mount_point"] = *config.MountPoint
- }
- if config.NumberOfDisks != nil {
- data["number_of_disks"] = int(*config.NumberOfDisks)
- }
- if config.RaidLevel != nil {
- data["raid_level"] = strconv.Itoa(int(*config.RaidLevel))
- }
- if config.Size != nil {
- data["size"] = int(*config.Size)
- }
- if config.VolumeType != nil {
- data["type"] = *config.VolumeType
- }
- }
-
- d.Set("ebs_volume", newValue)
-}
diff --git a/builtin/providers/aws/provider.go b/builtin/providers/aws/provider.go
deleted file mode 100644
index d5880d730..000000000
--- a/builtin/providers/aws/provider.go
+++ /dev/null
@@ -1,815 +0,0 @@
-package aws
-
-import (
- "bytes"
- "fmt"
- "log"
-
- "github.com/hashicorp/terraform/helper/hashcode"
- "github.com/hashicorp/terraform/helper/mutexkv"
- "github.com/hashicorp/terraform/helper/schema"
- "github.com/hashicorp/terraform/terraform"
-)
-
-// Provider returns a terraform.ResourceProvider.
-func Provider() terraform.ResourceProvider {
- // TODO: Move the validation to this, requires conditional schemas
- // TODO: Move the configuration to this, requires validation
-
- // The actual provider
- return &schema.Provider{
- Schema: map[string]*schema.Schema{
- "access_key": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["access_key"],
- },
-
- "secret_key": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["secret_key"],
- },
-
- "profile": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["profile"],
- },
-
- "assume_role": assumeRoleSchema(),
-
- "shared_credentials_file": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["shared_credentials_file"],
- },
-
- "token": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["token"],
- },
-
- "region": {
- Type: schema.TypeString,
- Required: true,
- DefaultFunc: schema.MultiEnvDefaultFunc([]string{
- "AWS_REGION",
- "AWS_DEFAULT_REGION",
- }, nil),
- Description: descriptions["region"],
- InputDefault: "us-east-1",
- },
-
- "max_retries": {
- Type: schema.TypeInt,
- Optional: true,
- Default: 25,
- Description: descriptions["max_retries"],
- },
-
- "allowed_account_ids": {
- Type: schema.TypeSet,
- Elem: &schema.Schema{Type: schema.TypeString},
- Optional: true,
- ConflictsWith: []string{"forbidden_account_ids"},
- Set: schema.HashString,
- },
-
- "forbidden_account_ids": {
- Type: schema.TypeSet,
- Elem: &schema.Schema{Type: schema.TypeString},
- Optional: true,
- ConflictsWith: []string{"allowed_account_ids"},
- Set: schema.HashString,
- },
-
- "dynamodb_endpoint": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["dynamodb_endpoint"],
- Removed: "Use `dynamodb` inside `endpoints` block instead",
- },
-
- "kinesis_endpoint": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["kinesis_endpoint"],
- Removed: "Use `kinesis` inside `endpoints` block instead",
- },
-
- "endpoints": endpointsSchema(),
-
- "insecure": {
- Type: schema.TypeBool,
- Optional: true,
- Default: false,
- Description: descriptions["insecure"],
- },
-
- "skip_credentials_validation": {
- Type: schema.TypeBool,
- Optional: true,
- Default: false,
- Description: descriptions["skip_credentials_validation"],
- },
-
- "skip_get_ec2_platforms": {
- Type: schema.TypeBool,
- Optional: true,
- Default: false,
- Description: descriptions["skip_get_ec2_platforms"],
- },
-
- "skip_region_validation": {
- Type: schema.TypeBool,
- Optional: true,
- Default: false,
- Description: descriptions["skip_region_validation"],
- },
-
- "skip_requesting_account_id": {
- Type: schema.TypeBool,
- Optional: true,
- Default: false,
- Description: descriptions["skip_requesting_account_id"],
- },
-
- "skip_metadata_api_check": {
- Type: schema.TypeBool,
- Optional: true,
- Default: false,
- Description: descriptions["skip_metadata_api_check"],
- },
-
- "s3_force_path_style": {
- Type: schema.TypeBool,
- Optional: true,
- Default: false,
- Description: descriptions["s3_force_path_style"],
- },
- },
-
- DataSourcesMap: map[string]*schema.Resource{
- "aws_acm_certificate": dataSourceAwsAcmCertificate(),
- "aws_alb": dataSourceAwsAlb(),
- "aws_alb_listener": dataSourceAwsAlbListener(),
- "aws_ami": dataSourceAwsAmi(),
- "aws_ami_ids": dataSourceAwsAmiIds(),
- "aws_autoscaling_groups": dataSourceAwsAutoscalingGroups(),
- "aws_availability_zone": dataSourceAwsAvailabilityZone(),
- "aws_availability_zones": dataSourceAwsAvailabilityZones(),
- "aws_billing_service_account": dataSourceAwsBillingServiceAccount(),
- "aws_caller_identity": dataSourceAwsCallerIdentity(),
- "aws_canonical_user_id": dataSourceAwsCanonicalUserId(),
- "aws_cloudformation_stack": dataSourceAwsCloudFormationStack(),
- "aws_db_instance": dataSourceAwsDbInstance(),
- "aws_db_snapshot": dataSourceAwsDbSnapshot(),
- "aws_ebs_snapshot": dataSourceAwsEbsSnapshot(),
- "aws_ebs_snapshot_ids": dataSourceAwsEbsSnapshotIds(),
- "aws_ebs_volume": dataSourceAwsEbsVolume(),
- "aws_ecs_cluster": dataSourceAwsEcsCluster(),
- "aws_ecs_container_definition": dataSourceAwsEcsContainerDefinition(),
- "aws_ecs_task_definition": dataSourceAwsEcsTaskDefinition(),
- "aws_efs_file_system": dataSourceAwsEfsFileSystem(),
- "aws_eip": dataSourceAwsEip(),
- "aws_elastic_beanstalk_solution_stack": dataSourceAwsElasticBeanstalkSolutionStack(),
- "aws_elasticache_cluster": dataSourceAwsElastiCacheCluster(),
- "aws_elb_hosted_zone_id": dataSourceAwsElbHostedZoneId(),
- "aws_elb_service_account": dataSourceAwsElbServiceAccount(),
- "aws_iam_account_alias": dataSourceAwsIamAccountAlias(),
- "aws_iam_policy_document": dataSourceAwsIamPolicyDocument(),
- "aws_iam_role": dataSourceAwsIAMRole(),
- "aws_iam_server_certificate": dataSourceAwsIAMServerCertificate(),
- "aws_instance": dataSourceAwsInstance(),
- "aws_ip_ranges": dataSourceAwsIPRanges(),
- "aws_kinesis_stream": dataSourceAwsKinesisStream(),
- "aws_kms_alias": dataSourceAwsKmsAlias(),
- "aws_kms_ciphertext": dataSourceAwsKmsCiphetext(),
- "aws_kms_secret": dataSourceAwsKmsSecret(),
- "aws_partition": dataSourceAwsPartition(),
- "aws_prefix_list": dataSourceAwsPrefixList(),
- "aws_redshift_service_account": dataSourceAwsRedshiftServiceAccount(),
- "aws_region": dataSourceAwsRegion(),
- "aws_route_table": dataSourceAwsRouteTable(),
- "aws_route53_zone": dataSourceAwsRoute53Zone(),
- "aws_s3_bucket_object": dataSourceAwsS3BucketObject(),
- "aws_sns_topic": dataSourceAwsSnsTopic(),
- "aws_ssm_parameter": dataSourceAwsSsmParameter(),
- "aws_subnet": dataSourceAwsSubnet(),
- "aws_subnet_ids": dataSourceAwsSubnetIDs(),
- "aws_security_group": dataSourceAwsSecurityGroup(),
- "aws_vpc": dataSourceAwsVpc(),
- "aws_vpc_endpoint": dataSourceAwsVpcEndpoint(),
- "aws_vpc_endpoint_service": dataSourceAwsVpcEndpointService(),
- "aws_vpc_peering_connection": dataSourceAwsVpcPeeringConnection(),
- "aws_vpn_gateway": dataSourceAwsVpnGateway(),
- },
-
- ResourcesMap: map[string]*schema.Resource{
- "aws_alb": resourceAwsAlb(),
- "aws_alb_listener": resourceAwsAlbListener(),
- "aws_alb_listener_rule": resourceAwsAlbListenerRule(),
- "aws_alb_target_group": resourceAwsAlbTargetGroup(),
- "aws_alb_target_group_attachment": resourceAwsAlbTargetGroupAttachment(),
- "aws_ami": resourceAwsAmi(),
- "aws_ami_copy": resourceAwsAmiCopy(),
- "aws_ami_from_instance": resourceAwsAmiFromInstance(),
- "aws_ami_launch_permission": resourceAwsAmiLaunchPermission(),
- "aws_api_gateway_account": resourceAwsApiGatewayAccount(),
- "aws_api_gateway_api_key": resourceAwsApiGatewayApiKey(),
- "aws_api_gateway_authorizer": resourceAwsApiGatewayAuthorizer(),
- "aws_api_gateway_base_path_mapping": resourceAwsApiGatewayBasePathMapping(),
- "aws_api_gateway_client_certificate": resourceAwsApiGatewayClientCertificate(),
- "aws_api_gateway_deployment": resourceAwsApiGatewayDeployment(),
- "aws_api_gateway_domain_name": resourceAwsApiGatewayDomainName(),
- "aws_api_gateway_integration": resourceAwsApiGatewayIntegration(),
- "aws_api_gateway_integration_response": resourceAwsApiGatewayIntegrationResponse(),
- "aws_api_gateway_method": resourceAwsApiGatewayMethod(),
- "aws_api_gateway_method_response": resourceAwsApiGatewayMethodResponse(),
- "aws_api_gateway_method_settings": resourceAwsApiGatewayMethodSettings(),
- "aws_api_gateway_model": resourceAwsApiGatewayModel(),
- "aws_api_gateway_resource": resourceAwsApiGatewayResource(),
- "aws_api_gateway_rest_api": resourceAwsApiGatewayRestApi(),
- "aws_api_gateway_stage": resourceAwsApiGatewayStage(),
- "aws_api_gateway_usage_plan": resourceAwsApiGatewayUsagePlan(),
- "aws_api_gateway_usage_plan_key": resourceAwsApiGatewayUsagePlanKey(),
- "aws_app_cookie_stickiness_policy": resourceAwsAppCookieStickinessPolicy(),
- "aws_appautoscaling_target": resourceAwsAppautoscalingTarget(),
- "aws_appautoscaling_policy": resourceAwsAppautoscalingPolicy(),
- "aws_autoscaling_attachment": resourceAwsAutoscalingAttachment(),
- "aws_autoscaling_group": resourceAwsAutoscalingGroup(),
- "aws_autoscaling_notification": resourceAwsAutoscalingNotification(),
- "aws_autoscaling_policy": resourceAwsAutoscalingPolicy(),
- "aws_autoscaling_schedule": resourceAwsAutoscalingSchedule(),
- "aws_cloudformation_stack": resourceAwsCloudFormationStack(),
- "aws_cloudfront_distribution": resourceAwsCloudFrontDistribution(),
- "aws_cloudfront_origin_access_identity": resourceAwsCloudFrontOriginAccessIdentity(),
- "aws_cloudtrail": resourceAwsCloudTrail(),
- "aws_cloudwatch_event_rule": resourceAwsCloudWatchEventRule(),
- "aws_cloudwatch_event_target": resourceAwsCloudWatchEventTarget(),
- "aws_cloudwatch_log_destination": resourceAwsCloudWatchLogDestination(),
- "aws_cloudwatch_log_destination_policy": resourceAwsCloudWatchLogDestinationPolicy(),
- "aws_cloudwatch_log_group": resourceAwsCloudWatchLogGroup(),
- "aws_cloudwatch_log_metric_filter": resourceAwsCloudWatchLogMetricFilter(),
- "aws_cloudwatch_log_stream": resourceAwsCloudWatchLogStream(),
- "aws_cloudwatch_log_subscription_filter": resourceAwsCloudwatchLogSubscriptionFilter(),
- "aws_config_config_rule": resourceAwsConfigConfigRule(),
- "aws_config_configuration_recorder": resourceAwsConfigConfigurationRecorder(),
- "aws_config_configuration_recorder_status": resourceAwsConfigConfigurationRecorderStatus(),
- "aws_config_delivery_channel": resourceAwsConfigDeliveryChannel(),
- "aws_cognito_identity_pool": resourceAwsCognitoIdentityPool(),
- "aws_autoscaling_lifecycle_hook": resourceAwsAutoscalingLifecycleHook(),
- "aws_cloudwatch_metric_alarm": resourceAwsCloudWatchMetricAlarm(),
- "aws_codedeploy_app": resourceAwsCodeDeployApp(),
- "aws_codedeploy_deployment_config": resourceAwsCodeDeployDeploymentConfig(),
- "aws_codedeploy_deployment_group": resourceAwsCodeDeployDeploymentGroup(),
- "aws_codecommit_repository": resourceAwsCodeCommitRepository(),
- "aws_codecommit_trigger": resourceAwsCodeCommitTrigger(),
- "aws_codebuild_project": resourceAwsCodeBuildProject(),
- "aws_codepipeline": resourceAwsCodePipeline(),
- "aws_customer_gateway": resourceAwsCustomerGateway(),
- "aws_db_event_subscription": resourceAwsDbEventSubscription(),
- "aws_db_instance": resourceAwsDbInstance(),
- "aws_db_option_group": resourceAwsDbOptionGroup(),
- "aws_db_parameter_group": resourceAwsDbParameterGroup(),
- "aws_db_security_group": resourceAwsDbSecurityGroup(),
- "aws_db_snapshot": resourceAwsDbSnapshot(),
- "aws_db_subnet_group": resourceAwsDbSubnetGroup(),
- "aws_devicefarm_project": resourceAwsDevicefarmProject(),
- "aws_directory_service_directory": resourceAwsDirectoryServiceDirectory(),
- "aws_dms_certificate": resourceAwsDmsCertificate(),
- "aws_dms_endpoint": resourceAwsDmsEndpoint(),
- "aws_dms_replication_instance": resourceAwsDmsReplicationInstance(),
- "aws_dms_replication_subnet_group": resourceAwsDmsReplicationSubnetGroup(),
- "aws_dms_replication_task": resourceAwsDmsReplicationTask(),
- "aws_dynamodb_table": resourceAwsDynamoDbTable(),
- "aws_ebs_snapshot": resourceAwsEbsSnapshot(),
- "aws_ebs_volume": resourceAwsEbsVolume(),
- "aws_ecr_repository": resourceAwsEcrRepository(),
- "aws_ecr_repository_policy": resourceAwsEcrRepositoryPolicy(),
- "aws_ecs_cluster": resourceAwsEcsCluster(),
- "aws_ecs_service": resourceAwsEcsService(),
- "aws_ecs_task_definition": resourceAwsEcsTaskDefinition(),
- "aws_efs_file_system": resourceAwsEfsFileSystem(),
- "aws_efs_mount_target": resourceAwsEfsMountTarget(),
- "aws_egress_only_internet_gateway": resourceAwsEgressOnlyInternetGateway(),
- "aws_eip": resourceAwsEip(),
- "aws_eip_association": resourceAwsEipAssociation(),
- "aws_elasticache_cluster": resourceAwsElasticacheCluster(),
- "aws_elasticache_parameter_group": resourceAwsElasticacheParameterGroup(),
- "aws_elasticache_replication_group": resourceAwsElasticacheReplicationGroup(),
- "aws_elasticache_security_group": resourceAwsElasticacheSecurityGroup(),
- "aws_elasticache_subnet_group": resourceAwsElasticacheSubnetGroup(),
- "aws_elastic_beanstalk_application": resourceAwsElasticBeanstalkApplication(),
- "aws_elastic_beanstalk_application_version": resourceAwsElasticBeanstalkApplicationVersion(),
- "aws_elastic_beanstalk_configuration_template": resourceAwsElasticBeanstalkConfigurationTemplate(),
- "aws_elastic_beanstalk_environment": resourceAwsElasticBeanstalkEnvironment(),
- "aws_elasticsearch_domain": resourceAwsElasticSearchDomain(),
- "aws_elasticsearch_domain_policy": resourceAwsElasticSearchDomainPolicy(),
- "aws_elastictranscoder_pipeline": resourceAwsElasticTranscoderPipeline(),
- "aws_elastictranscoder_preset": resourceAwsElasticTranscoderPreset(),
- "aws_elb": resourceAwsElb(),
- "aws_elb_attachment": resourceAwsElbAttachment(),
- "aws_emr_cluster": resourceAwsEMRCluster(),
- "aws_emr_instance_group": resourceAwsEMRInstanceGroup(),
- "aws_emr_security_configuration": resourceAwsEMRSecurityConfiguration(),
- "aws_flow_log": resourceAwsFlowLog(),
- "aws_glacier_vault": resourceAwsGlacierVault(),
- "aws_iam_access_key": resourceAwsIamAccessKey(),
- "aws_iam_account_alias": resourceAwsIamAccountAlias(),
- "aws_iam_account_password_policy": resourceAwsIamAccountPasswordPolicy(),
- "aws_iam_group_policy": resourceAwsIamGroupPolicy(),
- "aws_iam_group": resourceAwsIamGroup(),
- "aws_iam_group_membership": resourceAwsIamGroupMembership(),
- "aws_iam_group_policy_attachment": resourceAwsIamGroupPolicyAttachment(),
- "aws_iam_instance_profile": resourceAwsIamInstanceProfile(),
- "aws_iam_openid_connect_provider": resourceAwsIamOpenIDConnectProvider(),
- "aws_iam_policy": resourceAwsIamPolicy(),
- "aws_iam_policy_attachment": resourceAwsIamPolicyAttachment(),
- "aws_iam_role_policy_attachment": resourceAwsIamRolePolicyAttachment(),
- "aws_iam_role_policy": resourceAwsIamRolePolicy(),
- "aws_iam_role": resourceAwsIamRole(),
- "aws_iam_saml_provider": resourceAwsIamSamlProvider(),
- "aws_iam_server_certificate": resourceAwsIAMServerCertificate(),
- "aws_iam_user_policy_attachment": resourceAwsIamUserPolicyAttachment(),
- "aws_iam_user_policy": resourceAwsIamUserPolicy(),
- "aws_iam_user_ssh_key": resourceAwsIamUserSshKey(),
- "aws_iam_user": resourceAwsIamUser(),
- "aws_iam_user_login_profile": resourceAwsIamUserLoginProfile(),
- "aws_inspector_assessment_target": resourceAWSInspectorAssessmentTarget(),
- "aws_inspector_assessment_template": resourceAWSInspectorAssessmentTemplate(),
- "aws_inspector_resource_group": resourceAWSInspectorResourceGroup(),
- "aws_instance": resourceAwsInstance(),
- "aws_internet_gateway": resourceAwsInternetGateway(),
- "aws_key_pair": resourceAwsKeyPair(),
- "aws_kinesis_firehose_delivery_stream": resourceAwsKinesisFirehoseDeliveryStream(),
- "aws_kinesis_stream": resourceAwsKinesisStream(),
- "aws_kms_alias": resourceAwsKmsAlias(),
- "aws_kms_key": resourceAwsKmsKey(),
- "aws_lambda_function": resourceAwsLambdaFunction(),
- "aws_lambda_event_source_mapping": resourceAwsLambdaEventSourceMapping(),
- "aws_lambda_alias": resourceAwsLambdaAlias(),
- "aws_lambda_permission": resourceAwsLambdaPermission(),
- "aws_launch_configuration": resourceAwsLaunchConfiguration(),
- "aws_lightsail_domain": resourceAwsLightsailDomain(),
- "aws_lightsail_instance": resourceAwsLightsailInstance(),
- "aws_lightsail_key_pair": resourceAwsLightsailKeyPair(),
- "aws_lightsail_static_ip": resourceAwsLightsailStaticIp(),
- "aws_lightsail_static_ip_attachment": resourceAwsLightsailStaticIpAttachment(),
- "aws_lb_cookie_stickiness_policy": resourceAwsLBCookieStickinessPolicy(),
- "aws_load_balancer_policy": resourceAwsLoadBalancerPolicy(),
- "aws_load_balancer_backend_server_policy": resourceAwsLoadBalancerBackendServerPolicies(),
- "aws_load_balancer_listener_policy": resourceAwsLoadBalancerListenerPolicies(),
- "aws_lb_ssl_negotiation_policy": resourceAwsLBSSLNegotiationPolicy(),
- "aws_main_route_table_association": resourceAwsMainRouteTableAssociation(),
- "aws_nat_gateway": resourceAwsNatGateway(),
- "aws_network_acl": resourceAwsNetworkAcl(),
- "aws_default_network_acl": resourceAwsDefaultNetworkAcl(),
- "aws_network_acl_rule": resourceAwsNetworkAclRule(),
- "aws_network_interface": resourceAwsNetworkInterface(),
- "aws_network_interface_attachment": resourceAwsNetworkInterfaceAttachment(),
- "aws_opsworks_application": resourceAwsOpsworksApplication(),
- "aws_opsworks_stack": resourceAwsOpsworksStack(),
- "aws_opsworks_java_app_layer": resourceAwsOpsworksJavaAppLayer(),
- "aws_opsworks_haproxy_layer": resourceAwsOpsworksHaproxyLayer(),
- "aws_opsworks_static_web_layer": resourceAwsOpsworksStaticWebLayer(),
- "aws_opsworks_php_app_layer": resourceAwsOpsworksPhpAppLayer(),
- "aws_opsworks_rails_app_layer": resourceAwsOpsworksRailsAppLayer(),
- "aws_opsworks_nodejs_app_layer": resourceAwsOpsworksNodejsAppLayer(),
- "aws_opsworks_memcached_layer": resourceAwsOpsworksMemcachedLayer(),
- "aws_opsworks_mysql_layer": resourceAwsOpsworksMysqlLayer(),
- "aws_opsworks_ganglia_layer": resourceAwsOpsworksGangliaLayer(),
- "aws_opsworks_custom_layer": resourceAwsOpsworksCustomLayer(),
- "aws_opsworks_instance": resourceAwsOpsworksInstance(),
- "aws_opsworks_user_profile": resourceAwsOpsworksUserProfile(),
- "aws_opsworks_permission": resourceAwsOpsworksPermission(),
- "aws_opsworks_rds_db_instance": resourceAwsOpsworksRdsDbInstance(),
- "aws_placement_group": resourceAwsPlacementGroup(),
- "aws_proxy_protocol_policy": resourceAwsProxyProtocolPolicy(),
- "aws_rds_cluster": resourceAwsRDSCluster(),
- "aws_rds_cluster_instance": resourceAwsRDSClusterInstance(),
- "aws_rds_cluster_parameter_group": resourceAwsRDSClusterParameterGroup(),
- "aws_redshift_cluster": resourceAwsRedshiftCluster(),
- "aws_redshift_security_group": resourceAwsRedshiftSecurityGroup(),
- "aws_redshift_parameter_group": resourceAwsRedshiftParameterGroup(),
- "aws_redshift_subnet_group": resourceAwsRedshiftSubnetGroup(),
- "aws_route53_delegation_set": resourceAwsRoute53DelegationSet(),
- "aws_route53_record": resourceAwsRoute53Record(),
- "aws_route53_zone_association": resourceAwsRoute53ZoneAssociation(),
- "aws_route53_zone": resourceAwsRoute53Zone(),
- "aws_route53_health_check": resourceAwsRoute53HealthCheck(),
- "aws_route": resourceAwsRoute(),
- "aws_route_table": resourceAwsRouteTable(),
- "aws_default_route_table": resourceAwsDefaultRouteTable(),
- "aws_route_table_association": resourceAwsRouteTableAssociation(),
- "aws_ses_active_receipt_rule_set": resourceAwsSesActiveReceiptRuleSet(),
- "aws_ses_domain_identity": resourceAwsSesDomainIdentity(),
- "aws_ses_receipt_filter": resourceAwsSesReceiptFilter(),
- "aws_ses_receipt_rule": resourceAwsSesReceiptRule(),
- "aws_ses_receipt_rule_set": resourceAwsSesReceiptRuleSet(),
- "aws_ses_configuration_set": resourceAwsSesConfigurationSet(),
- "aws_ses_event_destination": resourceAwsSesEventDestination(),
- "aws_s3_bucket": resourceAwsS3Bucket(),
- "aws_s3_bucket_policy": resourceAwsS3BucketPolicy(),
- "aws_s3_bucket_object": resourceAwsS3BucketObject(),
- "aws_s3_bucket_notification": resourceAwsS3BucketNotification(),
- "aws_security_group": resourceAwsSecurityGroup(),
- "aws_default_security_group": resourceAwsDefaultSecurityGroup(),
- "aws_security_group_rule": resourceAwsSecurityGroupRule(),
- "aws_simpledb_domain": resourceAwsSimpleDBDomain(),
- "aws_ssm_activation": resourceAwsSsmActivation(),
- "aws_ssm_association": resourceAwsSsmAssociation(),
- "aws_ssm_document": resourceAwsSsmDocument(),
- "aws_ssm_maintenance_window": resourceAwsSsmMaintenanceWindow(),
- "aws_ssm_maintenance_window_target": resourceAwsSsmMaintenanceWindowTarget(),
- "aws_ssm_maintenance_window_task": resourceAwsSsmMaintenanceWindowTask(),
- "aws_ssm_patch_baseline": resourceAwsSsmPatchBaseline(),
- "aws_ssm_patch_group": resourceAwsSsmPatchGroup(),
- "aws_ssm_parameter": resourceAwsSsmParameter(),
- "aws_spot_datafeed_subscription": resourceAwsSpotDataFeedSubscription(),
- "aws_spot_instance_request": resourceAwsSpotInstanceRequest(),
- "aws_spot_fleet_request": resourceAwsSpotFleetRequest(),
- "aws_sqs_queue": resourceAwsSqsQueue(),
- "aws_sqs_queue_policy": resourceAwsSqsQueuePolicy(),
- "aws_snapshot_create_volume_permission": resourceAwsSnapshotCreateVolumePermission(),
- "aws_sns_topic": resourceAwsSnsTopic(),
- "aws_sns_topic_policy": resourceAwsSnsTopicPolicy(),
- "aws_sns_topic_subscription": resourceAwsSnsTopicSubscription(),
- "aws_sfn_activity": resourceAwsSfnActivity(),
- "aws_sfn_state_machine": resourceAwsSfnStateMachine(),
- "aws_default_subnet": resourceAwsDefaultSubnet(),
- "aws_subnet": resourceAwsSubnet(),
- "aws_volume_attachment": resourceAwsVolumeAttachment(),
- "aws_vpc_dhcp_options_association": resourceAwsVpcDhcpOptionsAssociation(),
- "aws_default_vpc_dhcp_options": resourceAwsDefaultVpcDhcpOptions(),
- "aws_vpc_dhcp_options": resourceAwsVpcDhcpOptions(),
- "aws_vpc_peering_connection": resourceAwsVpcPeeringConnection(),
- "aws_vpc_peering_connection_accepter": resourceAwsVpcPeeringConnectionAccepter(),
- "aws_default_vpc": resourceAwsDefaultVpc(),
- "aws_vpc": resourceAwsVpc(),
- "aws_vpc_endpoint": resourceAwsVpcEndpoint(),
- "aws_vpc_endpoint_route_table_association": resourceAwsVpcEndpointRouteTableAssociation(),
- "aws_vpn_connection": resourceAwsVpnConnection(),
- "aws_vpn_connection_route": resourceAwsVpnConnectionRoute(),
- "aws_vpn_gateway": resourceAwsVpnGateway(),
- "aws_vpn_gateway_attachment": resourceAwsVpnGatewayAttachment(),
- "aws_vpn_gateway_route_propagation": resourceAwsVpnGatewayRoutePropagation(),
- "aws_waf_byte_match_set": resourceAwsWafByteMatchSet(),
- "aws_waf_ipset": resourceAwsWafIPSet(),
- "aws_waf_rule": resourceAwsWafRule(),
- "aws_waf_size_constraint_set": resourceAwsWafSizeConstraintSet(),
- "aws_waf_web_acl": resourceAwsWafWebAcl(),
- "aws_waf_xss_match_set": resourceAwsWafXssMatchSet(),
- "aws_waf_sql_injection_match_set": resourceAwsWafSqlInjectionMatchSet(),
- "aws_wafregional_byte_match_set": resourceAwsWafRegionalByteMatchSet(),
- "aws_wafregional_ipset": resourceAwsWafRegionalIPSet(),
- },
- ConfigureFunc: providerConfigure,
- }
-}
-
-var descriptions map[string]string
-
-func init() {
- descriptions = map[string]string{
- "region": "The region where AWS operations will take place. Examples\n" +
- "are us-east-1, us-west-2, etc.",
-
- "access_key": "The access key for API operations. You can retrieve this\n" +
- "from the 'Security & Credentials' section of the AWS console.",
-
- "secret_key": "The secret key for API operations. You can retrieve this\n" +
- "from the 'Security & Credentials' section of the AWS console.",
-
- "profile": "The profile for API operations. If not set, the default profile\n" +
- "created with `aws configure` will be used.",
-
- "shared_credentials_file": "The path to the shared credentials file. If not set\n" +
- "this defaults to ~/.aws/credentials.",
-
- "token": "session token. A session token is only required if you are\n" +
- "using temporary security credentials.",
-
- "max_retries": "The maximum number of times an AWS API request is\n" +
- "being executed. If the API request still fails, an error is\n" +
- "thrown.",
-
- "cloudformation_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n",
-
- "cloudwatch_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n",
-
- "cloudwatchevents_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n",
-
- "cloudwatchlogs_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n",
-
- "devicefarm_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n",
-
- "dynamodb_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n" +
- "It's typically used to connect to dynamodb-local.",
-
- "kinesis_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n" +
- "It's typically used to connect to kinesalite.",
-
- "kms_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n",
-
- "iam_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n",
-
- "ec2_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n",
-
- "elb_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n",
-
- "rds_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n",
-
- "s3_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n",
-
- "sns_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n",
-
- "sqs_endpoint": "Use this to override the default endpoint URL constructed from the `region`.\n",
-
- "insecure": "Explicitly allow the provider to perform \"insecure\" SSL requests. If omitted," +
- "default value is `false`",
-
- "skip_credentials_validation": "Skip the credentials validation via STS API. " +
- "Used for AWS API implementations that do not have STS available/implemented.",
-
- "skip_get_ec2_platforms": "Skip getting the supported EC2 platforms. " +
- "Used by users that don't have ec2:DescribeAccountAttributes permissions.",
-
- "skip_region_validation": "Skip static validation of region name. " +
- "Used by users of alternative AWS-like APIs or users w/ access to regions that are not public (yet).",
-
- "skip_requesting_account_id": "Skip requesting the account ID. " +
- "Used for AWS API implementations that do not have IAM/STS API and/or metadata API.",
-
- "skip_medatadata_api_check": "Skip the AWS Metadata API check. " +
- "Used for AWS API implementations that do not have a metadata api endpoint.",
-
- "s3_force_path_style": "Set this to true to force the request to use path-style addressing,\n" +
- "i.e., http://s3.amazonaws.com/BUCKET/KEY. By default, the S3 client will\n" +
- "use virtual hosted bucket addressing when possible\n" +
- "(http://BUCKET.s3.amazonaws.com/KEY). Specific to the Amazon S3 service.",
-
- "assume_role_role_arn": "The ARN of an IAM role to assume prior to making API calls.",
-
- "assume_role_session_name": "The session name to use when assuming the role. If omitted," +
- " no session name is passed to the AssumeRole call.",
-
- "assume_role_external_id": "The external ID to use when assuming the role. If omitted," +
- " no external ID is passed to the AssumeRole call.",
-
- "assume_role_policy": "The permissions applied when assuming a role. You cannot use," +
- " this policy to grant further permissions that are in excess to those of the, " +
- " role that is being assumed.",
- }
-}
-
-func providerConfigure(d *schema.ResourceData) (interface{}, error) {
- config := Config{
- AccessKey: d.Get("access_key").(string),
- SecretKey: d.Get("secret_key").(string),
- Profile: d.Get("profile").(string),
- CredsFilename: d.Get("shared_credentials_file").(string),
- Token: d.Get("token").(string),
- Region: d.Get("region").(string),
- MaxRetries: d.Get("max_retries").(int),
- Insecure: d.Get("insecure").(bool),
- SkipCredsValidation: d.Get("skip_credentials_validation").(bool),
- SkipGetEC2Platforms: d.Get("skip_get_ec2_platforms").(bool),
- SkipRegionValidation: d.Get("skip_region_validation").(bool),
- SkipRequestingAccountId: d.Get("skip_requesting_account_id").(bool),
- SkipMetadataApiCheck: d.Get("skip_metadata_api_check").(bool),
- S3ForcePathStyle: d.Get("s3_force_path_style").(bool),
- }
-
- assumeRoleList := d.Get("assume_role").(*schema.Set).List()
- if len(assumeRoleList) == 1 {
- assumeRole := assumeRoleList[0].(map[string]interface{})
- config.AssumeRoleARN = assumeRole["role_arn"].(string)
- config.AssumeRoleSessionName = assumeRole["session_name"].(string)
- config.AssumeRoleExternalID = assumeRole["external_id"].(string)
-
- if v := assumeRole["policy"].(string); v != "" {
- config.AssumeRolePolicy = v
- }
-
- log.Printf("[INFO] assume_role configuration set: (ARN: %q, SessionID: %q, ExternalID: %q, Policy: %q)",
- config.AssumeRoleARN, config.AssumeRoleSessionName, config.AssumeRoleExternalID, config.AssumeRolePolicy)
- } else {
- log.Printf("[INFO] No assume_role block read from configuration")
- }
-
- endpointsSet := d.Get("endpoints").(*schema.Set)
-
- for _, endpointsSetI := range endpointsSet.List() {
- endpoints := endpointsSetI.(map[string]interface{})
- config.CloudFormationEndpoint = endpoints["cloudformation"].(string)
- config.CloudWatchEndpoint = endpoints["cloudwatch"].(string)
- config.CloudWatchEventsEndpoint = endpoints["cloudwatchevents"].(string)
- config.CloudWatchLogsEndpoint = endpoints["cloudwatchlogs"].(string)
- config.DeviceFarmEndpoint = endpoints["devicefarm"].(string)
- config.DynamoDBEndpoint = endpoints["dynamodb"].(string)
- config.Ec2Endpoint = endpoints["ec2"].(string)
- config.ElbEndpoint = endpoints["elb"].(string)
- config.IamEndpoint = endpoints["iam"].(string)
- config.KinesisEndpoint = endpoints["kinesis"].(string)
- config.KmsEndpoint = endpoints["kms"].(string)
- config.RdsEndpoint = endpoints["rds"].(string)
- config.S3Endpoint = endpoints["s3"].(string)
- config.SnsEndpoint = endpoints["sns"].(string)
- config.SqsEndpoint = endpoints["sqs"].(string)
- }
-
- if v, ok := d.GetOk("allowed_account_ids"); ok {
- config.AllowedAccountIds = v.(*schema.Set).List()
- }
-
- if v, ok := d.GetOk("forbidden_account_ids"); ok {
- config.ForbiddenAccountIds = v.(*schema.Set).List()
- }
-
- return config.Client()
-}
-
-// This is a global MutexKV for use within this plugin.
-var awsMutexKV = mutexkv.NewMutexKV()
-
-func assumeRoleSchema() *schema.Schema {
- return &schema.Schema{
- Type: schema.TypeSet,
- Optional: true,
- MaxItems: 1,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "role_arn": {
- Type: schema.TypeString,
- Optional: true,
- Description: descriptions["assume_role_role_arn"],
- },
-
- "session_name": {
- Type: schema.TypeString,
- Optional: true,
- Description: descriptions["assume_role_session_name"],
- },
-
- "external_id": {
- Type: schema.TypeString,
- Optional: true,
- Description: descriptions["assume_role_external_id"],
- },
-
- "policy": {
- Type: schema.TypeString,
- Optional: true,
- Description: descriptions["assume_role_policy"],
- },
- },
- },
- Set: assumeRoleToHash,
- }
-}
-
-func assumeRoleToHash(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%s-", m["role_arn"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["session_name"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["external_id"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["policy"].(string)))
- return hashcode.String(buf.String())
-}
-
-func endpointsSchema() *schema.Schema {
- return &schema.Schema{
- Type: schema.TypeSet,
- Optional: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "cloudwatch": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["cloudwatch_endpoint"],
- },
- "cloudwatchevents": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["cloudwatchevents_endpoint"],
- },
- "cloudwatchlogs": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["cloudwatchlogs_endpoint"],
- },
- "cloudformation": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["cloudformation_endpoint"],
- },
- "devicefarm": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["devicefarm_endpoint"],
- },
- "dynamodb": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["dynamodb_endpoint"],
- },
- "iam": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["iam_endpoint"],
- },
-
- "ec2": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["ec2_endpoint"],
- },
-
- "elb": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["elb_endpoint"],
- },
- "kinesis": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["kinesis_endpoint"],
- },
- "kms": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["kms_endpoint"],
- },
- "rds": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["rds_endpoint"],
- },
- "s3": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["s3_endpoint"],
- },
- "sns": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["sns_endpoint"],
- },
- "sqs": {
- Type: schema.TypeString,
- Optional: true,
- Default: "",
- Description: descriptions["sqs_endpoint"],
- },
- },
- },
- Set: endpointsToHash,
- }
-}
-
-func endpointsToHash(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%s-", m["cloudwatch"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["cloudwatchevents"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["cloudwatchlogs"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["cloudformation"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["devicefarm"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["dynamodb"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["iam"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["ec2"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["elb"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["kinesis"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["kms"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["rds"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["s3"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["sns"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["sqs"].(string)))
-
- return hashcode.String(buf.String())
-}
diff --git a/builtin/providers/aws/provider_test.go b/builtin/providers/aws/provider_test.go
deleted file mode 100644
index fee6cb0e5..000000000
--- a/builtin/providers/aws/provider_test.go
+++ /dev/null
@@ -1,53 +0,0 @@
-package aws
-
-import (
- "log"
- "os"
- "testing"
-
- "github.com/hashicorp/terraform/builtin/providers/template"
- "github.com/hashicorp/terraform/helper/schema"
- "github.com/hashicorp/terraform/terraform"
-)
-
-var testAccProviders map[string]terraform.ResourceProvider
-var testAccProvider *schema.Provider
-var testAccTemplateProvider *schema.Provider
-
-func init() {
- testAccProvider = Provider().(*schema.Provider)
- testAccTemplateProvider = template.Provider().(*schema.Provider)
- testAccProviders = map[string]terraform.ResourceProvider{
- "aws": testAccProvider,
- "template": testAccTemplateProvider,
- }
-}
-
-func TestProvider(t *testing.T) {
- if err := Provider().(*schema.Provider).InternalValidate(); err != nil {
- t.Fatalf("err: %s", err)
- }
-}
-
-func TestProvider_impl(t *testing.T) {
- var _ terraform.ResourceProvider = Provider()
-}
-
-func testAccPreCheck(t *testing.T) {
- if v := os.Getenv("AWS_PROFILE"); v == "" {
- if v := os.Getenv("AWS_ACCESS_KEY_ID"); v == "" {
- t.Fatal("AWS_ACCESS_KEY_ID must be set for acceptance tests")
- }
- if v := os.Getenv("AWS_SECRET_ACCESS_KEY"); v == "" {
- t.Fatal("AWS_SECRET_ACCESS_KEY must be set for acceptance tests")
- }
- }
- if v := os.Getenv("AWS_DEFAULT_REGION"); v == "" {
- log.Println("[INFO] Test: Using us-west-2 as test region")
- os.Setenv("AWS_DEFAULT_REGION", "us-west-2")
- }
- err := testAccProvider.Configure(terraform.NewResourceConfig(nil))
- if err != nil {
- t.Fatal(err)
- }
-}
diff --git a/builtin/providers/aws/resource_aws_alb.go b/builtin/providers/aws/resource_aws_alb.go
deleted file mode 100644
index d1652c680..000000000
--- a/builtin/providers/aws/resource_aws_alb.go
+++ /dev/null
@@ -1,497 +0,0 @@
-package aws
-
-import (
- "fmt"
- "log"
- "regexp"
- "strconv"
- "time"
-
- "github.com/aws/aws-sdk-go/aws"
- "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 resourceAwsAlb() *schema.Resource {
- return &schema.Resource{
- Create: resourceAwsAlbCreate,
- Read: resourceAwsAlbRead,
- Update: resourceAwsAlbUpdate,
- Delete: resourceAwsAlbDelete,
- Importer: &schema.ResourceImporter{
- State: schema.ImportStatePassthrough,
- },
-
- Timeouts: &schema.ResourceTimeout{
- Create: schema.DefaultTimeout(10 * time.Minute),
- Update: schema.DefaultTimeout(10 * time.Minute),
- Delete: schema.DefaultTimeout(10 * time.Minute),
- },
-
- Schema: map[string]*schema.Schema{
- "arn": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "arn_suffix": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "name": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- ForceNew: true,
- ConflictsWith: []string{"name_prefix"},
- ValidateFunc: validateElbName,
- },
-
- "name_prefix": {
- Type: schema.TypeString,
- Optional: true,
- ForceNew: true,
- ValidateFunc: validateElbNamePrefix,
- },
-
- "internal": {
- Type: schema.TypeBool,
- Optional: true,
- ForceNew: true,
- Computed: true,
- },
-
- "security_groups": {
- Type: schema.TypeSet,
- Elem: &schema.Schema{Type: schema.TypeString},
- Computed: true,
- Optional: true,
- Set: schema.HashString,
- },
-
- "subnets": {
- Type: schema.TypeSet,
- Elem: &schema.Schema{Type: schema.TypeString},
- Required: true,
- Set: schema.HashString,
- },
-
- "access_logs": {
- Type: schema.TypeList,
- Optional: true,
- MaxItems: 1,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "bucket": {
- Type: schema.TypeString,
- Required: true,
- },
- "prefix": {
- Type: schema.TypeString,
- Optional: true,
- },
- "enabled": {
- Type: schema.TypeBool,
- Optional: true,
- Default: true,
- },
- },
- },
- },
-
- "enable_deletion_protection": {
- Type: schema.TypeBool,
- Optional: true,
- Default: false,
- },
-
- "idle_timeout": {
- Type: schema.TypeInt,
- Optional: true,
- Default: 60,
- },
-
- "ip_address_type": {
- Type: schema.TypeString,
- Computed: true,
- Optional: true,
- },
-
- "vpc_id": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "zone_id": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "dns_name": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "tags": tagsSchema(),
- },
- }
-}
-
-func resourceAwsAlbCreate(d *schema.ResourceData, meta interface{}) error {
- elbconn := meta.(*AWSClient).elbv2conn
-
- 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("tf-lb-")
- }
- d.Set("name", name)
-
- elbOpts := &elbv2.CreateLoadBalancerInput{
- Name: aws.String(name),
- Tags: tagsFromMapELBv2(d.Get("tags").(map[string]interface{})),
- }
-
- if scheme, ok := d.GetOk("internal"); ok && scheme.(bool) {
- elbOpts.Scheme = aws.String("internal")
- }
-
- if v, ok := d.GetOk("security_groups"); ok {
- elbOpts.SecurityGroups = expandStringList(v.(*schema.Set).List())
- }
-
- if v, ok := d.GetOk("subnets"); ok {
- elbOpts.Subnets = expandStringList(v.(*schema.Set).List())
- }
-
- if v, ok := d.GetOk("ip_address_type"); ok {
- elbOpts.IpAddressType = aws.String(v.(string))
- }
-
- log.Printf("[DEBUG] ALB create configuration: %#v", elbOpts)
-
- resp, err := elbconn.CreateLoadBalancer(elbOpts)
- if err != nil {
- return errwrap.Wrapf("Error creating Application Load Balancer: {{err}}", err)
- }
-
- if len(resp.LoadBalancers) != 1 {
- return fmt.Errorf("No load balancers returned following creation of %s", d.Get("name").(string))
- }
-
- lb := resp.LoadBalancers[0]
- d.SetId(*lb.LoadBalancerArn)
- log.Printf("[INFO] ALB ID: %s", d.Id())
-
- stateConf := &resource.StateChangeConf{
- Pending: []string{"provisioning", "failed"},
- Target: []string{"active"},
- Refresh: func() (interface{}, string, error) {
- describeResp, err := elbconn.DescribeLoadBalancers(&elbv2.DescribeLoadBalancersInput{
- LoadBalancerArns: []*string{lb.LoadBalancerArn},
- })
- if err != nil {
- return nil, "", err
- }
-
- if len(describeResp.LoadBalancers) != 1 {
- return nil, "", fmt.Errorf("No load balancers returned for %s", *lb.LoadBalancerArn)
- }
- dLb := describeResp.LoadBalancers[0]
-
- log.Printf("[INFO] ALB state: %s", *dLb.State.Code)
-
- return describeResp, *dLb.State.Code, nil
- },
- Timeout: d.Timeout(schema.TimeoutCreate),
- MinTimeout: 10 * time.Second,
- Delay: 30 * time.Second, // Wait 30 secs before starting
- }
- _, err = stateConf.WaitForState()
- if err != nil {
- return err
- }
-
- return resourceAwsAlbUpdate(d, meta)
-}
-
-func resourceAwsAlbRead(d *schema.ResourceData, meta interface{}) error {
- elbconn := meta.(*AWSClient).elbv2conn
- albArn := d.Id()
-
- describeAlbOpts := &elbv2.DescribeLoadBalancersInput{
- LoadBalancerArns: []*string{aws.String(albArn)},
- }
-
- describeResp, err := elbconn.DescribeLoadBalancers(describeAlbOpts)
- if err != nil {
- if isLoadBalancerNotFound(err) {
- // The ALB is gone now, so just remove it from the state
- log.Printf("[WARN] ALB %s not found in AWS, removing from state", d.Id())
- d.SetId("")
- return nil
- }
-
- return errwrap.Wrapf("Error retrieving ALB: {{err}}", err)
- }
- if len(describeResp.LoadBalancers) != 1 {
- return fmt.Errorf("Unable to find ALB: %#v", describeResp.LoadBalancers)
- }
-
- return flattenAwsAlbResource(d, meta, describeResp.LoadBalancers[0])
-}
-
-func resourceAwsAlbUpdate(d *schema.ResourceData, meta interface{}) error {
- elbconn := meta.(*AWSClient).elbv2conn
-
- if !d.IsNewResource() {
- if err := setElbV2Tags(elbconn, d); err != nil {
- return errwrap.Wrapf("Error Modifying Tags on ALB: {{err}}", err)
- }
- }
-
- attributes := make([]*elbv2.LoadBalancerAttribute, 0)
-
- if d.HasChange("access_logs") {
- logs := d.Get("access_logs").([]interface{})
- if len(logs) == 1 {
- log := logs[0].(map[string]interface{})
-
- attributes = append(attributes,
- &elbv2.LoadBalancerAttribute{
- Key: aws.String("access_logs.s3.enabled"),
- Value: aws.String(strconv.FormatBool(log["enabled"].(bool))),
- },
- &elbv2.LoadBalancerAttribute{
- Key: aws.String("access_logs.s3.bucket"),
- Value: aws.String(log["bucket"].(string)),
- })
-
- if prefix, ok := log["prefix"]; ok {
- attributes = append(attributes, &elbv2.LoadBalancerAttribute{
- Key: aws.String("access_logs.s3.prefix"),
- Value: aws.String(prefix.(string)),
- })
- }
- } else if len(logs) == 0 {
- attributes = append(attributes, &elbv2.LoadBalancerAttribute{
- Key: aws.String("access_logs.s3.enabled"),
- Value: aws.String("false"),
- })
- }
- }
-
- if d.HasChange("enable_deletion_protection") {
- attributes = append(attributes, &elbv2.LoadBalancerAttribute{
- Key: aws.String("deletion_protection.enabled"),
- Value: aws.String(fmt.Sprintf("%t", d.Get("enable_deletion_protection").(bool))),
- })
- }
-
- if d.HasChange("idle_timeout") {
- attributes = append(attributes, &elbv2.LoadBalancerAttribute{
- Key: aws.String("idle_timeout.timeout_seconds"),
- Value: aws.String(fmt.Sprintf("%d", d.Get("idle_timeout").(int))),
- })
- }
-
- if len(attributes) != 0 {
- input := &elbv2.ModifyLoadBalancerAttributesInput{
- LoadBalancerArn: aws.String(d.Id()),
- Attributes: attributes,
- }
-
- log.Printf("[DEBUG] ALB Modify Load Balancer Attributes Request: %#v", input)
- _, err := elbconn.ModifyLoadBalancerAttributes(input)
- if err != nil {
- return fmt.Errorf("Failure configuring ALB attributes: %s", err)
- }
- }
-
- if d.HasChange("security_groups") {
- sgs := expandStringList(d.Get("security_groups").(*schema.Set).List())
-
- params := &elbv2.SetSecurityGroupsInput{
- LoadBalancerArn: aws.String(d.Id()),
- SecurityGroups: sgs,
- }
- _, err := elbconn.SetSecurityGroups(params)
- if err != nil {
- return fmt.Errorf("Failure Setting ALB Security Groups: %s", err)
- }
-
- }
-
- if d.HasChange("subnets") {
- subnets := expandStringList(d.Get("subnets").(*schema.Set).List())
-
- params := &elbv2.SetSubnetsInput{
- LoadBalancerArn: aws.String(d.Id()),
- Subnets: subnets,
- }
-
- _, err := elbconn.SetSubnets(params)
- if err != nil {
- return fmt.Errorf("Failure Setting ALB Subnets: %s", err)
- }
- }
-
- if d.HasChange("ip_address_type") {
-
- params := &elbv2.SetIpAddressTypeInput{
- LoadBalancerArn: aws.String(d.Id()),
- IpAddressType: aws.String(d.Get("ip_address_type").(string)),
- }
-
- _, err := elbconn.SetIpAddressType(params)
- if err != nil {
- return fmt.Errorf("Failure Setting ALB IP Address Type: %s", err)
- }
-
- }
-
- stateConf := &resource.StateChangeConf{
- Pending: []string{"active", "provisioning", "failed"},
- Target: []string{"active"},
- Refresh: func() (interface{}, string, error) {
- describeResp, err := elbconn.DescribeLoadBalancers(&elbv2.DescribeLoadBalancersInput{
- LoadBalancerArns: []*string{aws.String(d.Id())},
- })
- if err != nil {
- return nil, "", err
- }
-
- if len(describeResp.LoadBalancers) != 1 {
- return nil, "", fmt.Errorf("No load balancers returned for %s", d.Id())
- }
- dLb := describeResp.LoadBalancers[0]
-
- log.Printf("[INFO] ALB state: %s", *dLb.State.Code)
-
- return describeResp, *dLb.State.Code, nil
- },
- Timeout: d.Timeout(schema.TimeoutUpdate),
- MinTimeout: 10 * time.Second,
- Delay: 30 * time.Second, // Wait 30 secs before starting
- }
- _, err := stateConf.WaitForState()
- if err != nil {
- return err
- }
-
- return resourceAwsAlbRead(d, meta)
-}
-
-func resourceAwsAlbDelete(d *schema.ResourceData, meta interface{}) error {
- albconn := meta.(*AWSClient).elbv2conn
-
- log.Printf("[INFO] Deleting ALB: %s", d.Id())
-
- // Destroy the load balancer
- deleteElbOpts := elbv2.DeleteLoadBalancerInput{
- LoadBalancerArn: aws.String(d.Id()),
- }
- if _, err := albconn.DeleteLoadBalancer(&deleteElbOpts); err != nil {
- return fmt.Errorf("Error deleting ALB: %s", err)
- }
-
- return nil
-}
-
-// flattenSubnetsFromAvailabilityZones creates a slice of strings containing the subnet IDs
-// for the ALB based on the AvailabilityZones structure returned by the API.
-func flattenSubnetsFromAvailabilityZones(availabilityZones []*elbv2.AvailabilityZone) []string {
- var result []string
- for _, az := range availabilityZones {
- result = append(result, *az.SubnetId)
- }
- return result
-}
-
-func albSuffixFromARN(arn *string) string {
- if arn == nil {
- return ""
- }
-
- if arnComponents := regexp.MustCompile(`arn:.*:loadbalancer/(.*)`).FindAllStringSubmatch(*arn, -1); len(arnComponents) == 1 {
- if len(arnComponents[0]) == 2 {
- return arnComponents[0][1]
- }
- }
-
- return ""
-}
-
-// flattenAwsAlbResource takes a *elbv2.LoadBalancer and populates all respective resource fields.
-func flattenAwsAlbResource(d *schema.ResourceData, meta interface{}, alb *elbv2.LoadBalancer) error {
- elbconn := meta.(*AWSClient).elbv2conn
-
- d.Set("arn", alb.LoadBalancerArn)
- d.Set("arn_suffix", albSuffixFromARN(alb.LoadBalancerArn))
- d.Set("name", alb.LoadBalancerName)
- d.Set("internal", (alb.Scheme != nil && *alb.Scheme == "internal"))
- d.Set("security_groups", flattenStringList(alb.SecurityGroups))
- d.Set("subnets", flattenSubnetsFromAvailabilityZones(alb.AvailabilityZones))
- d.Set("vpc_id", alb.VpcId)
- d.Set("zone_id", alb.CanonicalHostedZoneId)
- d.Set("dns_name", alb.DNSName)
- d.Set("ip_address_type", alb.IpAddressType)
-
- respTags, err := elbconn.DescribeTags(&elbv2.DescribeTagsInput{
- ResourceArns: []*string{alb.LoadBalancerArn},
- })
- if err != nil {
- return errwrap.Wrapf("Error retrieving ALB Tags: {{err}}", err)
- }
-
- var et []*elbv2.Tag
- if len(respTags.TagDescriptions) > 0 {
- et = respTags.TagDescriptions[0].Tags
- }
- d.Set("tags", tagsToMapELBv2(et))
-
- attributesResp, err := elbconn.DescribeLoadBalancerAttributes(&elbv2.DescribeLoadBalancerAttributesInput{
- LoadBalancerArn: aws.String(d.Id()),
- })
- if err != nil {
- return errwrap.Wrapf("Error retrieving ALB Attributes: {{err}}", err)
- }
-
- accessLogMap := map[string]interface{}{}
- for _, attr := range attributesResp.Attributes {
- switch *attr.Key {
- case "access_logs.s3.enabled":
- accessLogMap["enabled"] = *attr.Value
- case "access_logs.s3.bucket":
- accessLogMap["bucket"] = *attr.Value
- case "access_logs.s3.prefix":
- accessLogMap["prefix"] = *attr.Value
- case "idle_timeout.timeout_seconds":
- timeout, err := strconv.Atoi(*attr.Value)
- if err != nil {
- return errwrap.Wrapf("Error parsing ALB timeout: {{err}}", err)
- }
- log.Printf("[DEBUG] Setting ALB Timeout Seconds: %d", timeout)
- d.Set("idle_timeout", timeout)
- case "deletion_protection.enabled":
- protectionEnabled := (*attr.Value) == "true"
- log.Printf("[DEBUG] Setting ALB Deletion Protection Enabled: %t", protectionEnabled)
- d.Set("enable_deletion_protection", protectionEnabled)
- }
- }
-
- log.Printf("[DEBUG] Setting ALB Access Logs: %#v", accessLogMap)
- if accessLogMap["bucket"] != "" || accessLogMap["prefix"] != "" {
- d.Set("access_logs", []interface{}{accessLogMap})
- } else {
- d.Set("access_logs", []interface{}{})
- }
-
- return nil
-}
diff --git a/builtin/providers/aws/resource_aws_alb_listener.go b/builtin/providers/aws/resource_aws_alb_listener.go
deleted file mode 100644
index f94e3b1a1..000000000
--- a/builtin/providers/aws/resource_aws_alb_listener.go
+++ /dev/null
@@ -1,284 +0,0 @@
-package aws
-
-import (
- "errors"
- "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/elbv2"
- "github.com/hashicorp/errwrap"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func resourceAwsAlbListener() *schema.Resource {
- return &schema.Resource{
- Create: resourceAwsAlbListenerCreate,
- Read: resourceAwsAlbListenerRead,
- Update: resourceAwsAlbListenerUpdate,
- Delete: resourceAwsAlbListenerDelete,
- Importer: &schema.ResourceImporter{
- State: schema.ImportStatePassthrough,
- },
-
- Schema: map[string]*schema.Schema{
- "arn": {
- Type: schema.TypeString,
- Computed: true,
- },
-
- "load_balancer_arn": {
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
-
- "port": {
- Type: schema.TypeInt,
- Required: true,
- ValidateFunc: validateAwsAlbListenerPort,
- },
-
- "protocol": {
- Type: schema.TypeString,
- Optional: true,
- Default: "HTTP",
- StateFunc: func(v interface{}) string {
- return strings.ToUpper(v.(string))
- },
- ValidateFunc: validateAwsAlbListenerProtocol,
- },
-
- "ssl_policy": {
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- },
-
- "certificate_arn": {
- Type: schema.TypeString,
- Optional: true,
- },
-
- "default_action": {
- Type: schema.TypeList,
- Required: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "target_group_arn": {
- Type: schema.TypeString,
- Required: true,
- },
- "type": {
- Type: schema.TypeString,
- Required: true,
- ValidateFunc: validateAwsAlbListenerActionType,
- },
- },
- },
- },
- },
- }
-}
-
-func resourceAwsAlbListenerCreate(d *schema.ResourceData, meta interface{}) error {
- elbconn := meta.(*AWSClient).elbv2conn
-
- albArn := d.Get("load_balancer_arn").(string)
-
- params := &elbv2.CreateListenerInput{
- LoadBalancerArn: aws.String(albArn),
- Port: aws.Int64(int64(d.Get("port").(int))),
- Protocol: aws.String(d.Get("protocol").(string)),
- }
-
- if sslPolicy, ok := d.GetOk("ssl_policy"); ok {
- params.SslPolicy = aws.String(sslPolicy.(string))
- }
-
- if certificateArn, ok := d.GetOk("certificate_arn"); ok {
- params.Certificates = make([]*elbv2.Certificate, 1)
- params.Certificates[0] = &elbv2.Certificate{
- CertificateArn: aws.String(certificateArn.(string)),
- }
- }
-
- if defaultActions := d.Get("default_action").([]interface{}); len(defaultActions) == 1 {
- params.DefaultActions = make([]*elbv2.Action, len(defaultActions))
-
- for i, defaultAction := range defaultActions {
- defaultActionMap := defaultAction.(map[string]interface{})
-
- params.DefaultActions[i] = &elbv2.Action{
- TargetGroupArn: aws.String(defaultActionMap["target_group_arn"].(string)),
- Type: aws.String(defaultActionMap["type"].(string)),
- }
- }
- }
-
- var resp *elbv2.CreateListenerOutput
-
- err := resource.Retry(5*time.Minute, func() *resource.RetryError {
- var err error
- log.Printf("[DEBUG] Creating ALB listener for ARN: %s", d.Get("load_balancer_arn").(string))
- resp, err = elbconn.CreateListener(params)
- if awsErr, ok := err.(awserr.Error); ok {
- if awsErr.Code() == "CertificateNotFound" {
- log.Printf("[WARN] Got an error while trying to create ALB listener for ARN: %s: %s", albArn, err)
- return resource.RetryableError(err)
- }
- }
- if err != nil {
- return resource.NonRetryableError(err)
- }
-
- return nil
- })
-
- if err != nil {
- return errwrap.Wrapf("Error creating ALB Listener: {{err}}", err)
- }
-
- if len(resp.Listeners) == 0 {
- return errors.New("Error creating ALB Listener: no listeners returned in response")
- }
-
- d.SetId(*resp.Listeners[0].ListenerArn)
-
- return resourceAwsAlbListenerRead(d, meta)
-}
-
-func resourceAwsAlbListenerRead(d *schema.ResourceData, meta interface{}) error {
- elbconn := meta.(*AWSClient).elbv2conn
-
- resp, err := elbconn.DescribeListeners(&elbv2.DescribeListenersInput{
- ListenerArns: []*string{aws.String(d.Id())},
- })
- if err != nil {
- if isListenerNotFound(err) {
- log.Printf("[WARN] DescribeListeners - removing %s from state", d.Id())
- d.SetId("")
- return nil
- }
- return errwrap.Wrapf("Error retrieving Listener: {{err}}", err)
- }
-
- if len(resp.Listeners) != 1 {
- return fmt.Errorf("Error retrieving Listener %q", d.Id())
- }
-
- listener := resp.Listeners[0]
-
- d.Set("arn", listener.ListenerArn)
- d.Set("load_balancer_arn", listener.LoadBalancerArn)
- d.Set("port", listener.Port)
- d.Set("protocol", listener.Protocol)
- d.Set("ssl_policy", listener.SslPolicy)
-
- if listener.Certificates != nil && len(listener.Certificates) == 1 {
- d.Set("certificate_arn", listener.Certificates[0].CertificateArn)
- }
-
- defaultActions := make([]map[string]interface{}, 0)
- if listener.DefaultActions != nil && len(listener.DefaultActions) > 0 {
- for _, defaultAction := range listener.DefaultActions {
- action := map[string]interface{}{
- "target_group_arn": *defaultAction.TargetGroupArn,
- "type": *defaultAction.Type,
- }
- defaultActions = append(defaultActions, action)
- }
- }
- d.Set("default_action", defaultActions)
-
- return nil
-}
-
-func resourceAwsAlbListenerUpdate(d *schema.ResourceData, meta interface{}) error {
- elbconn := meta.(*AWSClient).elbv2conn
-
- params := &elbv2.ModifyListenerInput{
- ListenerArn: aws.String(d.Id()),
- Port: aws.Int64(int64(d.Get("port").(int))),
- Protocol: aws.String(d.Get("protocol").(string)),
- }
-
- if sslPolicy, ok := d.GetOk("ssl_policy"); ok {
- params.SslPolicy = aws.String(sslPolicy.(string))
- }
-
- if certificateArn, ok := d.GetOk("certificate_arn"); ok {
- params.Certificates = make([]*elbv2.Certificate, 1)
- params.Certificates[0] = &elbv2.Certificate{
- CertificateArn: aws.String(certificateArn.(string)),
- }
- }
-
- if defaultActions := d.Get("default_action").([]interface{}); len(defaultActions) == 1 {
- params.DefaultActions = make([]*elbv2.Action, len(defaultActions))
-
- for i, defaultAction := range defaultActions {
- defaultActionMap := defaultAction.(map[string]interface{})
-
- params.DefaultActions[i] = &elbv2.Action{
- TargetGroupArn: aws.String(defaultActionMap["target_group_arn"].(string)),
- Type: aws.String(defaultActionMap["type"].(string)),
- }
- }
- }
-
- _, err := elbconn.ModifyListener(params)
- if err != nil {
- return errwrap.Wrapf("Error modifying ALB Listener: {{err}}", err)
- }
-
- return resourceAwsAlbListenerRead(d, meta)
-}
-
-func resourceAwsAlbListenerDelete(d *schema.ResourceData, meta interface{}) error {
- elbconn := meta.(*AWSClient).elbv2conn
-
- _, err := elbconn.DeleteListener(&elbv2.DeleteListenerInput{
- ListenerArn: aws.String(d.Id()),
- })
- if err != nil {
- return errwrap.Wrapf("Error deleting Listener: {{err}}", err)
- }
-
- return nil
-}
-
-func validateAwsAlbListenerPort(v interface{}, k string) (ws []string, errors []error) {
- port := v.(int)
- if port < 1 || port > 65536 {
- errors = append(errors, fmt.Errorf("%q must be a valid port number (1-65536)", k))
- }
- return
-}
-
-func validateAwsAlbListenerProtocol(v interface{}, k string) (ws []string, errors []error) {
- value := strings.ToLower(v.(string))
- if value == "http" || value == "https" {
- return
- }
-
- errors = append(errors, fmt.Errorf("%q must be either %q or %q", k, "HTTP", "HTTPS"))
- return
-}
-
-func validateAwsAlbListenerActionType(v interface{}, k string) (ws []string, errors []error) {
- value := strings.ToLower(v.(string))
- if value != "forward" {
- errors = append(errors, fmt.Errorf("%q must have the value %q", k, "forward"))
- }
- return
-}
-
-func isListenerNotFound(err error) bool {
- elberr, ok := err.(awserr.Error)
- return ok && elberr.Code() == "ListenerNotFound"
-}
diff --git a/builtin/providers/aws/resource_aws_alb_listener_rule.go b/builtin/providers/aws/resource_aws_alb_listener_rule.go
deleted file mode 100644
index 21292753c..000000000
--- a/builtin/providers/aws/resource_aws_alb_listener_rule.go
+++ /dev/null
@@ -1,293 +0,0 @@
-package aws
-
-import (
- "errors"
- "fmt"
- "log"
- "strconv"
-
- "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/schema"
-)
-
-func resourceAwsAlbListenerRule() *schema.Resource {
- return &schema.Resource{
- Create: resourceAwsAlbListenerRuleCreate,
- Read: resourceAwsAlbListenerRuleRead,
- Update: resourceAwsAlbListenerRuleUpdate,
- Delete: resourceAwsAlbListenerRuleDelete,
- Importer: &schema.ResourceImporter{
- State: schema.ImportStatePassthrough,
- },
-
- Schema: map[string]*schema.Schema{
- "arn": {
- Type: schema.TypeString,
- Computed: true,
- },
- "listener_arn": {
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
- "priority": {
- Type: schema.TypeInt,
- Required: true,
- ForceNew: true,
- ValidateFunc: validateAwsAlbListenerRulePriority,
- },
- "action": {
- Type: schema.TypeList,
- Required: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "target_group_arn": {
- Type: schema.TypeString,
- Required: true,
- },
- "type": {
- Type: schema.TypeString,
- Required: true,
- ValidateFunc: validateAwsAlbListenerActionType,
- },
- },
- },
- },
- "condition": {
- Type: schema.TypeList,
- Required: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "field": {
- Type: schema.TypeString,
- Optional: true,
- ValidateFunc: validateAwsListenerRuleField,
- },
- "values": {
- Type: schema.TypeList,
- MaxItems: 1,
- Elem: &schema.Schema{Type: schema.TypeString},
- Optional: true,
- },
- },
- },
- },
- },
- }
-}
-
-func resourceAwsAlbListenerRuleCreate(d *schema.ResourceData, meta interface{}) error {
- elbconn := meta.(*AWSClient).elbv2conn
-
- params := &elbv2.CreateRuleInput{
- ListenerArn: aws.String(d.Get("listener_arn").(string)),
- Priority: aws.Int64(int64(d.Get("priority").(int))),
- }
-
- actions := d.Get("action").([]interface{})
- params.Actions = make([]*elbv2.Action, len(actions))
- for i, action := range actions {
- actionMap := action.(map[string]interface{})
- params.Actions[i] = &elbv2.Action{
- TargetGroupArn: aws.String(actionMap["target_group_arn"].(string)),
- Type: aws.String(actionMap["type"].(string)),
- }
- }
-
- conditions := d.Get("condition").([]interface{})
- params.Conditions = make([]*elbv2.RuleCondition, len(conditions))
- for i, condition := range conditions {
- conditionMap := condition.(map[string]interface{})
- values := conditionMap["values"].([]interface{})
- params.Conditions[i] = &elbv2.RuleCondition{
- Field: aws.String(conditionMap["field"].(string)),
- Values: make([]*string, len(values)),
- }
- for j, value := range values {
- params.Conditions[i].Values[j] = aws.String(value.(string))
- }
- }
-
- resp, err := elbconn.CreateRule(params)
- if err != nil {
- return errwrap.Wrapf("Error creating ALB Listener Rule: {{err}}", err)
- }
-
- if len(resp.Rules) == 0 {
- return errors.New("Error creating ALB Listener Rule: no rules returned in response")
- }
-
- d.SetId(*resp.Rules[0].RuleArn)
-
- return resourceAwsAlbListenerRuleRead(d, meta)
-}
-
-func resourceAwsAlbListenerRuleRead(d *schema.ResourceData, meta interface{}) error {
- elbconn := meta.(*AWSClient).elbv2conn
-
- resp, err := elbconn.DescribeRules(&elbv2.DescribeRulesInput{
- RuleArns: []*string{aws.String(d.Id())},
- })
- if err != nil {
- if isRuleNotFound(err) {
- log.Printf("[WARN] DescribeRules - removing %s from state", d.Id())
- d.SetId("")
- return nil
- }
- return errwrap.Wrapf(fmt.Sprintf("Error retrieving Rules for listener %s: {{err}}", d.Id()), err)
- }
-
- if len(resp.Rules) != 1 {
- return fmt.Errorf("Error retrieving Rule %q", d.Id())
- }
-
- rule := resp.Rules[0]
-
- d.Set("arn", rule.RuleArn)
- // Rules are evaluated in priority order, from the lowest value to the highest value. The default rule has the lowest priority.
- if *rule.Priority == "default" {
- d.Set("priority", 99999)
- } else {
- if priority, err := strconv.Atoi(*rule.Priority); err != nil {
- return errwrap.Wrapf("Cannot convert rule priority %q to int: {{err}}", err)
- } else {
- d.Set("priority", priority)
- }
- }
-
- actions := make([]interface{}, len(rule.Actions))
- for i, action := range rule.Actions {
- actionMap := make(map[string]interface{})
- actionMap["target_group_arn"] = *action.TargetGroupArn
- actionMap["type"] = *action.Type
- actions[i] = actionMap
- }
- d.Set("action", actions)
-
- conditions := make([]interface{}, len(rule.Conditions))
- for i, condition := range rule.Conditions {
- conditionMap := make(map[string]interface{})
- conditionMap["field"] = *condition.Field
- conditionValues := make([]string, len(condition.Values))
- for k, value := range condition.Values {
- conditionValues[k] = *value
- }
- conditionMap["values"] = conditionValues
- conditions[i] = conditionMap
- }
- d.Set("condition", conditions)
-
- return nil
-}
-
-func resourceAwsAlbListenerRuleUpdate(d *schema.ResourceData, meta interface{}) error {
- elbconn := meta.(*AWSClient).elbv2conn
-
- d.Partial(true)
-
- if d.HasChange("priority") {
- params := &elbv2.SetRulePrioritiesInput{
- RulePriorities: []*elbv2.RulePriorityPair{
- {
- RuleArn: aws.String(d.Id()),
- Priority: aws.Int64(int64(d.Get("priority").(int))),
- },
- },
- }
-
- _, err := elbconn.SetRulePriorities(params)
- if err != nil {
- return err
- }
-
- d.SetPartial("priority")
- }
-
- requestUpdate := false
- params := &elbv2.ModifyRuleInput{
- RuleArn: aws.String(d.Id()),
- }
-
- if d.HasChange("action") {
- actions := d.Get("action").([]interface{})
- params.Actions = make([]*elbv2.Action, len(actions))
- for i, action := range actions {
- actionMap := action.(map[string]interface{})
- params.Actions[i] = &elbv2.Action{
- TargetGroupArn: aws.String(actionMap["target_group_arn"].(string)),
- Type: aws.String(actionMap["type"].(string)),
- }
- }
- requestUpdate = true
- d.SetPartial("action")
- }
-
- if d.HasChange("condition") {
- conditions := d.Get("condition").([]interface{})
- params.Conditions = make([]*elbv2.RuleCondition, len(conditions))
- for i, condition := range conditions {
- conditionMap := condition.(map[string]interface{})
- values := conditionMap["values"].([]interface{})
- params.Conditions[i] = &elbv2.RuleCondition{
- Field: aws.String(conditionMap["field"].(string)),
- Values: make([]*string, len(values)),
- }
- for j, value := range values {
- params.Conditions[i].Values[j] = aws.String(value.(string))
- }
- }
- requestUpdate = true
- d.SetPartial("condition")
- }
-
- if requestUpdate {
- resp, err := elbconn.ModifyRule(params)
- if err != nil {
- return errwrap.Wrapf("Error modifying ALB Listener Rule: {{err}}", err)
- }
-
- if len(resp.Rules) == 0 {
- return errors.New("Error modifying creating ALB Listener Rule: no rules returned in response")
- }
- }
-
- d.Partial(false)
-
- return resourceAwsAlbListenerRuleRead(d, meta)
-}
-
-func resourceAwsAlbListenerRuleDelete(d *schema.ResourceData, meta interface{}) error {
- elbconn := meta.(*AWSClient).elbv2conn
-
- _, err := elbconn.DeleteRule(&elbv2.DeleteRuleInput{
- RuleArn: aws.String(d.Id()),
- })
- if err != nil && !isRuleNotFound(err) {
- return errwrap.Wrapf("Error deleting ALB Listener Rule: {{err}}", err)
- }
- return nil
-}
-
-func validateAwsAlbListenerRulePriority(v interface{}, k string) (ws []string, errors []error) {
- value := v.(int)
- if value < 1 || value > 99999 {
- errors = append(errors, fmt.Errorf("%q must be in the range 1-99999", k))
- }
- return
-}
-
-func validateAwsListenerRuleField(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
- if len(value) > 64 {
- errors = append(errors, fmt.Errorf("%q must be a maximum of 64 characters", k))
- }
- return
-}
-
-func isRuleNotFound(err error) bool {
- elberr, ok := err.(awserr.Error)
- return ok && elberr.Code() == "RuleNotFound"
-}
diff --git a/builtin/providers/aws/resource_aws_alb_listener_rule_test.go b/builtin/providers/aws/resource_aws_alb_listener_rule_test.go
deleted file mode 100644
index 8ddc0ef9e..000000000
--- a/builtin/providers/aws/resource_aws_alb_listener_rule_test.go
+++ /dev/null
@@ -1,647 +0,0 @@
-package aws
-
-import (
- "errors"
- "fmt"
- "regexp"
- "testing"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/elbv2"
- "github.com/hashicorp/errwrap"
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAWSALBListenerRule_basic(t *testing.T) {
- var conf elbv2.Rule
- albName := fmt.Sprintf("testrule-basic-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum))
- targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb_listener_rule.static",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBListenerRuleDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBListenerRuleConfig_basic(albName, targetGroupName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBListenerRuleExists("aws_alb_listener_rule.static", &conf),
- resource.TestCheckResourceAttrSet("aws_alb_listener_rule.static", "arn"),
- resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "priority", "100"),
- resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "action.#", "1"),
- resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "action.0.type", "forward"),
- resource.TestCheckResourceAttrSet("aws_alb_listener_rule.static", "action.0.target_group_arn"),
- resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "condition.#", "1"),
- resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "condition.0.field", "path-pattern"),
- resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "condition.0.values.#", "1"),
- resource.TestCheckResourceAttrSet("aws_alb_listener_rule.static", "condition.0.values.0"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALBListenerRule_updateRulePriority(t *testing.T) {
- var rule elbv2.Rule
- albName := fmt.Sprintf("testrule-basic-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum))
- targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb_listener_rule.static",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBListenerRuleDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBListenerRuleConfig_basic(albName, targetGroupName),
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAWSALBListenerRuleExists("aws_alb_listener_rule.static", &rule),
- resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "priority", "100"),
- ),
- },
- {
- Config: testAccAWSALBListenerRuleConfig_updateRulePriority(albName, targetGroupName),
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAWSALBListenerRuleExists("aws_alb_listener_rule.static", &rule),
- resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "priority", "101"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALBListenerRule_changeListenerRuleArnForcesNew(t *testing.T) {
- var before, after elbv2.Rule
- albName := fmt.Sprintf("testrule-basic-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum))
- targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb_listener_rule.static",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBListenerRuleDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBListenerRuleConfig_basic(albName, targetGroupName),
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAWSALBListenerRuleExists("aws_alb_listener_rule.static", &before),
- ),
- },
- {
- Config: testAccAWSALBListenerRuleConfig_changeRuleArn(albName, targetGroupName),
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAWSALBListenerRuleExists("aws_alb_listener_rule.static", &after),
- testAccCheckAWSAlbListenerRuleRecreated(t, &before, &after),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALBListenerRule_multipleConditionThrowsError(t *testing.T) {
- albName := fmt.Sprintf("testrule-basic-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum))
- targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBListenerRuleDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBListenerRuleConfig_multipleConditions(albName, targetGroupName),
- ExpectError: regexp.MustCompile(`attribute supports 1 item maximum`),
- },
- },
- })
-}
-
-func testAccCheckAWSAlbListenerRuleRecreated(t *testing.T,
- before, after *elbv2.Rule) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- if *before.RuleArn == *after.RuleArn {
- t.Fatalf("Expected change of Listener Rule ARNs, but both were %v", before.RuleArn)
- }
- return nil
- }
-}
-
-func testAccCheckAWSALBListenerRuleExists(n string, res *elbv2.Rule) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return errors.New("No Listener Rule ID is set")
- }
-
- conn := testAccProvider.Meta().(*AWSClient).elbv2conn
-
- describe, err := conn.DescribeRules(&elbv2.DescribeRulesInput{
- RuleArns: []*string{aws.String(rs.Primary.ID)},
- })
-
- if err != nil {
- return err
- }
-
- if len(describe.Rules) != 1 ||
- *describe.Rules[0].RuleArn != rs.Primary.ID {
- return errors.New("Listener Rule not found")
- }
-
- *res = *describe.Rules[0]
- return nil
- }
-}
-
-func testAccCheckAWSALBListenerRuleDestroy(s *terraform.State) error {
- conn := testAccProvider.Meta().(*AWSClient).elbv2conn
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "aws_alb_listener_rule" {
- continue
- }
-
- describe, err := conn.DescribeRules(&elbv2.DescribeRulesInput{
- RuleArns: []*string{aws.String(rs.Primary.ID)},
- })
-
- if err == nil {
- if len(describe.Rules) != 0 &&
- *describe.Rules[0].RuleArn == rs.Primary.ID {
- return fmt.Errorf("Listener Rule %q still exists", rs.Primary.ID)
- }
- }
-
- // Verify the error
- if isRuleNotFound(err) {
- return nil
- } else {
- return errwrap.Wrapf("Unexpected error checking ALB Listener Rule destroyed: {{err}}", err)
- }
- }
-
- return nil
-}
-
-func testAccAWSALBListenerRuleConfig_multipleConditions(albName, targetGroupName string) string {
- return fmt.Sprintf(`resource "aws_alb_listener_rule" "static" {
- listener_arn = "${aws_alb_listener.front_end.arn}"
- priority = 100
-
- action {
- type = "forward"
- target_group_arn = "${aws_alb_target_group.test.arn}"
- }
-
- condition {
- field = "path-pattern"
- values = ["/static/*", "static"]
- }
-}
-
-resource "aws_alb_listener" "front_end" {
- load_balancer_arn = "${aws_alb.alb_test.id}"
- protocol = "HTTP"
- port = "80"
-
- default_action {
- target_group_arn = "${aws_alb_target_group.test.id}"
- type = "forward"
- }
-}
-
-resource "aws_alb" "alb_test" {
- name = "%s"
- internal = true
- security_groups = ["${aws_security_group.alb_test.id}"]
- subnets = ["${aws_subnet.alb_test.*.id}"]
-
- idle_timeout = 30
- enable_deletion_protection = false
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_alb_target_group" "test" {
- name = "%s"
- port = 8080
- protocol = "HTTP"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- health_check {
- path = "/health"
- interval = 60
- port = 8081
- protocol = "HTTP"
- timeout = 3
- healthy_threshold = 3
- unhealthy_threshold = 3
- matcher = "200-299"
- }
-}
-
-variable "subnets" {
- default = ["10.0.1.0/24", "10.0.2.0/24"]
- type = "list"
-}
-
-data "aws_availability_zones" "available" {}
-
-resource "aws_vpc" "alb_test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_subnet" "alb_test" {
- count = 2
- vpc_id = "${aws_vpc.alb_test.id}"
- cidr_block = "${element(var.subnets, count.index)}"
- map_public_ip_on_launch = true
- availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_security_group" "alb_test" {
- name = "allow_all_alb_test"
- description = "Used for ALB Testing"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- ingress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- egress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}`, albName, targetGroupName)
-}
-
-func testAccAWSALBListenerRuleConfig_basic(albName, targetGroupName string) string {
- return fmt.Sprintf(`resource "aws_alb_listener_rule" "static" {
- listener_arn = "${aws_alb_listener.front_end.arn}"
- priority = 100
-
- action {
- type = "forward"
- target_group_arn = "${aws_alb_target_group.test.arn}"
- }
-
- condition {
- field = "path-pattern"
- values = ["/static/*"]
- }
-}
-
-resource "aws_alb_listener" "front_end" {
- load_balancer_arn = "${aws_alb.alb_test.id}"
- protocol = "HTTP"
- port = "80"
-
- default_action {
- target_group_arn = "${aws_alb_target_group.test.id}"
- type = "forward"
- }
-}
-
-resource "aws_alb" "alb_test" {
- name = "%s"
- internal = true
- security_groups = ["${aws_security_group.alb_test.id}"]
- subnets = ["${aws_subnet.alb_test.*.id}"]
-
- idle_timeout = 30
- enable_deletion_protection = false
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_alb_target_group" "test" {
- name = "%s"
- port = 8080
- protocol = "HTTP"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- health_check {
- path = "/health"
- interval = 60
- port = 8081
- protocol = "HTTP"
- timeout = 3
- healthy_threshold = 3
- unhealthy_threshold = 3
- matcher = "200-299"
- }
-}
-
-variable "subnets" {
- default = ["10.0.1.0/24", "10.0.2.0/24"]
- type = "list"
-}
-
-data "aws_availability_zones" "available" {}
-
-resource "aws_vpc" "alb_test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_subnet" "alb_test" {
- count = 2
- vpc_id = "${aws_vpc.alb_test.id}"
- cidr_block = "${element(var.subnets, count.index)}"
- map_public_ip_on_launch = true
- availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_security_group" "alb_test" {
- name = "allow_all_alb_test"
- description = "Used for ALB Testing"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- ingress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- egress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}`, albName, targetGroupName)
-}
-
-func testAccAWSALBListenerRuleConfig_updateRulePriority(albName, targetGroupName string) string {
- return fmt.Sprintf(`
-resource "aws_alb_listener_rule" "static" {
- listener_arn = "${aws_alb_listener.front_end.arn}"
- priority = 101
-
- action {
- type = "forward"
- target_group_arn = "${aws_alb_target_group.test.arn}"
- }
-
- condition {
- field = "path-pattern"
- values = ["/static/*"]
- }
-}
-
-resource "aws_alb_listener" "front_end" {
- load_balancer_arn = "${aws_alb.alb_test.id}"
- protocol = "HTTP"
- port = "80"
-
- default_action {
- target_group_arn = "${aws_alb_target_group.test.id}"
- type = "forward"
- }
-}
-
-resource "aws_alb" "alb_test" {
- name = "%s"
- internal = true
- security_groups = ["${aws_security_group.alb_test.id}"]
- subnets = ["${aws_subnet.alb_test.*.id}"]
-
- idle_timeout = 30
- enable_deletion_protection = false
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_alb_target_group" "test" {
- name = "%s"
- port = 8080
- protocol = "HTTP"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- health_check {
- path = "/health"
- interval = 60
- port = 8081
- protocol = "HTTP"
- timeout = 3
- healthy_threshold = 3
- unhealthy_threshold = 3
- matcher = "200-299"
- }
-}
-
-variable "subnets" {
- default = ["10.0.1.0/24", "10.0.2.0/24"]
- type = "list"
-}
-
-data "aws_availability_zones" "available" {}
-
-resource "aws_vpc" "alb_test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_subnet" "alb_test" {
- count = 2
- vpc_id = "${aws_vpc.alb_test.id}"
- cidr_block = "${element(var.subnets, count.index)}"
- map_public_ip_on_launch = true
- availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_security_group" "alb_test" {
- name = "allow_all_alb_test"
- description = "Used for ALB Testing"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- ingress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- egress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}`, albName, targetGroupName)
-}
-
-func testAccAWSALBListenerRuleConfig_changeRuleArn(albName, targetGroupName string) string {
- return fmt.Sprintf(`
-resource "aws_alb_listener_rule" "static" {
- listener_arn = "${aws_alb_listener.front_end_ruleupdate.arn}"
- priority = 101
-
- action {
- type = "forward"
- target_group_arn = "${aws_alb_target_group.test.arn}"
- }
-
- condition {
- field = "path-pattern"
- values = ["/static/*"]
- }
-}
-
-resource "aws_alb_listener" "front_end" {
- load_balancer_arn = "${aws_alb.alb_test.id}"
- protocol = "HTTP"
- port = "80"
-
- default_action {
- target_group_arn = "${aws_alb_target_group.test.id}"
- type = "forward"
- }
-}
-
-resource "aws_alb_listener" "front_end_ruleupdate" {
- load_balancer_arn = "${aws_alb.alb_test.id}"
- protocol = "HTTP"
- port = "8080"
-
- default_action {
- target_group_arn = "${aws_alb_target_group.test.id}"
- type = "forward"
- }
-}
-
-resource "aws_alb" "alb_test" {
- name = "%s"
- internal = true
- security_groups = ["${aws_security_group.alb_test.id}"]
- subnets = ["${aws_subnet.alb_test.*.id}"]
-
- idle_timeout = 30
- enable_deletion_protection = false
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_alb_target_group" "test" {
- name = "%s"
- port = 8080
- protocol = "HTTP"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- health_check {
- path = "/health"
- interval = 60
- port = 8081
- protocol = "HTTP"
- timeout = 3
- healthy_threshold = 3
- unhealthy_threshold = 3
- matcher = "200-299"
- }
-}
-
-variable "subnets" {
- default = ["10.0.1.0/24", "10.0.2.0/24"]
- type = "list"
-}
-
-data "aws_availability_zones" "available" {}
-
-resource "aws_vpc" "alb_test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_subnet" "alb_test" {
- count = 2
- vpc_id = "${aws_vpc.alb_test.id}"
- cidr_block = "${element(var.subnets, count.index)}"
- map_public_ip_on_launch = true
- availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_security_group" "alb_test" {
- name = "allow_all_alb_test"
- description = "Used for ALB Testing"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- ingress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- egress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}`, albName, targetGroupName)
-}
diff --git a/builtin/providers/aws/resource_aws_alb_listener_test.go b/builtin/providers/aws/resource_aws_alb_listener_test.go
deleted file mode 100644
index 6fdd84c28..000000000
--- a/builtin/providers/aws/resource_aws_alb_listener_test.go
+++ /dev/null
@@ -1,393 +0,0 @@
-package aws
-
-import (
- "errors"
- "fmt"
- "math/rand"
- "testing"
- "time"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/elbv2"
- "github.com/hashicorp/errwrap"
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAWSALBListener_basic(t *testing.T) {
- var conf elbv2.Listener
- albName := fmt.Sprintf("testlistener-basic-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum))
- targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb_listener.front_end",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBListenerDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBListenerConfig_basic(albName, targetGroupName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBListenerExists("aws_alb_listener.front_end", &conf),
- resource.TestCheckResourceAttrSet("aws_alb_listener.front_end", "load_balancer_arn"),
- resource.TestCheckResourceAttrSet("aws_alb_listener.front_end", "arn"),
- resource.TestCheckResourceAttr("aws_alb_listener.front_end", "protocol", "HTTP"),
- resource.TestCheckResourceAttr("aws_alb_listener.front_end", "port", "80"),
- resource.TestCheckResourceAttr("aws_alb_listener.front_end", "default_action.#", "1"),
- resource.TestCheckResourceAttr("aws_alb_listener.front_end", "default_action.0.type", "forward"),
- resource.TestCheckResourceAttrSet("aws_alb_listener.front_end", "default_action.0.target_group_arn"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALBListener_https(t *testing.T) {
- var conf elbv2.Listener
- albName := fmt.Sprintf("testlistener-https-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum))
- targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb_listener.front_end",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBListenerDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBListenerConfig_https(albName, targetGroupName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBListenerExists("aws_alb_listener.front_end", &conf),
- resource.TestCheckResourceAttrSet("aws_alb_listener.front_end", "load_balancer_arn"),
- resource.TestCheckResourceAttrSet("aws_alb_listener.front_end", "arn"),
- resource.TestCheckResourceAttr("aws_alb_listener.front_end", "protocol", "HTTPS"),
- resource.TestCheckResourceAttr("aws_alb_listener.front_end", "port", "443"),
- resource.TestCheckResourceAttr("aws_alb_listener.front_end", "default_action.#", "1"),
- resource.TestCheckResourceAttr("aws_alb_listener.front_end", "default_action.0.type", "forward"),
- resource.TestCheckResourceAttrSet("aws_alb_listener.front_end", "default_action.0.target_group_arn"),
- resource.TestCheckResourceAttrSet("aws_alb_listener.front_end", "certificate_arn"),
- resource.TestCheckResourceAttr("aws_alb_listener.front_end", "ssl_policy", "ELBSecurityPolicy-2015-05"),
- ),
- },
- },
- })
-}
-
-func testAccCheckAWSALBListenerExists(n string, res *elbv2.Listener) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return errors.New("No Listener ID is set")
- }
-
- conn := testAccProvider.Meta().(*AWSClient).elbv2conn
-
- describe, err := conn.DescribeListeners(&elbv2.DescribeListenersInput{
- ListenerArns: []*string{aws.String(rs.Primary.ID)},
- })
-
- if err != nil {
- return err
- }
-
- if len(describe.Listeners) != 1 ||
- *describe.Listeners[0].ListenerArn != rs.Primary.ID {
- return errors.New("Listener not found")
- }
-
- *res = *describe.Listeners[0]
- return nil
- }
-}
-
-func testAccCheckAWSALBListenerDestroy(s *terraform.State) error {
- conn := testAccProvider.Meta().(*AWSClient).elbv2conn
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "aws_alb_listener" {
- continue
- }
-
- describe, err := conn.DescribeListeners(&elbv2.DescribeListenersInput{
- ListenerArns: []*string{aws.String(rs.Primary.ID)},
- })
-
- if err == nil {
- if len(describe.Listeners) != 0 &&
- *describe.Listeners[0].ListenerArn == rs.Primary.ID {
- return fmt.Errorf("Listener %q still exists", rs.Primary.ID)
- }
- }
-
- // Verify the error
- if isListenerNotFound(err) {
- return nil
- } else {
- return errwrap.Wrapf("Unexpected error checking ALB Listener destroyed: {{err}}", err)
- }
- }
-
- return nil
-}
-
-func testAccAWSALBListenerConfig_basic(albName, targetGroupName string) string {
- return fmt.Sprintf(`resource "aws_alb_listener" "front_end" {
- load_balancer_arn = "${aws_alb.alb_test.id}"
- protocol = "HTTP"
- port = "80"
-
- default_action {
- target_group_arn = "${aws_alb_target_group.test.id}"
- type = "forward"
- }
-}
-
-resource "aws_alb" "alb_test" {
- name = "%s"
- internal = true
- security_groups = ["${aws_security_group.alb_test.id}"]
- subnets = ["${aws_subnet.alb_test.*.id}"]
-
- idle_timeout = 30
- enable_deletion_protection = false
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_alb_target_group" "test" {
- name = "%s"
- port = 8080
- protocol = "HTTP"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- health_check {
- path = "/health"
- interval = 60
- port = 8081
- protocol = "HTTP"
- timeout = 3
- healthy_threshold = 3
- unhealthy_threshold = 3
- matcher = "200-299"
- }
-}
-
-variable "subnets" {
- default = ["10.0.1.0/24", "10.0.2.0/24"]
- type = "list"
-}
-
-data "aws_availability_zones" "available" {}
-
-resource "aws_vpc" "alb_test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_subnet" "alb_test" {
- count = 2
- vpc_id = "${aws_vpc.alb_test.id}"
- cidr_block = "${element(var.subnets, count.index)}"
- map_public_ip_on_launch = true
- availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_security_group" "alb_test" {
- name = "allow_all_alb_test"
- description = "Used for ALB Testing"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- ingress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- egress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}`, albName, targetGroupName)
-}
-
-func testAccAWSALBListenerConfig_https(albName, targetGroupName string) string {
- return fmt.Sprintf(`resource "aws_alb_listener" "front_end" {
- load_balancer_arn = "${aws_alb.alb_test.id}"
- protocol = "HTTPS"
- port = "443"
- ssl_policy = "ELBSecurityPolicy-2015-05"
- certificate_arn = "${aws_iam_server_certificate.test_cert.arn}"
-
- default_action {
- target_group_arn = "${aws_alb_target_group.test.id}"
- type = "forward"
- }
-}
-
-resource "aws_alb" "alb_test" {
- name = "%s"
- internal = false
- security_groups = ["${aws_security_group.alb_test.id}"]
- subnets = ["${aws_subnet.alb_test.*.id}"]
-
- idle_timeout = 30
- enable_deletion_protection = false
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_alb_target_group" "test" {
- name = "%s"
- port = 8080
- protocol = "HTTP"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- health_check {
- path = "/health"
- interval = 60
- port = 8081
- protocol = "HTTP"
- timeout = 3
- healthy_threshold = 3
- unhealthy_threshold = 3
- matcher = "200-299"
- }
-}
-
-variable "subnets" {
- default = ["10.0.1.0/24", "10.0.2.0/24"]
- type = "list"
-}
-
-data "aws_availability_zones" "available" {}
-
-resource "aws_vpc" "alb_test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_internet_gateway" "gw" {
- vpc_id = "${aws_vpc.alb_test.id}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_subnet" "alb_test" {
- count = 2
- vpc_id = "${aws_vpc.alb_test.id}"
- cidr_block = "${element(var.subnets, count.index)}"
- map_public_ip_on_launch = true
- availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_security_group" "alb_test" {
- name = "allow_all_alb_test"
- description = "Used for ALB Testing"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- ingress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- egress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_iam_server_certificate" "test_cert" {
- name = "terraform-test-cert-%d"
- certificate_body = < 0 {
- params := &elbv2.ModifyTargetGroupAttributesInput{
- TargetGroupArn: aws.String(d.Id()),
- Attributes: attrs,
- }
-
- _, err := elbconn.ModifyTargetGroupAttributes(params)
- if err != nil {
- return errwrap.Wrapf("Error modifying Target Group Attributes: {{err}}", err)
- }
- }
-
- return resourceAwsAlbTargetGroupRead(d, meta)
-}
-
-func resourceAwsAlbTargetGroupDelete(d *schema.ResourceData, meta interface{}) error {
- elbconn := meta.(*AWSClient).elbv2conn
-
- _, err := elbconn.DeleteTargetGroup(&elbv2.DeleteTargetGroupInput{
- TargetGroupArn: aws.String(d.Id()),
- })
- if err != nil {
- return errwrap.Wrapf("Error deleting Target Group: {{err}}", err)
- }
-
- return nil
-}
-
-func isTargetGroupNotFound(err error) bool {
- elberr, ok := err.(awserr.Error)
- return ok && elberr.Code() == "TargetGroupNotFound"
-}
-
-func validateAwsAlbTargetGroupHealthCheckPath(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
- if len(value) > 1024 {
- errors = append(errors, fmt.Errorf(
- "%q cannot be longer than 1024 characters: %q", k, value))
- }
- return
-}
-
-func validateAwsAlbTargetGroupHealthCheckPort(v interface{}, k string) (ws []string, errors []error) {
- value := v.(string)
-
- if value == "traffic-port" {
- return
- }
-
- port, err := strconv.Atoi(value)
- if err != nil {
- errors = append(errors, fmt.Errorf("%q must be a valid port number (1-65536) or %q", k, "traffic-port"))
- }
-
- if port < 1 || port > 65536 {
- errors = append(errors, fmt.Errorf("%q must be a valid port number (1-65536) or %q", k, "traffic-port"))
- }
-
- return
-}
-
-func validateAwsAlbTargetGroupHealthCheckHealthyThreshold(v interface{}, k string) (ws []string, errors []error) {
- value := v.(int)
- if value < 2 || value > 10 {
- errors = append(errors, fmt.Errorf("%q must be an integer between 2 and 10", k))
- }
- return
-}
-
-func validateAwsAlbTargetGroupHealthCheckTimeout(v interface{}, k string) (ws []string, errors []error) {
- value := v.(int)
- if value < 2 || value > 60 {
- errors = append(errors, fmt.Errorf("%q must be an integer between 2 and 60", k))
- }
- return
-}
-
-func validateAwsAlbTargetGroupHealthCheckProtocol(v interface{}, k string) (ws []string, errors []error) {
- value := strings.ToLower(v.(string))
- if value == "http" || value == "https" {
- return
- }
-
- errors = append(errors, fmt.Errorf("%q must be either %q or %q", k, "HTTP", "HTTPS"))
- return
-}
-
-func validateAwsAlbTargetGroupPort(v interface{}, k string) (ws []string, errors []error) {
- port := v.(int)
- if port < 1 || port > 65536 {
- errors = append(errors, fmt.Errorf("%q must be a valid port number (1-65536)", k))
- }
- return
-}
-
-func validateAwsAlbTargetGroupProtocol(v interface{}, k string) (ws []string, errors []error) {
- protocol := strings.ToLower(v.(string))
- if protocol == "http" || protocol == "https" {
- return
- }
-
- errors = append(errors, fmt.Errorf("%q must be either %q or %q", k, "HTTP", "HTTPS"))
- return
-}
-
-func validateAwsAlbTargetGroupDeregistrationDelay(v interface{}, k string) (ws []string, errors []error) {
- delay := v.(int)
- if delay < 0 || delay > 3600 {
- errors = append(errors, fmt.Errorf("%q must be in the range 0-3600 seconds", k))
- }
- return
-}
-
-func validateAwsAlbTargetGroupStickinessType(v interface{}, k string) (ws []string, errors []error) {
- stickinessType := v.(string)
- if stickinessType != "lb_cookie" {
- errors = append(errors, fmt.Errorf("%q must have the value %q", k, "lb_cookie"))
- }
- return
-}
-
-func validateAwsAlbTargetGroupStickinessCookieDuration(v interface{}, k string) (ws []string, errors []error) {
- duration := v.(int)
- if duration < 1 || duration > 604800 {
- errors = append(errors, fmt.Errorf("%q must be a between 1 second and 1 week (1-604800 seconds))", k))
- }
- return
-}
-
-func albTargetGroupSuffixFromARN(arn *string) string {
- if arn == nil {
- return ""
- }
-
- if arnComponents := regexp.MustCompile(`arn:.*:targetgroup/(.*)`).FindAllStringSubmatch(*arn, -1); len(arnComponents) == 1 {
- if len(arnComponents[0]) == 2 {
- return fmt.Sprintf("targetgroup/%s", arnComponents[0][1])
- }
- }
-
- return ""
-}
diff --git a/builtin/providers/aws/resource_aws_alb_target_group_attachment.go b/builtin/providers/aws/resource_aws_alb_target_group_attachment.go
deleted file mode 100644
index 55a3b7392..000000000
--- a/builtin/providers/aws/resource_aws_alb_target_group_attachment.go
+++ /dev/null
@@ -1,141 +0,0 @@
-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 resourceAwsAlbTargetGroupAttachment() *schema.Resource {
- return &schema.Resource{
- Create: resourceAwsAlbAttachmentCreate,
- Read: resourceAwsAlbAttachmentRead,
- Delete: resourceAwsAlbAttachmentDelete,
-
- 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,
- },
- },
- }
-}
-
-func resourceAwsAlbAttachmentCreate(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)))
- }
-
- 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 resourceAwsAlbAttachmentDelete(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)))
- }
-
- 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
-}
-
-// resourceAwsAlbAttachmentRead 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 resourceAwsAlbAttachmentRead(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)))
- }
-
- 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"
-}
diff --git a/builtin/providers/aws/resource_aws_alb_target_group_attachment_test.go b/builtin/providers/aws/resource_aws_alb_target_group_attachment_test.go
deleted file mode 100644
index 6ab8cab73..000000000
--- a/builtin/providers/aws/resource_aws_alb_target_group_attachment_test.go
+++ /dev/null
@@ -1,239 +0,0 @@
-package aws
-
-import (
- "errors"
- "fmt"
- "strconv"
- "testing"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/elbv2"
- "github.com/hashicorp/errwrap"
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAWSALBTargetGroupAttachment_basic(t *testing.T) {
- targetGroupName := fmt.Sprintf("test-target-group-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb_target_group.test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBTargetGroupAttachmentDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBTargetGroupAttachmentConfig_basic(targetGroupName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBTargetGroupAttachmentExists("aws_alb_target_group_attachment.test"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALBTargetGroupAttachment_withoutPort(t *testing.T) {
- targetGroupName := fmt.Sprintf("test-target-group-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb_target_group.test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBTargetGroupAttachmentDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBTargetGroupAttachmentConfigWithoutPort(targetGroupName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBTargetGroupAttachmentExists("aws_alb_target_group_attachment.test"),
- ),
- },
- },
- })
-}
-
-func testAccCheckAWSALBTargetGroupAttachmentExists(n string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return errors.New("No Target Group Attachment ID is set")
- }
-
- conn := testAccProvider.Meta().(*AWSClient).elbv2conn
-
- _, hasPort := rs.Primary.Attributes["port"]
- targetGroupArn, _ := rs.Primary.Attributes["target_group_arn"]
-
- target := &elbv2.TargetDescription{
- Id: aws.String(rs.Primary.Attributes["target_id"]),
- }
- if hasPort == true {
- port, _ := strconv.Atoi(rs.Primary.Attributes["port"])
- target.Port = aws.Int64(int64(port))
- }
-
- describe, err := conn.DescribeTargetHealth(&elbv2.DescribeTargetHealthInput{
- TargetGroupArn: aws.String(targetGroupArn),
- Targets: []*elbv2.TargetDescription{target},
- })
-
- if err != nil {
- return err
- }
-
- if len(describe.TargetHealthDescriptions) != 1 {
- return errors.New("Target Group Attachment not found")
- }
-
- return nil
- }
-}
-
-func testAccCheckAWSALBTargetGroupAttachmentDestroy(s *terraform.State) error {
- conn := testAccProvider.Meta().(*AWSClient).elbv2conn
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "aws_alb_target_group_attachment" {
- continue
- }
-
- _, hasPort := rs.Primary.Attributes["port"]
- targetGroupArn, _ := rs.Primary.Attributes["target_group_arn"]
-
- target := &elbv2.TargetDescription{
- Id: aws.String(rs.Primary.Attributes["target_id"]),
- }
- if hasPort == true {
- port, _ := strconv.Atoi(rs.Primary.Attributes["port"])
- target.Port = aws.Int64(int64(port))
- }
-
- describe, err := conn.DescribeTargetHealth(&elbv2.DescribeTargetHealthInput{
- TargetGroupArn: aws.String(targetGroupArn),
- Targets: []*elbv2.TargetDescription{target},
- })
- if err == nil {
- if len(describe.TargetHealthDescriptions) != 0 {
- return fmt.Errorf("Target Group Attachment %q still exists", rs.Primary.ID)
- }
- }
-
- // Verify the error
- if isTargetGroupNotFound(err) || isInvalidTarget(err) {
- return nil
- } else {
- return errwrap.Wrapf("Unexpected error checking ALB destroyed: {{err}}", err)
- }
- }
-
- return nil
-}
-
-func testAccAWSALBTargetGroupAttachmentConfigWithoutPort(targetGroupName string) string {
- return fmt.Sprintf(`
-resource "aws_alb_target_group_attachment" "test" {
- target_group_arn = "${aws_alb_target_group.test.arn}"
- target_id = "${aws_instance.test.id}"
-}
-
-resource "aws_instance" "test" {
- ami = "ami-f701cb97"
- instance_type = "t2.micro"
- subnet_id = "${aws_subnet.subnet.id}"
-}
-
-resource "aws_alb_target_group" "test" {
- name = "%s"
- port = 443
- protocol = "HTTPS"
- vpc_id = "${aws_vpc.test.id}"
-
- deregistration_delay = 200
-
- stickiness {
- type = "lb_cookie"
- cookie_duration = 10000
- }
-
- health_check {
- path = "/health"
- interval = 60
- port = 8081
- protocol = "HTTP"
- timeout = 3
- healthy_threshold = 3
- unhealthy_threshold = 3
- matcher = "200-299"
- }
-}
-
-resource "aws_subnet" "subnet" {
- cidr_block = "10.0.1.0/24"
- vpc_id = "${aws_vpc.test.id}"
-
-}
-
-resource "aws_vpc" "test" {
- cidr_block = "10.0.0.0/16"
- tags {
- Name = "testAccAWSALBTargetGroupAttachmentConfigWithoutPort"
- }
-}`, targetGroupName)
-}
-
-func testAccAWSALBTargetGroupAttachmentConfig_basic(targetGroupName string) string {
- return fmt.Sprintf(`
-resource "aws_alb_target_group_attachment" "test" {
- target_group_arn = "${aws_alb_target_group.test.arn}"
- target_id = "${aws_instance.test.id}"
- port = 80
-}
-
-resource "aws_instance" "test" {
- ami = "ami-f701cb97"
- instance_type = "t2.micro"
- subnet_id = "${aws_subnet.subnet.id}"
-}
-
-resource "aws_alb_target_group" "test" {
- name = "%s"
- port = 443
- protocol = "HTTPS"
- vpc_id = "${aws_vpc.test.id}"
-
- deregistration_delay = 200
-
- stickiness {
- type = "lb_cookie"
- cookie_duration = 10000
- }
-
- health_check {
- path = "/health"
- interval = 60
- port = 8081
- protocol = "HTTP"
- timeout = 3
- healthy_threshold = 3
- unhealthy_threshold = 3
- matcher = "200-299"
- }
-}
-
-resource "aws_subnet" "subnet" {
- cidr_block = "10.0.1.0/24"
- vpc_id = "${aws_vpc.test.id}"
-
-}
-
-resource "aws_vpc" "test" {
- cidr_block = "10.0.0.0/16"
- tags {
- Name = "testAccAWSALBTargetGroupAttachmentConfig_basic"
- }
-}`, targetGroupName)
-}
diff --git a/builtin/providers/aws/resource_aws_alb_target_group_test.go b/builtin/providers/aws/resource_aws_alb_target_group_test.go
deleted file mode 100644
index dc800cfd8..000000000
--- a/builtin/providers/aws/resource_aws_alb_target_group_test.go
+++ /dev/null
@@ -1,788 +0,0 @@
-package aws
-
-import (
- "errors"
- "fmt"
- "regexp"
- "testing"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/elbv2"
- "github.com/hashicorp/errwrap"
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestALBTargetGroupCloudwatchSuffixFromARN(t *testing.T) {
- cases := []struct {
- name string
- arn *string
- suffix string
- }{
- {
- name: "valid suffix",
- arn: aws.String(`arn:aws:elasticloadbalancing:us-east-1:123456:targetgroup/my-targets/73e2d6bc24d8a067`),
- suffix: `targetgroup/my-targets/73e2d6bc24d8a067`,
- },
- {
- name: "no suffix",
- arn: aws.String(`arn:aws:elasticloadbalancing:us-east-1:123456:targetgroup`),
- suffix: ``,
- },
- {
- name: "nil ARN",
- arn: nil,
- suffix: ``,
- },
- }
-
- for _, tc := range cases {
- actual := albTargetGroupSuffixFromARN(tc.arn)
- if actual != tc.suffix {
- t.Fatalf("bad suffix: %q\nExpected: %s\n Got: %s", tc.name, tc.suffix, actual)
- }
- }
-}
-
-func TestAccAWSALBTargetGroup_basic(t *testing.T) {
- var conf elbv2.TargetGroup
- targetGroupName := fmt.Sprintf("test-target-group-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb_target_group.test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBTargetGroupDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBTargetGroupConfig_basic(targetGroupName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &conf),
- resource.TestCheckResourceAttrSet("aws_alb_target_group.test", "arn"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "name", targetGroupName),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "port", "443"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "protocol", "HTTPS"),
- resource.TestCheckResourceAttrSet("aws_alb_target_group.test", "vpc_id"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "deregistration_delay", "200"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "stickiness.#", "1"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "stickiness.0.enabled", "true"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "stickiness.0.type", "lb_cookie"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "stickiness.0.cookie_duration", "10000"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.#", "1"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.path", "/health"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.interval", "60"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.port", "8081"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.protocol", "HTTP"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.timeout", "3"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.healthy_threshold", "3"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.unhealthy_threshold", "3"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.matcher", "200-299"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "tags.%", "1"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "tags.TestName", "TestAccAWSALBTargetGroup_basic"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALBTargetGroup_namePrefix(t *testing.T) {
- var conf elbv2.TargetGroup
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb_target_group.test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBTargetGroupDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBTargetGroupConfig_namePrefix,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &conf),
- resource.TestMatchResourceAttr("aws_alb_target_group.test", "name", regexp.MustCompile("^tf-")),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALBTargetGroup_generatedName(t *testing.T) {
- var conf elbv2.TargetGroup
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb_target_group.test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBTargetGroupDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBTargetGroupConfig_generatedName,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &conf),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALBTargetGroup_changeNameForceNew(t *testing.T) {
- var before, after elbv2.TargetGroup
- targetGroupNameBefore := fmt.Sprintf("test-target-group-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
- targetGroupNameAfter := fmt.Sprintf("test-target-group-%s", acctest.RandStringFromCharSet(4, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb_target_group.test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBTargetGroupDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBTargetGroupConfig_basic(targetGroupNameBefore),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &before),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "name", targetGroupNameBefore),
- ),
- },
- {
- Config: testAccAWSALBTargetGroupConfig_basic(targetGroupNameAfter),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &after),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "name", targetGroupNameAfter),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALBTargetGroup_changeProtocolForceNew(t *testing.T) {
- var before, after elbv2.TargetGroup
- targetGroupName := fmt.Sprintf("test-target-group-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb_target_group.test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBTargetGroupDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBTargetGroupConfig_basic(targetGroupName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &before),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "protocol", "HTTPS"),
- ),
- },
- {
- Config: testAccAWSALBTargetGroupConfig_updatedProtocol(targetGroupName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &after),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "protocol", "HTTP"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALBTargetGroup_changePortForceNew(t *testing.T) {
- var before, after elbv2.TargetGroup
- targetGroupName := fmt.Sprintf("test-target-group-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb_target_group.test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBTargetGroupDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBTargetGroupConfig_basic(targetGroupName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &before),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "port", "443"),
- ),
- },
- {
- Config: testAccAWSALBTargetGroupConfig_updatedPort(targetGroupName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &after),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "port", "442"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALBTargetGroup_changeVpcForceNew(t *testing.T) {
- var before, after elbv2.TargetGroup
- targetGroupName := fmt.Sprintf("test-target-group-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb_target_group.test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBTargetGroupDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBTargetGroupConfig_basic(targetGroupName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &before),
- ),
- },
- {
- Config: testAccAWSALBTargetGroupConfig_updatedVpc(targetGroupName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &after),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALBTargetGroup_tags(t *testing.T) {
- var conf elbv2.TargetGroup
- targetGroupName := fmt.Sprintf("test-target-group-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb_target_group.test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBTargetGroupDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBTargetGroupConfig_basic(targetGroupName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &conf),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "tags.%", "1"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "tags.TestName", "TestAccAWSALBTargetGroup_basic"),
- ),
- },
- {
- Config: testAccAWSALBTargetGroupConfig_updateTags(targetGroupName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &conf),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "tags.%", "2"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "tags.Environment", "Production"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "tags.Type", "ALB Target Group"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALBTargetGroup_updateHealthCheck(t *testing.T) {
- var conf elbv2.TargetGroup
- targetGroupName := fmt.Sprintf("test-target-group-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb_target_group.test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBTargetGroupDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBTargetGroupConfig_basic(targetGroupName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &conf),
- resource.TestCheckResourceAttrSet("aws_alb_target_group.test", "arn"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "name", targetGroupName),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "port", "443"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "protocol", "HTTPS"),
- resource.TestCheckResourceAttrSet("aws_alb_target_group.test", "vpc_id"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "deregistration_delay", "200"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "stickiness.#", "1"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "stickiness.0.type", "lb_cookie"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "stickiness.0.cookie_duration", "10000"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.#", "1"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.path", "/health"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.interval", "60"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.port", "8081"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.protocol", "HTTP"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.timeout", "3"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.healthy_threshold", "3"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.unhealthy_threshold", "3"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.matcher", "200-299"),
- ),
- },
- {
- Config: testAccAWSALBTargetGroupConfig_updateHealthCheck(targetGroupName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &conf),
- resource.TestCheckResourceAttrSet("aws_alb_target_group.test", "arn"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "name", targetGroupName),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "port", "443"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "protocol", "HTTPS"),
- resource.TestCheckResourceAttrSet("aws_alb_target_group.test", "vpc_id"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "deregistration_delay", "200"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "stickiness.#", "1"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "stickiness.0.type", "lb_cookie"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "stickiness.0.cookie_duration", "10000"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.#", "1"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.path", "/health2"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.interval", "30"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.port", "8082"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.protocol", "HTTPS"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.timeout", "4"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.healthy_threshold", "4"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.unhealthy_threshold", "4"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.matcher", "200"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALBTargetGroup_updateSticknessEnabled(t *testing.T) {
- var conf elbv2.TargetGroup
- targetGroupName := fmt.Sprintf("test-target-group-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb_target_group.test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBTargetGroupDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBTargetGroupConfig_stickiness(targetGroupName, false, false),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &conf),
- resource.TestCheckResourceAttrSet("aws_alb_target_group.test", "arn"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "name", targetGroupName),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "port", "443"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "protocol", "HTTPS"),
- resource.TestCheckResourceAttrSet("aws_alb_target_group.test", "vpc_id"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "deregistration_delay", "200"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.#", "1"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.path", "/health2"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.interval", "30"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.port", "8082"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.protocol", "HTTPS"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.timeout", "4"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.healthy_threshold", "4"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.unhealthy_threshold", "4"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.matcher", "200"),
- ),
- },
- {
- Config: testAccAWSALBTargetGroupConfig_stickiness(targetGroupName, true, true),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &conf),
- resource.TestCheckResourceAttrSet("aws_alb_target_group.test", "arn"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "name", targetGroupName),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "port", "443"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "protocol", "HTTPS"),
- resource.TestCheckResourceAttrSet("aws_alb_target_group.test", "vpc_id"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "deregistration_delay", "200"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "stickiness.#", "1"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "stickiness.0.enabled", "true"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "stickiness.0.type", "lb_cookie"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "stickiness.0.cookie_duration", "10000"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.#", "1"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.path", "/health2"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.interval", "30"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.port", "8082"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.protocol", "HTTPS"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.timeout", "4"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.healthy_threshold", "4"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.unhealthy_threshold", "4"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.matcher", "200"),
- ),
- },
- {
- Config: testAccAWSALBTargetGroupConfig_stickiness(targetGroupName, true, false),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBTargetGroupExists("aws_alb_target_group.test", &conf),
- resource.TestCheckResourceAttrSet("aws_alb_target_group.test", "arn"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "name", targetGroupName),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "port", "443"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "protocol", "HTTPS"),
- resource.TestCheckResourceAttrSet("aws_alb_target_group.test", "vpc_id"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "deregistration_delay", "200"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "stickiness.#", "1"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "stickiness.0.enabled", "false"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "stickiness.0.type", "lb_cookie"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "stickiness.0.cookie_duration", "10000"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.#", "1"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.path", "/health2"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.interval", "30"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.port", "8082"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.protocol", "HTTPS"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.timeout", "4"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.healthy_threshold", "4"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.unhealthy_threshold", "4"),
- resource.TestCheckResourceAttr("aws_alb_target_group.test", "health_check.0.matcher", "200"),
- ),
- },
- },
- })
-}
-
-func testAccCheckAWSALBTargetGroupExists(n string, res *elbv2.TargetGroup) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return errors.New("No Target Group ID is set")
- }
-
- conn := testAccProvider.Meta().(*AWSClient).elbv2conn
-
- describe, err := conn.DescribeTargetGroups(&elbv2.DescribeTargetGroupsInput{
- TargetGroupArns: []*string{aws.String(rs.Primary.ID)},
- })
-
- if err != nil {
- return err
- }
-
- if len(describe.TargetGroups) != 1 ||
- *describe.TargetGroups[0].TargetGroupArn != rs.Primary.ID {
- return errors.New("Target Group not found")
- }
-
- *res = *describe.TargetGroups[0]
- return nil
- }
-}
-
-func testAccCheckAWSALBTargetGroupDestroy(s *terraform.State) error {
- conn := testAccProvider.Meta().(*AWSClient).elbv2conn
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "aws_alb_target_group" {
- continue
- }
-
- describe, err := conn.DescribeTargetGroups(&elbv2.DescribeTargetGroupsInput{
- TargetGroupArns: []*string{aws.String(rs.Primary.ID)},
- })
-
- if err == nil {
- if len(describe.TargetGroups) != 0 &&
- *describe.TargetGroups[0].TargetGroupArn == rs.Primary.ID {
- return fmt.Errorf("Target Group %q still exists", rs.Primary.ID)
- }
- }
-
- // Verify the error
- if isTargetGroupNotFound(err) {
- return nil
- } else {
- return errwrap.Wrapf("Unexpected error checking ALB destroyed: {{err}}", err)
- }
- }
-
- return nil
-}
-
-func testAccAWSALBTargetGroupConfig_basic(targetGroupName string) string {
- return fmt.Sprintf(`resource "aws_alb_target_group" "test" {
- name = "%s"
- port = 443
- protocol = "HTTPS"
- vpc_id = "${aws_vpc.test.id}"
-
- deregistration_delay = 200
-
- stickiness {
- type = "lb_cookie"
- cookie_duration = 10000
- }
-
- health_check {
- path = "/health"
- interval = 60
- port = 8081
- protocol = "HTTP"
- timeout = 3
- healthy_threshold = 3
- unhealthy_threshold = 3
- matcher = "200-299"
- }
-
- tags {
- TestName = "TestAccAWSALBTargetGroup_basic"
- }
-}
-
-resource "aws_vpc" "test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALBTargetGroup_basic"
- }
-}`, targetGroupName)
-}
-
-func testAccAWSALBTargetGroupConfig_updatedPort(targetGroupName string) string {
- return fmt.Sprintf(`resource "aws_alb_target_group" "test" {
- name = "%s"
- port = 442
- protocol = "HTTPS"
- vpc_id = "${aws_vpc.test.id}"
-
- deregistration_delay = 200
-
- stickiness {
- type = "lb_cookie"
- cookie_duration = 10000
- }
-
- health_check {
- path = "/health"
- interval = 60
- port = 8081
- protocol = "HTTP"
- timeout = 3
- healthy_threshold = 3
- unhealthy_threshold = 3
- matcher = "200-299"
- }
-
- tags {
- TestName = "TestAccAWSALBTargetGroup_basic"
- }
-}
-
-resource "aws_vpc" "test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALBTargetGroup_basic"
- }
-}`, targetGroupName)
-}
-
-func testAccAWSALBTargetGroupConfig_updatedProtocol(targetGroupName string) string {
- return fmt.Sprintf(`resource "aws_alb_target_group" "test" {
- name = "%s"
- port = 443
- protocol = "HTTP"
- vpc_id = "${aws_vpc.test2.id}"
-
- deregistration_delay = 200
-
- stickiness {
- type = "lb_cookie"
- cookie_duration = 10000
- }
-
- health_check {
- path = "/health"
- interval = 60
- port = 8081
- protocol = "HTTP"
- timeout = 3
- healthy_threshold = 3
- unhealthy_threshold = 3
- matcher = "200-299"
- }
-
- tags {
- TestName = "TestAccAWSALBTargetGroup_basic"
- }
-}
-
-resource "aws_vpc" "test2" {
- cidr_block = "10.10.0.0/16"
-
- tags {
- TestName = "TestAccAWSALBTargetGroup_basic"
- }
-}
-
-resource "aws_vpc" "test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALBTargetGroup_basic"
- }
-}`, targetGroupName)
-}
-
-func testAccAWSALBTargetGroupConfig_updatedVpc(targetGroupName string) string {
- return fmt.Sprintf(`resource "aws_alb_target_group" "test" {
- name = "%s"
- port = 443
- protocol = "HTTPS"
- vpc_id = "${aws_vpc.test.id}"
-
- deregistration_delay = 200
-
- stickiness {
- type = "lb_cookie"
- cookie_duration = 10000
- }
-
- health_check {
- path = "/health"
- interval = 60
- port = 8081
- protocol = "HTTP"
- timeout = 3
- healthy_threshold = 3
- unhealthy_threshold = 3
- matcher = "200-299"
- }
-
- tags {
- TestName = "TestAccAWSALBTargetGroup_basic"
- }
-}
-
-resource "aws_vpc" "test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALBTargetGroup_basic"
- }
-}`, targetGroupName)
-}
-
-func testAccAWSALBTargetGroupConfig_updateTags(targetGroupName string) string {
- return fmt.Sprintf(`resource "aws_alb_target_group" "test" {
- name = "%s"
- port = 443
- protocol = "HTTPS"
- vpc_id = "${aws_vpc.test.id}"
-
- deregistration_delay = 200
-
- stickiness {
- type = "lb_cookie"
- cookie_duration = 10000
- }
-
- health_check {
- path = "/health"
- interval = 60
- port = 8081
- protocol = "HTTP"
- timeout = 3
- healthy_threshold = 3
- unhealthy_threshold = 3
- matcher = "200-299"
- }
-
- tags {
- Environment = "Production"
- Type = "ALB Target Group"
- }
-}
-
-resource "aws_vpc" "test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALBTargetGroup_basic"
- }
-}`, targetGroupName)
-}
-
-func testAccAWSALBTargetGroupConfig_updateHealthCheck(targetGroupName string) string {
- return fmt.Sprintf(`resource "aws_alb_target_group" "test" {
- name = "%s"
- port = 443
- protocol = "HTTPS"
- vpc_id = "${aws_vpc.test.id}"
-
- deregistration_delay = 200
-
- stickiness {
- type = "lb_cookie"
- cookie_duration = 10000
- }
-
- health_check {
- path = "/health2"
- interval = 30
- port = 8082
- protocol = "HTTPS"
- timeout = 4
- healthy_threshold = 4
- unhealthy_threshold = 4
- matcher = "200"
- }
-}
-
-resource "aws_vpc" "test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALBTargetGroup_basic"
- }
-}`, targetGroupName)
-}
-
-func testAccAWSALBTargetGroupConfig_stickiness(targetGroupName string, addStickinessBlock bool, enabled bool) string {
- var stickinessBlock string
-
- if addStickinessBlock {
- stickinessBlock = fmt.Sprintf(`stickiness {
- enabled = "%t"
- type = "lb_cookie"
- cookie_duration = 10000
- }`, enabled)
- }
-
- return fmt.Sprintf(`resource "aws_alb_target_group" "test" {
- name = "%s"
- port = 443
- protocol = "HTTPS"
- vpc_id = "${aws_vpc.test.id}"
-
- deregistration_delay = 200
-
- %s
-
- health_check {
- path = "/health2"
- interval = 30
- port = 8082
- protocol = "HTTPS"
- timeout = 4
- healthy_threshold = 4
- unhealthy_threshold = 4
- matcher = "200"
- }
-}
-
-resource "aws_vpc" "test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALBTargetGroup_stickiness"
- }
-}`, targetGroupName, stickinessBlock)
-}
-
-const testAccAWSALBTargetGroupConfig_namePrefix = `
-resource "aws_alb_target_group" "test" {
- name_prefix = "tf-"
- port = 80
- protocol = "HTTP"
- vpc_id = "${aws_vpc.test.id}"
-}
-
-resource "aws_vpc" "test" {
- cidr_block = "10.0.0.0/16"
- tags {
- Name = "testAccAWSALBTargetGroupConfig_namePrefix"
- }
-}
-`
-
-const testAccAWSALBTargetGroupConfig_generatedName = `
-resource "aws_alb_target_group" "test" {
- port = 80
- protocol = "HTTP"
- vpc_id = "${aws_vpc.test.id}"
-}
-
-resource "aws_vpc" "test" {
- cidr_block = "10.0.0.0/16"
- tags {
- Name = "testAccAWSALBTargetGroupConfig_generatedName"
- }
-}
-`
diff --git a/builtin/providers/aws/resource_aws_alb_test.go b/builtin/providers/aws/resource_aws_alb_test.go
deleted file mode 100644
index 5e766d74b..000000000
--- a/builtin/providers/aws/resource_aws_alb_test.go
+++ /dev/null
@@ -1,1317 +0,0 @@
-package aws
-
-import (
- "errors"
- "fmt"
- "regexp"
- "testing"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/elbv2"
- "github.com/hashicorp/errwrap"
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestALBCloudwatchSuffixFromARN(t *testing.T) {
- cases := []struct {
- name string
- arn *string
- suffix string
- }{
- {
- name: "valid suffix",
- arn: aws.String(`arn:aws:elasticloadbalancing:us-east-1:123456:loadbalancer/app/my-alb/abc123`),
- suffix: `app/my-alb/abc123`,
- },
- {
- name: "no suffix",
- arn: aws.String(`arn:aws:elasticloadbalancing:us-east-1:123456:loadbalancer`),
- suffix: ``,
- },
- {
- name: "nil ARN",
- arn: nil,
- suffix: ``,
- },
- }
-
- for _, tc := range cases {
- actual := albSuffixFromARN(tc.arn)
- if actual != tc.suffix {
- t.Fatalf("bad suffix: %q\nExpected: %s\n Got: %s", tc.name, tc.suffix, actual)
- }
- }
-}
-
-func TestAccAWSALB_basic(t *testing.T) {
- var conf elbv2.LoadBalancer
- albName := fmt.Sprintf("testaccawsalb-basic-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb.alb_test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBConfig_basic(albName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBExists("aws_alb.alb_test", &conf),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "name", albName),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "internal", "true"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "subnets.#", "2"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "security_groups.#", "1"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "tags.%", "1"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "tags.TestName", "TestAccAWSALB_basic"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "enable_deletion_protection", "false"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "idle_timeout", "30"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "ip_address_type", "ipv4"),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "vpc_id"),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "zone_id"),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "dns_name"),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "arn"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALB_generatedName(t *testing.T) {
- var conf elbv2.LoadBalancer
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb.alb_test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBConfig_generatedName(),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBExists("aws_alb.alb_test", &conf),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "name"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALB_generatesNameForZeroValue(t *testing.T) {
- var conf elbv2.LoadBalancer
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb.alb_test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBConfig_zeroValueName(),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBExists("aws_alb.alb_test", &conf),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "name"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALB_namePrefix(t *testing.T) {
- var conf elbv2.LoadBalancer
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb.alb_test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBConfig_namePrefix(),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBExists("aws_alb.alb_test", &conf),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "name"),
- resource.TestMatchResourceAttr("aws_alb.alb_test", "name",
- regexp.MustCompile("^tf-lb-")),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALB_tags(t *testing.T) {
- var conf elbv2.LoadBalancer
- albName := fmt.Sprintf("testaccawsalb-basic-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb.alb_test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBConfig_basic(albName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBExists("aws_alb.alb_test", &conf),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "tags.%", "1"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "tags.TestName", "TestAccAWSALB_basic"),
- ),
- },
- {
- Config: testAccAWSALBConfig_updatedTags(albName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBExists("aws_alb.alb_test", &conf),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "tags.%", "2"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "tags.Type", "Sample Type Tag"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "tags.Environment", "Production"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALB_updatedSecurityGroups(t *testing.T) {
- var pre, post elbv2.LoadBalancer
- albName := fmt.Sprintf("testaccawsalb-basic-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb.alb_test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBConfig_basic(albName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBExists("aws_alb.alb_test", &pre),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "security_groups.#", "1"),
- ),
- },
- {
- Config: testAccAWSALBConfig_updateSecurityGroups(albName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBExists("aws_alb.alb_test", &post),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "security_groups.#", "2"),
- testAccCheckAWSAlbARNs(&pre, &post),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALB_updatedSubnets(t *testing.T) {
- var pre, post elbv2.LoadBalancer
- albName := fmt.Sprintf("testaccawsalb-basic-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb.alb_test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBConfig_basic(albName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBExists("aws_alb.alb_test", &pre),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "subnets.#", "2"),
- ),
- },
- {
- Config: testAccAWSALBConfig_updateSubnets(albName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBExists("aws_alb.alb_test", &post),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "subnets.#", "3"),
- testAccCheckAWSAlbARNs(&pre, &post),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALB_updatedIpAddressType(t *testing.T) {
- var pre, post elbv2.LoadBalancer
- albName := fmt.Sprintf("testaccawsalb-basic-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb.alb_test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBConfigWithIpAddressType(albName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBExists("aws_alb.alb_test", &pre),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "ip_address_type", "ipv4"),
- ),
- },
- {
- Config: testAccAWSALBConfigWithIpAddressTypeUpdated(albName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBExists("aws_alb.alb_test", &post),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "ip_address_type", "dualstack"),
- ),
- },
- },
- })
-}
-
-// TestAccAWSALB_noSecurityGroup regression tests the issue in #8264,
-// where if an ALB is created without a security group, a default one
-// is assigned.
-func TestAccAWSALB_noSecurityGroup(t *testing.T) {
- var conf elbv2.LoadBalancer
- albName := fmt.Sprintf("testaccawsalb-nosg-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb.alb_test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBConfig_nosg(albName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBExists("aws_alb.alb_test", &conf),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "name", albName),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "internal", "true"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "subnets.#", "2"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "security_groups.#", "1"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "tags.%", "1"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "tags.TestName", "TestAccAWSALB_basic"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "enable_deletion_protection", "false"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "idle_timeout", "30"),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "vpc_id"),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "zone_id"),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "dns_name"),
- ),
- },
- },
- })
-}
-
-func TestAccAWSALB_accesslogs(t *testing.T) {
- var conf elbv2.LoadBalancer
- bucketName := fmt.Sprintf("testaccawsalbaccesslogs-%s", acctest.RandStringFromCharSet(6, acctest.CharSetAlphaNum))
- albName := fmt.Sprintf("testaccawsalbaccesslog-%s", acctest.RandStringFromCharSet(4, acctest.CharSetAlpha))
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_alb.alb_test",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSALBDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSALBConfig_basic(albName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBExists("aws_alb.alb_test", &conf),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "name", albName),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "internal", "true"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "subnets.#", "2"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "security_groups.#", "1"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "tags.%", "1"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "tags.TestName", "TestAccAWSALB_basic"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "enable_deletion_protection", "false"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "idle_timeout", "30"),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "vpc_id"),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "zone_id"),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "dns_name"),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "arn"),
- ),
- },
- {
- Config: testAccAWSALBConfig_accessLogs(true, albName, bucketName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBExists("aws_alb.alb_test", &conf),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "name", albName),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "internal", "true"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "subnets.#", "2"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "security_groups.#", "1"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "tags.%", "1"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "tags.TestName", "TestAccAWSALB_basic1"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "enable_deletion_protection", "false"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "idle_timeout", "50"),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "vpc_id"),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "zone_id"),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "dns_name"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "access_logs.#", "1"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "access_logs.0.bucket", bucketName),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "access_logs.0.prefix", "testAccAWSALBConfig_accessLogs"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "access_logs.0.enabled", "true"),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "arn"),
- ),
- },
- {
- Config: testAccAWSALBConfig_accessLogs(false, albName, bucketName),
- Check: resource.ComposeAggregateTestCheckFunc(
- testAccCheckAWSALBExists("aws_alb.alb_test", &conf),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "name", albName),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "internal", "true"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "subnets.#", "2"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "security_groups.#", "1"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "tags.%", "1"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "tags.TestName", "TestAccAWSALB_basic1"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "enable_deletion_protection", "false"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "idle_timeout", "50"),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "vpc_id"),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "zone_id"),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "dns_name"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "access_logs.#", "1"),
- resource.TestCheckResourceAttr("aws_alb.alb_test", "access_logs.0.enabled", "false"),
- resource.TestCheckResourceAttrSet("aws_alb.alb_test", "arn"),
- ),
- },
- },
- })
-}
-
-func testAccCheckAWSAlbARNs(pre, post *elbv2.LoadBalancer) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- if *pre.LoadBalancerArn != *post.LoadBalancerArn {
- return errors.New("ALB has been recreated. ARNs are different")
- }
-
- return nil
- }
-}
-
-func testAccCheckAWSALBExists(n string, res *elbv2.LoadBalancer) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return errors.New("No ALB ID is set")
- }
-
- conn := testAccProvider.Meta().(*AWSClient).elbv2conn
-
- describe, err := conn.DescribeLoadBalancers(&elbv2.DescribeLoadBalancersInput{
- LoadBalancerArns: []*string{aws.String(rs.Primary.ID)},
- })
-
- if err != nil {
- return err
- }
-
- if len(describe.LoadBalancers) != 1 ||
- *describe.LoadBalancers[0].LoadBalancerArn != rs.Primary.ID {
- return errors.New("ALB not found")
- }
-
- *res = *describe.LoadBalancers[0]
- return nil
- }
-}
-
-func testAccCheckAWSALBDestroy(s *terraform.State) error {
- conn := testAccProvider.Meta().(*AWSClient).elbv2conn
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "aws_alb" {
- continue
- }
-
- describe, err := conn.DescribeLoadBalancers(&elbv2.DescribeLoadBalancersInput{
- LoadBalancerArns: []*string{aws.String(rs.Primary.ID)},
- })
-
- if err == nil {
- if len(describe.LoadBalancers) != 0 &&
- *describe.LoadBalancers[0].LoadBalancerArn == rs.Primary.ID {
- return fmt.Errorf("ALB %q still exists", rs.Primary.ID)
- }
- }
-
- // Verify the error
- if isLoadBalancerNotFound(err) {
- return nil
- } else {
- return errwrap.Wrapf("Unexpected error checking ALB destroyed: {{err}}", err)
- }
- }
-
- return nil
-}
-
-func testAccAWSALBConfigWithIpAddressTypeUpdated(albName string) string {
- return fmt.Sprintf(`resource "aws_alb" "alb_test" {
- name = "%s"
- security_groups = ["${aws_security_group.alb_test.id}"]
- subnets = ["${aws_subnet.alb_test_1.id}", "${aws_subnet.alb_test_2.id}"]
-
- ip_address_type = "dualstack"
-
- idle_timeout = 30
- enable_deletion_protection = false
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_alb_listener" "test" {
- load_balancer_arn = "${aws_alb.alb_test.id}"
- protocol = "HTTP"
- port = "80"
-
- default_action {
- target_group_arn = "${aws_alb_target_group.test.id}"
- type = "forward"
- }
-}
-
-resource "aws_alb_target_group" "test" {
- name = "%s"
- port = 80
- protocol = "HTTP"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- deregistration_delay = 200
-
- stickiness {
- type = "lb_cookie"
- cookie_duration = 10000
- }
-
- health_check {
- path = "/health2"
- interval = 30
- port = 8082
- protocol = "HTTPS"
- timeout = 4
- healthy_threshold = 4
- unhealthy_threshold = 4
- matcher = "200"
- }
-}
-
-resource "aws_egress_only_internet_gateway" "igw" {
- vpc_id = "${aws_vpc.alb_test.id}"
-}
-
-resource "aws_vpc" "alb_test" {
- cidr_block = "10.0.0.0/16"
- assign_generated_ipv6_cidr_block = true
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_internet_gateway" "foo" {
- vpc_id = "${aws_vpc.alb_test.id}"
-}
-
-resource "aws_subnet" "alb_test_1" {
- vpc_id = "${aws_vpc.alb_test.id}"
- cidr_block = "10.0.1.0/24"
- map_public_ip_on_launch = true
- availability_zone = "us-west-2a"
- ipv6_cidr_block = "${cidrsubnet(aws_vpc.alb_test.ipv6_cidr_block, 8, 1)}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_subnet" "alb_test_2" {
- vpc_id = "${aws_vpc.alb_test.id}"
- cidr_block = "10.0.2.0/24"
- map_public_ip_on_launch = true
- availability_zone = "us-west-2b"
- ipv6_cidr_block = "${cidrsubnet(aws_vpc.alb_test.ipv6_cidr_block, 8, 2)}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_security_group" "alb_test" {
- name = "allow_all_alb_test"
- description = "Used for ALB Testing"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- ingress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}`, albName, albName)
-}
-
-func testAccAWSALBConfigWithIpAddressType(albName string) string {
- return fmt.Sprintf(`resource "aws_alb" "alb_test" {
- name = "%s"
- security_groups = ["${aws_security_group.alb_test.id}"]
- subnets = ["${aws_subnet.alb_test_1.id}", "${aws_subnet.alb_test_2.id}"]
-
- ip_address_type = "ipv4"
-
- idle_timeout = 30
- enable_deletion_protection = false
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_alb_listener" "test" {
- load_balancer_arn = "${aws_alb.alb_test.id}"
- protocol = "HTTP"
- port = "80"
-
- default_action {
- target_group_arn = "${aws_alb_target_group.test.id}"
- type = "forward"
- }
-}
-
-resource "aws_alb_target_group" "test" {
- name = "%s"
- port = 80
- protocol = "HTTP"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- deregistration_delay = 200
-
- stickiness {
- type = "lb_cookie"
- cookie_duration = 10000
- }
-
- health_check {
- path = "/health2"
- interval = 30
- port = 8082
- protocol = "HTTPS"
- timeout = 4
- healthy_threshold = 4
- unhealthy_threshold = 4
- matcher = "200"
- }
-}
-
-resource "aws_egress_only_internet_gateway" "igw" {
- vpc_id = "${aws_vpc.alb_test.id}"
-}
-
-resource "aws_vpc" "alb_test" {
- cidr_block = "10.0.0.0/16"
- assign_generated_ipv6_cidr_block = true
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_internet_gateway" "foo" {
- vpc_id = "${aws_vpc.alb_test.id}"
-}
-
-resource "aws_subnet" "alb_test_1" {
- vpc_id = "${aws_vpc.alb_test.id}"
- cidr_block = "10.0.1.0/24"
- map_public_ip_on_launch = true
- availability_zone = "us-west-2a"
- ipv6_cidr_block = "${cidrsubnet(aws_vpc.alb_test.ipv6_cidr_block, 8, 1)}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_subnet" "alb_test_2" {
- vpc_id = "${aws_vpc.alb_test.id}"
- cidr_block = "10.0.2.0/24"
- map_public_ip_on_launch = true
- availability_zone = "us-west-2b"
- ipv6_cidr_block = "${cidrsubnet(aws_vpc.alb_test.ipv6_cidr_block, 8, 2)}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_security_group" "alb_test" {
- name = "allow_all_alb_test"
- description = "Used for ALB Testing"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- ingress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}`, albName, albName)
-}
-
-func testAccAWSALBConfig_basic(albName string) string {
- return fmt.Sprintf(`resource "aws_alb" "alb_test" {
- name = "%s"
- internal = true
- security_groups = ["${aws_security_group.alb_test.id}"]
- subnets = ["${aws_subnet.alb_test.*.id}"]
-
- idle_timeout = 30
- enable_deletion_protection = false
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-variable "subnets" {
- default = ["10.0.1.0/24", "10.0.2.0/24"]
- type = "list"
-}
-
-data "aws_availability_zones" "available" {}
-
-resource "aws_vpc" "alb_test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_subnet" "alb_test" {
- count = 2
- vpc_id = "${aws_vpc.alb_test.id}"
- cidr_block = "${element(var.subnets, count.index)}"
- map_public_ip_on_launch = true
- availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_security_group" "alb_test" {
- name = "allow_all_alb_test"
- description = "Used for ALB Testing"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- ingress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- egress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}`, albName)
-}
-
-func testAccAWSALBConfig_updateSubnets(albName string) string {
- return fmt.Sprintf(`resource "aws_alb" "alb_test" {
- name = "%s"
- internal = true
- security_groups = ["${aws_security_group.alb_test.id}"]
- subnets = ["${aws_subnet.alb_test.*.id}"]
-
- idle_timeout = 30
- enable_deletion_protection = false
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-variable "subnets" {
- default = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
- type = "list"
-}
-
-data "aws_availability_zones" "available" {}
-
-resource "aws_vpc" "alb_test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_subnet" "alb_test" {
- count = 3
- vpc_id = "${aws_vpc.alb_test.id}"
- cidr_block = "${element(var.subnets, count.index)}"
- map_public_ip_on_launch = true
- availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_security_group" "alb_test" {
- name = "allow_all_alb_test"
- description = "Used for ALB Testing"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- ingress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- egress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}`, albName)
-}
-
-func testAccAWSALBConfig_generatedName() string {
- return fmt.Sprintf(`
-resource "aws_alb" "alb_test" {
- internal = true
- security_groups = ["${aws_security_group.alb_test.id}"]
- subnets = ["${aws_subnet.alb_test.*.id}"]
-
- idle_timeout = 30
- enable_deletion_protection = false
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-variable "subnets" {
- default = ["10.0.1.0/24", "10.0.2.0/24"]
- type = "list"
-}
-
-data "aws_availability_zones" "available" {}
-
-resource "aws_vpc" "alb_test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_internet_gateway" "gw" {
- vpc_id = "${aws_vpc.alb_test.id}"
-
- tags {
- Name = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_subnet" "alb_test" {
- count = 2
- vpc_id = "${aws_vpc.alb_test.id}"
- cidr_block = "${element(var.subnets, count.index)}"
- map_public_ip_on_launch = true
- availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_security_group" "alb_test" {
- name = "allow_all_alb_test"
- description = "Used for ALB Testing"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- ingress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- egress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}`)
-}
-
-func testAccAWSALBConfig_zeroValueName() string {
- return fmt.Sprintf(`
-resource "aws_alb" "alb_test" {
- name = ""
- internal = true
- security_groups = ["${aws_security_group.alb_test.id}"]
- subnets = ["${aws_subnet.alb_test.*.id}"]
-
- idle_timeout = 30
- enable_deletion_protection = false
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-variable "subnets" {
- default = ["10.0.1.0/24", "10.0.2.0/24"]
- type = "list"
-}
-
-data "aws_availability_zones" "available" {}
-
-resource "aws_vpc" "alb_test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_internet_gateway" "gw" {
- vpc_id = "${aws_vpc.alb_test.id}"
-
- tags {
- Name = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_subnet" "alb_test" {
- count = 2
- vpc_id = "${aws_vpc.alb_test.id}"
- cidr_block = "${element(var.subnets, count.index)}"
- map_public_ip_on_launch = true
- availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_security_group" "alb_test" {
- name = "allow_all_alb_test"
- description = "Used for ALB Testing"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- ingress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- egress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}`)
-}
-
-func testAccAWSALBConfig_namePrefix() string {
- return fmt.Sprintf(`
-resource "aws_alb" "alb_test" {
- name_prefix = "tf-lb-"
- internal = true
- security_groups = ["${aws_security_group.alb_test.id}"]
- subnets = ["${aws_subnet.alb_test.*.id}"]
-
- idle_timeout = 30
- enable_deletion_protection = false
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-variable "subnets" {
- default = ["10.0.1.0/24", "10.0.2.0/24"]
- type = "list"
-}
-
-data "aws_availability_zones" "available" {}
-
-resource "aws_vpc" "alb_test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_subnet" "alb_test" {
- count = 2
- vpc_id = "${aws_vpc.alb_test.id}"
- cidr_block = "${element(var.subnets, count.index)}"
- map_public_ip_on_launch = true
- availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_security_group" "alb_test" {
- name = "allow_all_alb_test"
- description = "Used for ALB Testing"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- ingress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- egress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}`)
-}
-func testAccAWSALBConfig_updatedTags(albName string) string {
- return fmt.Sprintf(`resource "aws_alb" "alb_test" {
- name = "%s"
- internal = true
- security_groups = ["${aws_security_group.alb_test.id}"]
- subnets = ["${aws_subnet.alb_test.*.id}"]
-
- idle_timeout = 30
- enable_deletion_protection = false
-
- tags {
- Environment = "Production"
- Type = "Sample Type Tag"
- }
-}
-
-variable "subnets" {
- default = ["10.0.1.0/24", "10.0.2.0/24"]
- type = "list"
-}
-
-data "aws_availability_zones" "available" {}
-
-resource "aws_vpc" "alb_test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_subnet" "alb_test" {
- count = 2
- vpc_id = "${aws_vpc.alb_test.id}"
- cidr_block = "${element(var.subnets, count.index)}"
- map_public_ip_on_launch = true
- availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_security_group" "alb_test" {
- name = "allow_all_alb_test"
- description = "Used for ALB Testing"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- ingress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- egress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}`, albName)
-}
-
-func testAccAWSALBConfig_accessLogs(enabled bool, albName, bucketName string) string {
- return fmt.Sprintf(`resource "aws_alb" "alb_test" {
- name = "%s"
- internal = true
- security_groups = ["${aws_security_group.alb_test.id}"]
- subnets = ["${aws_subnet.alb_test.*.id}"]
-
- idle_timeout = 50
- enable_deletion_protection = false
-
- access_logs {
- bucket = "${aws_s3_bucket.logs.bucket}"
- prefix = "${var.bucket_prefix}"
- enabled = "%t"
- }
-
- tags {
- TestName = "TestAccAWSALB_basic1"
- }
-}
-
-variable "bucket_name" {
- type = "string"
- default = "%s"
-}
-
-variable "bucket_prefix" {
- type = "string"
- default = "testAccAWSALBConfig_accessLogs"
-}
-
-resource "aws_s3_bucket" "logs" {
- bucket = "${var.bucket_name}"
- policy = "${data.aws_iam_policy_document.logs_bucket.json}"
- # dangerous, only here for the test...
- force_destroy = true
-
- tags {
- Name = "ALB Logs Bucket Test"
- }
-}
-
-data "aws_caller_identity" "current" {}
-
-data "aws_elb_service_account" "current" {}
-
-data "aws_iam_policy_document" "logs_bucket" {
- statement {
- actions = ["s3:PutObject"]
- effect = "Allow"
- resources = ["arn:aws:s3:::${var.bucket_name}/${var.bucket_prefix}/AWSLogs/${data.aws_caller_identity.current.account_id}/*"]
-
- principals = {
- type = "AWS"
- identifiers = ["arn:aws:iam::${data.aws_elb_service_account.current.id}:root"]
- }
- }
-}
-
-variable "subnets" {
- default = ["10.0.1.0/24", "10.0.2.0/24"]
- type = "list"
-}
-
-data "aws_availability_zones" "available" {}
-
-resource "aws_vpc" "alb_test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_subnet" "alb_test" {
- count = 2
- vpc_id = "${aws_vpc.alb_test.id}"
- cidr_block = "${element(var.subnets, count.index)}"
- map_public_ip_on_launch = true
- availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_security_group" "alb_test" {
- name = "allow_all_alb_test"
- description = "Used for ALB Testing"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- ingress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- egress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}`, albName, enabled, bucketName)
-}
-
-func testAccAWSALBConfig_nosg(albName string) string {
- return fmt.Sprintf(`resource "aws_alb" "alb_test" {
- name = "%s"
- internal = true
- subnets = ["${aws_subnet.alb_test.*.id}"]
-
- idle_timeout = 30
- enable_deletion_protection = false
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-variable "subnets" {
- default = ["10.0.1.0/24", "10.0.2.0/24"]
- type = "list"
-}
-
-data "aws_availability_zones" "available" {}
-
-resource "aws_vpc" "alb_test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_subnet" "alb_test" {
- count = 2
- vpc_id = "${aws_vpc.alb_test.id}"
- cidr_block = "${element(var.subnets, count.index)}"
- map_public_ip_on_launch = true
- availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}`, albName)
-}
-
-func testAccAWSALBConfig_updateSecurityGroups(albName string) string {
- return fmt.Sprintf(`resource "aws_alb" "alb_test" {
- name = "%s"
- internal = true
- security_groups = ["${aws_security_group.alb_test.id}", "${aws_security_group.alb_test_2.id}"]
- subnets = ["${aws_subnet.alb_test.*.id}"]
-
- idle_timeout = 30
- enable_deletion_protection = false
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-variable "subnets" {
- default = ["10.0.1.0/24", "10.0.2.0/24"]
- type = "list"
-}
-
-data "aws_availability_zones" "available" {}
-
-resource "aws_vpc" "alb_test" {
- cidr_block = "10.0.0.0/16"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_subnet" "alb_test" {
- count = 2
- vpc_id = "${aws_vpc.alb_test.id}"
- cidr_block = "${element(var.subnets, count.index)}"
- map_public_ip_on_launch = true
- availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}"
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}
-
-resource "aws_security_group" "alb_test_2" {
- name = "allow_all_alb_test_2"
- description = "Used for ALB Testing"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- ingress {
- from_port = 80
- to_port = 80
- protocol = "TCP"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- tags {
- TestName = "TestAccAWSALB_basic_2"
- }
-}
-
-resource "aws_security_group" "alb_test" {
- name = "allow_all_alb_test"
- description = "Used for ALB Testing"
- vpc_id = "${aws_vpc.alb_test.id}"
-
- ingress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- egress {
- from_port = 0
- to_port = 0
- protocol = "-1"
- cidr_blocks = ["0.0.0.0/0"]
- }
-
- tags {
- TestName = "TestAccAWSALB_basic"
- }
-}`, albName)
-}
diff --git a/builtin/providers/aws/resource_aws_ami.go b/builtin/providers/aws/resource_aws_ami.go
deleted file mode 100644
index d01c402ed..000000000
--- a/builtin/providers/aws/resource_aws_ami.go
+++ /dev/null
@@ -1,562 +0,0 @@
-package aws
-
-import (
- "bytes"
- "errors"
- "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/ec2"
-
- "github.com/hashicorp/terraform/helper/hashcode"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-const (
- AWSAMIRetryTimeout = 40 * time.Minute
- AWSAMIDeleteRetryTimeout = 90 * time.Minute
- AWSAMIRetryDelay = 5 * time.Second
- AWSAMIRetryMinTimeout = 3 * time.Second
-)
-
-func resourceAwsAmi() *schema.Resource {
- // Our schema is shared also with aws_ami_copy and aws_ami_from_instance
- resourceSchema := resourceAwsAmiCommonSchema(false)
-
- return &schema.Resource{
- Create: resourceAwsAmiCreate,
-
- Schema: resourceSchema,
-
- // The Read, Update and Delete operations are shared with aws_ami_copy
- // and aws_ami_from_instance, since they differ only in how the image
- // is created.
- Read: resourceAwsAmiRead,
- Update: resourceAwsAmiUpdate,
- Delete: resourceAwsAmiDelete,
- }
-}
-
-func resourceAwsAmiCreate(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AWSClient).ec2conn
-
- req := &ec2.RegisterImageInput{
- Name: aws.String(d.Get("name").(string)),
- Description: aws.String(d.Get("description").(string)),
- Architecture: aws.String(d.Get("architecture").(string)),
- ImageLocation: aws.String(d.Get("image_location").(string)),
- RootDeviceName: aws.String(d.Get("root_device_name").(string)),
- SriovNetSupport: aws.String(d.Get("sriov_net_support").(string)),
- VirtualizationType: aws.String(d.Get("virtualization_type").(string)),
- }
-
- if kernelId := d.Get("kernel_id").(string); kernelId != "" {
- req.KernelId = aws.String(kernelId)
- }
- if ramdiskId := d.Get("ramdisk_id").(string); ramdiskId != "" {
- req.RamdiskId = aws.String(ramdiskId)
- }
-
- ebsBlockDevsSet := d.Get("ebs_block_device").(*schema.Set)
- ephemeralBlockDevsSet := d.Get("ephemeral_block_device").(*schema.Set)
- for _, ebsBlockDevI := range ebsBlockDevsSet.List() {
- ebsBlockDev := ebsBlockDevI.(map[string]interface{})
- blockDev := &ec2.BlockDeviceMapping{
- DeviceName: aws.String(ebsBlockDev["device_name"].(string)),
- Ebs: &ec2.EbsBlockDevice{
- DeleteOnTermination: aws.Bool(ebsBlockDev["delete_on_termination"].(bool)),
- VolumeType: aws.String(ebsBlockDev["volume_type"].(string)),
- },
- }
- if iops, ok := ebsBlockDev["iops"]; ok {
- if iop := iops.(int); iop != 0 {
- blockDev.Ebs.Iops = aws.Int64(int64(iop))
- }
- }
- if size, ok := ebsBlockDev["volume_size"]; ok {
- if s := size.(int); s != 0 {
- blockDev.Ebs.VolumeSize = aws.Int64(int64(s))
- }
- }
- encrypted := ebsBlockDev["encrypted"].(bool)
- if snapshotId := ebsBlockDev["snapshot_id"].(string); snapshotId != "" {
- blockDev.Ebs.SnapshotId = aws.String(snapshotId)
- if encrypted {
- return errors.New("can't set both 'snapshot_id' and 'encrypted'")
- }
- } else if encrypted {
- blockDev.Ebs.Encrypted = aws.Bool(true)
- }
- req.BlockDeviceMappings = append(req.BlockDeviceMappings, blockDev)
- }
- for _, ephemeralBlockDevI := range ephemeralBlockDevsSet.List() {
- ephemeralBlockDev := ephemeralBlockDevI.(map[string]interface{})
- blockDev := &ec2.BlockDeviceMapping{
- DeviceName: aws.String(ephemeralBlockDev["device_name"].(string)),
- VirtualName: aws.String(ephemeralBlockDev["virtual_name"].(string)),
- }
- req.BlockDeviceMappings = append(req.BlockDeviceMappings, blockDev)
- }
-
- res, err := client.RegisterImage(req)
- if err != nil {
- return err
- }
-
- id := *res.ImageId
- d.SetId(id)
- d.Partial(true) // make sure we record the id even if the rest of this gets interrupted
- d.Set("id", id)
- d.Set("manage_ebs_block_devices", false)
- d.SetPartial("id")
- d.SetPartial("manage_ebs_block_devices")
- d.Partial(false)
-
- _, err = resourceAwsAmiWaitForAvailable(id, client)
- if err != nil {
- return err
- }
-
- return resourceAwsAmiUpdate(d, meta)
-}
-
-func resourceAwsAmiRead(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AWSClient).ec2conn
- id := d.Id()
-
- req := &ec2.DescribeImagesInput{
- ImageIds: []*string{aws.String(id)},
- }
-
- res, err := client.DescribeImages(req)
- if err != nil {
- if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidAMIID.NotFound" {
- log.Printf("[DEBUG] %s no longer exists, so we'll drop it from the state", id)
- d.SetId("")
- return nil
- }
-
- return err
- }
-
- if len(res.Images) != 1 {
- d.SetId("")
- return nil
- }
-
- image := res.Images[0]
- state := *image.State
-
- if state == "pending" {
- // This could happen if a user manually adds an image we didn't create
- // to the state. We'll wait for the image to become available
- // before we continue. We should never take this branch in normal
- // circumstances since we would've waited for availability during
- // the "Create" step.
- image, err = resourceAwsAmiWaitForAvailable(id, client)
- if err != nil {
- return err
- }
- state = *image.State
- }
-
- if state == "deregistered" {
- d.SetId("")
- return nil
- }
-
- if state != "available" {
- return fmt.Errorf("AMI has become %s", state)
- }
-
- d.Set("name", image.Name)
- d.Set("description", image.Description)
- d.Set("image_location", image.ImageLocation)
- d.Set("architecture", image.Architecture)
- d.Set("kernel_id", image.KernelId)
- d.Set("ramdisk_id", image.RamdiskId)
- d.Set("root_device_name", image.RootDeviceName)
- d.Set("sriov_net_support", image.SriovNetSupport)
- d.Set("virtualization_type", image.VirtualizationType)
-
- var ebsBlockDevs []map[string]interface{}
- var ephemeralBlockDevs []map[string]interface{}
-
- for _, blockDev := range image.BlockDeviceMappings {
- if blockDev.Ebs != nil {
- ebsBlockDev := map[string]interface{}{
- "device_name": *blockDev.DeviceName,
- "delete_on_termination": *blockDev.Ebs.DeleteOnTermination,
- "encrypted": *blockDev.Ebs.Encrypted,
- "iops": 0,
- "volume_size": int(*blockDev.Ebs.VolumeSize),
- "volume_type": *blockDev.Ebs.VolumeType,
- }
- if blockDev.Ebs.Iops != nil {
- ebsBlockDev["iops"] = int(*blockDev.Ebs.Iops)
- }
- // The snapshot ID might not be set.
- if blockDev.Ebs.SnapshotId != nil {
- ebsBlockDev["snapshot_id"] = *blockDev.Ebs.SnapshotId
- }
- ebsBlockDevs = append(ebsBlockDevs, ebsBlockDev)
- } else {
- ephemeralBlockDevs = append(ephemeralBlockDevs, map[string]interface{}{
- "device_name": *blockDev.DeviceName,
- "virtual_name": *blockDev.VirtualName,
- })
- }
- }
-
- d.Set("ebs_block_device", ebsBlockDevs)
- d.Set("ephemeral_block_device", ephemeralBlockDevs)
-
- d.Set("tags", tagsToMap(image.Tags))
-
- return nil
-}
-
-func resourceAwsAmiUpdate(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AWSClient).ec2conn
-
- d.Partial(true)
-
- if err := setTags(client, d); err != nil {
- return err
- } else {
- d.SetPartial("tags")
- }
-
- if d.Get("description").(string) != "" {
- _, err := client.ModifyImageAttribute(&ec2.ModifyImageAttributeInput{
- ImageId: aws.String(d.Id()),
- Description: &ec2.AttributeValue{
- Value: aws.String(d.Get("description").(string)),
- },
- })
- if err != nil {
- return err
- }
- d.SetPartial("description")
- }
-
- d.Partial(false)
-
- return resourceAwsAmiRead(d, meta)
-}
-
-func resourceAwsAmiDelete(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AWSClient).ec2conn
-
- req := &ec2.DeregisterImageInput{
- ImageId: aws.String(d.Id()),
- }
-
- _, err := client.DeregisterImage(req)
- if err != nil {
- return err
- }
-
- // If we're managing the EBS snapshots then we need to delete those too.
- if d.Get("manage_ebs_snapshots").(bool) {
- errs := map[string]error{}
- ebsBlockDevsSet := d.Get("ebs_block_device").(*schema.Set)
- req := &ec2.DeleteSnapshotInput{}
- for _, ebsBlockDevI := range ebsBlockDevsSet.List() {
- ebsBlockDev := ebsBlockDevI.(map[string]interface{})
- snapshotId := ebsBlockDev["snapshot_id"].(string)
- if snapshotId != "" {
- req.SnapshotId = aws.String(snapshotId)
- _, err := client.DeleteSnapshot(req)
- if err != nil {
- errs[snapshotId] = err
- }
- }
- }
-
- if len(errs) > 0 {
- errParts := []string{"Errors while deleting associated EBS snapshots:"}
- for snapshotId, err := range errs {
- errParts = append(errParts, fmt.Sprintf("%s: %s", snapshotId, err))
- }
- errParts = append(errParts, "These are no longer managed by Terraform and must be deleted manually.")
- return errors.New(strings.Join(errParts, "\n"))
- }
- }
-
- // Verify that the image is actually removed, if not we need to wait for it to be removed
- if err := resourceAwsAmiWaitForDestroy(d.Id(), client); err != nil {
- return err
- }
-
- // No error, ami was deleted successfully
- d.SetId("")
- return nil
-}
-
-func AMIStateRefreshFunc(client *ec2.EC2, id string) resource.StateRefreshFunc {
- return func() (interface{}, string, error) {
- emptyResp := &ec2.DescribeImagesOutput{}
-
- resp, err := client.DescribeImages(&ec2.DescribeImagesInput{ImageIds: []*string{aws.String(id)}})
- if err != nil {
- if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidAMIID.NotFound" {
- return emptyResp, "destroyed", nil
- } else if resp != nil && len(resp.Images) == 0 {
- return emptyResp, "destroyed", nil
- } else {
- return emptyResp, "", fmt.Errorf("Error on refresh: %+v", err)
- }
- }
-
- if resp == nil || resp.Images == nil || len(resp.Images) == 0 {
- return emptyResp, "destroyed", nil
- }
-
- // AMI is valid, so return it's state
- return resp.Images[0], *resp.Images[0].State, nil
- }
-}
-
-func resourceAwsAmiWaitForDestroy(id string, client *ec2.EC2) error {
- log.Printf("Waiting for AMI %s to be deleted...", id)
-
- stateConf := &resource.StateChangeConf{
- Pending: []string{"available", "pending", "failed"},
- Target: []string{"destroyed"},
- Refresh: AMIStateRefreshFunc(client, id),
- Timeout: AWSAMIDeleteRetryTimeout,
- Delay: AWSAMIRetryDelay,
- MinTimeout: AWSAMIRetryTimeout,
- }
-
- _, err := stateConf.WaitForState()
- if err != nil {
- return fmt.Errorf("Error waiting for AMI (%s) to be deleted: %v", id, err)
- }
-
- return nil
-}
-
-func resourceAwsAmiWaitForAvailable(id string, client *ec2.EC2) (*ec2.Image, error) {
- log.Printf("Waiting for AMI %s to become available...", id)
-
- stateConf := &resource.StateChangeConf{
- Pending: []string{"pending"},
- Target: []string{"available"},
- Refresh: AMIStateRefreshFunc(client, id),
- Timeout: AWSAMIRetryTimeout,
- Delay: AWSAMIRetryDelay,
- MinTimeout: AWSAMIRetryMinTimeout,
- }
-
- info, err := stateConf.WaitForState()
- if err != nil {
- return nil, fmt.Errorf("Error waiting for AMI (%s) to be ready: %v", id, err)
- }
- return info.(*ec2.Image), nil
-}
-
-func resourceAwsAmiCommonSchema(computed bool) map[string]*schema.Schema {
- // The "computed" parameter controls whether we're making
- // a schema for an AMI that's been implicitly registered (aws_ami_copy, aws_ami_from_instance)
- // or whether we're making a schema for an explicit registration (aws_ami).
- // When set, almost every attribute is marked as "computed".
- // When not set, only the "id" attribute is computed.
- // "name" and "description" are never computed, since they must always
- // be provided by the user.
-
- var virtualizationTypeDefault interface{}
- var deleteEbsOnTerminationDefault interface{}
- var sriovNetSupportDefault interface{}
- var architectureDefault interface{}
- var volumeTypeDefault interface{}
- if !computed {
- virtualizationTypeDefault = "paravirtual"
- deleteEbsOnTerminationDefault = true
- sriovNetSupportDefault = "simple"
- architectureDefault = "x86_64"
- volumeTypeDefault = "standard"
- }
-
- return map[string]*schema.Schema{
- "id": {
- Type: schema.TypeString,
- Computed: true,
- },
- "image_location": {
- Type: schema.TypeString,
- Optional: !computed,
- Computed: true,
- ForceNew: !computed,
- },
- "architecture": {
- Type: schema.TypeString,
- Optional: !computed,
- Computed: computed,
- ForceNew: !computed,
- Default: architectureDefault,
- },
- "description": {
- Type: schema.TypeString,
- Optional: true,
- },
- "kernel_id": {
- Type: schema.TypeString,
- Optional: !computed,
- Computed: computed,
- ForceNew: !computed,
- },
- "name": {
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
- "ramdisk_id": {
- Type: schema.TypeString,
- Optional: !computed,
- Computed: computed,
- ForceNew: !computed,
- },
- "root_device_name": {
- Type: schema.TypeString,
- Optional: !computed,
- Computed: computed,
- ForceNew: !computed,
- },
- "sriov_net_support": {
- Type: schema.TypeString,
- Optional: !computed,
- Computed: computed,
- ForceNew: !computed,
- Default: sriovNetSupportDefault,
- },
- "virtualization_type": {
- Type: schema.TypeString,
- Optional: !computed,
- Computed: computed,
- ForceNew: !computed,
- Default: virtualizationTypeDefault,
- },
-
- // The following block device attributes intentionally mimick the
- // corresponding attributes on aws_instance, since they have the
- // same meaning.
- // However, we don't use root_block_device here because the constraint
- // on which root device attributes can be overridden for an instance to
- // not apply when registering an AMI.
-
- "ebs_block_device": {
- Type: schema.TypeSet,
- Optional: true,
- Computed: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "delete_on_termination": {
- Type: schema.TypeBool,
- Optional: !computed,
- Default: deleteEbsOnTerminationDefault,
- ForceNew: !computed,
- Computed: computed,
- },
-
- "device_name": {
- Type: schema.TypeString,
- Required: !computed,
- ForceNew: !computed,
- Computed: computed,
- },
-
- "encrypted": {
- Type: schema.TypeBool,
- Optional: !computed,
- Computed: computed,
- ForceNew: !computed,
- },
-
- "iops": {
- Type: schema.TypeInt,
- Optional: !computed,
- Computed: computed,
- ForceNew: !computed,
- },
-
- "snapshot_id": {
- Type: schema.TypeString,
- Optional: !computed,
- Computed: computed,
- ForceNew: !computed,
- },
-
- "volume_size": {
- Type: schema.TypeInt,
- Optional: !computed,
- Computed: true,
- ForceNew: !computed,
- },
-
- "volume_type": {
- Type: schema.TypeString,
- Optional: !computed,
- Computed: computed,
- ForceNew: !computed,
- Default: volumeTypeDefault,
- },
- },
- },
- Set: func(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%s-", m["device_name"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["snapshot_id"].(string)))
- return hashcode.String(buf.String())
- },
- },
-
- "ephemeral_block_device": {
- Type: schema.TypeSet,
- Optional: true,
- Computed: true,
- ForceNew: true,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "device_name": {
- Type: schema.TypeString,
- Required: !computed,
- Computed: computed,
- },
-
- "virtual_name": {
- Type: schema.TypeString,
- Required: !computed,
- Computed: computed,
- },
- },
- },
- Set: func(v interface{}) int {
- var buf bytes.Buffer
- m := v.(map[string]interface{})
- buf.WriteString(fmt.Sprintf("%s-", m["device_name"].(string)))
- buf.WriteString(fmt.Sprintf("%s-", m["virtual_name"].(string)))
- return hashcode.String(buf.String())
- },
- },
-
- "tags": tagsSchema(),
-
- // Not a public attribute; used to let the aws_ami_copy and aws_ami_from_instance
- // resources record that they implicitly created new EBS snapshots that we should
- // now manage. Not set by aws_ami, since the snapshots used there are presumed to
- // be independently managed.
- "manage_ebs_snapshots": {
- Type: schema.TypeBool,
- Computed: true,
- ForceNew: true,
- },
- }
-}
diff --git a/builtin/providers/aws/resource_aws_ami_copy.go b/builtin/providers/aws/resource_aws_ami_copy.go
deleted file mode 100644
index 3452d5b52..000000000
--- a/builtin/providers/aws/resource_aws_ami_copy.go
+++ /dev/null
@@ -1,90 +0,0 @@
-package aws
-
-import (
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/ec2"
-
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func resourceAwsAmiCopy() *schema.Resource {
- // Inherit all of the common AMI attributes from aws_ami, since we're
- // implicitly creating an aws_ami resource.
- resourceSchema := resourceAwsAmiCommonSchema(true)
-
- // Additional attributes unique to the copy operation.
- resourceSchema["source_ami_id"] = &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- }
- resourceSchema["source_ami_region"] = &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- }
-
- resourceSchema["encrypted"] = &schema.Schema{
- Type: schema.TypeBool,
- Optional: true,
- Default: false,
- ForceNew: true,
- }
-
- resourceSchema["kms_key_id"] = &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- Computed: true,
- ForceNew: true,
- ValidateFunc: validateArn,
- }
-
- return &schema.Resource{
- Create: resourceAwsAmiCopyCreate,
-
- Schema: resourceSchema,
-
- // The remaining operations are shared with the generic aws_ami resource,
- // since the aws_ami_copy resource only differs in how it's created.
- Read: resourceAwsAmiRead,
- Update: resourceAwsAmiUpdate,
- Delete: resourceAwsAmiDelete,
- }
-}
-
-func resourceAwsAmiCopyCreate(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AWSClient).ec2conn
-
- req := &ec2.CopyImageInput{
- Name: aws.String(d.Get("name").(string)),
- Description: aws.String(d.Get("description").(string)),
- SourceImageId: aws.String(d.Get("source_ami_id").(string)),
- SourceRegion: aws.String(d.Get("source_ami_region").(string)),
- Encrypted: aws.Bool(d.Get("encrypted").(bool)),
- }
-
- if v, ok := d.GetOk("kms_key_id"); ok {
- req.KmsKeyId = aws.String(v.(string))
- }
-
- res, err := client.CopyImage(req)
- if err != nil {
- return err
- }
-
- id := *res.ImageId
- d.SetId(id)
- d.Partial(true) // make sure we record the id even if the rest of this gets interrupted
- d.Set("id", id)
- d.Set("manage_ebs_snapshots", true)
- d.SetPartial("id")
- d.SetPartial("manage_ebs_snapshots")
- d.Partial(false)
-
- _, err = resourceAwsAmiWaitForAvailable(id, client)
- if err != nil {
- return err
- }
-
- return resourceAwsAmiUpdate(d, meta)
-}
diff --git a/builtin/providers/aws/resource_aws_ami_copy_test.go b/builtin/providers/aws/resource_aws_ami_copy_test.go
deleted file mode 100644
index 4fd5f5264..000000000
--- a/builtin/providers/aws/resource_aws_ami_copy_test.go
+++ /dev/null
@@ -1,201 +0,0 @@
-package aws
-
-import (
- "errors"
- "fmt"
- "strings"
- "testing"
-
- "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/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAWSAMICopy(t *testing.T) {
- var amiId string
- snapshots := []string{}
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSAMICopyConfig,
- Check: func(state *terraform.State) error {
- rs, ok := state.RootModule().Resources["aws_ami_copy.test"]
- if !ok {
- return fmt.Errorf("AMI resource not found")
- }
-
- amiId = rs.Primary.ID
-
- if amiId == "" {
- return fmt.Errorf("AMI id is not set")
- }
-
- conn := testAccProvider.Meta().(*AWSClient).ec2conn
- req := &ec2.DescribeImagesInput{
- ImageIds: []*string{aws.String(amiId)},
- }
- describe, err := conn.DescribeImages(req)
- if err != nil {
- return err
- }
-
- if len(describe.Images) != 1 ||
- *describe.Images[0].ImageId != rs.Primary.ID {
- return fmt.Errorf("AMI not found")
- }
-
- image := describe.Images[0]
- if expected := "available"; *image.State != expected {
- return fmt.Errorf("invalid image state; expected %v, got %v", expected, image.State)
- }
- if expected := "machine"; *image.ImageType != expected {
- return fmt.Errorf("wrong image type; expected %v, got %v", expected, image.ImageType)
- }
- if expected := "terraform-acc-ami-copy"; *image.Name != expected {
- return fmt.Errorf("wrong name; expected %v, got %v", expected, image.Name)
- }
-
- for _, bdm := range image.BlockDeviceMappings {
- // The snapshot ID might not be set,
- // even for a block device that is an
- // EBS volume.
- if bdm.Ebs != nil && bdm.Ebs.SnapshotId != nil {
- snapshots = append(snapshots, *bdm.Ebs.SnapshotId)
- }
- }
-
- if expected := 1; len(snapshots) != expected {
- return fmt.Errorf("wrong number of snapshots; expected %v, got %v", expected, len(snapshots))
- }
-
- return nil
- },
- },
- },
- CheckDestroy: func(state *terraform.State) error {
- conn := testAccProvider.Meta().(*AWSClient).ec2conn
- diReq := &ec2.DescribeImagesInput{
- ImageIds: []*string{aws.String(amiId)},
- }
- diRes, err := conn.DescribeImages(diReq)
- if err != nil {
- return err
- }
-
- if len(diRes.Images) > 0 {
- state := diRes.Images[0].State
- return fmt.Errorf("AMI %v remains in state %v", amiId, state)
- }
-
- stillExist := make([]string, 0, len(snapshots))
- checkErrors := make(map[string]error)
- for _, snapshotId := range snapshots {
- dsReq := &ec2.DescribeSnapshotsInput{
- SnapshotIds: []*string{aws.String(snapshotId)},
- }
- _, err := conn.DescribeSnapshots(dsReq)
- if err == nil {
- stillExist = append(stillExist, snapshotId)
- continue
- }
-
- awsErr, ok := err.(awserr.Error)
- if !ok {
- checkErrors[snapshotId] = err
- continue
- }
-
- if awsErr.Code() != "InvalidSnapshot.NotFound" {
- checkErrors[snapshotId] = err
- continue
- }
- }
-
- if len(stillExist) > 0 || len(checkErrors) > 0 {
- errParts := []string{
- "Expected all snapshots to be gone, but:",
- }
- for _, snapshotId := range stillExist {
- errParts = append(
- errParts,
- fmt.Sprintf("- %v still exists", snapshotId),
- )
- }
- for snapshotId, err := range checkErrors {
- errParts = append(
- errParts,
- fmt.Sprintf("- checking %v gave error: %v", snapshotId, err),
- )
- }
- return errors.New(strings.Join(errParts, "\n"))
- }
-
- return nil
- },
- })
-}
-
-var testAccAWSAMICopyConfig = `
-provider "aws" {
- region = "us-east-1"
-}
-
-// An AMI can't be directly copied from one account to another, and
-// we can't rely on any particular AMI being available since anyone
-// can run this test in whatever account they like.
-// Therefore we jump through some hoops here:
-// - Spin up an EC2 instance based on a public AMI
-// - Create an AMI by snapshotting that EC2 instance, using
-// aws_ami_from_instance .
-// - Copy the new AMI using aws_ami_copy .
-//
-// Thus this test can only succeed if the aws_ami_from_instance resource
-// is working. If it's misbehaving it will likely cause this test to fail too.
-
-// Since we're booting a t2.micro HVM instance we need a VPC for it to boot
-// up into.
-
-resource "aws_vpc" "foo" {
- cidr_block = "10.1.0.0/16"
- tags {
- Name = "testAccAWSAMICopyConfig"
- }
-}
-
-resource "aws_subnet" "foo" {
- cidr_block = "10.1.1.0/24"
- vpc_id = "${aws_vpc.foo.id}"
-}
-
-resource "aws_instance" "test" {
- // This AMI has one block device mapping, so we expect to have
- // one snapshot in our created AMI.
- // This is an Ubuntu Linux HVM AMI. A public HVM AMI is required
- // because paravirtual images cannot be copied between accounts.
- ami = "ami-0f8bce65"
- instance_type = "t2.micro"
- tags {
- Name = "terraform-acc-ami-copy-victim"
- }
-
- subnet_id = "${aws_subnet.foo.id}"
-}
-
-resource "aws_ami_from_instance" "test" {
- name = "terraform-acc-ami-copy-victim"
- description = "Testing Terraform aws_ami_from_instance resource"
- source_instance_id = "${aws_instance.test.id}"
-}
-
-resource "aws_ami_copy" "test" {
- name = "terraform-acc-ami-copy"
- description = "Testing Terraform aws_ami_copy resource"
- source_ami_id = "${aws_ami_from_instance.test.id}"
- source_ami_region = "us-east-1"
-}
-`
diff --git a/builtin/providers/aws/resource_aws_ami_from_instance.go b/builtin/providers/aws/resource_aws_ami_from_instance.go
deleted file mode 100644
index cc272d3c1..000000000
--- a/builtin/providers/aws/resource_aws_ami_from_instance.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package aws
-
-import (
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/ec2"
-
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func resourceAwsAmiFromInstance() *schema.Resource {
- // Inherit all of the common AMI attributes from aws_ami, since we're
- // implicitly creating an aws_ami resource.
- resourceSchema := resourceAwsAmiCommonSchema(true)
-
- // Additional attributes unique to the copy operation.
- resourceSchema["source_instance_id"] = &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- }
- resourceSchema["snapshot_without_reboot"] = &schema.Schema{
- Type: schema.TypeBool,
- Optional: true,
- ForceNew: true,
- }
-
- return &schema.Resource{
- Create: resourceAwsAmiFromInstanceCreate,
-
- Schema: resourceSchema,
-
- // The remaining operations are shared with the generic aws_ami resource,
- // since the aws_ami_copy resource only differs in how it's created.
- Read: resourceAwsAmiRead,
- Update: resourceAwsAmiUpdate,
- Delete: resourceAwsAmiDelete,
- }
-}
-
-func resourceAwsAmiFromInstanceCreate(d *schema.ResourceData, meta interface{}) error {
- client := meta.(*AWSClient).ec2conn
-
- req := &ec2.CreateImageInput{
- Name: aws.String(d.Get("name").(string)),
- Description: aws.String(d.Get("description").(string)),
- InstanceId: aws.String(d.Get("source_instance_id").(string)),
- NoReboot: aws.Bool(d.Get("snapshot_without_reboot").(bool)),
- }
-
- res, err := client.CreateImage(req)
- if err != nil {
- return err
- }
-
- id := *res.ImageId
- d.SetId(id)
- d.Partial(true) // make sure we record the id even if the rest of this gets interrupted
- d.Set("id", id)
- d.Set("manage_ebs_snapshots", true)
- d.SetPartial("id")
- d.SetPartial("manage_ebs_snapshots")
- d.Partial(false)
-
- _, err = resourceAwsAmiWaitForAvailable(id, client)
- if err != nil {
- return err
- }
-
- return resourceAwsAmiUpdate(d, meta)
-}
diff --git a/builtin/providers/aws/resource_aws_ami_from_instance_test.go b/builtin/providers/aws/resource_aws_ami_from_instance_test.go
deleted file mode 100644
index e130a6cbc..000000000
--- a/builtin/providers/aws/resource_aws_ami_from_instance_test.go
+++ /dev/null
@@ -1,163 +0,0 @@
-package aws
-
-import (
- "errors"
- "fmt"
- "strings"
- "testing"
-
- "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/acctest"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAWSAMIFromInstance(t *testing.T) {
- var amiId string
- snapshots := []string{}
- rInt := acctest.RandInt()
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- Steps: []resource.TestStep{
- {
- Config: testAccAWSAMIFromInstanceConfig(rInt),
- Check: func(state *terraform.State) error {
- rs, ok := state.RootModule().Resources["aws_ami_from_instance.test"]
- if !ok {
- return fmt.Errorf("AMI resource not found")
- }
-
- amiId = rs.Primary.ID
-
- if amiId == "" {
- return fmt.Errorf("AMI id is not set")
- }
-
- conn := testAccProvider.Meta().(*AWSClient).ec2conn
- req := &ec2.DescribeImagesInput{
- ImageIds: []*string{aws.String(amiId)},
- }
- describe, err := conn.DescribeImages(req)
- if err != nil {
- return err
- }
-
- if len(describe.Images) != 1 ||
- *describe.Images[0].ImageId != rs.Primary.ID {
- return fmt.Errorf("AMI not found")
- }
-
- image := describe.Images[0]
- if expected := "available"; *image.State != expected {
- return fmt.Errorf("invalid image state; expected %v, got %v", expected, *image.State)
- }
- if expected := "machine"; *image.ImageType != expected {
- return fmt.Errorf("wrong image type; expected %v, got %v", expected, *image.ImageType)
- }
- if expected := fmt.Sprintf("terraform-acc-ami-from-instance-%d", rInt); *image.Name != expected {
- return fmt.Errorf("wrong name; expected %v, got %v", expected, *image.Name)
- }
-
- for _, bdm := range image.BlockDeviceMappings {
- if bdm.Ebs != nil && bdm.Ebs.SnapshotId != nil {
- snapshots = append(snapshots, *bdm.Ebs.SnapshotId)
- }
- }
-
- if expected := 1; len(snapshots) != expected {
- return fmt.Errorf("wrong number of snapshots; expected %v, got %v", expected, len(snapshots))
- }
-
- return nil
- },
- },
- },
- CheckDestroy: func(state *terraform.State) error {
- conn := testAccProvider.Meta().(*AWSClient).ec2conn
- diReq := &ec2.DescribeImagesInput{
- ImageIds: []*string{aws.String(amiId)},
- }
- diRes, err := conn.DescribeImages(diReq)
- if err != nil {
- return err
- }
-
- if len(diRes.Images) > 0 {
- state := diRes.Images[0].State
- return fmt.Errorf("AMI %v remains in state %v", amiId, state)
- }
-
- stillExist := make([]string, 0, len(snapshots))
- checkErrors := make(map[string]error)
- for _, snapshotId := range snapshots {
- dsReq := &ec2.DescribeSnapshotsInput{
- SnapshotIds: []*string{aws.String(snapshotId)},
- }
- _, err := conn.DescribeSnapshots(dsReq)
- if err == nil {
- stillExist = append(stillExist, snapshotId)
- continue
- }
-
- awsErr, ok := err.(awserr.Error)
- if !ok {
- checkErrors[snapshotId] = err
- continue
- }
-
- if awsErr.Code() != "InvalidSnapshot.NotFound" {
- checkErrors[snapshotId] = err
- continue
- }
- }
-
- if len(stillExist) > 0 || len(checkErrors) > 0 {
- errParts := []string{
- "Expected all snapshots to be gone, but:",
- }
- for _, snapshotId := range stillExist {
- errParts = append(
- errParts,
- fmt.Sprintf("- %v still exists", snapshotId),
- )
- }
- for snapshotId, err := range checkErrors {
- errParts = append(
- errParts,
- fmt.Sprintf("- checking %v gave error: %v", snapshotId, err),
- )
- }
- return errors.New(strings.Join(errParts, "\n"))
- }
-
- return nil
- },
- })
-}
-
-func testAccAWSAMIFromInstanceConfig(rInt int) string {
- return fmt.Sprintf(`
- provider "aws" {
- region = "us-east-1"
- }
-
- resource "aws_instance" "test" {
- // This AMI has one block device mapping, so we expect to have
- // one snapshot in our created AMI.
- ami = "ami-408c7f28"
- instance_type = "t1.micro"
- tags {
- Name = "testAccAWSAMIFromInstanceConfig_TestAMI"
- }
- }
-
- resource "aws_ami_from_instance" "test" {
- name = "terraform-acc-ami-from-instance-%d"
- description = "Testing Terraform aws_ami_from_instance resource"
- source_instance_id = "${aws_instance.test.id}"
- }`, rInt)
-}
diff --git a/builtin/providers/aws/resource_aws_ami_launch_permission.go b/builtin/providers/aws/resource_aws_ami_launch_permission.go
deleted file mode 100644
index 278e9d9ab..000000000
--- a/builtin/providers/aws/resource_aws_ami_launch_permission.go
+++ /dev/null
@@ -1,114 +0,0 @@
-package aws
-
-import (
- "fmt"
- "log"
- "strings"
-
- "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/schema"
-)
-
-func resourceAwsAmiLaunchPermission() *schema.Resource {
- return &schema.Resource{
- Exists: resourceAwsAmiLaunchPermissionExists,
- Create: resourceAwsAmiLaunchPermissionCreate,
- Read: resourceAwsAmiLaunchPermissionRead,
- Delete: resourceAwsAmiLaunchPermissionDelete,
-
- Schema: map[string]*schema.Schema{
- "image_id": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
- "account_id": &schema.Schema{
- Type: schema.TypeString,
- Required: true,
- ForceNew: true,
- },
- },
- }
-}
-
-func resourceAwsAmiLaunchPermissionExists(d *schema.ResourceData, meta interface{}) (bool, error) {
- conn := meta.(*AWSClient).ec2conn
-
- image_id := d.Get("image_id").(string)
- account_id := d.Get("account_id").(string)
- return hasLaunchPermission(conn, image_id, account_id)
-}
-
-func resourceAwsAmiLaunchPermissionCreate(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).ec2conn
-
- image_id := d.Get("image_id").(string)
- account_id := d.Get("account_id").(string)
-
- _, err := conn.ModifyImageAttribute(&ec2.ModifyImageAttributeInput{
- ImageId: aws.String(image_id),
- Attribute: aws.String("launchPermission"),
- LaunchPermission: &ec2.LaunchPermissionModifications{
- Add: []*ec2.LaunchPermission{
- &ec2.LaunchPermission{UserId: aws.String(account_id)},
- },
- },
- })
- if err != nil {
- return fmt.Errorf("error creating ami launch permission: %s", err)
- }
-
- d.SetId(fmt.Sprintf("%s-%s", image_id, account_id))
- return nil
-}
-
-func resourceAwsAmiLaunchPermissionRead(d *schema.ResourceData, meta interface{}) error {
- return nil
-}
-
-func resourceAwsAmiLaunchPermissionDelete(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).ec2conn
-
- image_id := d.Get("image_id").(string)
- account_id := d.Get("account_id").(string)
-
- _, err := conn.ModifyImageAttribute(&ec2.ModifyImageAttributeInput{
- ImageId: aws.String(image_id),
- Attribute: aws.String("launchPermission"),
- LaunchPermission: &ec2.LaunchPermissionModifications{
- Remove: []*ec2.LaunchPermission{
- &ec2.LaunchPermission{UserId: aws.String(account_id)},
- },
- },
- })
- if err != nil {
- return fmt.Errorf("error removing ami launch permission: %s", err)
- }
-
- return nil
-}
-
-func hasLaunchPermission(conn *ec2.EC2, image_id string, account_id string) (bool, error) {
- attrs, err := conn.DescribeImageAttribute(&ec2.DescribeImageAttributeInput{
- ImageId: aws.String(image_id),
- Attribute: aws.String("launchPermission"),
- })
- if err != nil {
- // When an AMI disappears out from under a launch permission resource, we will
- // see either InvalidAMIID.NotFound or InvalidAMIID.Unavailable.
- if ec2err, ok := err.(awserr.Error); ok && strings.HasPrefix(ec2err.Code(), "InvalidAMIID") {
- log.Printf("[DEBUG] %s no longer exists, so we'll drop launch permission for %s from the state", image_id, account_id)
- return false, nil
- }
- return false, err
- }
-
- for _, lp := range attrs.LaunchPermissions {
- if *lp.UserId == account_id {
- return true, nil
- }
- }
- return false, nil
-}
diff --git a/builtin/providers/aws/resource_aws_ami_launch_permission_test.go b/builtin/providers/aws/resource_aws_ami_launch_permission_test.go
deleted file mode 100644
index 4ccb35c7c..000000000
--- a/builtin/providers/aws/resource_aws_ami_launch_permission_test.go
+++ /dev/null
@@ -1,147 +0,0 @@
-package aws
-
-import (
- "fmt"
- "os"
- "testing"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/ec2"
- r "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAWSAMILaunchPermission_Basic(t *testing.T) {
- imageID := ""
- accountID := os.Getenv("AWS_ACCOUNT_ID")
-
- r.Test(t, r.TestCase{
- PreCheck: func() {
- testAccPreCheck(t)
- if os.Getenv("AWS_ACCOUNT_ID") == "" {
- t.Fatal("AWS_ACCOUNT_ID must be set")
- }
- },
- Providers: testAccProviders,
- Steps: []r.TestStep{
- // Scaffold everything
- r.TestStep{
- Config: testAccAWSAMILaunchPermissionConfig(accountID, true),
- Check: r.ComposeTestCheckFunc(
- testCheckResourceGetAttr("aws_ami_copy.test", "id", &imageID),
- testAccAWSAMILaunchPermissionExists(accountID, &imageID),
- ),
- },
- // Drop just launch permission to test destruction
- r.TestStep{
- Config: testAccAWSAMILaunchPermissionConfig(accountID, false),
- Check: r.ComposeTestCheckFunc(
- testAccAWSAMILaunchPermissionDestroyed(accountID, &imageID),
- ),
- },
- // Re-add everything so we can test when AMI disappears
- r.TestStep{
- Config: testAccAWSAMILaunchPermissionConfig(accountID, true),
- Check: r.ComposeTestCheckFunc(
- testCheckResourceGetAttr("aws_ami_copy.test", "id", &imageID),
- testAccAWSAMILaunchPermissionExists(accountID, &imageID),
- ),
- },
- // Here we delete the AMI to verify the follow-on refresh after this step
- // should not error.
- r.TestStep{
- Config: testAccAWSAMILaunchPermissionConfig(accountID, true),
- Check: r.ComposeTestCheckFunc(
- testAccAWSAMIDisappears(&imageID),
- ),
- ExpectNonEmptyPlan: true,
- },
- },
- })
-}
-
-func testCheckResourceGetAttr(name, key string, value *string) r.TestCheckFunc {
- return func(s *terraform.State) error {
- ms := s.RootModule()
- rs, ok := ms.Resources[name]
- if !ok {
- return fmt.Errorf("Not found: %s", name)
- }
-
- is := rs.Primary
- if is == nil {
- return fmt.Errorf("No primary instance: %s", name)
- }
-
- *value = is.Attributes[key]
- return nil
- }
-}
-
-func testAccAWSAMILaunchPermissionExists(accountID string, imageID *string) r.TestCheckFunc {
- return func(s *terraform.State) error {
- conn := testAccProvider.Meta().(*AWSClient).ec2conn
- if has, err := hasLaunchPermission(conn, *imageID, accountID); err != nil {
- return err
- } else if !has {
- return fmt.Errorf("launch permission does not exist for '%s' on '%s'", accountID, *imageID)
- }
- return nil
- }
-}
-
-func testAccAWSAMILaunchPermissionDestroyed(accountID string, imageID *string) r.TestCheckFunc {
- return func(s *terraform.State) error {
- conn := testAccProvider.Meta().(*AWSClient).ec2conn
- if has, err := hasLaunchPermission(conn, *imageID, accountID); err != nil {
- return err
- } else if has {
- return fmt.Errorf("launch permission still exists for '%s' on '%s'", accountID, *imageID)
- }
- return nil
- }
-}
-
-// testAccAWSAMIDisappears is technically a "test check function" but really it
-// exists to perform a side effect of deleting an AMI out from under a resource
-// so we can test that Terraform will react properly
-func testAccAWSAMIDisappears(imageID *string) r.TestCheckFunc {
- return func(s *terraform.State) error {
- conn := testAccProvider.Meta().(*AWSClient).ec2conn
- req := &ec2.DeregisterImageInput{
- ImageId: aws.String(*imageID),
- }
-
- _, err := conn.DeregisterImage(req)
- if err != nil {
- return err
- }
-
- if err := resourceAwsAmiWaitForDestroy(*imageID, conn); err != nil {
- return err
- }
- return nil
- }
-}
-
-func testAccAWSAMILaunchPermissionConfig(accountID string, includeLaunchPermission bool) string {
- base := `
-resource "aws_ami_copy" "test" {
- name = "launch-permission-test"
- description = "Launch Permission Test Copy"
- source_ami_id = "ami-7172b611"
- source_ami_region = "us-west-2"
-}
-`
-
- if !includeLaunchPermission {
- return base
- }
-
- return base + fmt.Sprintf(`
-resource "aws_ami_launch_permission" "self-test" {
- image_id = "${aws_ami_copy.test.id}"
- account_id = "%s"
-}
-`, accountID)
-}
diff --git a/builtin/providers/aws/resource_aws_ami_test.go b/builtin/providers/aws/resource_aws_ami_test.go
deleted file mode 100644
index 2f2e481a4..000000000
--- a/builtin/providers/aws/resource_aws_ami_test.go
+++ /dev/null
@@ -1,234 +0,0 @@
-package aws
-
-import (
- "fmt"
- "log"
- "testing"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/ec2"
- "github.com/hashicorp/terraform/helper/acctest"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAWSAMI_basic(t *testing.T) {
- var ami ec2.Image
- rInt := acctest.RandInt()
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAmiDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAmiConfig_basic(rInt),
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAmiExists("aws_ami.foo", &ami),
- resource.TestCheckResourceAttr(
- "aws_ami.foo", "name", fmt.Sprintf("tf-testing-%d", rInt)),
- ),
- },
- },
- })
-}
-
-func TestAccAWSAMI_snapshotSize(t *testing.T) {
- var ami ec2.Image
- var bd ec2.BlockDeviceMapping
- rInt := acctest.RandInt()
-
- expectedDevice := &ec2.EbsBlockDevice{
- DeleteOnTermination: aws.Bool(true),
- Encrypted: aws.Bool(false),
- Iops: aws.Int64(0),
- VolumeSize: aws.Int64(20),
- VolumeType: aws.String("standard"),
- }
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAmiDestroy,
- Steps: []resource.TestStep{
- {
- Config: testAccAmiConfig_snapshotSize(rInt),
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAmiExists("aws_ami.foo", &ami),
- testAccCheckAmiBlockDevice(&ami, &bd, "/dev/sda1"),
- testAccCheckAmiEbsBlockDevice(&bd, expectedDevice),
- resource.TestCheckResourceAttr(
- "aws_ami.foo", "name", fmt.Sprintf("tf-testing-%d", rInt)),
- resource.TestCheckResourceAttr(
- "aws_ami.foo", "architecture", "x86_64"),
- ),
- },
- },
- })
-}
-
-func testAccCheckAmiDestroy(s *terraform.State) error {
- conn := testAccProvider.Meta().(*AWSClient).ec2conn
-
- for _, rs := range s.RootModule().Resources {
- if rs.Type != "aws_ami" {
- continue
- }
-
- // Try to find the AMI
- log.Printf("AMI-ID: %s", rs.Primary.ID)
- DescribeAmiOpts := &ec2.DescribeImagesInput{
- ImageIds: []*string{aws.String(rs.Primary.ID)},
- }
- resp, err := conn.DescribeImages(DescribeAmiOpts)
- if err != nil {
- if isAWSErr(err, "InvalidAMIID", "NotFound") {
- log.Printf("[DEBUG] AMI not found, passing")
- return nil
- }
- return err
- }
-
- if len(resp.Images) > 0 {
- state := resp.Images[0].State
- return fmt.Errorf("AMI %s still exists in the state: %s.", *resp.Images[0].ImageId, *state)
- }
- }
- return nil
-}
-
-func testAccCheckAmiExists(n string, ami *ec2.Image) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("AMI Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No AMI ID is set")
- }
-
- conn := testAccProvider.Meta().(*AWSClient).ec2conn
- opts := &ec2.DescribeImagesInput{
- ImageIds: []*string{aws.String(rs.Primary.ID)},
- }
- resp, err := conn.DescribeImages(opts)
- if err != nil {
- return err
- }
- if len(resp.Images) == 0 {
- return fmt.Errorf("AMI not found")
- }
- *ami = *resp.Images[0]
- return nil
- }
-}
-
-func testAccCheckAmiBlockDevice(ami *ec2.Image, blockDevice *ec2.BlockDeviceMapping, n string) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- devices := make(map[string]*ec2.BlockDeviceMapping)
- for _, device := range ami.BlockDeviceMappings {
- devices[*device.DeviceName] = device
- }
-
- // Check if the block device exists
- if _, ok := devices[n]; !ok {
- return fmt.Errorf("block device doesn't exist: %s", n)
- }
-
- *blockDevice = *devices[n]
- return nil
- }
-}
-
-func testAccCheckAmiEbsBlockDevice(bd *ec2.BlockDeviceMapping, ed *ec2.EbsBlockDevice) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- // Test for things that ed has, don't care about unset values
- cd := bd.Ebs
- if ed.VolumeType != nil {
- if *ed.VolumeType != *cd.VolumeType {
- return fmt.Errorf("Volume type mismatch. Expected: %s Got: %s",
- *ed.VolumeType, *cd.VolumeType)
- }
- }
- if ed.DeleteOnTermination != nil {
- if *ed.DeleteOnTermination != *cd.DeleteOnTermination {
- return fmt.Errorf("DeleteOnTermination mismatch. Expected: %t Got: %t",
- *ed.DeleteOnTermination, *cd.DeleteOnTermination)
- }
- }
- if ed.Encrypted != nil {
- if *ed.Encrypted != *cd.Encrypted {
- return fmt.Errorf("Encrypted mismatch. Expected: %t Got: %t",
- *ed.Encrypted, *cd.Encrypted)
- }
- }
- // Integer defaults need to not be `0` so we don't get a panic
- if ed.Iops != nil && *ed.Iops != 0 {
- if *ed.Iops != *cd.Iops {
- return fmt.Errorf("IOPS mismatch. Expected: %d Got: %d",
- *ed.Iops, *cd.Iops)
- }
- }
- if ed.VolumeSize != nil && *ed.VolumeSize != 0 {
- if *ed.VolumeSize != *cd.VolumeSize {
- return fmt.Errorf("Volume Size mismatch. Expected: %d Got: %d",
- *ed.VolumeSize, *cd.VolumeSize)
- }
- }
-
- return nil
- }
-}
-
-func testAccAmiConfig_basic(rInt int) string {
- return fmt.Sprintf(`
-resource "aws_ebs_volume" "foo" {
- availability_zone = "us-west-2a"
- size = 8
- tags {
- Name = "testAccAmiConfig_basic"
- }
-}
-
-resource "aws_ebs_snapshot" "foo" {
- volume_id = "${aws_ebs_volume.foo.id}"
-}
-
-resource "aws_ami" "foo" {
- name = "tf-testing-%d"
- virtualization_type = "hvm"
- root_device_name = "/dev/sda1"
- ebs_block_device {
- device_name = "/dev/sda1"
- snapshot_id = "${aws_ebs_snapshot.foo.id}"
- }
-}
- `, rInt)
-}
-
-func testAccAmiConfig_snapshotSize(rInt int) string {
- return fmt.Sprintf(`
-resource "aws_ebs_volume" "foo" {
- availability_zone = "us-west-2a"
- size = 20
- tags {
- Name = "testAccAmiConfig_snapshotSize"
- }
-}
-
-resource "aws_ebs_snapshot" "foo" {
- volume_id = "${aws_ebs_volume.foo.id}"
-}
-
-resource "aws_ami" "foo" {
- name = "tf-testing-%d"
- virtualization_type = "hvm"
- root_device_name = "/dev/sda1"
- ebs_block_device {
- device_name = "/dev/sda1"
- snapshot_id = "${aws_ebs_snapshot.foo.id}"
- }
-}
- `, rInt)
-}
diff --git a/builtin/providers/aws/resource_aws_api_gateway_account.go b/builtin/providers/aws/resource_aws_api_gateway_account.go
deleted file mode 100644
index 7b786270a..000000000
--- a/builtin/providers/aws/resource_aws_api_gateway_account.go
+++ /dev/null
@@ -1,127 +0,0 @@
-package aws
-
-import (
- "fmt"
- "log"
- "time"
-
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/service/apigateway"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/helper/schema"
-)
-
-func resourceAwsApiGatewayAccount() *schema.Resource {
- return &schema.Resource{
- Create: resourceAwsApiGatewayAccountUpdate,
- Read: resourceAwsApiGatewayAccountRead,
- Update: resourceAwsApiGatewayAccountUpdate,
- Delete: resourceAwsApiGatewayAccountDelete,
- Importer: &schema.ResourceImporter{
- State: schema.ImportStatePassthrough,
- },
-
- Schema: map[string]*schema.Schema{
- "cloudwatch_role_arn": &schema.Schema{
- Type: schema.TypeString,
- Optional: true,
- },
- "throttle_settings": &schema.Schema{
- Type: schema.TypeList,
- Computed: true,
- MaxItems: 1,
- Elem: &schema.Resource{
- Schema: map[string]*schema.Schema{
- "burst_limit": &schema.Schema{
- Type: schema.TypeInt,
- Computed: true,
- },
- "rate_limit": &schema.Schema{
- Type: schema.TypeFloat,
- Computed: true,
- },
- },
- },
- },
- },
- }
-}
-
-func resourceAwsApiGatewayAccountRead(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).apigateway
-
- log.Printf("[INFO] Reading API Gateway Account %s", d.Id())
- account, err := conn.GetAccount(&apigateway.GetAccountInput{})
- if err != nil {
- return err
- }
-
- log.Printf("[DEBUG] Received API Gateway Account: %s", account)
-
- if _, ok := d.GetOk("cloudwatch_role_arn"); ok {
- // CloudwatchRoleArn cannot be empty nor made empty via API
- // This resource can however be useful w/out defining cloudwatch_role_arn
- // (e.g. for referencing throttle_settings)
- d.Set("cloudwatch_role_arn", account.CloudwatchRoleArn)
- }
- d.Set("throttle_settings", flattenApiGatewayThrottleSettings(account.ThrottleSettings))
-
- return nil
-}
-
-func resourceAwsApiGatewayAccountUpdate(d *schema.ResourceData, meta interface{}) error {
- conn := meta.(*AWSClient).apigateway
-
- input := apigateway.UpdateAccountInput{}
- operations := make([]*apigateway.PatchOperation, 0)
-
- if d.HasChange("cloudwatch_role_arn") {
- arn := d.Get("cloudwatch_role_arn").(string)
- if len(arn) > 0 {
- // Unfortunately AWS API doesn't allow empty ARNs,
- // even though that's default settings for new AWS accounts
- // BadRequestException: The role ARN is not well formed
- operations = append(operations, &apigateway.PatchOperation{
- Op: aws.String("replace"),
- Path: aws.String("/cloudwatchRoleArn"),
- Value: aws.String(arn),
- })
- }
- }
- input.PatchOperations = operations
-
- log.Printf("[INFO] Updating API Gateway Account: %s", input)
-
- // Retry due to eventual consistency of IAM
- expectedErrMsg := "The role ARN does not have required permissions set to API Gateway"
- otherErrMsg := "API Gateway could not successfully write to CloudWatch Logs using the ARN specified"
- var out *apigateway.Account
- var err error
- err = resource.Retry(2*time.Minute, func() *resource.RetryError {
- out, err = conn.UpdateAccount(&input)
-
- if err != nil {
- if isAWSErr(err, "BadRequestException", expectedErrMsg) ||
- isAWSErr(err, "BadRequestException", otherErrMsg) {
- log.Printf("[DEBUG] Retrying API Gateway Account update: %s", err)
- return resource.RetryableError(err)
- }
- return resource.NonRetryableError(err)
- }
-
- return nil
- })
- if err != nil {
- return fmt.Errorf("Updating API Gateway Account failed: %s", err)
- }
- log.Printf("[DEBUG] API Gateway Account updated: %s", out)
-
- d.SetId("api-gateway-account")
- return resourceAwsApiGatewayAccountRead(d, meta)
-}
-
-func resourceAwsApiGatewayAccountDelete(d *schema.ResourceData, meta interface{}) error {
- // There is no API for "deleting" account or resetting it to "default" settings
- d.SetId("")
- return nil
-}
diff --git a/builtin/providers/aws/resource_aws_api_gateway_account_test.go b/builtin/providers/aws/resource_aws_api_gateway_account_test.go
deleted file mode 100644
index c50339f7e..000000000
--- a/builtin/providers/aws/resource_aws_api_gateway_account_test.go
+++ /dev/null
@@ -1,205 +0,0 @@
-package aws
-
-import (
- "fmt"
- "regexp"
- "testing"
-
- "github.com/aws/aws-sdk-go/service/apigateway"
- "github.com/hashicorp/terraform/helper/resource"
- "github.com/hashicorp/terraform/terraform"
-)
-
-func TestAccAWSAPIGatewayAccount_basic(t *testing.T) {
- var conf apigateway.Account
-
- expectedRoleArn_first := regexp.MustCompile("[0-9]+")
- expectedRoleArn_second := regexp.MustCompile("[0-9]+")
-
- resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- Providers: testAccProviders,
- CheckDestroy: testAccCheckAWSAPIGatewayAccountDestroy,
- Steps: []resource.TestStep{
- resource.TestStep{
- Config: testAccAWSAPIGatewayAccountConfig_updated,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAWSAPIGatewayAccountExists("aws_api_gateway_account.test", &conf),
- testAccCheckAWSAPIGatewayAccountCloudwatchRoleArn(&conf, expectedRoleArn_first),
- resource.TestMatchResourceAttr("aws_api_gateway_account.test", "cloudwatch_role_arn", expectedRoleArn_first),
- ),
- },
- resource.TestStep{
- Config: testAccAWSAPIGatewayAccountConfig_updated2,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAWSAPIGatewayAccountExists("aws_api_gateway_account.test", &conf),
- testAccCheckAWSAPIGatewayAccountCloudwatchRoleArn(&conf, expectedRoleArn_second),
- resource.TestMatchResourceAttr("aws_api_gateway_account.test", "cloudwatch_role_arn", expectedRoleArn_second),
- ),
- },
- resource.TestStep{
- Config: testAccAWSAPIGatewayAccountConfig_empty,
- Check: resource.ComposeTestCheckFunc(
- testAccCheckAWSAPIGatewayAccountExists("aws_api_gateway_account.test", &conf),
- testAccCheckAWSAPIGatewayAccountCloudwatchRoleArn(&conf, expectedRoleArn_second),
- ),
- },
- },
- })
-}
-
-func testAccCheckAWSAPIGatewayAccountCloudwatchRoleArn(conf *apigateway.Account, expectedArn *regexp.Regexp) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- if expectedArn == nil && conf.CloudwatchRoleArn == nil {
- return nil
- }
- if expectedArn == nil && conf.CloudwatchRoleArn != nil {
- return fmt.Errorf("Expected empty CloudwatchRoleArn, given: %q", *conf.CloudwatchRoleArn)
- }
- if expectedArn != nil && conf.CloudwatchRoleArn == nil {
- return fmt.Errorf("Empty CloudwatchRoleArn, expected: %q", expectedArn)
- }
- if !expectedArn.MatchString(*conf.CloudwatchRoleArn) {
- return fmt.Errorf("CloudwatchRoleArn didn't match. Expected: %q, Given: %q", expectedArn, *conf.CloudwatchRoleArn)
- }
- return nil
- }
-}
-
-func testAccCheckAWSAPIGatewayAccountExists(n string, res *apigateway.Account) resource.TestCheckFunc {
- return func(s *terraform.State) error {
- rs, ok := s.RootModule().Resources[n]
- if !ok {
- return fmt.Errorf("Not found: %s", n)
- }
-
- if rs.Primary.ID == "" {
- return fmt.Errorf("No API Gateway Account ID is set")
- }
-
- conn := testAccProvider.Meta().(*AWSClient).apigateway
-
- req := &apigateway.GetAccountInput{}
- describe, err := conn.GetAccount(req)
- if err != nil {
- return err
- }
- if describe == nil {
- return fmt.Errorf("Got nil account ?!")
- }
-
- *res = *describe
-
- return nil
- }
-}
-
-func testAccCheckAWSAPIGatewayAccountDestroy(s *terraform.State) error {
- // Intentionally noop
- // as there is no API method for deleting or resetting account settings
- return nil
-}
-
-const testAccAWSAPIGatewayAccountConfig_empty = `
-resource "aws_api_gateway_account" "test" {
-}
-`
-
-const testAccAWSAPIGatewayAccountConfig_updated = `
-resource "aws_api_gateway_account" "test" {
- cloudwatch_role_arn = "${aws_iam_role.cloudwatch.arn}"
-}
-
-resource "aws_iam_role" "cloudwatch" {
- name = "api_gateway_cloudwatch_global"
- assume_role_policy = <Foo