AWS Billing to Slack 项目教程

AWS Billing to Slack 项目教程

aws-billing-to-slackSend a daily AWS cost report to a Slack channel of your choice.项目地址:https://gitcode.com/gh_mirrors/aw/aws-billing-to-slack

1. 项目的目录结构及介绍

aws-billing-to-slack/
├── README.md
├── serverless.yml
├── handler.py
├── requirements.txt
└── .gitignore
  • README.md: 项目说明文档,包含项目的基本信息和使用指南。
  • serverless.yml: Serverless 框架的配置文件,定义了 AWS Lambda 函数和其他 AWS 资源。
  • handler.py: 项目的主处理文件,包含 AWS Lambda 函数的具体实现。
  • requirements.txt: Python 依赖文件,列出了项目所需的 Python 包。
  • .gitignore: Git 忽略文件,指定不需要纳入版本管理的文件和目录。

2. 项目的启动文件介绍

handler.py

handler.py 是项目的启动文件,主要包含 AWS Lambda 函数的处理逻辑。以下是文件的主要内容:

import json
import boto3
from datetime import datetime, timedelta

def report_cost(event, context):
    # 获取 AWS 账单信息
    client = boto3.client('costexplorer')
    response = client.get_cost_and_usage(
        TimePeriod={
            'Start': (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d'),
            'End': datetime.now().strftime('%Y-%m-%d')
        },
        Granularity='DAILY',
        Metrics=['UnblendedCost']
    )
    
    # 处理账单信息并发送至 Slack
    cost = response['ResultsByTime'][0]['Total']['UnblendedCost']['Amount']
    message = f"AWS Daily Cost Report: ${cost}"
    
    # 发送消息至 Slack
    slack_url = event['slack_url']
    payload = {
        'text': message
    }
    requests.post(slack_url, data=json.dumps(payload))
    
    return {
        'statusCode': 200,
        'body': json.dumps('Cost report sent to Slack')
    }

该文件定义了一个名为 report_cost 的 Lambda 函数,用于获取 AWS 每日账单信息并将其发送到指定的 Slack 频道。

3. 项目的配置文件介绍

serverless.yml

serverless.yml 是 Serverless 框架的配置文件,定义了 AWS Lambda 函数和其他 AWS 资源。以下是文件的主要内容:

service: aws-billing-to-slack

provider:
  name: aws
  runtime: python3.8
  region: us-east-1

functions:
  report_cost:
    handler: handler.report_cost
    events:
      - schedule: rate(1 day)
    environment:
      SLACK_URL: ${param:slack_url}

plugins:
  - serverless-python-requirements

custom:
  pythonRequirements:
    dockerizePip: true
  • service: 定义了服务的名称。
  • provider: 定义了云服务提供商和运行时环境。
  • functions: 定义了 Lambda 函数,包括处理函数的路径、触发事件和环境变量。
  • plugins: 定义了使用的插件,如 serverless-python-requirements

通过以上配置,项目可以自动部署到 AWS,并定期执行账单报告任务。

aws-billing-to-slackSend a daily AWS cost report to a Slack channel of your choice.项目地址:https://gitcode.com/gh_mirrors/aw/aws-billing-to-slack

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

姬忆慈Loveable

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值