diff --git a/builtin/providers/aws/provider.go b/builtin/providers/aws/provider.go index 2573b8edb..f41f7e25b 100644 --- a/builtin/providers/aws/provider.go +++ b/builtin/providers/aws/provider.go @@ -153,6 +153,7 @@ func Provider() terraform.ResourceProvider { ResourcesMap: map[string]*schema.Resource{ "aws_alb": resourceAwsAlb(), + "aws_alb_listener": resourceAwsAlbListener(), "aws_alb_target_group": resourceAwsAlbTargetGroup(), "aws_ami": resourceAwsAmi(), "aws_ami_copy": resourceAwsAmiCopy(), diff --git a/builtin/providers/aws/resource_aws_alb_listener.go b/builtin/providers/aws/resource_aws_alb_listener.go new file mode 100644 index 000000000..a2bdf2413 --- /dev/null +++ b/builtin/providers/aws/resource_aws_alb_listener.go @@ -0,0 +1,261 @@ +package aws + +import ( + "errors" + "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/elbv2" + "github.com/hashicorp/errwrap" + "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, + }, + + "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: validateAwsAlbListenerDefaultActionType, + }, + }, + }, + }, + }, + } +} + +func resourceAwsAlbListenerCreate(d *schema.ResourceData, meta interface{}) error { + elbconn := meta.(*AWSClient).elbv2conn + + params := &elbv2.CreateListenerInput{ + LoadBalancerArn: aws.String(d.Get("load_balancer_arn").(string)), + 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)), + } + } + } + + resp, err := elbconn.CreateListener(params) + 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 validateAwsAlbListenerDefaultActionType(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_test.go b/builtin/providers/aws/resource_aws_alb_listener_test.go new file mode 100644 index 000000000..6b41657df --- /dev/null +++ b/builtin/providers/aws/resource_aws_alb_listener_test.go @@ -0,0 +1,385 @@ +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 = 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_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_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 = <aws_alb + > + aws_alb_listener + + > aws_alb_target_group - + > aws_ami