-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathupload_certs_to_aliyun.py
57 lines (45 loc) · 2.06 KB
/
upload_certs_to_aliyun.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import datetime
import os
from aliyunsdkcore.client import AcsClient
from aliyunsdkcdn.request.v20180510 import SetCdnDomainSSLCertificateRequest
def get_env_var(key):
value = os.getenv(key)
if not value:
raise EnvironmentError(f"Environment variable {key} not set")
return value
def file_exists_and_not_empty(file_path):
expanded_path = os.path.expanduser(file_path)
return os.path.isfile(expanded_path) and os.path.getsize(expanded_path) > 0
def upload_certificate(client, domain_name, cert_path, key_path):
expanded_cert_path = os.path.expanduser(cert_path)
expanded_key_path = os.path.expanduser(key_path)
if not file_exists_and_not_empty(expanded_cert_path) or not file_exists_and_not_empty(expanded_key_path):
raise FileNotFoundError(f"Certificate or key file for domain {domain_name} is missing or empty")
with open(expanded_cert_path, 'r') as f:
cert = f.read()
with open(expanded_key_path, 'r') as f:
key = f.read()
request = SetCdnDomainSSLCertificateRequest.SetCdnDomainSSLCertificateRequest()
# CDN加速域名
request.set_DomainName(domain_name)
# 证书名称
request.set_CertName(domain_name + datetime.datetime.now().strftime("%Y%m%d"))
request.set_CertType('upload')
request.set_SSLProtocol('on')
request.set_SSLPub(cert)
request.set_SSLPri(key)
request.set_CertRegion('cn-hangzhou')
response = client.do_action_with_exception(request)
print(str(response, encoding='utf-8'))
def main():
access_key_id = get_env_var('ALIYUN_ACCESS_KEY_ID')
access_key_secret = get_env_var('ALIYUN_ACCESS_KEY_SECRET')
domains = get_env_var('DOMAINS').split(',')
cdn_domains = get_env_var('ALIYUN_CDN_DOMAINS').split(',')
client = AcsClient(access_key_id, access_key_secret, 'cn-hangzhou')
for domain, cdn_domain in zip(domains, cdn_domains):
cert_path = f'~/certs/{domain}/fullchain.pem'
key_path = f'~/certs/{domain}/privkey.pem'
upload_certificate(client, cdn_domain, cert_path, key_path)
if __name__ == "__main__":
main()