EC2 startup on schedule

后端 未结 11 790
后悔当初
后悔当初 2020-12-01 09:13

I need to start up an EC2 instance at (say) 6am every day. The constraints are that I\'d like to avoid having a computer running all day to do the startup or use a paid solu

11条回答
  •  春和景丽
    2020-12-01 10:02

    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.

提交回复
热议问题