Error: Error creating SslCertificate: googleapi: Error 409: The resource already exists, alreadyExists

Martin Beranek
2 min readJul 27, 2023
generated by midjourney

What a weird title, huh? This is just a small manual how to go around this issue happening in Terraform if you need to change a TLS certificate of a load balancer. It mainly applies to Ackee Terraform lb module.

Usually, the error displays after terraform apply:


│ Error: Error creating SslCertificate: googleapi: Error 409: The resource 'projects/staging/global/sslCertificates/staging-cert-7m1fl' already exists, alreadyExists

│ with module.cloudrun_lb.google_compute_ssl_certificate.gcs_certs,
│ on .terraform/modules/cloudrun_lb/tls.tf line 37, in resource "google_compute_ssl_certificate" "gcs_certs":
│ 37: resource "google_compute_ssl_certificate" "gcs_certs" {

Check for deposed objects with terraform plan and remove them with terraform apply -target='module.cloudrun_lb.tls_self_signed_cert.lb_cert. Your target path may differ. Also, be careful with target , it can have undesired consequences. Deposed object is usually a certificate you deployed on your own. In our case, that’s a self signed certificate. Your setup might differ.

Check new certificate which haven’t got applied: terraform show -json | python3 search.py module.cloudrun_lb.tls_self_signed_cert.lb_cert where search.py is a snippet you can get on github.

Create new adhoc certificate:

terraform show -json | python3 search.py module.cloudrun_lb.tls_self_signed_cert.lb_cert | jq -r .values.cert_pem > cert.pem
terraform show -json | python3 search.py module.cloudrun_lb.tls_self_signed_cert.lb_cert | jq -r .values.private_key_pem > private_key.pem
gcloud compute ssl-certificates create migration-certificate-`date +"%d%m%Y"` --certificate=cert.pem --private-key=private_key.pem

Check certificates list:

gcloud compute ssl-certificates list
gcloud compute target-https-proxies list

ssl-certificates list shows you the list of certificates and target-https-proxies tells you which certificate is deployed to the load balancer. Note the certificate, it will be handy later.

Now deploy the temporary certificate:

gcloud compute target-https-proxies update staging-7m1fl --ssl-certificates=migration-certificate-`date +"%d%m%Y"`

To be sure there is no outage, I do like to check in a while loop everything is running as it should:

while true; do
curl -I https://api-stage.test.com
sleep 1
done

Once done, let’s straight up the setup with terraform apply. If everything executes correctly, remove the temporary certificate:

gcloud compute ssl-certificates delete migration-certificate-`date +"%d%m%Y"`

In case you won’t be able to remove the certificate, it might be still used Check target-https-proxy to see if you haven’t missed anything.

--

--

Martin Beranek

I am an Infra Team Lead at Shipmonk. My interest is Terraform mainly in GCP. I am also enthusiastic about backend and related topics: Golang, Typescript, ...