Skip to content

Commit

Permalink
Merge pull request #7710 from terraform-providers/td-aws_cloudfront_d…
Browse files Browse the repository at this point in the history
…istribution-remove-deprecated

resource/aws_cloudfront_distribution: Remove deprecated cache_behaviors configuration block
  • Loading branch information
bflad authored Feb 25, 2019
2 parents d86762f + b5f10a9 commit eacb05c
Show file tree
Hide file tree
Showing 5 changed files with 17 additions and 250 deletions.
91 changes: 3 additions & 88 deletions aws/cloudfront_distribution_configuration_structure.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ func (p StringPtrSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
// Used by the aws_cloudfront_distribution Create and Update functions.
func expandDistributionConfig(d *schema.ResourceData) *cloudfront.DistributionConfig {
distributionConfig := &cloudfront.DistributionConfig{
CacheBehaviors: expandCacheBehaviors(d.Get("ordered_cache_behavior").([]interface{})),
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)),
Expand All @@ -50,11 +51,7 @@ func expandDistributionConfig(d *schema.ResourceData) *cloudfront.DistributionCo
Origins: expandOrigins(d.Get("origin").(*schema.Set)),
PriceClass: aws.String(d.Get("price_class").(string)),
}
if v, ok := d.GetOk("ordered_cache_behavior"); ok {
distributionConfig.CacheBehaviors = expandCacheBehaviors(v.([]interface{}))
} else {
distributionConfig.CacheBehaviors = expandCacheBehaviorsDeprecated(d.Get("cache_behavior").(*schema.Set))
}

