本文整理匯總了Golang中github.com/aws/aws-sdk-go/service/ec2.EC2類的典型用法代碼示例。如果您正苦於以下問題:Golang EC2類的具體用法?Golang EC2怎麽用?Golang EC2使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了EC2類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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
}
示例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
}
}
示例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)
}
示例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
}
}
示例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
}
}
示例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
}
示例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
}
}
示例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
}
示例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
}
示例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
}
}
示例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
}
示例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
}
示例13: createSnapshot
func createSnapshot(svc *ec2.EC2, volumeId string) {
description := descriptionPrefix + time.Now().Local().String()
svc.CreateSnapshot(&ec2.CreateSnapshotInput{
VolumeId: &volumeId,
Description: &description,
})
}
示例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
}
示例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
}
}