Attaching a certificate to a load balancer using Terraform
You can create an Elastic Load Balancer and attach a certificate to it using Terraform. This page provides an example Terraform script for Application Load Balancer.
The aws_lambda_invocation
data source enables you to invoke the sectigoAWSCM-invoke
Lambda function that enrolls a certificate and attaches the certificate’s ARN to the load balancer.
Sample data source
data "aws_lambda_invocation" "sectigoAWSCM-invoke" {
function_name = "SectigoAWSCM-ca-central-1"
input = <<JSON
{
"domains": "04112023test.ccmqa.com",
"action": "enroll",
"account": "your_scm_account_name"
}
JSON
}
Complete Terraform script
The following Terraform script creates a load balancer, enrolls a certificate, and attaches the certificate to the load balancer.
Sample main.tf
----
provider "aws" {
region = var.aws-region
}
data "aws_lambda_invocation" "sectigoAWSCM-invoke" {
function_name = "SectigoAWSCM-ca-central-1"
input = <<JSON
{
"domains": "${var.domain_name}",
"action": "enroll",
"account": "your_scm_account_name"
}
JSON
}
module "alb" {
source = "terraform-aws-modules/alb/aws"
version = "~> 6.0"
name = var.load-bal-name
load_balancer_type = "application"
vpc_id = var.vpc-id
security_groups = [var.sg-id]
subnets = [var.subnet-id-01, var.subnet-id-02]
enable_deletion_protection = false
target_groups = [
{
name_prefix = "awscm-"
backend_protocol = "HTTP"
backend_port = 80
target_type = "instance"
targets = [
{
target_id = var.tg-id
port = 80
}
]
}
]
https_listeners = [
{
port = 443
protocol = "HTTPS"
certificate_arn = "${jsondecode(data.aws_lambda_invocation.sectigoAWSCM-invoke.result)}"
target_group_index = 0
}
]
}
Sample terraform.tfvars
aws-region="ca-central-1"
load-bal-name="sectigoawscm-application-lb"
sg-id="sg-00202042640d41ee2"
vpc-id="vpc-0906e3ecf99d7f912"
subnet-id-01="subnet-094e21db2f6341d8b"
subnet-id-02="subnet-0f0ca139a81f19cd4"
tg-id="i-057af7069aab6427e"
domain_name = "sony_application_lb.ccmqa.com"
Sample variables.tf
variable "aws-region"{
description = "AWS region"
}
variable "load-bal-name"{
description = "Load balancer name"
}
variable "vpc-id"{
description = "AWS virtual private cloud ID "
}
variable "subnet-id-01"{
description = "AWS subnet ID"
}
variable "subnet-id-02"{
description = "AWS subnet ID"
}
variable "tg-id"{
description = "Target group ID"
}
variable "sg-id"{
description = "Target group ID"
}
variable "domain_name" {
description = "The Name of the domain"
}