Skip to content

Instantly share code, notes, and snippets.

@imod
Last active September 16, 2020 19:45
Show Gist options
  • Save imod/52050eec87f87a60b5944c29ebf0f7a1 to your computer and use it in GitHub Desktop.
Save imod/52050eec87f87a60b5944c29ebf0f7a1 to your computer and use it in GitHub Desktop.
A terraform configuration generate a managed certificate and bind it to a custom domain on azure
resource "azurerm_app_service_custom_hostname_binding" "app_domain" {
hostname = "dummy.mydomain.com"
app_service_name = "my_app_name"
resource_group_name = "my_resource_group"
provisioner "local-exec" {
command = "./ensure_cert_for_domain.sh"
environment = {
RG_NAME = azurerm_app_service_custom_hostname_binding.app_domain.resource_group_name
APP_NAME = azurerm_app_service_custom_hostname_binding.app_domain.app_service_name
FQDN = azurerm_app_service_custom_hostname_binding.app_domain.hostname
}
}
lifecycle {
ignore_changes = [
# Ignore changes to these fields, these are updated by the script
ssl_state,
thumbprint
]
}
}
#!/usr/bin/env bash
# - tries to find an existing certificate for the given domain
# - if not found, create a new managed certificate
# - bind the certificate to the custom domain
#
# usage:
# RG_NAME=my_resource_group FQDN="dummy.mydomain.com" APP_NAME=my_app_name
# 1. try to find an thumbprint of an exsiting cert for the given domain
THUMBPRINT=$(az webapp config ssl list --resource-group "$RG_NAME" -o tsv --query "[?canonicalName=='$FQDN'].thumbprint")
if [ -z "$THUMBPRINT" ]; then
echo "generate new cert"
# 2. generate cert and only return the thunbprint
THUMBPRINT=$(az webapp config ssl create --resource-group "$RG_NAME" --name "$APP_NAME" --hostname "$FQDN" -o tsv --query "thumbprint")
else
echo "found existing thumbprint $THUMBPRINT for $FQDN"
fi
# 3. bind the SSL certificate to the web app (via thumbprint).
NAME=$(az webapp config ssl bind --ssl-type SNI --resource-group "$RG_NAME" --name "$APP_NAME" --certificate-thumbprint "$THUMBPRINT" -o tsv --query "name")
if [ $? -eq 0 ]; then
echo "successfully bound certificate $THUMBPRINT to $NAME for $FQDN"
else
echo "failed to bind certifcate $THUMBPRINT to $APP_NAME for $FQDN"
exit 1
fi
@imod
Copy link
Author

imod commented Sep 16, 2020

be aware: the certificate might change its thumbprint - if this happens, you should mark the binding as tainted so it can be recreated by terraform.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment