日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

函数计算自动化运维实战1 -- 定时任务

發布時間:2025/3/20 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 函数计算自动化运维实战1 -- 定时任务 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

函數計算

阿里云函數計算是一個事件驅動的全托管計算服務。通過函數計算,您無需管理服務器等基礎設施,只需編寫代碼并上傳。函數計算會為您準備好計算資源,以彈性、可靠的方式運行您的代碼,并提供日志查詢,性能監控,報警等功能。借助于函數計算,您可以快速構建任何類型的應用和服務,無需管理和運維。更棒的是,您只需要為代碼實際運行消耗的資源付費,而代碼未運行則不產生費用。

函數計算中的TimeTrigger

觸發器是觸發函數執行的方式。有時候您不想手動調用函數執行,您希望當某件事情發生時自動觸發函數的執行,這個事情就是事件源。您可以通過配置觸發器的方式設置事件源觸發函數執行。
例如,設置定時觸發器,可以在某個時間點觸發函數執行或者每隔5分鐘觸發函數一次;函數計算timetrigger

專題傳送門 => 函數計算進行自動化運維專題

定時任務自動化場景分析

定時任務示例場景1

某些賬號ak需要定期更換,以確保ak安全;
在下面的代碼示例中,授權service具有訪問kms權限的能力,使用kms,先對一個具有創建和刪除ak權限的ak加密密文解密,獲取具有創建和刪除ak權限的AK, 之后利用這個AK進行ak的創建和刪除操作

說明: 除了使用kms加密解密來獲取較大權限的AK, 通過函數計算環境變量的設置也是一種很好的方法

操作步驟

  • 創建函數,函數創建可參考函數計算helloworld

注:記得給函數的service的role設置訪問kms權限

  • 給函數配置定時器,詳情可參考定時觸發函數

  • 函數代碼(函數計算已經內置了相關sdk,直接使用下面的代碼即可)
# -*- coding: utf-8 -*- import logging, time, json from aliyunsdkcore import client from aliyunsdkram.request.v20150501.CreateAccessKeyRequest import CreateAccessKeyRequest from aliyunsdkram.request.v20150501.DeleteAccessKeyRequest import DeleteAccessKeyRequest from aliyunsdkkms.request.v20160120.EncryptRequest import EncryptRequest from aliyunsdkkms.request.v20160120.DecryptRequest import DecryptRequest from aliyunsdkcore.auth.credentials import StsTokenCredential # ak Encrypt content AK_CiphertextBlob = "NmQyY2ZhODMtMTlhYS00MTNjLTlmZjAtZTQxYTFiYWVmMzZmM1B1NXhTZENCNXVWd1dhdTNMWVRvb3V6dU9QcVVlMXRBQUFBQUFBQUFBQ3gwZTkzeGhDdHVzMWhDUCtZeVVuMWlobzlCa3VxMlErOXFHWWdXXXHELLwL1NSZTFvUURYSW9lak5Hak1lMnF0R2I1TWUxMEJiYmkzVnBwZHlrWGYzc3kyK2tQbGlKb2lHQ3lrZUdieHN2eXZwSVYzN2Qyd1cydz09" USER_NAME = "ls-test" # sub-account name LOGGER = logging.getLogger() def handler(event, context):creds = context.credentialssts_token_credential = StsTokenCredential(creds.access_key_id, creds.access_key_secret, creds.security_token)# this demo ecs and function in same region, if not in same region, you need change region_id to your ecs instance's region_idclt = client.AcsClient(region_id=context.region, credential=sts_token_credential)request = DecryptRequest()request.set_CiphertextBlob(AK_CiphertextBlob)response = _send_request(clt, request)ak_info = json.loads(response.get("Plaintext","{}"))if not ak_info:return "KMS Decrypt ERROR"ak_id = ak_info["ak_id"]ak_secret = ak_info["ak_secret"]LOGGER.info("Decrypt sucessfully with key id: {}".format(response.get("KeyId","{}")))clt2 = client.AcsClient(ak_id, ak_secret, context.region)request = CreateAccessKeyRequest()request.set_UserName(USER_NAME) # 給子賬號ls-test創建AKresponse = _send_request(clt2, request)create_ak_id = response.get("AccessKey",{}).get("AccessKeyId")if not create_ak_id:returnLOGGER.info("create ak {} sucess!".format(create_ak_id))time.sleep(10)request = DeleteAccessKeyRequest()request.set_UserName(USER_NAME) request.set_UserAccessKeyId(create_ak_id)response = _send_request(clt2, request)LOGGER.info("delete ak {} sucess!".format(create_ak_id))return "OK"# send open api request def _send_request(clt, request):request.set_accept_format('json')try:response_str = clt.do_action_with_exception(request)LOGGER.debug(response_str)response_detail = json.loads(response_str)return response_detailexcept Exception as e:LOGGER.error(e)

