Ở các phần trước, mình đã hoàn thành việc đăng ký chứng chỉ SSL và upload lên Alibaba Cloud. Ở phần này, mình sẽ tập trung vào triển khai DCDN qua python SDK.
Để triển khai DCDN, người dùng cần có một dịch vụ đang chạy. Sau khi Active dịch vụ DCDN trên giao diện web của Alibaba Cloud, có thể tiến hành deploy một domain lên Alibaba Cloud DCDN. Các bước có thể tóm tắt như sau:
Lưu ý: DCDN có thể triển khai với second-level domain nhưng chỉ xác thực với first-level domain.
def GetDnsRecordValue(AccessKey, SecretKey,PrimaryDomain,RR): # RR is hostname
config = open_api_models.Config(
access_key_id=AccessKey,
access_key_secret=SecretKey,
region_id="ap-southeast-1"
)
config.endpoint="alidns.ap-southeast-1.aliyuncs.com"
#[product_code].[region_id].aliyuncs.com
dns_client=AlidnsClient(config)
describe_domain_record_request = alidns_models.DescribeDomainRecordsRequest(
domain_name=PrimaryDomain,
search_mode= "EXACT",
page_number=1,
page_size=1, # new record first
key_word=RR,
)
try:
repons = dns_client.describe_domain_records_with_options(describe_domain_record_request, util_models.RuntimeOptions())
return repons
except Exception as error:
print(error)
def DeleteDnsRecord(AccessKey, SecretKey,RecordID): # RR is hostname
config = open_api_models.Config(
access_key_id=AccessKey,
access_key_secret=SecretKey,
region_id="ap-southeast-1"
)
config.endpoint="alidns.ap-southeast-1.aliyuncs.com"
#[product_code].[region_id].aliyuncs.com
dns_client=AlidnsClient(config)
delete_domain_record_request = alidns_models.DeleteDomainRecordRequest(
record_id=RecordID,
)
try:
repons = dns_client.delete_domain_record_with_options(delete_domain_record_request, util_models.RuntimeOptions())
return repons
except Exception as error:
print(error)
def DcdnVerifyDomain(AccessKey, SecretKey, DomainName): #Verify First Level-Domain
config = open_api_models.Config(
access_key_id=AccessKey,
access_key_secret=SecretKey,
region_id="ap-southeast-1"
)
dcdn_client=dcdnClient(config)
parts=DomainName.split('.')
primary_domain='.'.join(parts[-2:])
describe_verify_content_request = dcdn_models.DescribeDcdnVerifyContentRequest(
domain_name=primary_domain
)
check_dns=False
try:
repons = dcdn_client.describe_dcdn_verify_content_with_options(describe_verify_content_request, util_models.RuntimeOptions())
value=repons.body.content
addRecordResult=addDnsRecord(AccessKey,SecretKey,primary_domain,"TXT","verification",value)
print("Check Record verification."+primary_domain, "Value: ",value)
sleep(10)
for i in range(1,5):
res = GetDnsRecordValue(AccessKey,SecretKey,primary_domain,'verification')
if (res.body.total_count > 0) and (res.body.domain_records.record[0].value==value):
check_dns=True
break
else:
if (i==4):
print("Failed to GetDnsRecordValue")
return 0
else:
sleep(10)
continue
except Exception as error:
print(error)
if check_dns:
verify_content_own_request= dcdn_models.VerifyDcdnDomainOwnerRequest(
domain_name=primary_domain,
verify_type="dnsCheck"
)
try:
repons_own = dcdn_client.verify_dcdn_domain_owner_with_options(verify_content_own_request, util_models.RuntimeOptions())
return repons_own
except Exception as error:
print(error)
return 0
else:
print("Failed to addDnsRecord")
return 0
def DcdnAddDomain(AccessKey, SecretKey, DomainName,OrginAddr,OrginType,OriginPort,Scope):
config = open_api_models.Config(
access_key_id=AccessKey,
access_key_secret=SecretKey,
region_id="ap-southeast-1"
)
dcdn_client=dcdnClient(config)
originType=("ipaddr","domain","oss")
scope_define=("global","overseas","domestic")
Scene=('apiscene','webservicescene','staticscene','null')
my_scope=""
if OrginType in originType:
Type=OrginType
else:
Type="ipaddr"
if Scope in scope_define:
my_scope=Scope
else:
Type="overseas"
source=[{"content":OrginAddr,"type":Type,"priority":"20","port":OriginPort}]
add_dcdn_domain_request = dcdn_models.AddDcdnDomainRequest(
domain_name=DomainName,
sources=json.dumps(source),
scope=my_scope,
)
try:
repons = dcdn_client.add_dcdn_domain_with_options(add_dcdn_domain_request, util_models.RuntimeOptions())
return repons
except Exception as error:
print(error)
return 0
def DcdnConfigCname(AccessKey, SecretKey, DomainName):
config = open_api_models.Config(
access_key_id=AccessKey,
access_key_secret=SecretKey,
region_id="ap-southeast-1"
)
dcdn_client=dcdnClient(config)
describe_dcdn_domain_detail_request = dcdn_models.DescribeDcdnDomainDetailRequest(
domain_name=DomainName,
)
cname_record=''
parts = DomainName.split('.')
RR='@' #hostname, domain is vinahost.cloud, hostname blog -> blog.vinahost.cloud
if len(parts) > 2: # parts <2 Primary Domain
RR = '.'.join(parts[:-2])
primary_domain='.'.join(parts[-2:])
try:
for i in range(1,5):
repons = dcdn_client.describe_dcdn_domain_detail_with_options(describe_dcdn_domain_detail_request, util_models.RuntimeOptions())
cname_record=repons.body.domain_detail.cname
print(repons.body.domain_detail)
print("Add CNAME Value: ",repons.body.domain_detail.cname," for domain: "+ primary_domain, " RR = ", RR)
if cname_record != '':
res=GetDnsRecordValue(AccessKey,SecretKey,primary_domain,RR)
while res.body.total_count>0: # Clear all A record
print('Find:',res.body.total_count,'Record',res.body.domain_records.record[0].record_id)
rid=res.body.domain_records.record[0].record_id
resp=DeleteDnsRecord(AccessKey,SecretKey,rid)
res=GetDnsRecordValue(AccessKey,SecretKey,primary_domain,RR)
result=addDnsRecord(AccessKey, SecretKey, primary_domain,"CNAME",RR,cname_record)
return result
else:
if (i==4):
if cname_record=="":
print("describe_dcdn_domain_detail failed!")
return 0
else:
sleep(10*i)
continue
except Exception as error:
print(error)
return 0
def DcdnEnableHTTPS(AccessKey, SecretKey, DomainName, CertName,CertID):
config = open_api_models.Config(
access_key_id=AccessKey,
access_key_secret=SecretKey,
region_id="ap-southeast-1"
)
dcdn_client=dcdnClient(config)
set_dcdn_domain_SSL_certificate_request = dcdn_models.SetDcdnDomainSSLCertificateRequest(
domain_name=DomainName,
cert_type="cas",
sslprotocol="on",
cert_name=CertName,
cert_region="ap-southeast-1",
cert_id=CertID
)
try:
repons = dcdn_client.set_dcdn_domain_sslcertificate_with_options(set_dcdn_domain_SSL_certificate_request, util_models.RuntimeOptions())
print("Enable DCDN Success")
return repons
except Exception as error:
print(error)
return 0
def DcndCheckDomainDetail(AccessKey, SecretKey, DomainName):
config = open_api_models.Config(
access_key_id=AccessKey,
access_key_secret=SecretKey,
region_id="ap-southeast-1"
)
dcdn_client=dcdnClient(config)
describe_dcdn_domain_detail_request = dcdn_models.DescribeDcdnDomainDetailRequest(
domain_name=DomainName,
)
try:
res = dcdn_client.describe_dcdn_domain_detail_with_options(describe_dcdn_domain_detail_request, util_models.RuntimeOptions())
return res.body.domain_detail
except Exception as error:
print(error)
def DcdnStartOnAlibabaCloud(AccessKey, SecretKey, DomainName,Endpoint,CertID):
res=DcdnVerifyDomain(AccessKey, SecretKey,DomainName)
if res==0:
print("Failed to DcdnVerifyDomain")
return 0
ipaddr=Endpoint['ip']
port=Endpoint['port']
res=DcdnAddDomain(AccessKey, SecretKey, DomainName ,ipaddr,"ipaddr",port,"overseas")
print("Add Dcdn Domain:",res)
count=3
flag_check=False
while count:
res=DcndCheckDomainDetail(AccessKey, SecretKey, DomainName)
if(res.domain_status=="configuring"):
flag_check=True
break
else:
print("domain_status configuring check",count)
sleep(10)
count-=1
continue
if not flag_check:
print("DcdnStartOnAlibabaCloud Failed!")
return 0
else:
DcdnConfigCname(AccessKey, SecretKey, DomainName)
count=20
flag_check=False
while count:
res=DcndCheckDomainDetail(AccessKey, SecretKey, DomainName)
if(res.domain_status=="online"):
flag_check=True
break
else:
print("domain_status online check",count)
sleep(60)
count-=1
continue
if not flag_check:
print("DcdnConfigCname Failed!")
return 0
else:
DcdnEnableHTTPS(AccessKey, SecretKey, DomainName,DomainName,CertID)
sleep(10)
res=DcndCheckDomainDetail(AccessKey, SecretKey, DomainName)
print("DcdnStartOnAlibabaCloud Result:")
print('Domain Name:', res.domain_name)
print('Domain Status:', res.domain_status)
print('DCDN Scope:', res.scope)
return 0
def main():
print("===========START-MAIN==============")
AccessKey='XXXXXX'
SecretKey='mXXXXXXX'
emailAddress = 'pmagic@gmail.com'
accountKeyFile="Accout_Key"
#Get SSL
GenAccountKey(accountKeyFile)
acme_client=GetACMEAccount(emailAddress,False)
domainName = "blog.vinahost.cloud"
endPoint={'ip':"0.0.0.0",'port':"443"}
KEY_FILE = domainName + '.key' #Private Key
CSR_FILE = domainName + '.csr'
CERT_FILE= domainName + '.cert' #FullChain.pem
cert=GenSSLCert(acme_client,domainName,emailAddress,AccessKey, SecretKey)
with open(CERT_FILE, "rt") as f:
cert_file=f.read()
cert_pem,chain_pem=SplitFullChainPem(cert_file)
priv_pem=LoadPrivateKeyAsText(KEY_FILE)
cert_id=UploadUserCertToCAS(AccessKey,SecretKey,cert_pem,priv_pem,chain_pem,domainName)
DcdnStartOnAlibabaCloud(AccessKey,SecretKey,domainName,endPoint,cert_id)
print("===========END-MAIN==============")
main()
cryptography
acme
alibabacloud_alidns20150109
alibabacloud_cas20200407
alibabacloud_dcdn20180115
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from acme import errors as acme_errors
from acme import messages, client, crypto_util, challenges, jose
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_alidns20150109.client import Client as AlidnsClient
from alibabacloud_alidns20150109 import models as alidns_models
from alibabacloud_tea_util import models as util_models
from time import sleep
import json
import os
from alibabacloud_cas20200407.client import Client as casClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_cas20200407 import models as cas_20200407_models
from alibabacloud_dcdn20180115.client import Client as dcdnClient
from alibabacloud_dcdn20180115 import models as dcdn_models
Tự động triển khai DCDN bằng Python SDK với Free SSL từ Let's encrypt (Phần 2)
5 posts | 1 followers
FollowNguyen Phuc Khang - June 4, 2024
Nguyen Phuc Khang - June 4, 2024
Regional Content Hub - August 29, 2024
Regional Content Hub - August 29, 2024
Regional Content Hub - August 29, 2024
Nguyen Phuc Khang - July 13, 2024
5 posts | 1 followers
FollowA scalable and high-performance content delivery service for accelerated distribution of content to users across the globe
Learn MoreOpenAPI Explorer allows you to call an API through its web interface or WebCLI, and view the entire process.
Learn MoreAPI Gateway provides you with high-performance and high-availability API hosting services to deploy and release your APIs on Alibaba Cloud products.
Learn MoreSave egress traffic cost. Eliminate all complexity in managing storage cost.
Learn More