Azure云 VM远程开关机脚本

背景

在Azure云上准备的测试环境,考虑到运行的成本,需要通过计划任务设置定时开关机。

此操作可以通过多种方法实现,例如Azure提供的runbook,或者调用Azure SDK来实现,本文使用Azure sdk for python实现。

支持判断中国法定节假日、周六日,按Resource Group为单位进行开关机。


Code:


credentials.py

#!/usr/bin/python
from msrestazure.azure_cloud import AZURE_CHINA_CLOUD
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.compute import ComputeManagementClient

# Credentials
SUBSCRIPTION_ID = '1f6xxx46-167a-433c-bxxx-ff18f5xxxdd3'
CLIENT_SECRET = 'A123456'
CLIENT_ID = 'e8xx-5dxxf-47x3-99xxd-22xxxa0a'
TENANT = 'xxfxx14-8x47-4x8-x4c-386xd2d'

def get_credentials():
    credentials = ServicePrincipalCredentials(
        client_id = CLIENT_ID,
        secret = CLIENT_SECRET,
        tenant = TENANT,
        china = True
    )
    return credentials
    
def auth():
    credentials = get_credentials()
    compute_client = ComputeManagementClient(
        credentials, 
        SUBSCRIPTION_ID,
        base_url=AZURE_CHINA_CLOUD.endpoints.resource_manager
    )
  
    return compute_client


vm_power.py

#!/usr/bin/python
# -*- coding: utf-8 -*-
from datetime import datetime
from chinese_calendar import is_holiday
from  credentials import auth
import sys
import logging
RESOURCE_GROUPS = ['clusters', 'website']
compute_client = auth()  

def vm_start(group_name):
    for vm in compute_client.virtual_machines.list(group_name):
        async_vm = compute_client.virtual_machines.start(group_name, vm.name)
        async_vm.wait()
        
def vm_deallocate(group_name):
    for vm in compute_client.virtual_machines.list(group_name):
        async_vm = compute_client.virtual_machines.deallocate(group_name, vm.name)
        async_vm.wait()
        
def check_args():
    args = ['start', 'deallocate']
    if len(sys.argv) == 2:
        if sys.argv[1] not in args:
            logging.error("Input must be %s" % args)
            sys.exit(1)
        return sys.argv[1]
        
if __name__ == '__main__':
    today = datetime.date(datetime.now())
    cmd = check_args()
    action = {'start': vm_start, 'deallocate' : vm_deallocate}
    if is_holiday(today) and cmd != 'deallocate':
        logging.error("Can't exec %s in holiday" % cmd)
        sys.exit(1)
    else:
        for group in RESOURCE_GROUPS:
            action[cmd](group)


使用方法

使用此脚本需要先安装Azure SDK和 chinese_calendar,chinese_calendar用于判断中国的法定节假日。

此脚本可以部署在能访问Azure的主机上或是Azure的一个服务上,通过计划任务的方式进行调度执行,来达到节省成本的目的。


END:

由于笔者的水平有限,文中难免会出现一些错误或者不准确的地方,不妥之处恳请读者批评指正。

我也会继续分享我的一些工作经验和心得,喜欢笔者的文章,右上角点一波关注,谢谢!


猜你喜欢

转载自blog.51cto.com/5109252/2152065