Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

r/aws_elasticsearch_domain: Add custom endpoint support #16192

Merged
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion aws/resource_aws_elasticsearch_domain.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,8 @@ func resourceAwsElasticSearchDomain() *schema.Resource {
Schema: map[string]*schema.Schema{
"enforce_https": {
Type: schema.TypeBool,
Required: true,
Optional: true,
Default: true,
Comment on lines +143 to +144
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What was the reasoning for this change? I don't see any explanation in 5217ecb and it looks like an unnecessary change at a glance.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi, because it doesn't has to be a necessary attribute to set. For example, you might want to enable a custom endpoint, so you would have to just set custom_endpoint_enabled and custom_endpoint attributes and no more that that.

},
"tls_security_policy": {
Type: schema.TypeString,
Expand All @@ -151,6 +152,29 @@ func resourceAwsElasticSearchDomain() *schema.Resource {
elasticsearch.TLSSecurityPolicyPolicyMinTls12201907,
}, false),
},
"custom_endpoint_enabled": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"custom_endpoint": {
Type: schema.TypeString,
Optional: true,
StateFunc: func(v interface{}) string {
// AWS Provider aws_acm_certification.domain_validation_options.resource_record_name
// references (and perhaps others) contain a trailing period, requiring a custom StateFunc
// to trim the string to prevent Route53 API error
value := strings.TrimSuffix(v.(string), ".")
return strings.ToLower(value)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks like it has been lifted directly from aws/resource_aws_route53_record.go. Is it strictly needed here because of a similar API error on the ES API? Sadly https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-configuration-api.html#es-configuration-api-datatypes-domainendpointoptions leaves any validation undocumented.

https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-customendpoint.html suggests you can leave a trailing dot at the end but the console may just strip that.

I was also wondering if there was a common validate function that checks it's a valid FQDN (max length in total and per label etc) but I don't see one elsewhere in the code base or in the plugin SDK.

At the least the comment here probably wants updating.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, I have just lifted that code from aws/resource_aws_route53_record.go. I was trying to find a common validation function but it doesn't exist, it might be becose the different AWS API endpoints require different validations to be done. I agree with you about the comment update, I will do that. Thank you!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is generally preferable to leave out these types of StateFunc where possible. If the API has issues with trailing periods, we can introduce validation to try and catch that early.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perfect @bflad , I will get rid of that validation.

},
DiffSuppressFunc: isCustomEndpointDisabled,
},
"custom_endpoint_certificate_arn": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateArn,
DiffSuppressFunc: isCustomEndpointDisabled,
},
},
},
},
Expand Down Expand Up @@ -1037,6 +1061,15 @@ func isDedicatedMasterDisabled(k, old, new string, d *schema.ResourceData) bool
return false
}

func isCustomEndpointDisabled(k, old, new string, d *schema.ResourceData) bool {
v, ok := d.GetOk("domain_endpoint_options")
if ok {
domainEndpointOptions := v.([]interface{})[0].(map[string]interface{})
return !domainEndpointOptions["custom_endpoint_enabled"].(bool)
}
return false
}

func expandESNodeToNodeEncryptionOptions(s map[string]interface{}) *elasticsearch.NodeToNodeEncryptionOptions {
options := elasticsearch.NodeToNodeEncryptionOptions{}

Expand Down
100 changes: 100 additions & 0 deletions aws/resource_aws_elasticsearch_domain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,57 @@ func TestAccAWSElasticSearchDomain_RequireHTTPS(t *testing.T) {
})
}

func TestAccAWSElasticSearchDomain_CustomEndpoint(t *testing.T) {
var domain elasticsearch.ElasticsearchDomainStatus
ri := acctest.RandInt()
resourceId := fmt.Sprintf("tf-test-%d", ri)
resourceName := "aws_elasticsearch_domain.example"
customEndpoint := fmt.Sprintf("%s.example.com", resourceId)
certResourceName := "aws_acm_certificate.example"
certKey := tlsRsaPrivateKeyPem(2048)
certificate := tlsRsaX509SelfSignedCertificatePem(certKey, customEndpoint)

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckESDomainDestroy,
Steps: []resource.TestStep{
{
Config: testAccESDomainConfig_CustomEndpoint(ri, true, "Policy-Min-TLS-1-0-2019-07", true, customEndpoint, certKey, certificate),
Check: resource.ComposeTestCheckFunc(
testAccCheckESDomainExists(resourceName, &domain),
resource.TestCheckResourceAttr(resourceName, "domain_endpoint_options.#", "1"),
resource.TestCheckResourceAttr(resourceName, "domain_endpoint_options.0.custom_endpoint_enabled", "true"),
resource.TestCheckResourceAttrSet(resourceName, "domain_endpoint_options.0.custom_endpoint"),
resource.TestCheckResourceAttrPair(resourceName, "domain_endpoint_options.0.custom_endpoint_certificate_arn", certResourceName, "arn"),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateId: resourceId,
ImportStateVerify: true,
},
{
Config: testAccESDomainConfig_CustomEndpoint(ri, true, "Policy-Min-TLS-1-0-2019-07", true, customEndpoint, certKey, certificate),
Check: resource.ComposeTestCheckFunc(
testAccCheckESDomainExists(resourceName, &domain),
testAccCheckESDomainEndpointOptions(true, "Policy-Min-TLS-1-0-2019-07", &domain),
testAccCheckESCustomEndpoint(resourceName, true, customEndpoint, &domain),
),
},
{
Config: testAccESDomainConfig_CustomEndpoint(ri, true, "Policy-Min-TLS-1-0-2019-07", false, customEndpoint, certKey, certificate),
Check: resource.ComposeTestCheckFunc(
testAccCheckESDomainExists(resourceName, &domain),
testAccCheckESDomainEndpointOptions(true, "Policy-Min-TLS-1-0-2019-07", &domain),
testAccCheckESCustomEndpoint(resourceName, false, customEndpoint, &domain),
),
},
},
})
}

func TestAccAWSElasticSearchDomain_ClusterConfig_ZoneAwarenessConfig(t *testing.T) {
var domain1, domain2, domain3, domain4 elasticsearch.ElasticsearchDomainStatus
rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(16, acctest.CharSetAlphaNum)) // len = 28
Expand Down Expand Up @@ -1092,6 +1143,29 @@ func testAccCheckESDomainEndpointOptions(enforceHTTPS bool, tls string, status *
}
}

func testAccCheckESCustomEndpoint(n string, customEndpointEnabled bool, customEndpoint string, status *elasticsearch.ElasticsearchDomainStatus) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
options := status.DomainEndpointOptions
if *options.CustomEndpointEnabled != customEndpointEnabled {
return fmt.Errorf("CustomEndpointEnabled differ. Given: %t, Expected: %t", *options.CustomEndpointEnabled, customEndpointEnabled)
}
if *options.CustomEndpointEnabled {
if *options.CustomEndpoint != customEndpoint {
return fmt.Errorf("CustomEndpoint differ. Given: %s, Expected: %s", *options.CustomEndpoint, customEndpoint)
}
customEndpointCertificateArn := rs.Primary.Attributes["domain_endpoint_options.0.custom_endpoint_certificate_arn"]
if *options.CustomEndpointCertificateArn != customEndpointCertificateArn {
return fmt.Errorf("CustomEndpointCertificateArn differ. Given: %s, Expected: %s", *options.CustomEndpointCertificateArn, customEndpointCertificateArn)
}
}
return nil
}
}

