函数计算对进行自动化运维的一些姿势
rsong 2018-04-12 11:21:38 浏览69 评论0摘要: 函数计算是一个事件驱动的全托管计算服务。通过函数计算,您无需管理服务器等基础设施,只需编写代码并上传。函数计算会为您准备好计算资源,以弹性、可靠的方式运行您的代码,这就给用户极大的自由来实现自定义的功能,一旦和自定义自动化运维相遇,会擦出不一样的火花
什么是函数计算
阿里云函数计算是一个事件驱动的全托管计算服务。通过函数计算,您无需管理服务器等基础设施,只需编写代码并上传。函数计算会为您准备好计算资源,以弹性、可靠的方式运行您的代码,并提供日志查询,性能监控,报警等功能。借助于函数计算,您可以快速构建任何类型的应用和服务,无需管理和运维。更棒的是,您只需要为代码实际运行消耗的资源付费,而代码未运行则不产生费用。
函数计算遇见自动化运维
函数计算给用户极大的自由来实现自定义的功能,一旦和自定义自动化运维相遇,会擦出不一样的火花
示例场景1
某些账号ak需要定期更换,以确保ak安全
示例场景2
定期检查自己ecs对应暴露的端口,确保安全,比如你的ecs是一个网站服务器,可能只需要对外暴露80端口就行,如果出现0.0.0.0/0这种允许所有人访问的,需要出现报警或者自动修复
示例具体实现
定期更换ak,函数计算结合定时器
- 创建函数,函数创建可参考函数计算helloworld
- 给函数配置定时器,详情可参考定时触发函数
- 核心代码,可去附件下载完整代码
# -*- 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 = "NmQyY2ZhODMtMTlhYS00MTNjLTlmZjAtZTQxYTFiYWVmMzZmM1B1NXhTZENCNXVWd1dhdTNMWVRvb3V6dU9QcVVlMXRBQUFBQUFBQUFBQ3gwZTkzeGhDdHVzMWhDUCtZeVVuMWlobzlCa3VxMlErOXFHWWdZMSt1MkdZYlgwL1NSZTFvUURYSW9lak5Hak1lMnF0R2I1TWUxMEJiYmkzVnBwZHlrWGYzc3kyK2tQbGlKb2lHQ3lrZUdieHN2eXZwSVYzN2Qyd1cydz09"
USER_NAME = "ls-test" # sub-account name
LOGGER = logging.getLogger()
def handler(event, context):
creds = context.credentials
sts_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_id
clt = 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创建AK
response = _send_request(clt2, request)
create_ak_id = response.get("AccessKey",{}).get("AccessKeyId")
if not create_ak_id:
return
LOGGER.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_detail
except Exception as e:
LOGGER.error(e)
定期检查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.credentials
global clt
sts_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_id
clt = 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] = ret
return 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", [])
break
if 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:
continue
for 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_detail
except Exception as e:
LOGGER.error(e)
附件下载:
code.zip[rsong].1523503335.zip
用云栖社区APP,舒服~
【云栖快讯】新手小白必看!编程语言系列讲座火爆进行中,与行业资深专家一起学习Python、C++、JavaScript、Java!从入门到进阶 详情请点击 评论 (0) 点赞 (0) 收藏 (1)相关文章
- Kerberoast攻击的另一种姿势
- 动画重定向技术分析及其在Unity中的应用
- 谷歌教机器人理解语义,像人一样学习复杂技能 | 附3篇论…
- 化繁为简 海云捷迅为企业提供应用OpenStack新“姿…
- 按需付费:使用云计算的正确姿势
- Redux 并不慢,只是你使用姿势不对 —— 一份优化指…
- 双11技术攻略:企业云架构的正确姿势
- 双11技术攻略:企业云架构的正确姿势
- 你应该这个姿势学习PHP(1)
- 你应该这个姿势学习PHP(2)