• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang ec2.EC2类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/aws/aws-sdk-go/service/ec2.EC2的典型用法代码示例。如果您正苦于以下问题:Golang EC2类的具体用法?Golang EC2怎么用?Golang EC2使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了EC2类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: setupSecurityGroup

// Sets up a security group based on it's ID.  Returns an error if it isn't able.
func setupSecurityGroup(name, desc, vpc string, ec2client *ec2.EC2) (string, error) {
	//Create the input struct with the appropriate settings, making sure to use the aws string pointer type
	sgReq := ec2.CreateSecurityGroupInput{
		GroupName:   aws.String(name),
		Description: aws.String(desc),
		VpcId:       aws.String(vpc),
	}

	//Attempt to create the security group
	sgResp, err := ec2client.CreateSecurityGroup(&sgReq)
	if err != nil {
		return "", err
	}

	authReq := ec2.AuthorizeSecurityGroupIngressInput{
		CidrIp:     aws.String("0.0.0.0/0"),
		FromPort:   aws.Int64(9443),
		ToPort:     aws.Int64(9443),
		IpProtocol: aws.String("tcp"),
		GroupId:    sgResp.GroupId,
	}
	_, err = ec2client.AuthorizeSecurityGroupIngress(&authReq)
	if err != nil {
		return "", err
	}

	return *sgResp.GroupId, nil
}
开发者ID:roo7break,项目名称:cracklord,代码行数:29,代码来源:aws-api.go


示例2: SpotRequestStateRefreshFunc

// SpotRequestStateRefreshFunc returns a StateRefreshFunc that is used to watch
// a spot request for state changes.
func SpotRequestStateRefreshFunc(conn *ec2.EC2, spotRequestId string) StateRefreshFunc {
	return func() (interface{}, string, error) {
		resp, err := conn.DescribeSpotInstanceRequests(&ec2.DescribeSpotInstanceRequestsInput{
			SpotInstanceRequestIDs: []*string{&spotRequestId},
		})

		if err != nil {
			if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidSpotInstanceRequestID.NotFound" {
				// Set this to nil as if we didn't find anything.
				resp = nil
			} else if isTransientNetworkError(err) {
				// Transient network error, treat it as if we didn't find anything
				resp = nil
			} else {
				log.Printf("Error on SpotRequestStateRefresh: %s", err)
				return nil, "", err
			}
		}

		if resp == nil || len(resp.SpotInstanceRequests) == 0 {
			// Sometimes AWS has consistency issues and doesn't see the
			// SpotRequest. Return an empty state.
			return nil, "", nil
		}

		i := resp.SpotInstanceRequests[0]
		return i, *i.State, nil
	}
}
开发者ID:jamesleech,项目名称:packer,代码行数:31,代码来源:state.go


示例3: findResourceRoute

// Helper: retrieve a route
func findResourceRoute(conn *ec2.EC2, rtbid string, cidr string) (*ec2.Route, error) {
	routeTableID := rtbid

	findOpts := &ec2.DescribeRouteTablesInput{
		RouteTableIds: []*string{&routeTableID},
	}

	resp, err := conn.DescribeRouteTables(findOpts)
	if err != nil {
		return nil, err
	}

	if len(resp.RouteTables) < 1 || resp.RouteTables[0] == nil {
		return nil, fmt.Errorf("Route table %s is gone, so route does not exist.",
			routeTableID)
	}

	for _, route := range (*resp.RouteTables[0]).Routes {
		if *route.DestinationCidrBlock == cidr {
			return route, nil
		}
	}

	return nil, fmt.Errorf(`
error finding matching route for Route table (%s) and destination CIDR block (%s)`,
		rtbid, cidr)
}
开发者ID:tompao,项目名称:terraform,代码行数:28,代码来源:resource_aws_route.go


示例4: VPCStateRefreshFunc

// VPCStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch
// a VPC.
func VPCStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		DescribeVpcOpts := &ec2.DescribeVPCsInput{
			VPCIDs: []*string{aws.String(id)},
		}
		resp, err := conn.DescribeVPCs(DescribeVpcOpts)
		if err != nil {
			if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidVpcID.NotFound" {
				resp = nil
			} else {
				log.Printf("Error on VPCStateRefresh: %s", err)
				return nil, "", err
			}
		}

		if resp == nil {
			// Sometimes AWS just has consistency issues and doesn't see
			// our instance yet. Return an empty state.
			return nil, "", nil
		}

		vpc := resp.VPCs[0]
		return vpc, *vpc.State, nil
	}
}
开发者ID:sheldonh,项目名称:terraform,代码行数:27,代码来源:resource_aws_vpc.go


