本文整理匯總了Golang中github.com/mitchellh/goamz/ec2.EC2類的典型用法代碼示例。如果您正苦於以下問題:Golang EC2類的具體用法?Golang EC2怎麽用?Golang EC2使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了EC2類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: resource_aws_internet_gateway_attach
func resource_aws_internet_gateway_attach(
ec2conn *ec2.EC2,
s *terraform.ResourceState,
vpcId string) error {
log.Printf(
"[INFO] Attaching Internet Gateway '%s' to VPC '%s'",
s.ID,
vpcId)
_, err := ec2conn.AttachInternetGateway(s.ID, vpcId)
if err != nil {
return err
}
// Wait for it to be fully attached before continuing
log.Printf("[DEBUG] Waiting for internet gateway (%s) to attach", s.ID)
stateConf := &resource.StateChangeConf{
Pending: []string{"detached", "attaching"},
Target: "available",
Refresh: IGAttachStateRefreshFunc(ec2conn, s.ID, "available"),
Timeout: 1 * time.Minute,
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf(
"Error waiting for internet gateway (%s) to attach: %s",
s.ID, err)
}
return nil
}
示例2: waitForState
func waitForState(ec2conn *ec2.EC2, originalInstance *ec2.Instance, pending []string, target string) (i *ec2.Instance, err error) {
log.Printf("Waiting for instance state to become: %s", target)
i = originalInstance
for i.State.Name != target {
found := false
for _, allowed := range pending {
if i.State.Name == allowed {
found = true
break
}
}
if !found {
fmt.Errorf("unexpected state '%s', wanted target '%s'", i.State.Name, target)
return
}
var resp *ec2.InstancesResp
resp, err = ec2conn.Instances([]string{i.InstanceId}, ec2.NewFilter())
if err != nil {
return
}
i = &resp.Reservations[0].Instances[0]
time.Sleep(2 * time.Second)
}
return
}
示例3: copyAMI
// copyAMI starts the AMI copy
func copyAMI(awsec2dest *ec2.EC2, s *session, amis *map[string]string) {
if s.destRegion.Name != s.sourceRegion.Name {
for amiId, instanceId := range *amis {
backupAmiName := fmt.Sprintf("%s-%s-%s", s.instanceNameTag, timeStamp, amiId)
backupDesc := fmt.Sprintf("%s %s %s", s.instanceNameTag, timeString, amiId)
copyOpts := ec2.CopyImage{
SourceRegion: s.sourceRegion.Name,
SourceImageId: amiId,
Name: backupAmiName,
Description: backupDesc,
ClientToken: "",
}
copyResp, err := awsec2dest.CopyImage(©Opts)
if err != nil {
s.fatal("EC2 API CopyImage failed")
}
s.debug(fmt.Sprintf("Started copy of %s from %s (%s) to %s (%s).", s.instanceNameTag, s.sourceRegion.Name, amiId, s.destRegion.Name, copyResp.ImageId))
_, err = awsec2dest.CreateTags([]string{copyResp.ImageId}, []ec2.Tag{
{"hostname", s.instanceNameTag},
{"instance", instanceId},
{"sourceregion", s.sourceRegion.Name},
{"date", timeString},
{"timestamp", timeSecs},
})
if err != nil {
s.fatal(fmt.Sprintf("Error tagging new AMI: %s", err.Error()))
}
}
} else {
s.debug("Not copying AMI - source and dest regions match")
}
}
示例4: SSHAddress
// SSHAddress returns a function that can be given to the SSH communicator
// for determining the SSH address based on the instance DNS name.
func SSHAddress(e *ec2.EC2, port int) func(multistep.StateBag) (string, error) {
return func(state multistep.StateBag) (string, error) {
for j := 0; j < 2; j++ {
var host string
i := state.Get("instance").(*ec2.Instance)
if i.DNSName != "" {
host = i.DNSName
} else if i.VpcId != "" {
if i.PublicIpAddress != "" {
host = i.PublicIpAddress
} else {
host = i.PrivateIpAddress
}
}
if host != "" {
return fmt.Sprintf("%s:%d", host, port), nil
}
r, err := e.Instances([]string{i.InstanceId}, ec2.NewFilter())
if err != nil {
return "", err
}
if len(r.Reservations) == 0 || len(r.Reservations[0].Instances) == 0 {
return "", fmt.Errorf("instance not found: %s", i.InstanceId)
}
state.Put("instance", &r.Reservations[0].Instances[0])
time.Sleep(1 * time.Second)
}
return "", errors.New("couldn't determine IP address for instance")
}
}
示例5: InstanceStateRefreshFunc
// InstanceStateRefreshFunc returns a StateRefreshFunc that is used to watch
// an EC2 instance.
func InstanceStateRefreshFunc(conn *ec2.EC2, i *ec2.Instance) StateRefreshFunc {
return func() (interface{}, string, error) {
resp, err := conn.Instances([]string{i.InstanceId}, ec2.NewFilter())
if err != nil {
if ec2err, ok := err.(*ec2.Error); ok && ec2err.Code == "InvalidInstanceID.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 InstanceStateRefresh: %s", err)
return nil, "", err
}
}
if resp == nil || len(resp.Reservations) == 0 || len(resp.Reservations[0].Instances) == 0 {
// Sometimes AWS just has consistency issues and doesn't see
// our instance yet. Return an empty state.
return nil, "", nil
}
i = &resp.Reservations[0].Instances[0]
return i, i.State.Name, nil
}
}
示例6: 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.DescribeSpotRequests([]string{spotRequestId}, ec2.NewFilter())
if err != nil {
if ec2err, ok := err.(*ec2.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.SpotRequestResults) == 0 {
// Sometimes AWS has consistency issues and doesn't see the
// SpotRequest. Return an empty state.
return nil, "", nil
}
i := resp.SpotRequestResults[0]
return i, i.State, nil
}
}
示例7: resource_aws_eip_retrieve_address
// Returns a single address by its ID
func resource_aws_eip_retrieve_address(id string, vpc bool, ec2conn *ec2.EC2) (*ec2.Address, error) {
// Get the full address description for saving to state for
// use in other resources
assocIds := []string{}
publicIps := []string{}
if vpc {
assocIds = []string{id}
} else {
publicIps = []string{id}
}
log.Printf("[DEBUG] EIP describe configuration: %#v, %#v (vpc: %v)", assocIds, publicIps, vpc)
describeAddresses, err := ec2conn.Addresses(publicIps, assocIds, nil)
if err != nil {
return nil, fmt.Errorf("Error retrieving EIP: %s", err)
}
// Verify AWS returned our EIP
if len(describeAddresses.Addresses) != 1 ||
describeAddresses.Addresses[0].AllocationId != id ||
describeAddresses.Addresses[0].PublicIp != id {
if err != nil {
return nil, fmt.Errorf("Unable to find EIP: %#v", describeAddresses.Addresses)
}
}
address := describeAddresses.Addresses[0]
return &address, nil
}
示例8: SGStateRefreshFunc
// SGStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch
// a security group.
func SGStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
sgs := []ec2.SecurityGroup{ec2.SecurityGroup{Id: id}}
resp, err := conn.SecurityGroups(sgs, nil)
if err != nil {
if ec2err, ok := err.(*ec2.Error); ok {
if ec2err.Code == "InvalidSecurityGroupID.NotFound" ||
ec2err.Code == "InvalidGroup.NotFound" {
resp = nil
err = nil
}
}
if err != nil {
log.Printf("Error on SGStateRefresh: %s", err)
return nil, "", err
}
}
if resp == nil {
return nil, "", nil
}
group := &resp.Groups[0]
return group, "exists", nil
}
}
示例9: terminateInstances
func terminateInstances(c *C, e *ec2.EC2, insts []*ec2.Instance) {
var ids []string
for _, inst := range insts {
if inst != nil {
ids = append(ids, inst.InstanceId)
}
}
_, err := e.TerminateInstances(ids)
c.Check(err, IsNil, Commentf("%d INSTANCES LEFT RUNNING!!!", len(ids)))
}
示例10: attachTags
//attachTags makes a call to EC2 to attach the given map of tags to a resource.
func attachTags(ec2Handle *ec2.EC2,
tags map[string]string, instance string) error {
tagSlice := []ec2.Tag{}
for tag, value := range tags {
tagSlice = append(tagSlice, ec2.Tag{tag, value})
}
_, err := ec2Handle.CreateTags([]string{instance}, tagSlice)
return err
}
示例11: InstanceStateRefreshFunc
// InstanceStateRefreshFunc returns a StateRefreshFunc that is used to watch
// an EC2 instance.
func InstanceStateRefreshFunc(conn *ec2.EC2, i *ec2.Instance) StateRefreshFunc {
return func() (interface{}, string, error) {
resp, err := conn.Instances([]string{i.InstanceId}, ec2.NewFilter())
if err != nil {
return nil, "", err
}
i = &resp.Reservations[0].Instances[0]
return i, i.State.Name, nil
}
}
示例12: resource_aws_internet_gateway_detach
func resource_aws_internet_gateway_detach(
ec2conn *ec2.EC2,
s *terraform.ResourceState) error {
if s.Attributes["vpc_id"] == "" {
return nil
}
log.Printf(
"[INFO] Detaching Internet Gateway '%s' from VPC '%s'",
s.ID,
s.Attributes["vpc_id"])
wait := true
_, err := ec2conn.DetachInternetGateway(s.ID, s.Attributes["vpc_id"])
if err != nil {
ec2err, ok := err.(*ec2.Error)
if ok {
if ec2err.Code == "InvalidInternetGatewayID.NotFound" {
err = nil
wait = false
} else if ec2err.Code == "Gateway.NotAttached" {
err = nil
wait = false
}
}
if err != nil {
return err
}
}
delete(s.Attributes, "vpc_id")
if !wait {
return nil
}
// Wait for it to be fully detached before continuing
log.Printf("[DEBUG] Waiting for internet gateway (%s) to detach", s.ID)
stateConf := &resource.StateChangeConf{
Pending: []string{"attached", "detaching", "available"},
Target: "detached",
Refresh: IGAttachStateRefreshFunc(ec2conn, s.ID, "detached"),
Timeout: 1 * time.Minute,
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf(
"Error waiting for internet gateway (%s) to detach: %s",
s.ID, err)
}
return nil
}
示例13: findInstances
// findInstances searches for our instances
func findInstances(awsec2 *ec2.EC2, s *session) []ec2.Instance {
filter := ec2.NewFilter()
filter.Add("tag:Name", s.instanceNameTag)
resp, err := awsec2.Instances(nil, filter)
if err != nil {
s.fatal(fmt.Sprintf("EC2 API DescribeInstances failed: %s", err.Error()))
}
instances := []ec2.Instance{}
for _, reservation := range resp.Reservations {
for _, instance := range reservation.Instances {
instances = append(instances, instance)
}
}
return instances
}
示例14: findSnapshots
// findSnapshots returns a map of snapshots associated with an AMI
func findSnapshots(amiid string, awsec2 *ec2.EC2) (map[string]string, error) {
snaps := make(map[string]string)
resp, err := awsec2.Images([]string{amiid}, nil)
if err != nil {
return snaps, fmt.Errorf("EC2 API DescribeImages failed: %s", err.Error())
}
for _, image := range resp.Images {
for _, bd := range image.BlockDevices {
if len(bd.SnapshotId) > 0 {
snaps[bd.SnapshotId] = bd.DeviceName
}
}
}
return snaps, nil
}
示例15: WaitForAMI
// WaitForAMI waits for the given AMI ID to become ready.
func WaitForAMI(c *ec2.EC2, imageId string) error {
for {
imageResp, err := c.Images([]string{imageId}, ec2.NewFilter())
if err != nil {
return err
}
if imageResp.Images[0].State == "available" {
return nil
}
log.Printf("Image in state %s, sleeping 2s before checking again",
imageResp.Images[0].State)
time.Sleep(2 * time.Second)
}
}