Skip to content

Instantly share code, notes, and snippets.

@johnbeynon
Last active June 13, 2023 15:37
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnbeynon/8accbb18c4791c0ef4449161af34dc94 to your computer and use it in GitHub Desktop.
Save johnbeynon/8accbb18c4791c0ef4449161af34dc94 to your computer and use it in GitHub Desktop.
Add custom domain to Render preview environment app
#!/usr/bin/ruby
# Script to add a custom domain to a preview environment web service. Use it via the buildCommand
#
# Resultant custom domain added to the service will be:
# <servicename>-pr-<number>.prs.mydomain.com
#
# Setup:
#
# Add a wildcard DNS entry to your domain, something like *.prs.mydomain.com pointing to 216.57.24.1
#
# Create a Render environment group and add:
# CUSTOM_DOMAIN_SUFFIX - set this to the DNS entry you added minus the * symbol, eg .prs.mydomain.com
# RENDER_API_TOKEN - get one from your account settings
#
# Then, in your render.yaml
#
# envVars:
# - fromGroup: <name of env group>
require 'uri'
require 'net/http'
require 'openssl'
# we only want to run on Render in pull requests for web services
if ENV['RENDER'] == 'true' && ENV['IS_PULL_REQUEST'] == 'true' && ENV['RENDER_SERVICE_TYPE'] == 'web' && ENV['CUSTOM_DOMAIN_SUFFIX'] && ENV['RENDER_API_TOKEN']
CUSTOM_DOMAIN_TO_ADD = ENV['RENDER_SERVICE_NAME'] + ENV['CUSTOM_DOMAIN_SUFFIX']
SERVICE_ID = ENV['RENDER_SERVICE_ID']
url = URI("https://api.render.com/v1/services/#{SERVICE_ID}/custom-domains")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
# Arbitary change
request = Net::HTTP::Post.new(url)
request["Accept"] = 'application/json'
request["Content-Type"] = 'application/json'
request["Authorization"] = "Bearer #{ENV['RENDER_API_TOKEN']}"
request.body = "{\"name\":\"#{CUSTOM_DOMAIN_TO_ADD}\"}"
response = http.request(request)
puts response.read_body
puts "Added custom domain to #{SERVICE_ID}"
puts "Access via: https://#{CUSTOM_DOMAIN_TO_ADD}"
else
puts "Unable to add custom domain to service, because..."
puts "> Not Deploying to Render" if !ENV['RENDER']
puts "> Not a pull request" if !ENV['IS_PULL_REQUEST']
puts "> Not a web service" if !ENV['RENDER_SERVICE_TYPE'] =='web'
puts "> Custom domain suffix not provided" if !ENV['CUSTOM_DOMAIN_SUFFIX']
puts "> Render API token not provider" if !ENV['RENDER_API_TOKEN']
end
@igl
Copy link

igl commented Nov 22, 2021

a RENDER_SERVICE_ID does not exist?

right now i have to grep on RENDER_INSTANCE_ID

@zlotnika
Copy link

zlotnika commented Oct 5, 2022

I found that I had to take RENDER_INSTANCE_ID and do .replace(/[-][a-z0-9]+[-][a-z0-9]+$/, '') to it (to get the SERVICE_ID from the INSTANCE_ID).

Alternatively, one could get it from calling https://api-docs.render.com/reference/get-services, filtering on slug == RENDER_SERVICE_NAME.

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