示例5: volumeAttachmentStateRefreshFunc

func volumeAttachmentStateRefreshFunc(conn *ec2.EC2, volumeID, instanceID string) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {

		request := &ec2.DescribeVolumesInput{
			VolumeIds: []*string{aws.String(volumeID)},
			Filters: []*ec2.Filter{
				&ec2.Filter{
					Name:   aws.String("attachment.instance-id"),
					Values: []*string{aws.String(instanceID)},
				},
			},
		}

		resp, err := conn.DescribeVolumes(request)
		if err != nil {
			if awsErr, ok := err.(awserr.Error); ok {
				return nil, "failed", fmt.Errorf("code: %s, message: %s", awsErr.Code(), awsErr.Message())
			}
			return nil, "failed", err
		}

		if len(resp.Volumes) > 0 {
			v := resp.Volumes[0]
			for _, a := range v.Attachments {
				if a.InstanceId != nil && *a.InstanceId == instanceID {
					return a, *a.State, nil
				}
			}
		}
		// assume detached if volume count is 0
		return 42, "detached", nil
	}
}
开发者ID:Zordrak,项目名称:terraform,代码行数:33,代码来源:resource_aws_volume_attachment.go


示例6: GetContainerInstances

// GetContainerInstances will return a slice of ECS Container Instances within a cluster
func GetContainerInstances(svc *ecs.ECS, ec2svc *ec2.EC2, cluster *string) (containerInstances []*ecs.ContainerInstance, instances []*ec2.Reservation, e error) {

	var ciArns []*string

	// List clusters
	reqParams := &ecs.ListContainerInstancesInput{
		Cluster:    cluster,
		MaxResults: aws.Int64(100),
		NextToken:  aws.String(""),
	}

	// Loop through tokens until no more results remain
	for {
		resp, err := svc.ListContainerInstances(reqParams)

		// Error check
		if err != nil {
			return nil, nil, fmt.Errorf("ecs.ListContainerInstances: %s", err.Error())
		}

		// Expand slice of container instances and append to our comprehensive list
		ciArns = append(ciArns, resp.ContainerInstanceArns...)

		// Cycle token
		if resp.NextToken != nil {
			reqParams.NextToken = resp.NextToken
		} else {
			// Kill loop ... out of response pages
			break
		}

	}

	// Describe the tasks that we just got back
	ciResponse, err := svc.DescribeContainerInstances(&ecs.DescribeContainerInstancesInput{
		Cluster:            cluster,
		ContainerInstances: ciArns,
	})

	if err != nil {
		return nil, nil, fmt.Errorf("ecs.DescribeContainerInstances: %s", err.Error())
	}

	var instanceIds []*string
	for _, k := range ciResponse.ContainerInstances {
		instanceIds = append(instanceIds, k.Ec2InstanceId)
	}

	// Create a map of container instances by ci arn...
	// Note: Will work for <= 1000 instances w/o having to use NextToken
	ec2Resp, err := ec2svc.DescribeInstances(&ec2.DescribeInstancesInput{
		InstanceIds: instanceIds,
	})

	if err != nil {
		return nil, nil, fmt.Errorf("ec2.DescribeInstances: %s", err.Error())
	}

	return ciResponse.ContainerInstances, ec2Resp.Reservations, nil
}
开发者ID:colinmutter,项目名称:go-ecs,代码行数:61,代码来源:ecs.go


示例7: customerGatewayRefreshFunc

func customerGatewayRefreshFunc(conn *ec2.EC2, gatewayId string) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		gatewayFilter := &ec2.Filter{
			Name:   aws.String("customer-gateway-id"),
			Values: []*string{aws.String(gatewayId)},
		}

		resp, err := conn.DescribeCustomerGateways(&ec2.DescribeCustomerGatewaysInput{
			Filters: []*ec2.Filter{gatewayFilter},
		})
		if err != nil {
			if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidCustomerGatewayID.NotFound" {
				resp = nil
			} else {
				log.Printf("Error on CustomerGatewayRefresh: %s", err)
				return nil, "", err
			}
		}

		if resp == nil || len(resp.CustomerGateways) == 0 {
			// handle consistency issues
			return nil, "", nil
		}

		gateway := resp.CustomerGateways[0]
		return gateway, *gateway.State, nil
	}
}
开发者ID:Originate,项目名称:terraform,代码行数:28,代码来源:resource_aws_customer_gateway.go


示例8: getSecurityGroupIdsByVPC

func getSecurityGroupIdsByVPC(c *ec2.EC2, vpcid string) []*string {
	secgroupids := make([]*string, 0)
	filters := make([]*ec2.Filter, 0)
	keyname := "vpc-id"
	filter := ec2.Filter{
		Name: &keyname, Values: []*string{&vpcid}}
	filters = append(filters, &filter)

	dsgi := &ec2.DescribeSecurityGroupsInput{Filters: filters}
	dsgo, err := c.DescribeSecurityGroups(dsgi)
	if err != nil {
		fmt.Println("Describe security groups failed.")
		panic(err)
	}

	for i := range dsgo.SecurityGroups {
		if *dsgo.SecurityGroups[i].GroupName == "default" {
			continue
		} else {
			secgroupids = append(secgroupids, dsgo.SecurityGroups[i].GroupId)
		}
	}

	return secgroupids

}
开发者ID:jamesunger,项目名称:saws,代码行数:26,代码来源:saws.go


示例9: getSecurityGroupIds

func getSecurityGroupIds(c *ec2.EC2, config *Config, secgroups []string) []*string {

	//secgroups := make([]*string,0)
	secgroupids := make([]*string, 0)
	for i := range secgroups {
		filters := make([]*ec2.Filter, 0)

		keyname := "group-name"
		keyname2 := "vpc-id"
		filter := ec2.Filter{
			Name: &keyname, Values: []*string{&secgroups[i]}}
		filter2 := ec2.Filter{
			Name: &keyname2, Values: []*string{&config.VpcId}}
		filters = append(filters, &filter)
		filters = append(filters, &filter2)

		//fmt.Println("Filters ", filters)

		dsgi := &ec2.DescribeSecurityGroupsInput{Filters: filters}
		dsgo, err := c.DescribeSecurityGroups(dsgi)
		if err != nil {
			fmt.Println("Describe security groups failed.")
			panic(err)
		}

		for i := range dsgo.SecurityGroups {
			secgroupids = append(secgroupids, dsgo.SecurityGroups[i].GroupId)
		}

	}

	//fmt.Println("Security Groups!", secgroupids)
	return secgroupids

}
开发者ID:jamesunger,项目名称:saws,代码行数:35,代码来源:saws.go


示例10: resourceDHCPOptionsStateRefreshFunc

func resourceDHCPOptionsStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		DescribeDhcpOpts := &ec2.DescribeDhcpOptionsInput{
			DhcpOptionsIds: []*string{
				aws.String(id),
			},
		}

		resp, err := conn.DescribeDhcpOptions(DescribeDhcpOpts)
		if err != nil {
			if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidDhcpOptionsID.NotFound" {
				resp = nil
			} else {
				log.Printf("Error on DHCPOptionsStateRefresh: %s", err)
				return nil, "", err
			}
		}

		if resp == nil {
			// Sometimes AWS just has consistency issues and doesn't see
			// our instance yet. Return an empty state.
			return nil, "", nil
		}

		dos := resp.DhcpOptions[0]
		return dos, "created", nil
	}
}
开发者ID:mnbbrown,项目名称:terraform,代码行数:28,代码来源:resource_aws_vpc_dhcp_options.go


示例11: createSubnets

func createSubnets(svc *ec2.EC2, config *Config) (*ec2.CreateSubnetOutput, *ec2.CreateSubnetOutput, error) {

	var csi *ec2.CreateSubnetInput
	if config.AvailZone1 != "" {
		csi = &ec2.CreateSubnetInput{CidrBlock: &config.PublicNet, VpcId: &config.VpcId, AvailabilityZone: &config.AvailZone1}
	} else {
		csi = &ec2.CreateSubnetInput{CidrBlock: &config.PublicNet, VpcId: &config.VpcId}
	}
	//csi := &ec2.CreateSubnetInput{ CidrBlock: &config.PublicNet, VpcId: &config.VpcId }
	cso1, err := svc.CreateSubnet(csi)
	if err != nil {
		fmt.Println("Create public subnet failed")
		return nil, nil, err
	}
	//fmt.Println(cso1)
	config.PublicSubnetId = *cso1.Subnet.SubnetId

	if config.AvailZone2 != "" {
		csi = &ec2.CreateSubnetInput{CidrBlock: &config.PrivateNet, VpcId: &config.VpcId, AvailabilityZone: &config.AvailZone2}
	} else {
		csi = &ec2.CreateSubnetInput{CidrBlock: &config.PrivateNet, VpcId: &config.VpcId}
	}
	//csi := &ec2.CreateSubnetInput{ CidrBlock: &config.PublicNet, VpcId: &config.VpcId }
	//csi = &ec2.CreateSubnetInput{ CidrBlock: &config.PrivateNet, VpcId: &config.VpcId}
	cso2, err := svc.CreateSubnet(csi)
	if err != nil {
		fmt.Println("Create private subnet failed")
		return nil, nil, err
	}
	//fmt.Println(cso2)
	config.PrivateSubnetId = *cso2.Subnet.SubnetId

	return cso1, cso2, nil

}
开发者ID:jamesunger,项目名称:saws,代码行数:35,代码来源:saws.go


