Skip to content

Instantly share code, notes, and snippets.

@nwithan8
Last active January 8, 2021 02:13
Show Gist options
  • Select an option

  • Save nwithan8/6ca01aa0062d3821f2e5433f209e2bcc to your computer and use it in GitHub Desktop.

Select an option

Save nwithan8/6ca01aa0062d3821f2e5433f209e2bcc to your computer and use it in GitHub Desktop.
Make an A record on Cloudflare and generate corresponding Apache2 reverse proxy site file
import CloudFlare
import argparse
CLOUDFLARE_API_KEY = "XXXXXXX"
parser = argparse.ArgumentParser(description="Make a reverse proxy file and CloudFlare DNS entry")
parser.add_argument('subdomain',
type=str,
help='new subdomain prefix')
parser.add_argument('domain',
type=str,
help='Base domain')
parser.add_argument('external_ip',
type=str,
help="External IP address")
parser.add_argument('-6',
'--ipv6',
action='store_true',
help="Use IPV6 address")
parser.add_argument('destination',
type=str,
help="Destination of proxy (ex. http://192.168.1.1:80")
args = parser.parse_args()
template = """
<VirtualHost *:80>
ServerName {subdomain}.{domain}
Redirect permanent / https://{subdomain}.{domain}/
ErrorLog /var/log/apache2/{domain}-error.log
CustomLog /var/log/apache2/{domain}-access.log combined
</VirtualHost>
<VirtualHost *:443>
ServerName {subdomain}.{domain}
ProxyPreserveHost On
ProxyPass "/" "{localip}/"
ProxyPassReverse "/" "{localip}/"
SSLEngine on
Protocols h2 http/1.1
ErrorLog /var/log/apache2/{domain}-error.log
CustomLog /var/log/apache2/{domain}-access.log combined
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/{domain}/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/{domain}/privkey.pem
</VirtualHost>
"""
def write_to_file(string, filename):
with open(filename, 'w+') as f:
f.write(string)
def make_dns_record(subdomain, zone_id, ip_address, IPV6: bool = False):
new_record = {'name': subdomain, 'type': ('AAAA' if IPV6 else 'A'), 'content': ip_address}
if not cf.zones.dns_records.post(zone_id, data=new_record):
raise Exception("Could not make DNS entry on CloudFlare.")
cf = CloudFlare.CloudFlare(token=CLOUDFLARE_API_KEY)
zone_id = cf.zones.get(params = {'name':args.domain,'per_page':1})[0]['id']
make_dns_record(subdomain=args.subdomain, zone_id=zone_id, ip_address=args.external_ip, IPV6=args.ipv6)
proxy_entry = template.format(subdomain=args.subdomain, domain=args.domain, localip=args.destination)
write_to_file(string=proxy_entry, filename=f"/etc/apache2/sites-available/{args.subdomain}-{args.domain}.conf")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment