Exemple #1
0
func StopInstances(cmd *cobra.Command, args []string) (resp map[string]*ec2.StopInstancesOutput, err error) {
	var (
		dryrun bool
		data   map[string]*ec2.DescribeInstancesOutput
		svc    *ec2.EC2
		r      *ec2.StopInstancesOutput
	)

	resp = make(map[string]*ec2.StopInstancesOutput)

	dryrun, _ = cmd.Flags().GetBool("dryrun")

	data, err = GetEC2Instances(cmd, args)
	if err == nil {
		for region, _ := range data {
			var instanceIds []*string
			svc = ec2.New(session.New(), &aws.Config{Region: aws.String(region)})
			for idx, _ := range data[region].Reservations {
				for _, inst := range data[region].Reservations[idx].Instances {
					if !IsTagged(inst) && IsRunning(inst) {
						if IsSpot(inst) {
							log.Printf("Can not stop spot instance: %s", *inst.InstanceId)
							continue
						}
						instanceIds = append(instanceIds, inst.InstanceId)
					}
				}
			}

			if len(instanceIds) > 0 {
				params := &ec2.StopInstancesInput{
					InstanceIds: instanceIds,
					DryRun:      aws.Bool(dryrun),
				}
				r, err = svc.StopInstances(params)
				if err != nil {
					fmt.Println("OMG")
					fmt.Println(r.StoppingInstances)
					fmt.Println("OMG")
					resp[region] = r
				}
			}
		}
	}

	return
}