示例12: getInstancesWithTag

func getInstancesWithTag(ec2Client *ec2.EC2, key string, value string) ([]*ec2.Instance, error) {
	var instances []*ec2.Instance

	err := ec2Client.DescribeInstancesPages(&ec2.DescribeInstancesInput{
		Filters: []*ec2.Filter{
			&ec2.Filter{
				Name:   aws.String("instance-state-name"),
				Values: []*string{aws.String("running")},
			},
			&ec2.Filter{
				Name:   aws.String(fmt.Sprintf("tag:%s", key)),
				Values: []*string{aws.String(value)},
			},
		},
	}, func(result *ec2.DescribeInstancesOutput, _ bool) bool {
		for _, reservation := range result.Reservations {
			instances = append(instances, reservation.Instances...)
		}
		return true // keep going
	})
	if err != nil {
		return nil, err
	}

	return instances, nil
}
开发者ID:hanazuki,项目名称:check-consul-members,代码行数:26,代码来源:main.go


示例13: createSnapshot

func createSnapshot(svc *ec2.EC2, volumeId string) {
	description := descriptionPrefix + time.Now().Local().String()
	svc.CreateSnapshot(&ec2.CreateSnapshotInput{
		VolumeId:    &volumeId,
		Description: &description,
	})
}
开发者ID:csimsek,项目名称:aws-autosnapshots-go,代码行数:7,代码来源:aws-autosnapshots.go


示例14: findInstance

func findInstance(ec2HostConfig *config.Ec2HostConfig, svc *ec2.EC2) (*ec2.Instance, error) {
	region, name := ec2HostConfig.Region, ec2HostConfig.Name

	log.Printf("Searching for instance named %q in region %s", name, region)

	params := &ec2.DescribeInstancesInput{
		Filters: []*ec2.Filter{
			{
				Name: aws.String("tag:Name"),
				Values: []*string{
					aws.String(ec2HostConfig.Name),
				},
			},
		},
	}
	resp, err := svc.DescribeInstances(params)
	if err != nil {
		return nil, err
	}

	if len(resp.Reservations) < 1 {
		return nil, fmt.Errorf("no instance found in %s with name %s", region, name)
	}
	if len(resp.Reservations) > 1 || len(resp.Reservations[0].Instances) != 1 {
		return nil, fmt.Errorf("multiple instances found in %s with name %s", region, name)
	}
	return resp.Reservations[0].Instances[0], nil
}
开发者ID:djmitche,项目名称:proj,代码行数:28,代码来源:ec2.go


示例15: NGStateRefreshFunc

// NGStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch
// a NAT Gateway.
func NGStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		opts := &ec2.DescribeNatGatewaysInput{
			NatGatewayIds: []*string{aws.String(id)},
		}
		resp, err := conn.DescribeNatGateways(opts)
		if err != nil {
			if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "NatGatewayNotFound" {
				resp = nil
			} else {
				log.Printf("Error on NGStateRefresh: %s", err)
				return nil, "", err
			}
		}

		if resp == nil {
			// Sometimes AWS just has consistency issues and doesn't see
			// our instance yet. Return an empty state.
			return nil, "", nil
		}

		ng := resp.NatGateways[0]
		return ng, *ng.State, nil
	}
}
开发者ID:devendraPSL,项目名称:terraform-api,代码行数:27,代码来源:resource_aws_nat_gateway.go


示例16: waitForDetachedNetwork

func waitForDetachedNetwork(svc *ec2.EC2, instanceid *string) error {
	iids := []*string{instanceid}
	dii := &ec2.DescribeInstancesInput{
		InstanceIds: iids,
	}

	dio, err := svc.DescribeInstances(dii)
	if err != nil {
		panic(err)
	}

	//fmt.Println(dio)
	count := 0
	for {
		dio, err = svc.DescribeInstances(dii)
		if err != nil {
			panic(err)
		}

		if len(dio.Reservations[0].Instances[0].NetworkInterfaces) == 0 {
			return nil
		}

		if count > 60 {
			break
		}

		time.Sleep(2 * time.Second)
		count++
	}

	return errors.New(fmt.Sprintf("Waited too long for EC2 to remove networking."))

}
开发者ID:jamesunger,项目名称:saws,代码行数:34,代码来源:saws.go