// This sets CallerReference if it's still pending computation (ie: new resource)
if v, ok := d.GetOk("caller_reference"); !ok {
distributionConfig.CallerReference = aws.String(time.Now().Format(time.RFC3339Nano))
Expand Down Expand Up @@ -144,13 +141,7 @@ func flattenDistributionConfig(d *schema.ResourceData, distributionConfig *cloud
}
}
if distributionConfig.CacheBehaviors != nil {
if _, ok := d.GetOk("cache_behavior"); ok {
err = d.Set("cache_behavior", flattenCacheBehaviorsDeprecated(distributionConfig.CacheBehaviors))
} else {
err = d.Set("ordered_cache_behavior", flattenCacheBehaviors(distributionConfig.CacheBehaviors))
}

if err != nil {
if err := d.Set("ordered_cache_behavior", flattenCacheBehaviors(distributionConfig.CacheBehaviors)); err != nil {
return err
}
}
Expand Down Expand Up @@ -254,27 +245,6 @@ func defaultCacheBehaviorHash(v interface{}) int {
return hashcode.String(buf.String())
}

func expandCacheBehaviorsDeprecated(s *schema.Set) *cloudfront.CacheBehaviors {
var qty int64
var items []*cloudfront.CacheBehavior
for _, v := range s.List() {
items = append(items, expandCacheBehaviorDeprecated(v.(map[string]interface{})))
qty++
}
return &cloudfront.CacheBehaviors{
Quantity: aws.Int64(qty),
Items: items,
}
}

func flattenCacheBehaviorsDeprecated(cbs *cloudfront.CacheBehaviors) *schema.Set {
s := []interface{}{}
for _, v := range cbs.Items {
s = append(s, flattenCacheBehaviorDeprecated(v))
}
return schema.NewSet(cacheBehaviorHash, s)
}

func expandCacheBehaviors(lst []interface{}) *cloudfront.CacheBehaviors {
var qty int64
var items []*cloudfront.CacheBehavior
Expand Down Expand Up @@ -445,61 +415,6 @@ func flattenCacheBehavior(cb *cloudfront.CacheBehavior) map[string]interface{} {
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["field_level_encryption_id"]; ok && d.(string) != "" {
buf.WriteString(fmt.Sprintf("%s-", d.(string)))
}
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 {
Expand Down
141 changes: 0 additions & 141 deletions aws/cloudfront_distribution_configuration_structure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,22 +27,6 @@ func defaultCacheBehaviorConf() map[string]interface{} {
}
}

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"}
}
Expand Down Expand Up @@ -310,131 +294,6 @@ func TestCloudFrontStructure_flattenDefaultCacheBehavior(t *testing.T) {
}
}

func TestCloudFrontStructure_expandCacheBehavior(t *testing.T) {
data := cacheBehaviorConf1()
cb := expandCacheBehaviorDeprecated(data)
if !*cb.Compress {
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())) {
t.Fatalf("Expected Items to be %v, got %v", headersConf(), cb.ForwardedValues.Headers.Items)
}
if *cb.MinTTL != 0 {
t.Fatalf("Expected MinTTL to be 0, got %v", *cb.MinTTL)
}
if !reflect.DeepEqual(cb.TrustedSigners.Items, expandStringList(trustedSignersConf())) {
t.Fatalf("Expected TrustedSigners.Items to be %v, got %v", trustedSignersConf(), cb.TrustedSigners.Items)
}
if *cb.MaxTTL != 31536000 {
t.Fatalf("Expected MaxTTL to be 31536000, got %v", *cb.MaxTTL)
}
if *cb.SmoothStreaming {
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())) {
t.Fatalf("Expected AllowedMethods.Items to be %v, got %v", allowedMethodsConf(), cb.AllowedMethods.Items)
}
if !reflect.DeepEqual(cb.AllowedMethods.CachedMethods.Items, expandStringList(cachedMethodsConf())) {
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 := expandCacheBehaviorDeprecated(in)
out := flattenCacheBehaviorDeprecated(cb)
var diff *schema.Set
if !out["compress"].(bool) {
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(0) {
t.Fatalf("Expected out[min_ttl] to be 0 (int), got %v", out["min_ttl"])
}
if !reflect.DeepEqual(out["trusted_signers"], in["trusted_signers"]) {
t.Fatalf("Expected out[trusted_signers] to be %v, got %v", in["trusted_signers"], out["trusted_signers"])
}
if out["max_ttl"] != int(31536000) {
t.Fatalf("Expected out[max_ttl] to be 31536000 (int), got %v", out["max_ttl"])
}
if out["smooth_streaming"].(bool) {
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"]) {
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"]) {
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 := expandCacheBehaviorsDeprecated(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 := expandCacheBehaviorsDeprecated(in)
out := flattenCacheBehaviorsDeprecated(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)
Expand Down
13 changes: 5 additions & 8 deletions aws/resource_aws_cloudfront_distribution.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,9 @@ func resourceAwsCloudFrontDistribution() *schema.Resource {
Set: aliasesHash,
},
"cache_behavior": {
Type: schema.TypeSet,
Optional: true,
Set: cacheBehaviorHash,
ConflictsWith: []string{"ordered_cache_behavior"},
Deprecated: "Use `ordered_cache_behavior` instead",
Type: schema.TypeSet,
Optional: true,
Removed: "Use `ordered_cache_behavior` configuration block(s) instead",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"allowed_methods": {
Expand Down Expand Up @@ -167,9 +165,8 @@ func resourceAwsCloudFrontDistribution() *schema.Resource {
},
},
"ordered_cache_behavior": {
Type: schema.TypeList,
Optional: true,
ConflictsWith: []string{"cache_behavior"},
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"allowed_methods": {
Expand Down
10 changes: 5 additions & 5 deletions aws/resource_aws_cloudfront_distribution_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,9 +207,9 @@ func TestAccAWSCloudFrontDistribution_multiOrigin(t *testing.T) {
Config: testAccAWSCloudFrontDistributionMultiOriginConfig,
Check: resource.ComposeTestCheckFunc(
testAccCheckCloudFrontDistributionExistence(resourceName),
resource.TestCheckResourceAttr(resourceName, "cache_behavior.#", "2"),
resource.TestCheckResourceAttr(resourceName, "cache_behavior.2106187217.default_ttl", "50"),
resource.TestCheckResourceAttr(resourceName, "cache_behavior.2106187217.path_pattern", "images1/*.jpg"),
resource.TestCheckResourceAttr(resourceName, "ordered_cache_behavior.#", "2"),
resource.TestCheckResourceAttr(resourceName, "ordered_cache_behavior.0.default_ttl", "50"),
resource.TestCheckResourceAttr(resourceName, "ordered_cache_behavior.0.path_pattern", "images1/*.jpg"),
),
},
},
Expand Down Expand Up @@ -763,7 +763,7 @@ resource "aws_cloudfront_distribution" "multi_origin_distribution" {
max_ttl = 100
viewer_protocol_policy = "allow-all"
}
cache_behavior {
ordered_cache_behavior {
allowed_methods = [ "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT" ]
cached_methods = [ "GET", "HEAD" ]
target_origin_id = "myS3Origin"
Expand All @@ -779,7 +779,7 @@ resource "aws_cloudfront_distribution" "multi_origin_distribution" {
viewer_protocol_policy = "allow-all"
path_pattern = "images1/*.jpg"
}
cache_behavior {
ordered_cache_behavior {
allowed_methods = [ "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT" ]
cached_methods = [ "GET", "HEAD" ]
target_origin_id = "myCustomOrigin"
Expand Down
12 changes: 4 additions & 8 deletions website/docs/r/cloudfront_distribution.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -154,12 +154,6 @@ of several sub-resources - these resources are laid out below.
* `aliases` (Optional) - Extra CNAMEs (alternate domain names), if any, for
this distribution.

* `cache_behavior` (Optional) - **Deprecated**, use `ordered_cache_behavior` instead.

* `ordered_cache_behavior` (Optional) - An ordered list of [cache behaviors](#cache-behavior-arguments)
resource for this distribution. List from top to bottom
+ in order of precedence. The topmost cache behavior will have precedence 0.

* `comment` (Optional) - Any comments you want to include about the
distribution.

Expand All @@ -184,6 +178,10 @@ of several sub-resources - these resources are laid out below.
configuration](#logging-config-arguments) that controls how logs are written
to your distribution (maximum one).

* `ordered_cache_behavior` (Optional) - An ordered list of [cache behaviors](#cache-behavior-arguments)
resource for this distribution. List from top to bottom
in order of precedence. The topmost cache behavior will have precedence 0.

* `origin` (Required) - One or more [origins](#origin-arguments) for this
distribution (multiples allowed).

Expand Down Expand Up @@ -477,7 +475,6 @@ In addition to all arguments above, the following attributes are exported:
route an [Alias Resource Record Set][7] to. This attribute is simply an
alias for the zone ID `Z2FDTNDATAQYW2`.


[1]: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Introduction.html
[2]: https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateDistribution.html
[3]: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html
Expand All @@ -486,7 +483,6 @@ In addition to all arguments above, the following attributes are exported:
[6]: https://aws.amazon.com/certificate-manager/
[7]: http://docs.aws.amazon.com/Route53/latest/APIReference/CreateAliasRRSAPI.html


## Import

Cloudfront Distributions can be imported using the `id`, e.g.
Expand Down

0 comments on commit eacb05c

Please sign in to comment.