本文整理汇总了Golang中github.com/aws/aws-sdk-go/service/ec2.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: AllSecurityGroups
// AllSecurityGroups describes every instance in the requested regions
// *SecurityGroups are created for each *ec2.SecurityGroup
// and are passed to a channel
func AllSecurityGroups() chan *SecurityGroup {
ch := make(chan *SecurityGroup, len(config.Regions))
// waitgroup for all regions
wg := sync.WaitGroup{}
for _, region := range config.Regions {
wg.Add(1)
go func(region string) {
defer wg.Done()
// add region to waitgroup
api := ec2.New(sess, aws.NewConfig().WithRegion(region))
resp, err := api.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{})
for _, sg := range resp.SecurityGroups {
ch <- NewSecurityGroup(region, sg)
}
if err != nil {
// probably should do something here...
log.Error(err.Error())
}
}(region)
}
go func() {
// in a separate goroutine, wait for all regions to finish
// when they finish, close the chan
wg.Wait()
close(ch)
}()
return ch
}
示例2: handleDescribeInstances
func handleDescribeInstances(req *cwRequest, c *middleware.Context) {
svc := ec2.New(&aws.Config{Region: aws.String(req.Region)})
reqParam := &struct {
Parameters struct {
Filters []*ec2.Filter `json:"filters"`
InstanceIds []*string `json:"instanceIds"`
} `json:"parameters"`
}{}
json.Unmarshal(req.Body, reqParam)
params := &ec2.DescribeInstancesInput{}
if len(reqParam.Parameters.Filters) > 0 {
params.Filters = reqParam.Parameters.Filters
}
if len(reqParam.Parameters.InstanceIds) > 0 {
params.InstanceIds = reqParam.Parameters.InstanceIds
}
resp, err := svc.DescribeInstances(params)
if err != nil {
c.JsonApiErr(500, "Unable to call AWS API", err)
return
}
c.JSON(200, resp)
}
示例3: clientEC2
// clientEC2 creates a client to interact with AWS EC2 API.
func (b *backend) clientEC2(s logical.Storage, region string) (*ec2.EC2, error) {
b.configMutex.RLock()
if b.EC2ClientsMap[region] != nil {
defer b.configMutex.RUnlock()
// If the client object was already created, return it.
return b.EC2ClientsMap[region], nil
}
// Release the read lock and acquire the write lock.
b.configMutex.RUnlock()
b.configMutex.Lock()
defer b.configMutex.Unlock()
// If the client gets created while switching the locks, return it.
if b.EC2ClientsMap[region] != nil {
return b.EC2ClientsMap[region], nil
}
// Create a AWS config object using a chain of providers.
awsConfig, err := b.getClientConfig(s, region)
if err != nil {
return nil, err
}
// Create a new EC2 client object, cache it and return the same.
b.EC2ClientsMap[region] = ec2.New(session.New(awsConfig))
return b.EC2ClientsMap[region], nil
}
示例4: NewEbsVolumeDriver
func NewEbsVolumeDriver() (VolumeDriver, error) {
d := &ebsVolumeDriver{
volumes: make(map[string]*ebsVolume),
}
ec2sess := session.New()
d.ec2meta = ec2metadata.New(ec2sess)
// Fetch AWS information, validating along the way.
if !d.ec2meta.Available() {
return nil, errors.New("Not running on an EC2 instance.")
}
var err error
if d.awsInstanceId, err = d.ec2meta.GetMetadata("instance-id"); err != nil {
return nil, err
}
if d.awsRegion, err = d.ec2meta.Region(); err != nil {
return nil, err
}
if d.awsAvailabilityZone, err =
d.ec2meta.GetMetadata("placement/availability-zone"); err != nil {
return nil, err
}
d.ec2 = ec2.New(ec2sess, &aws.Config{Region: aws.String(d.awsRegion)})
// Print some diagnostic information and then return the driver.
log("Auto-detected EC2 information:\n")
log("\tInstanceId : %v\n", d.awsInstanceId)
log("\tRegion : %v\n", d.awsRegion)
log("\tAvailability Zone : %v\n", d.awsAvailabilityZone)
return d, nil
}
示例5: getTags
func getTags(region *string, instanceId *string) []string {
output := []string{}
service := ec2.New(&aws.Config{
Region: region,
})
instances, err := service.DescribeInstances(&ec2.DescribeInstancesInput{
InstanceIds: []*string{instanceId},
})
if err != nil {
log.Fatal(err)
}
if len(instances.Reservations) > 1 {
// more than one reservation isn't expected
log.Fatal("Not Expected: Reservations > 1")
}
for _, res := range instances.Reservations {
if len(res.Instances) > 1 {
// more than one instance isn't expected
log.Fatal("Not Expected: Instances > 1")
}
for _, instance := range res.Instances {
for _, tag := range instance.Tags {
output = append(output, *tag.Key+"="+*tag.Value)
}
}
}
return output
}
示例6: New
func New(config Config) *Client {
credentials := credentials.NewStaticCredentials(config.AccessKey, config.SecretKey, "")
sdkConfig := &aws.Config{
Credentials: credentials,
Region: aws.String(config.RegionName),
}
endpointOverrides := config.EndpointOverrides
if endpointOverrides == nil {
endpointOverrides = &Endpoints{}
}
route53Client := route53.New(sdkConfig.Merge(&aws.Config{MaxRetries: aws.Int(7), Endpoint: aws.String(endpointOverrides.Route53)}))
ec2Client := ec2.New(sdkConfig.Merge(&aws.Config{MaxRetries: aws.Int(7), Endpoint: aws.String(endpointOverrides.EC2)}))
s3Client := s3.New(sdkConfig.Merge(&aws.Config{MaxRetries: aws.Int(7), Endpoint: aws.String(endpointOverrides.S3), S3ForcePathStyle: aws.Bool(true)}))
cloudformationClient := cloudformation.New(sdkConfig.Merge(&aws.Config{MaxRetries: aws.Int(7), Endpoint: aws.String(endpointOverrides.Cloudformation)}))
return &Client{
EC2: ec2Client,
S3: s3Client,
Route53: route53Client,
Cloudformation: cloudformationClient,
// HostedZoneID: config.HostedZoneID,
// HostedZoneName: config.HostedZoneName,
Bucket: config.Bucket,
}
}
示例7: GetSnapshotsByTag
// GetSnapshotsByTag returns a slice of EBS Snapshots that match the provided region and Tag key/value
func GetSnapshotsByTag(region, key, value string) (Snapshots, error) {
svc := ec2.New(session.New(&aws.Config{Region: aws.String(region)}))
params := &ec2.DescribeSnapshotsInput{
OwnerIds: []*string{aws.String("self")},
Filters: []*ec2.Filter{
{
Name: aws.String("tag:" + key),
Values: []*string{
aws.String(value),
},
},
},
}
result, err := svc.DescribeSnapshots(params)
snapList := make(Snapshots, len(result.Snapshots))
for i, snapshot := range result.Snapshots {
snapList[i].Marshal(snapshot, region)
}
if len(snapList) == 0 {
return snapList, errors.New("No Snapshot found with tag [" + key + "] of [" + value + "] in [" + region + "].")
}
return snapList, err
}
示例8: FindDefaultVPC
// FindDefaultVPC looks for the default VPC in a given region
// and returns its ID if found.
func FindDefaultVPC(region string) (string, error) {
ec2Service := ec2.New(&aws.Config{Region: aws.String(region)})
// Call the DescribeInstances Operation
resp, err := ec2Service.DescribeVpcs(&ec2.DescribeVpcsInput{
Filters: []*ec2.Filter{
{
Name: aws.String("isDefault"),
Values: []*string{aws.String("true")},
},
},
})
if err != nil {
return "", err
}
if len(resp.Vpcs) == 0 {
return "", util.Errorf("no default VPC found in region %s", region)
}
if len(resp.Vpcs) > 1 {
return "", util.Errorf("found %d default Vpcs in region %s", len(resp.Vpcs), region)
}
return *resp.Vpcs[0].VpcId, nil
}
示例9: main
// This example will list instances with a filter
//
// Usage:
// filter_ec2_by_tag <name_filter>
func main() {
sess, err := session.NewSession()
if err != nil {
log.Fatalf("failed to create session %v\n", err)
}
nameFilter := os.Args[1]
awsRegion := "us-east-1"
svc := ec2.New(sess, &aws.Config{Region: aws.String(awsRegion)})
fmt.Printf("listing instances with tag %v in: %v\n", nameFilter, awsRegion)
params := &ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("tag:Name"),
Values: []*string{
aws.String(strings.Join([]string{"*", nameFilter, "*"}, "")),
},
},
},
}
resp, err := svc.DescribeInstances(params)
if err != nil {
fmt.Println("there was an error listing instances in", awsRegion, err.Error())
log.Fatal(err.Error())
}
fmt.Printf("%+v\n", *resp)
}
示例10: main
func main() {
svc := ec2.New(session.New(), &aws.Config{Region: aws.String("sa-east-1")})
resp, err := svc.DescribeInstances(nil)
if err != nil {
panic(err)
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Tag Name", "Instance Id", "Instance Type", "AZ", "IP", "Status"})
for _, res := range resp.Reservations {
for _, instance := range res.Instances {
var tag_name string
for _, tag := range instance.Tags {
if *tag.Key == "Name" {
tag_name = *tag.Value
}
}
table.Append([]string{
tag_name,
*instance.InstanceId,
*instance.InstanceType,
*instance.Placement.AvailabilityZone,
*instance.PrivateIpAddress,
*instance.State.Name,
})
}
}
table.Render()
}
示例11: main
func main() {
defaults.DefaultConfig.Region = aws.String("us-west-2")
svc := ec2.New(nil)
var filters = []*ec2.Filter{
&ec2.Filter{
Name: aws.String("instance-state-name"),
Values: []*string{aws.String("running")},
},
}
request := ec2.DescribeInstancesInput{Filters: filters}
result, err := svc.DescribeInstances(&request)
if err != nil {
log.Fatalf("Error getting description: %s", err)
}
for _, reservation := range result.Reservations {
for _, instance := range reservation.Instances {
var id = *instance.InstanceId
var publicIp = *instance.PublicIpAddress
var privateIp = *instance.PrivateIpAddress
var keyName = *instance.KeyName
fmt.Printf("%s\t%s\t%s\t%s\n", id, publicIp, privateIp, keyName)
}
}
}
示例12: Stop
func Stop(config *Config) {
svc := ec2.New(session.New())
for i := range config.EC2 {
fmt.Println("Stopping ", config.EC2[i].Name)
//fmt.Println(config.EC2[i].InstanceType)
instances := getInstancesByName(svc, config.EC2[i].Name)
for k := range instances {
if *instances[k].State.Name == "terminated" {
//fmt.Println("Instance is terminated:", *instances[k].InstanceId)
} else {
fmt.Println("Instance will be shutdown: ", *instances[k].InstanceId)
instanceids := []*string{instances[k].InstanceId}
sii := ec2.StopInstancesInput{InstanceIds: instanceids}
_, err := svc.StopInstances(&sii)
if err != nil {
panic(err)
}
fmt.Println("Stopped instance ", *instances[k].InstanceId)
}
}
}
}
示例13: GetImagesByTag
// GetImagesByTag returns a slice of Amazon Machine Images given the provided region, and tag key/values
func GetImagesByTag(region, key, value string) (Images, error) {
svc := ec2.New(session.New(&aws.Config{Region: aws.String(region)}))
params := &ec2.DescribeImagesInput{
Owners: []*string{aws.String("self")},
Filters: []*ec2.Filter{
{
Name: aws.String("tag:" + key),
Values: []*string{
aws.String(value),
},
},
},
}
result, err := svc.DescribeImages(params)
imgList := make(Images, len(result.Images))
for i, image := range result.Images {
imgList[i].Marshal(image, region)
}
if len(imgList) == 0 {
return imgList, errors.New("No Images found with tag [" + key + "] of [" + value + "] in [" + region + "].")
}
return imgList, err
}
示例14: copyImage
// private function without prompts
func copyImage(image Image, region string, dryRun bool) (*ec2.CopyImageOutput, error) {
svc := ec2.New(session.New(&aws.Config{Region: aws.String(region)}))
// Copy image to the destination region
params := &ec2.CopyImageInput{
Name: aws.String(image.Name),
SourceImageId: aws.String(image.ImageID),
SourceRegion: aws.String(image.Region),
DryRun: aws.Bool(dryRun),
//ClientToken: aws.String("String"),
//Description: aws.String("String"),
//Encrypted: aws.Bool(true),
//KmsKeyId: aws.String("String"),
}
copyImageResp, err := svc.CopyImage(params)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
return copyImageResp, errors.New(awsErr.Message())
}
}
return copyImageResp, err
}
示例15: GetRunningInstances
// GetRunningInstances returns the list of running instances.
func GetRunningInstances() ([]Instance, error) {
var svc = ec2.New(session.New(), nil)
request := ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
&ec2.Filter{
Name: aws.String("instance-state-name"),
Values: []*string{aws.String("running")},
},
},
}
resp, err := svc.DescribeInstances(&request)
if err != nil {
return nil, err
}
var instances = make([]Instance, 0)
for _, res := range resp.Reservations {
for _, ins := range res.Instances {
var tag = ""
if len(ins.Tags) > 0 {
tag = *ins.Tags[0].Value
}
var i = Instance{
ID: *ins.InstanceId,
PublicIP: *ins.PublicIpAddress,
PrivateIP: *ins.PrivateIpAddress,
Tag: tag,
}
instances = append(instances, i)
}
}
return instances, nil
}