AK 存在環境變量版本

# -*- coding: utf-8 -*- import os, logging, time, json from aliyunsdkcore import client from aliyunsdkram.request.v20150501.CreateAccessKeyRequest import CreateAccessKeyRequest from aliyunsdkram.request.v20150501.DeleteAccessKeyRequest import DeleteAccessKeyRequest USER_NAME = "ls-test" # sub-account name LOGGER = logging.getLogger() def handler(event, context):ak_id = os.environ['AK_ID']ak_secret = os.environ['AK_SECRET']clt = client.AcsClient(ak_id, ak_secret, context.region)request = CreateAccessKeyRequest()request.set_UserName(USER_NAME) # 給子賬號USER_NAME創建AKresponse = _send_request(clt, request)create_ak_id = response.get("AccessKey", "").get("AccessKeyId")if not create_ak_id:returnLOGGER.info("create ak {} sucess!".format(create_ak_id))time.sleep(5)request = DeleteAccessKeyRequest()request.set_UserName(USER_NAME) request.set_UserAccessKeyId(create_ak_id)response = _send_request(clt, request)LOGGER.info("delete ak {} sucess!".format(create_ak_id))return "OK"# send open api request def _send_request(clt, request):request.set_accept_format('json')try:response_str = clt.do_action_with_exception(request)LOGGER.info(response_str)response_detail = json.loads(response_str)return response_detailexcept Exception as e:LOGGER.error(e)

定時任務示例場景2

定期檢查自己ecs對應暴露的端口,確保安全,比如你的ecs是一個網站服務器,可能只需要對外暴露80端口就行,如果出現0.0.0.0/0這種允許所有人訪問的,需要出現報警或者自動修復

操作步驟

  • 創建函數,函數創建可參考函數計算helloworld

注:記得給函數的service的role設置管理ecs權限

  • 給函數配置定時器,詳情可參考定時觸發函數
# -*- coding: utf-8 -*- import logging import json, random, string, time from aliyunsdkcore import client from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest from aliyunsdkecs.request.v20140526.DescribeSecurityGroupAttributeRequest import DescribeSecurityGroupAttributeRequest from aliyunsdkcore.auth.credentials import StsTokenCredential LOGGER = logging.getLogger() clt = None # 需要檢查的ecs列表, 修改成你的ecs id 列表 ECS_INST_IDS = ["i-uf6h07zdscdg9g55zkxx", "i-uf6bwkxfxh847a1e2xxx"] def handler(event, context):creds = context.credentialsglobal cltsts_token_credential = StsTokenCredential(creds.access_key_id, creds.access_key_secret, creds.security_token)# this demo ecs and function in same region, if not in same region, you need change region_id to your ecs instance's region_idclt = client.AcsClient(region_id=context.region, credential=sts_token_credential)invalid_perssions = {}for ecs_id in ECS_INST_IDS:ret = check_and_modify_security_rule(ecs_id)if ret:invalid_perssions[ecs_id] = retreturn invalid_perssions def check_and_modify_security_rule(instance_id):LOGGER.info("check_and_modify_security_rule, instance_id is %s ", instance_id)request = DescribeInstancesRequest()request.set_InstanceIds(json.dumps([instance_id]))response = _send_request(request)SecurityGroupIds = []if response is not None:instance_list = response.get('Instances', {}).get('Instance')for item in instance_list:SecurityGroupIds = item.get('SecurityGroupIds', {}).get("SecurityGroupId", [])breakif not SecurityGroupIds:LOGGER.error("ecs {} do not have SecurityGroupIds".format(instance_id))return invalid_perssions = []for sg_id in SecurityGroupIds:request = DescribeSecurityGroupAttributeRequest()request.set_SecurityGroupId(sg_id)response = _send_request(request)LOGGER.info("Find a securityGroup id {}".format(sg_id))permissions = response.get("Permissions", {}).get("Permission",[])if not permissions:continuefor permission in permissions:if permission["Direction"] == "ingress" and permission["SourceCidrIp"] == "0.0.0.0/0":LOGGER.error("ecs {0} , SecurityGroup id {1}, have a risk, need fix; permission = {2}".format(instance_id, sg_id, permission))invalid_perssions.append(permission)return invalid_perssions # send open api request def _send_request(request):request.set_accept_format('json')try:response_str = clt.do_action_with_exception(request)LOGGER.debug(response_str)response_detail = json.loads(response_str)return response_detailexcept Exception as e:LOGGER.error(e)

“ 阿里巴巴云原生微信公眾號(ID:Alicloudnative)關注微服務、Serverless、容器、Service Mesh等技術領域、聚焦云原生流行技術趨勢、云原生大規模的落地實踐,做最懂云原生開發者的技術公眾號。”

《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

總結

以上是生活随笔為你收集整理的函数计算自动化运维实战1 -- 定时任务的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。