Пример #1
0
func (c *UntagCommand) Run(args []string) int {
	var (
		dryRun           bool
		instanceIDString string
		instanceIDs      []*string
		tagString        string
		tags             []*ec2.Tag
	)

	var (
		arguments []string
	)

	svc := ec2.New(session.New(), &aws.Config{})

	flags := flag.NewFlagSet("dtan4", flag.ContinueOnError)
	flags.Usage = func() {}

	flags.BoolVar(&dryRun, "dry-run", false, "Dry run (default: false)")
	flags.StringVar(&instanceIDString, "instance", "", "Instance Ids")
	flags.StringVar(&tagString, "tags", "", "KEY tags")

	if err := flags.Parse(args[0:]); err != nil {
		return 1
	}

	for 0 < flags.NArg() {
		arguments = append(arguments, flags.Arg(0))
		flags.Parse(flags.Args()[1:])
	}

	for _, id := range strings.Split(instanceIDString, ",") {
		instanceIDs = append(instanceIDs, aws.String(id))
	}

	for _, tag := range strings.Split(tagString, ",") {
		tags = append(tags, &ec2.Tag{
			Key: aws.String(tag),
		})
	}

	opts := &ec2.DeleteTagsInput{
		DryRun:    aws.Bool(dryRun),
		Resources: instanceIDs,
		Tags:      tags,
	}

	_, err := svc.DeleteTags(opts)
	if err != nil {
		msg.Errorf("Failed to delete tag. error: %s\n", err)
		return 1
	}

	return 0
}
Пример #2
0
Файл: list.go Проект: dtan4/ec2c
func (c *ListCommand) Run(args []string) int {
	svc := ec2.New(session.New(), &aws.Config{})

	resp, err := svc.DescribeInstances(nil)
	if err != nil {
		msg.Errorf("Failed to retrieve instance list. error: %s\n", err)
		return 1
	}

	var privateIPAddress, publicIPAddress, instanceName string

	w := new(tabwriter.Writer)
	w.Init(os.Stdout, 0, 8, 0, '\t', 0)

	fmt.Fprintln(w, strings.Join([]string{"INSTANCE ID", "STATUS", "INSTANCE TYPE", "PRIVATE IP", "PUBLIC IP", "NAME", "TAG"}, "\t"))
	for idx, _ := range resp.Reservations {
		for _, instance := range resp.Reservations[idx].Instances {
			if instance.PrivateIpAddress != nil {
				privateIPAddress = *instance.PrivateIpAddress
			} else {
				privateIPAddress = ""
			}

			if instance.PublicIpAddress != nil {
				publicIPAddress = *instance.PublicIpAddress
			} else {
				publicIPAddress = ""
			}

			instanceName = ""
			tagKeyValue := []string{}

			for _, tag := range instance.Tags {
				keyValue := *tag.Key
				if *tag.Key == "Name" {
					instanceName = *tag.Value
				}
				if len(*tag.Value) > 0 {
					keyValue += "=" + *tag.Value
				}
				tagKeyValue = append(tagKeyValue, keyValue)
			}

			fmt.Fprintln(w, strings.Join(
				[]string{*instance.InstanceId, *instance.State.Name, *instance.InstanceType, privateIPAddress, publicIPAddress, instanceName, strings.Join(tagKeyValue, ",")}, "\t",
			))
		}
	}

	w.Flush()

	return 0
}
Пример #3
0
func (c *TerminateCommand) Run(args []string) int {
	var (
		dryRun           bool
		instanceIDString string
		instanceIDs      []*string
	)

	var (
		arguments []string
	)

	svc := ec2.New(session.New(), &aws.Config{})

	flags := flag.NewFlagSet("dtan4", flag.ContinueOnError)
	flags.Usage = func() {}

	flags.BoolVar(&dryRun, "dry-run", false, "Dry run (default: false)")
	flags.StringVar(&instanceIDString, "instance", "", "Instance IDs")

	if err := flags.Parse(args[0:]); err != nil {
		return 1
	}

	for 0 < flags.NArg() {
		arguments = append(arguments, flags.Arg(0))
		flags.Parse(flags.Args()[1:])
	}

	for _, id := range strings.Split(instanceIDString, ",") {
		instanceIDs = append(instanceIDs, aws.String(id))
	}

	opts := &ec2.TerminateInstancesInput{
		DryRun:      aws.Bool(dryRun),
		InstanceIds: instanceIDs,
	}

	resp, err := svc.TerminateInstances(opts)
	if err != nil {
		msg.Errorf("Failed to terminate instance. error: %s\n", err)
		return 1
	}

	for _, instance := range resp.TerminatingInstances {
		fmt.Println(*instance.InstanceId)
	}

	return 0
}
Пример #4
0
func (c *ListRequestsCommand) Run(args []string) int {
	svc := ec2.New(session.New(), &aws.Config{})

	resp, err := svc.DescribeSpotInstanceRequests(nil)
	if err != nil {
		msg.Errorf("Failed to retrieve SpotRequest list. error: %s\n", err)
		return 1
	}

	var instanceID, requestName string

	w := new(tabwriter.Writer)
	w.Init(os.Stdout, 0, 8, 0, '\t', 0)

	fmt.Fprintln(w, strings.Join([]string{"REQUEST ID", "MAX PRICE", "INSTANCE TYPE", "INSTANCE ID", "STATE", "STATUS", "NAME"}, "\t"))
	for _, request := range resp.SpotInstanceRequests {
		requestName = ""

		if request.InstanceId != nil {
			instanceID = *request.InstanceId
		} else {
			instanceID = ""
		}

		for _, tag := range request.Tags {
			if *tag.Key == "Name" {
				requestName = *tag.Value
				break
			}
		}

		fmt.Fprintln(w, strings.Join(
			[]string{
				*request.SpotInstanceRequestId,
				*request.SpotPrice,
				*request.LaunchSpecification.InstanceType,
				instanceID,
				*request.State,
				*request.Status.Code,
				requestName,
			}, "\t",
		))
	}

	w.Flush()

	return 0
}
Пример #5
0
func (c *CancelCommand) Run(args []string) int {
	var (
		dryRun          bool
		requestIDString string
		requestIDs      []*string
	)

	var (
		arguments []string
	)

	svc := ec2.New(session.New(), &aws.Config{})

	flags := flag.NewFlagSet("dtan4", flag.ContinueOnError)
	flags.Usage = func() {}

	flags.BoolVar(&dryRun, "dry-run", false, "Dry run (default: false)")
	flags.StringVar(&requestIDString, "request", "", "Spot Instance request IDs")

	if err := flags.Parse(args[0:]); err != nil {
		return 1
	}

	for 0 < flags.NArg() {
		arguments = append(arguments, flags.Arg(0))
		flags.Parse(flags.Args()[1:])
	}

	for _, id := range strings.Split(requestIDString, ",") {
		requestIDs = append(requestIDs, aws.String(id))
	}

	opts := &ec2.CancelSpotInstanceRequestsInput{
		DryRun:                 aws.Bool(dryRun),
		SpotInstanceRequestIds: requestIDs,
	}

	resp, err := svc.CancelSpotInstanceRequests(opts)
	if err != nil {
		msg.Errorf("Failed to cancel SpotRequest. error: %s\n", err)
		return 1
	}

	fmt.Println(resp)

	return 0
}
Пример #6
0
func (c *RequestCommand) Run(args []string) int {
	var (
		amiID                    string
		associatePublicIPAddress bool
		availabilityZone         string
		dryRun                   bool
		instanceCount            int64
		instanceType             string
		keyName                  string
		securityGroupIDs         string
		securityGroups           []*string
		spotPrice                string
		subnetID                 string
		userData                 string
		volumeSize               int64
		volumeType               string
	)

	var (
		arguments []string
	)

	svc := ec2.New(session.New(), &aws.Config{})

	flags := flag.NewFlagSet("dtan4", flag.ContinueOnError)
	flags.Usage = func() {}

	flags.StringVar(&amiID, "ami", "", "AMI Id")
	flags.BoolVar(&associatePublicIPAddress, "publicip", false, "Associate Public Ip (default: false)")
	flags.StringVar(&availabilityZone, "az", "", "Availability zone")
	flags.BoolVar(&dryRun, "dry-run", false, "Dry run (default: false)")
	flags.Int64Var(&instanceCount, "count", 1, "Number of instances (default: 1)")
	flags.StringVar(&instanceType, "type", "", "Instance type")
	flags.StringVar(&keyName, "key", "", "SSH key name")
	flags.StringVar(&securityGroupIDs, "sg", "", "Security group Ids")
	flags.StringVar(&spotPrice, "spotPrice", "", "Maximum bidding price")
	flags.StringVar(&subnetID, "subnet", "", "Subnet Id")
	flags.StringVar(&userData, "userData", "", "User data")
	flags.Int64Var(&volumeSize, "volumeSize", 8, "Volume size (default: 8)")
	flags.StringVar(&volumeType, "volumeType", "gp2", "Volume type (default: gp2)")

	if err := flags.Parse(args[0:]); err != nil {
		return 1
	}

	for 0 < flags.NArg() {
		arguments = append(arguments, flags.Arg(0))
		flags.Parse(flags.Args()[1:])
	}

	for _, id := range strings.Split(securityGroupIDs, ",") {
		securityGroups = append(securityGroups, aws.String(id))
	}

	blockDeviceMappings := []*ec2.BlockDeviceMapping{
		&ec2.BlockDeviceMapping{
			DeviceName: aws.String("/dev/xvda"),
			Ebs: &ec2.EbsBlockDevice{
				DeleteOnTermination: aws.Bool(true),
				VolumeSize:          aws.Int64(volumeSize),
				VolumeType:          aws.String(volumeType),
			},
		},
	}

	monitoring := &ec2.RunInstancesMonitoringEnabled{
		Enabled: aws.Bool(true),
	}

	launchSpecification := &ec2.RequestSpotLaunchSpecification{
		BlockDeviceMappings: blockDeviceMappings,
		ImageId:             aws.String(amiID),
		KeyName:             aws.String(keyName),
		InstanceType:        aws.String(instanceType),
		Monitoring:          monitoring,
		SecurityGroups:      securityGroups,
		SubnetId:            aws.String(subnetID),
	}

	if subnetID != "" && associatePublicIPAddress {
		launchSpecification.NetworkInterfaces = []*ec2.InstanceNetworkInterfaceSpecification{
			&ec2.InstanceNetworkInterfaceSpecification{
				AssociatePublicIpAddress: aws.Bool(associatePublicIPAddress),
				DeviceIndex:              aws.Int64(int64(0)),
				SubnetId:                 aws.String(subnetID),
				Groups:                   securityGroups,
			},
		}
	}

	if userData != "" {
		buf, err := ioutil.ReadFile(userData)
		if err != nil {
			msg.Errorf("Failed to read user-data. error: %s\n", err)
			return 1
		}

		launchSpecification.UserData = aws.String(base64.StdEncoding.EncodeToString(buf))
	}

	opts := &ec2.RequestSpotInstancesInput{
		DryRun:              aws.Bool(dryRun),
		InstanceCount:       aws.Int64(instanceCount),
		LaunchSpecification: launchSpecification,
		SpotPrice:           aws.String(spotPrice),
	}

	resp, err := svc.RequestSpotInstances(opts)
	if err != nil {
		msg.Errorf("Failed to retrieve SpotRequest list. error: %s\n", err)
		return 1
	}

	fmt.Println(resp)

	return 0
}