AWS:为什么我的 RDS 实例在关闭后仍继续启动?

2024-01-07

我在 AWS 上有一个 RDS 数据库实例,目前已将其关闭。但是,每隔几天它就会自行启动。我现在没有任何其他服务正在运行。

我的 RDS 日志中有此事件: “数据库实例正在启动,因为它超出了允许的最大停止时间。”

为什么我的 RDS 实例的停止时间有限制?我只想将我的项目搁置几周,但 AWS 不允许我关闭数据库?让它闲置的成本为 12.50 美元/月,所以我不想为此付费,而且我当然不希望 AWS 为我启动一个不被使用的实例。

请帮忙!


这是这个的限制新功能 https://aws.amazon.com/about-aws/whats-new/2017/06/amazon-rds-supports-stopping-and-starting-of-database-instances/.

您一次最多可以停止实例 7 天。 7天后,它将自动启动。有关停止和启动数据库实例的更多详细信息,请参阅停止和启动数据库实例 https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_StopInstance.html在 Amazon RDS 用户指南中。

您可以设置 cron 作业以在 7 天后再次停止实例。您还可以更改为较小的实例大小以节省资金。

另一种选择是即将到来的极光无服务器 https://aws.amazon.com/blogs/aws/in-the-works-amazon-aurora-serverless/它会自动为您停止和启动。当运行 24/7 时,它可能比专用实例更昂贵。

最后,总有Heroku https://www.heroku.com/这给你一个免费数据库实例 https://www.heroku.com/free它会自行启动和停止,但有一些限制。


您还可以尝试将以下 CloudFormation 模板另存为KeepDbStopped.yml然后使用以下命令进行部署:

aws cloudformation deploy --template-file KeepDbStopped.yml --stack-name stop-db --capabilities CAPABILITY_IAM --parameter-overrides DB=arn:aws:rds:us-east-1:XXX:db:XXX

确保改变arn:aws:rds:us-east-1:XXX:db:XXX到您的 RDS ARN。

Description: Automatically stop RDS instance every time it turns on due to exceeding the maximum allowed time being stopped
Parameters:
  DB:
    Description: ARN of database that needs to be stopped
    Type: String
    AllowedPattern: arn:aws:rds:[a-z0-9\-]+:[0-9]+:db:[^:]*
Resources:
  DatabaseStopperFunction:
    Type: AWS::Lambda::Function
    Properties:
      Role: !GetAtt DatabaseStopperRole.Arn
      Runtime: python3.6
      Handler: index.handler
      Timeout: 20
      Code:
        ZipFile:
          Fn::Sub: |
            import boto3
            import time

            def handler(event, context):
              print("got", event)
              db = event["detail"]["SourceArn"]
              id = event["detail"]["SourceIdentifier"]
              message = event["detail"]["Message"]
              region = event["region"]
              rds = boto3.client("rds", region_name=region)

              if message == "DB instance is being started due to it exceeding the maximum allowed time being stopped.":
                print("database turned on automatically, setting last seen tag...")
                last_seen = int(time.time())
                rds.add_tags_to_resource(ResourceName=db, Tags=[{"Key": "DbStopperLastSeen", "Value": str(last_seen)}])

              elif message == "DB instance started":
                print("database started (and sort of available?)")

                last_seen = 0
                for t in rds.list_tags_for_resource(ResourceName=db)["TagList"]:
                  if t["Key"] == "DbStopperLastSeen":
                    last_seen = int(t["Value"])

                if time.time() < last_seen + (60 * 20):
                  print("database was automatically started in the last 20 minutes, turning off...")
                  time.sleep(10)  # even waiting for the "started" event is not enough, so add some wait
                  rds.stop_db_instance(DBInstanceIdentifier=id)

                  print("success! removing auto-start tag...")
                  rds.add_tags_to_resource(ResourceName=db, Tags=[{"Key": "DbStopperLastSeen", "Value": "0"}])

                else:
                  print("ignoring manual database start")

              else:
                print("error: unknown database event!")
  DatabaseStopperRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Action:
              - sts:AssumeRole
            Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Policies:
        - PolicyName: Notify
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Action:
                  - rds:StopDBInstance
                Effect: Allow
                Resource: !Ref DB
              - Action:
                  - rds:AddTagsToResource
                  - rds:ListTagsForResource
                  - rds:RemoveTagsFromResource
                Effect: Allow
                Resource: !Ref DB
                Condition:
                  ForAllValues:StringEquals:
                    aws:TagKeys:
                      - DbStopperLastSeen
  DatabaseStopperPermission:
    Type: AWS::Lambda::Permission
    Properties:
      Action: lambda:InvokeFunction
      FunctionName: !GetAtt DatabaseStopperFunction.Arn
      Principal: events.amazonaws.com
      SourceArn: !GetAtt DatabaseStopperRule.Arn
  DatabaseStopperRule:
    Type: AWS::Events::Rule
    Properties:
      EventPattern:
        source:
          - aws.rds
        detail-type:
          - "RDS DB Instance Event"
        resources:
          - !Ref DB
        detail:
          Message:
            - "DB instance is being started due to it exceeding the maximum allowed time being stopped."
            - "DB instance started"
      Targets:
        - Arn: !GetAtt DatabaseStopperFunction.Arn
          Id: DatabaseStopperLambda

它至少对一个人有效。如果您有问题请报告here https://gist.github.com/kichik/7a2ecb0d36358c50c7b878ad9fd982bc.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

AWS:为什么我的 RDS 实例在关闭后仍继续启动? 的相关文章

随机推荐