Combining Certificate Generation And Server Creation
Technical Background
Traditionally, creating a TLS certificate and configuring it on a server are two separate steps:
1. Request and validate a certificate from a Certificate Authority (CA).
2. Manually install and configure it on the server.
This exercise demonstrates how to automate both steps in a single Terraform configuration by:
- Generating a wildcard certificate with the ACME provider.
- Using cloud-init via the user_data
mechanism to configure Nginx with the generated key and certificate.
Info
This approach creates a fully configured HTTPS-enabled Nginx server immediately at creation time, eliminating the need for manual configuration after deployment.
Solutions
Prerequisits
Create the same files and folder structure as done before in exercise 23 Testing Your Web Certificate.
Update Cloud-init
Add a write_files
attribute inside your /tpl/userData.yml
:
write_files:
- path: /etc/nginx/ssl/certificate.pem
content: |
${certificate_pem}
owner: root:root
permissions: '0600'
- path: /etc/nginx/ssl/private.pem
content: |
${private_key_pem}
owner: root:root
permissions: '0600'
- path: /etc/nginx/sites-available/default
content: |
server {
listen 80 default_server;
listen [::]:80 default_server;
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
ssl_certificate /etc/nginx/ssl/certificate.pem;
ssl_certificate_key /etc/nginx/ssl/private.pem;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
try_files $uri $uri/ =404;
}
}
owner: root:root
permissions: '0644'
Note
This overwrite the default Nginx configuration on the server and activates HTTPS on Port 443.
- Update the run command to restart Nginx:
# Nginx setup
- systemctl enable nginx
- mkdir -p /etc/nginx/ssl
- rm /var/www/html/*
- >
- bash -c 'echo "I\'m Nginx @ $(hostname -I) created $(date -u)" > /var/www/html/index.html'
- systemctl restart nginx
- Verify HTTPS access by opening these addresses in your browser:
https://g11.sdi.hdm-stuttgart.cloud
https://www.g11.sdi.hdm-stuttgart.cloud
https://mail.g11.sdi.hdm-stuttgart.cloud
Note
Inspect the certificate to ensure it includes g03.sdi.hdm-stuttgart.cloud and *.g011.sdi.hdm-stuttgart.cloud.
Related Links
Understanding Web Certificates