示例17: resourceAwsVPCPeeringConnectionStateRefreshFunc

// resourceAwsVPCPeeringConnectionStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch
// a VPCPeeringConnection.
func resourceAwsVPCPeeringConnectionStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {

		resp, err := conn.DescribeVpcPeeringConnections(&ec2.DescribeVpcPeeringConnectionsInput{
			VpcPeeringConnectionIds: []*string{aws.String(id)},
		})
		if err != nil {
			if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidVpcPeeringConnectionID.NotFound" {
				resp = nil
			} else {
				log.Printf("Error reading VPC Peering Connection details: %s", err)
				return nil, "", err
			}
		}

		if resp == nil {
			// Sometimes AWS just has consistency issues and doesn't see
			// our instance yet. Return an empty state.
			return nil, "", nil
		}

		pc := resp.VpcPeeringConnections[0]

		return pc, *pc.Status.Code, nil
	}
}
开发者ID:richardbowden,项目名称:terraform,代码行数:28,代码来源:resource_aws_vpc_peering_connection.go


示例18: getMainRouteTableFromVPC

func getMainRouteTableFromVPC(svc *ec2.EC2, VpcId *string) (*string, error) {

	keyname := "association.main"
	asbool := "true"
	filters := make([]*ec2.Filter, 0)
	filter := ec2.Filter{
		Name: &keyname, Values: []*string{&asbool}}
	filters = append(filters, &filter)

	//fmt.Println("Filters ", filters)

	drti := &ec2.DescribeRouteTablesInput{Filters: filters}
	drto, err := svc.DescribeRouteTables(drti)
	if err != nil {
		panic(err)
	}

	for i := range drto.RouteTables {
		if *drto.RouteTables[i].VpcId == *VpcId {
			//fmt.Println("Route table is", *drto.RouteTables[i].RouteTableId)
			return drto.RouteTables[i].RouteTableId, nil
		}
	}

	return nil, errors.New(fmt.Sprintf("No main route table found for vpc", *VpcId))

}
开发者ID:jamesunger,项目名称:saws,代码行数:27,代码来源:saws.go


示例19: resourceAwsVpcSetDefaultRouteTable

func resourceAwsVpcSetDefaultRouteTable(conn *ec2.EC2, d *schema.ResourceData) error {
	filter1 := &ec2.Filter{
		Name:   aws.String("association.main"),
		Values: []*string{aws.String("true")},
	}
	filter2 := &ec2.Filter{
		Name:   aws.String("vpc-id"),
		Values: []*string{aws.String(d.Id())},
	}

	findOpts := &ec2.DescribeRouteTablesInput{
		Filters: []*ec2.Filter{filter1, filter2},
	}

	resp, err := conn.DescribeRouteTables(findOpts)
	if err != nil {
		return err
	}

	if len(resp.RouteTables) < 1 || resp.RouteTables[0] == nil {
		return fmt.Errorf("Default Route table not found")
	}

	// There Can Be Only 1 ... Default Route Table
	d.Set("default_route_table_id", resp.RouteTables[0].RouteTableId)

	return nil
}
开发者ID:koding,项目名称:terraform,代码行数:28,代码来源:resource_aws_vpc.go


示例20: getPrivateRouteTable

func getPrivateRouteTable(svc *ec2.EC2, subnetid *string, VpcId string) (*string, error) {
	keyname := "association.subnet-id"
	filters := make([]*ec2.Filter, 0)
	filter := ec2.Filter{
		Name: &keyname, Values: []*string{subnetid}}
	filters = append(filters, &filter)

	//fmt.Println("Filters ", filters)

	drti := &ec2.DescribeRouteTablesInput{Filters: filters}
	drto, err := svc.DescribeRouteTables(drti)
	if err != nil {
		panic(err)
	}

	for i := range drto.RouteTables {
		if *drto.RouteTables[i].VpcId == VpcId {
			//fmt.Println("Route table is", *drto.RouteTables[i].RouteTableId)
			return drto.RouteTables[i].RouteTableId, nil
		}
	}

	return nil, errors.New(fmt.Sprintf("No route table found for subnet", *subnetid))

}
开发者ID:jamesunger,项目名称:saws,代码行数:25,代码来源:saws.go



注:本文中的github.com/aws/aws-sdk-go/service/ec2.EC2类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang ec2.IPPermission类代码示例发布时间:2022-05-24
下一篇:
Golang ec2.DescribeInstancesOutput类代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap