Auto Shutdown and Start Amazon EC2 Instance

后端 未结 14 1044
执念已碎
执念已碎 2020-12-04 06:49

Can I automatically start and terminate my Amazon instance using Amazon API? Can you please describe how this can be done? I ideally need to start the instance and stop the

相关标签:
14条回答
  • 2020-12-04 07:07

    AutoScaling is limited to terminating instances. If you want to stop an instance and retain the server state then an external script is the best approach.

    You can do this by running a job on another instance that is running 24/7 or you can use a 3rd party service such as Ylastic (mentioned above) or Rocket Peak.

    For example in C# the code to stop a server is quite straightforward:

    public void stopInstance(string instance_id, string AWSRegion)
            {
                RegionEndpoint myAWSRegion = RegionEndpoint.GetBySystemName(AWSRegion);
                AmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client(AWSAccessKey, AWSSecretKey, myAWSRegion);
                ec2.StopInstances(new StopInstancesRequest().WithInstanceId(instance_id));
            }
    
    0 讨论(0)
  • 2020-12-04 07:09

    The company I work for had customers regularly asking about this so we've written a freeware EC2 scheduling app available here:

    http://blog.simple-help.com/2012/03/free-ec2-scheduler/

    It works on Windows and Mac, lets you create multiple daily/weekly/monthly schedules and lets you use matching filters to include large numbers of instances easily or includes ones that you add in the future.

    0 讨论(0)
  • 2020-12-04 07:13

    You cannot do this automatically, or at least not without some programming and API manipulation in script files. If you want to a reliable solution to stop, restart and manage your images (presumably to control costs in your environment) then you may want to look at LabSlice. Disclaimer: I work for this company.

    0 讨论(0)
  • 2020-12-04 07:14

    You could look at Ylastic to do this. The alternative seems to be having one machine running that shuts down/starts other instances using a cron job or scheduled task.

    Obviously if you only want one instance this is an expensive solution, as one machine has to always be running, and paying ~$80 a month for one machine to run cron jobs isn't cost effective.

    0 讨论(0)
  • 2020-12-04 07:16

    AWS Data Pipeline is working fine. https://aws.amazon.com/premiumsupport/knowledge-center/stop-start-ec2-instances/

    If you wish exclude days from starting (e.g. weekend) add a ShellCommandPrecondition object.

    In AWS Console/Data Pipeline, create a new pipeline. It's easyer to edit/import a definition (JSON)

        {
    "objects": [
    {
      "failureAndRerunMode": "CASCADE",
      "schedule": {
        "ref": "DefaultSchedule"
      },
      "resourceRole": "DataPipelineDefaultResourceRole",
      "role": "DataPipelineDefaultRole",
      "pipelineLogUri": "s3://MY_BUCKET/log/",
      "scheduleType": "cron",
      "name": "Default",
      "id": "Default"
    },
    {
      "name": "CliActivity",
      "id": "CliActivity",
      "runsOn": {
        "ref": "Ec2Instance"
      },
      "precondition": {
        "ref": "PreconditionDow"
      },
      "type": "ShellCommandActivity",
      "command": "(sudo yum -y update aws-cli) && (#{myAWSCLICmd})"
    },
    {
      "period": "1 days",
      "startDateTime": "2015-10-27T13:00:00",
      "name": "Every 1 day",
      "id": "DefaultSchedule",
      "type": "Schedule"
    },
    {
      "scriptUri": "s3://MY_BUCKET/script/dow.sh",
      "name": "DayOfWeekPrecondition",
      "id": "PreconditionDow",
      "type": "ShellCommandPrecondition"
    },
    {
      "instanceType": "t1.micro",
      "name": "Ec2Instance",
      "id": "Ec2Instance",
      "type": "Ec2Resource",
      "terminateAfter": "50 Minutes"
    }
    ],
    "parameters": [
    {
      "watermark": "aws [options] <command> <subcommand> [parameters]",
      "description": "AWS CLI command",
      "id": "myAWSCLICmd",
      "type": "String"
    }
     ],
    "values": {
    "myAWSCLICmd": "aws ec2 start-instances --instance-ids i-12345678 --region eu-west-1"
    }
    }
    

    Put the Bash script to be dowloaded and executed as precondition in your S3 bucket

    #!/bin/sh
    if [ "$(date +%u)" -lt 6 ]
    then exit 0
    else exit 1
    fi
    

    On activating and running the pipeline on weekend days, the AWS console Pipeline Health Status reads a misleading "ERROR". The bash script returns an error (exit 1) and EC2 isn't started. On days 1 to 5, the status is "HEALTHY".

    To stop EC2 automatically at closing office time, use the AWS CLI command daily wihtout precondition.

    0 讨论(0)
  • 2020-12-04 07:17

    IMHO adding a schedule to an auto scaling group is the best "cloud like" approach as mentioned before.

    But in case you can't terminate your instances and use new ones, for example if you have Elastic IPs associated with etc.

    You could create a Ruby script to start and stop your instances based on a date time range.

    #!/usr/bin/env ruby
    
    # based on https://github.com/phstc/amazon_start_stop
    
    require 'fog'
    require 'tzinfo'
    
    START_HOUR = 6 # Start 6AM
    STOP_HOUR  = 0 # Stop  0AM (midnight)
    
    conn = Fog::Compute::AWS.new(aws_access_key_id:     ENV['AWS_ACCESS_KEY_ID'],
                                 aws_secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'])
    
    server = conn.servers.get('instance-id')
    
    tz = TZInfo::Timezone.get('America/Sao_Paulo')
    
    now = tz.now
    
    stopped_range = (now.hour >= STOP_HOUR && now.hour < START_HOUR)
    running_range = !stopped_range
    
    if stopped_range && server.state != 'stopped'
      server.stop
    end
    
    if running_range && server.state != 'running'
      server.start
    
      # if you need an Elastic IP
      # (everytime you stop an instance Amazon dissociates Elastic IPs)
      #
      # server.wait_for { state == 'running' }
      # conn.associate_address server.id, 127.0.0.0
    end
    

    Have a look at amazon_start_stop to create a scheduler for free using Heroku Scheduler.

    0 讨论(0)
提交回复
热议问题