func testAccCheckESNumberOfSecurityGroups(numberOfSecurityGroups int, status *elasticsearch.ElasticsearchDomainStatus) resource.TestCheckFunc {
return func(s *terraform.State) error {
count := len(status.VPCOptions.SecurityGroupIds)
Expand Down Expand Up @@ -1355,6 +1429,32 @@ resource "aws_elasticsearch_domain" "example" {
`, randInt, enforceHttps, tlsSecurityPolicy)
}

func testAccESDomainConfig_CustomEndpoint(randInt int, enforceHttps bool, tlsSecurityPolicy string, customEndpointEnabled bool, customEndpoint string, certKey string, certBody string) string {
return fmt.Sprintf(`
resource "aws_acm_certificate" "example" {
private_key = "%[6]s"
certificate_body = "%[7]s"
}

resource "aws_elasticsearch_domain" "example" {
domain_name = "tf-test-%[1]d"

domain_endpoint_options {
enforce_https = %[2]t
tls_security_policy = %[3]q
custom_endpoint_enabled = %[4]t
custom_endpoint = "%[5]s"
custom_endpoint_certificate_arn = aws_acm_certificate.example.arn
}

ebs_options {
ebs_enabled = true
volume_size = 10
}
}
`, randInt, enforceHttps, tlsSecurityPolicy, customEndpointEnabled, customEndpoint, tlsPemEscapeNewlines(certKey), tlsPemEscapeNewlines(certBody))
}

func testAccESDomainConfig_ClusterConfig_ZoneAwarenessConfig_AvailabilityZoneCount(rName string, availabilityZoneCount int) string {
return fmt.Sprintf(`
resource "aws_elasticsearch_domain" "test" {
Expand Down
27 changes: 25 additions & 2 deletions aws/structure.go
Original file line number Diff line number Diff line change
Expand Up @@ -1376,6 +1376,20 @@ func expandESDomainEndpointOptions(l []interface{}) *elasticsearch.DomainEndpoin
domainEndpointOptions.TLSSecurityPolicy = aws.String(v)
}

if customEndpointEnabled, ok := m["custom_endpoint_enabled"]; ok {
domainEndpointOptions.CustomEndpointEnabled = aws.Bool(customEndpointEnabled.(bool))

if customEndpointEnabled.(bool) {
if v, ok := m["custom_endpoint"].(string); ok && v != "" {
domainEndpointOptions.CustomEndpoint = aws.String(v)
}

if v, ok := m["custom_endpoint_certificate_arn"].(string); ok && v != "" {
domainEndpointOptions.CustomEndpointCertificateArn = aws.String(v)
}
}
}

return domainEndpointOptions
}

Expand All @@ -1385,8 +1399,17 @@ func flattenESDomainEndpointOptions(domainEndpointOptions *elasticsearch.DomainE
}

m := map[string]interface{}{
"enforce_https": aws.BoolValue(domainEndpointOptions.EnforceHTTPS),
"tls_security_policy": aws.StringValue(domainEndpointOptions.TLSSecurityPolicy),
"enforce_https": aws.BoolValue(domainEndpointOptions.EnforceHTTPS),
"tls_security_policy": aws.StringValue(domainEndpointOptions.TLSSecurityPolicy),
"custom_endpoint_enabled": aws.BoolValue(domainEndpointOptions.CustomEndpointEnabled),
}
if aws.BoolValue(domainEndpointOptions.CustomEndpointEnabled) {
if domainEndpointOptions.CustomEndpoint != nil {
m["custom_endpoint"] = aws.StringValue(domainEndpointOptions.CustomEndpoint)
}
if domainEndpointOptions.CustomEndpointCertificateArn != nil {
m["custom_endpoint_certificate_arn"] = aws.StringValue(domainEndpointOptions.CustomEndpointCertificateArn)
}
}

return []interface{}{m}
Expand Down
5 changes: 4 additions & 1 deletion website/docs/r/elasticsearch_domain.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -252,8 +252,11 @@ The **advanced_security_options** block supports the following attributes:

**domain_endpoint_options** supports the following attributes:

* `enforce_https` - (Required) Whether or not to require HTTPS
* `enforce_https` - (Optional) Whether or not to require HTTPS
* `tls_security_policy` - (Optional) The name of the TLS security policy that needs to be applied to the HTTPS endpoint. Valid values: `Policy-Min-TLS-1-0-2019-07` and `Policy-Min-TLS-1-2-2019-07`. Terraform will only perform drift detection if a configuration value is provided.
* `custom_endpoint_enabled` - (Optional) Whether to enable custom endpoint for the Elasticsearch domain
* `custom_endpoint` - (Optional) Fully qualified domain for your custom endpoint
* `custom_endpoint_certificate_arn` - (Optional) ACM certificate ARN for your custom endpoint

**cluster_config** supports the following attributes:

Expand Down