예제 #1
0
func main() {
	AccessKey := os.Getenv("AWS_ACCESS_KEY")
	SecretKey := os.Getenv("AWS_SECRET_KEY")
	creds := aws.Creds(AccessKey, SecretKey, "")

	svc := ec2.New(&aws.Config{Credentials: creds, Region: "ap-southeast-1"})
	resp, err := svc.DescribeInstances(nil)
	fmt.Println(reflect.TypeOf(resp))
	if err != nil {
		panic(err)
	}

	//fmt.Println(resp.Reservations)
	for _, reservation := range resp.Reservations {
		//fmt.Println(reservation.Instances)
		for _, instance := range reservation.Instances {
			for _, t := range instance.Tags {
				if *t.Value == "cassandra" {
					fmt.Print(*instance.InstanceID, "\t", *instance.InstanceType, "\t", *instance.PrivateIPAddress, "\t")
					fmt.Println(*t.Value)
					fmt.Println()
				}
			}
		}
	}
}
예제 #2
0
func main() {
	svc := ec2.New(&aws.Config{Region: "ap-northeast-1"})
	res, err := svc.DescribeInstances(nil)
	if err !- nil {
		panic(err)
	}

	for _, r := range res.Reservations {
		for _, i := range r.Instances {
			var tag_name string
			for _, t := range i.Tags {
				if *t.Key == "Name" {
					tag_name = *t.Vvalue
				}
			}
			fmt.Println (
				tag_name,
				*i.InstanceID,
				*i.InstanceType,
				*i.Placement.AvailabilityZone,
				*i.PrivateIPAddress,
				*i.State.Name,
			)
		}
	}
}
func TestMakingABasicRequest(t *testing.T) {
	client := ec2.New(nil)
	resp, e := client.DescribeRegions(&ec2.DescribeRegionsInput{})
	err := aws.Error(e)
	_, _, _ = resp, e, err // avoid unused warnings

	assert.NoError(t, nil, err)

}
예제 #4
0
파일: main.go 프로젝트: StevenMaude/jump
func main() {
	if os.Getenv("SSH_AUTH_SOCK") == "" {
		fmt.Fprintln(os.Stderr, "Warning: agent forwarding not enabled")
	}

	client := ec2.New(nil)

	if len(os.Args) > 1 && os.Args[1] == "@" {
		Watch(client)
		return
	}

	JumpTo(client)
}
func TestErrorHandling(t *testing.T) {
	client := ec2.New(nil)
	resp, e := client.DescribeInstances(&ec2.DescribeInstancesInput{
		InstanceIDs: []*string{
			aws.String("i-12345678"),
		},
	})
	err := aws.Error(e)
	_, _, _ = resp, e, err // avoid unused warnings

	assert.NotEqual(t, nil, err)
	assert.Equal(t, "InvalidInstanceID.NotFound", err.Code)
	utilassert.Match(t, "The instance ID 'i-12345678' does not exist", err.Message)

}
예제 #6
0
func TestCopySnapshotPresignedURL(t *testing.T) {
	svc := ec2.New(&aws.Config{Region: "us-west-2"})

	assert.NotPanics(t, func() {
		// Doesn't panic on nil input
		req, _ := svc.CopySnapshotRequest(nil)
		req.Sign()
	})

	req, _ := svc.CopySnapshotRequest(&ec2.CopySnapshotInput{
		SourceRegion:     aws.String("us-west-1"),
		SourceSnapshotID: aws.String("snap-id"),
	})
	req.Sign()

	b, _ := ioutil.ReadAll(req.HTTPRequest.Body)
	q, _ := url.ParseQuery(string(b))
	url, _ := url.QueryUnescape(q.Get("PresignedUrl"))
	assert.Equal(t, "us-west-2", q.Get("DestinationRegion"))
	assert.Regexp(t, `^https://ec2\.us-west-1\.amazon.+&DestinationRegion=us-west-2`, url)
}
예제 #7
0
파일: main.go 프로젝트: StevenMaude/jump
func Watch(client *ec2.EC2) {
	c := ec2.New(nil)

	finish := make(chan struct{})
	go func() {
		defer close(finish)
		// Await stdin closure
		io.Copy(ioutil.Discard, os.Stdin)
	}()

	goUp := func() {}

	for {
		queryStart := time.Now()
		ConfigureHTTP(true)

		ec2Instances, err := c.DescribeInstances(&ec2.DescribeInstancesInput{})
		if err != nil {
			log.Fatal("DescribeInstances error:", err)
		}

		ConfigureHTTP(false)

		instances := InstancesFromEC2Result(ec2Instances)

		goUp()

		ShowInstances(instances)

		queryDuration := time.Since(queryStart)

		select {
		case <-time.After(1*time.Second - queryDuration):
		case <-finish:
			return
		}
		goUp = func() { CursorUp(len(instances) + N_TABLE_DECORATIONS) }
	}

}
예제 #8
0
파일: aws.go 프로젝트: cjnygard/origin
// newAWSCloud creates a new instance of AWSCloud.
// authFunc and instanceId are primarily for tests
func newAWSCloud(config io.Reader, authFunc AuthFunc, metadata AWSMetadata) (*AWSCloud, error) {
	cfg, err := readAWSCloudConfig(config, metadata)
	if err != nil {
		return nil, fmt.Errorf("unable to read AWS cloud provider config file: %v", err)
	}

	creds := authFunc()

	zone := cfg.Global.Zone
	if len(zone) <= 1 {
		return nil, fmt.Errorf("invalid AWS zone in config file: %s", zone)
	}
	regionName := zone[:len(zone)-1]

	valid := isRegionValid(regionName)
	if !valid {
		return nil, fmt.Errorf("not a valid AWS zone (unknown region): %s", zone)
	}

	ec2 := &awsSdkEC2{
		ec2: ec2.New(&aws.Config{
			Region:      regionName,
			Credentials: creds,
		}),
	}

	awsCloud := &AWSCloud{
		ec2:              ec2,
		cfg:              cfg,
		region:           regionName,
		availabilityZone: zone,
		metadata:         metadata,
	}

	return awsCloud, nil
}
예제 #9
0
func TestInterface(t *testing.T) {
	assert.Implements(t, (*ec2iface.EC2API)(nil), ec2.New(nil))
}
예제 #10
0
func NewClient(region string) *AWSClient {
	return &AWSClient{
		EC2Client: ec2.New(&aws.Config{Region: region}),
	}
}
예제 #11
0
파일: client.go 프로젝트: ninefive/confd
func init() {
	Before("@ec2", func() {
		World["client"] = ec2.New(nil)
	})
}
예제 #12
0
func (m *Monitor) monitorPolicy(p *Policy) {
	//first, get historical data dump
	m.RLock()
	pData := m.policies[p]
	m.RUnlock()
	m.credsLock.Lock()
	cli := ec2.New(m.creds, p.Region, nil)
	m.credsLock.Unlock()
	//Fetch historical data
	pData.Lock()
	log.Println("Fetching historical data!")
	var requestParameters ec2.DescribeSpotPriceHistoryRequest
	requestParameters.InstanceTypes = []string{p.InstanceType}
	requestParameters.ProductDescriptions = []string{p.ProductDescription}
	requestParameters.AvailabilityZone = aws.String(p.AvailabilityZone)
	resp, err := cli.DescribeSpotPriceHistory(&requestParameters)
	if err != nil {
		panic(err)
	}
	for _, spotPrice := range resp.SpotPriceHistory {
		price, err := strconv.ParseFloat(*spotPrice.SpotPrice, 64)
		if err != nil {
			panic(err)
		}
		pData.priceData = append(pData.priceData, &PriceDatum{*spotPrice.AvailabilityZone, *spotPrice.InstanceType, *spotPrice.ProductDescription, price, spotPrice.Timestamp})
	}
	sort.Sort(byTimestamp(pData.priceData))
	pData.Unlock()
	//Now check for new data
	for {
		select {
		case <-p.done:
			close(p.channel)
			p.channel = nil
			break
		case <-time.After(time.Second * 30):
			pData.Lock()
			requestParameters.StartTime = aws.Time(pData.priceData[len(pData.priceData)-1].Timestamp.Add(time.Millisecond * 5))
			resp, err := cli.DescribeSpotPriceHistory(&requestParameters)
			if err != nil {
				panic(err)
			}
			//TODO: should sort incoming price data chronologically, even if the API says it will be sorted.
			for i, spotPrice := range resp.SpotPriceHistory {
				price, err := strconv.ParseFloat(*spotPrice.SpotPrice, 64)
				if err != nil {
					panic(err)
				}
				datum := &PriceDatum{*spotPrice.AvailabilityZone, *spotPrice.InstanceType, *spotPrice.ProductDescription, price, spotPrice.Timestamp}
				//Filter out duplicates, AWS seems to send the current price regardless of the StartTime
				if *pData.priceData[len(pData.priceData)-len(resp.SpotPriceHistory)+i] == *datum {
					continue
				}
				p.channel <- datum
				pData.priceData = append(pData.priceData)
			}
			pData.Unlock()
		}
		if p.channel == nil {
			break
		}
	}
}