本文整理匯總了Golang中github.com/mitchellh/goamz/ec2.New函數的典型用法代碼示例。如果您正苦於以下問題:Golang New函數的具體用法?Golang New怎麽用?Golang New使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了New函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Run
func (s *StepCreateTags) Run(state multistep.StateBag) multistep.StepAction {
ec2conn := state.Get("ec2").(*ec2.EC2)
ui := state.Get("ui").(packer.Ui)
amis := state.Get("amis").(map[string]string)
if len(s.Tags) > 0 {
for region, ami := range amis {
ui.Say(fmt.Sprintf("Adding tags to AMI (%s)...", ami))
var ec2Tags []ec2.Tag
for key, value := range s.Tags {
ui.Message(fmt.Sprintf("Adding tag: \"%s\": \"%s\"", key, value))
ec2Tags = append(ec2Tags, ec2.Tag{key, value})
}
regionconn := ec2.New(ec2conn.Auth, aws.Regions[region])
_, err := regionconn.CreateTags([]string{ami}, ec2Tags)
if err != nil {
err := fmt.Errorf("Error adding tags to AMI (%s): %s", ami, err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
}
}
return multistep.ActionContinue
}
示例2: TestRegions
// Communicate with all EC2 endpoints to see if they are alive.
func (s *ClientTests) TestRegions(c *C) {
name := sessionName("goamz-region-test")
perms := []ec2.IPPerm{{
Protocol: "tcp",
FromPort: 80,
ToPort: 80,
SourceIPs: []string{"127.0.0.1/32"},
}}
errs := make(chan error, len(allRegions))
for _, region := range allRegions {
go func(r aws.Region) {
e := ec2.New(s.ec2.Auth, r)
_, err := e.AuthorizeSecurityGroup(ec2.SecurityGroup{Name: name}, perms)
errs <- err
}(region)
}
for _ = range allRegions {
err := <-errs
if err != nil {
ec2_err, ok := err.(*ec2.Error)
if ok {
c.Check(ec2_err.Code, Matches, "InvalidGroup.NotFound")
} else {
c.Errorf("Non-EC2 error: %s", err)
}
} else {
c.Errorf("Test should have errored but it seems to have succeeded")
}
}
}
示例3: newAWSCloud
// 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)
}
auth, err := authFunc()
if err != nil {
return nil, err
}
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]
region, ok := aws.Regions[regionName]
if !ok {
return nil, fmt.Errorf("not a valid AWS zone (unknown region): %s", zone)
}
ec2 := &goamzEC2{ec2: ec2.New(auth, region)}
awsCloud := &AWSCloud{
ec2: ec2,
cfg: cfg,
region: region,
availabilityZone: zone,
metadata: metadata,
}
return awsCloud, nil
}
示例4: main
func main() {
kingpin.Version("0.0.1")
kingpin.CommandLine.Help = "AWS deployment tools."
kingpin.Parse()
auth, err := aws.EnvAuth()
Check(err)
state := new(multistep.BasicStateBag)
// This allows us to share our client connections while in each of the steps.
state.Put("client_elb", elb.New(auth, aws.USWest2))
state.Put("client_ec2", ec2.New(auth, aws.USWest2))
// Standard configuration that has been passed in via the CLI.
state.Put("elb", *elbId)
state.Put("ami", *amiId)
state.Put("key", *key)
state.Put("size", *size)
state.Put("region", aws.Regions[*region])
state.Put("security", *security)
state.Put("tags", *tags)
steps := []multistep.Step{
&StepDestroy{}, // Remove the existing hosts from the Load balancer.
&StepCreate{}, // Create some EC2 instances and ensure they are ready to be deployed.
}
runner := &multistep.BasicRunner{Steps: steps}
runner.Run(state)
}
示例5: main
func main() {
var regionStr string
flag.StringVar(®ionStr, "r", "us-east-1", "Region")
flag.Parse()
region, err := strToRegion(regionStr)
if err == nil {
log.Fatal(err)
}
auth, err := aws.EnvAuth()
if err != nil {
log.Fatal(err)
}
client := ec2.New(auth, *region)
resp, err := client.Instances(nil, nil)
if err != nil {
log.Fatal(err)
}
instances := []ec2.Instance{}
for _, reservation := range resp.Reservations {
instances = append(instances, reservation.Instances...)
}
b, err := json.Marshal(instances)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", b)
}
示例6: SetUpSuite
func (s *AmazonServerSuite) SetUpSuite(c *C) {
if !testutil.Amazon {
c.Skip("AmazonServerSuite tests not enabled")
}
s.srv.SetUp(c)
s.ServerTests.ec2 = ec2.New(s.srv.auth, aws.USEast)
}
示例7: NewEc2Discoverer
func NewEc2Discoverer(c *cli.Context) Ec2Discoverer {
auth, err := aws.EnvAuth()
if err != nil {
log.Fatal(err)
}
tag := c.String("ec2-tag")
if tag == "" {
log.Fatal(errors.New("You must specify --ec2-tag option"))
}
t := strings.Split(tag, ":")
tagKey, tagValue := t[0], t[1]
regionStr := c.String("ec2-region")
region, ok := aws.Regions[regionStr]
if !ok {
log.Fatal(fmt.Errorf("%s region is not valid", regionStr))
}
client := ec2.New(auth, region)
return Ec2Discoverer{
Client: client,
TagKey: tagKey,
TagValue: tagValue,
}
}
示例8: amiRegionCopy
// amiRegionCopy does a copy for the given AMI to the target region and
// returns the resulting ID or error.
func amiRegionCopy(state multistep.StateBag, auth aws.Auth, imageId string,
target aws.Region, source aws.Region) (string, error) {
// Connect to the region where the AMI will be copied to
regionconn := ec2.New(auth, target)
resp, err := regionconn.CopyImage(&ec2.CopyImage{
SourceRegion: source.Name,
SourceImageId: imageId,
})
if err != nil {
return "", fmt.Errorf("Error Copying AMI (%s) to region (%s): %s",
imageId, target.Name, err)
}
stateChange := StateChangeConf{
Pending: []string{"pending"},
Target: "available",
Refresh: AMIStateRefreshFunc(regionconn, resp.ImageId),
StepState: state,
}
if _, err := WaitForState(&stateChange); err != nil {
return "", fmt.Errorf("Error waiting for AMI (%s) in region (%s): %s",
resp.ImageId, target.Name, err)
}
return resp.ImageId, nil
}
示例9: Instances
func (cache *EC2Cache) Instances() (*ec2.InstancesResp, error) {
auth, err := aws.GetAuth(cache.accessKey, cache.secretKey)
if err != nil {
return nil, err
}
return ec2.New(auth, cache.region).Instances(nil, nil)
}
示例10: main
func main() {
s := &session{}
handleOptions(s)
// connect to AWS
auth := aws.Auth{AccessKey: s.awsAccessKeyId, SecretKey: s.awsSecretAccessKey}
awsec2 := ec2.New(auth, s.sourceRegion)
awsec2dest := ec2.New(auth, s.destRegion)
// purge old AMIs and snapshots in both regions
if len(s.windows) > 0 {
err := purgeAMIs(awsec2, s.instanceNameTag, s.windows, s)
if err != nil {
s.warning(fmt.Sprintf("Error purging old AMIs: %s", err.Error()))
}
if s.destRegion.Name != s.sourceRegion.Name {
err = purgeAMIs(awsec2dest, s.instanceNameTag, s.windows, s)
if err != nil {
s.warning(fmt.Sprintf("Error purging old AMIs: %s", err.Error()))
}
}
}
if s.purgeonly {
s.ok("Purging done and --purgeonly specified - exiting.")
os.Exit(s.finish())
}
// search for our instances
instances := findInstances(awsec2, s)
if len(instances) < 1 {
s.fatal(fmt.Sprintf("No instances with matching name tag: %s", s.instanceNameTag))
} else {
s.debug(fmt.Sprintf("Found %d instances with matching Name tag: %s", len(instances), s.instanceNameTag))
}
// create local AMIs
newAMIs := createAMIs(awsec2, instances, s)
// create AMIs to backup region
copyAMI(awsec2dest, s, &newAMIs)
// this finish() call gives us nagios output, if desired
os.Exit(s.finish())
}
示例11: Run
func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) {
region, ok := aws.Regions[b.config.Region]
if !ok {
panic("region not found")
}
auth := aws.Auth{b.config.AccessKey, b.config.SecretKey}
ec2conn := ec2.New(auth, region)
// Setup the state bag and initial state for the steps
state := make(map[string]interface{})
state["config"] = b.config
state["ec2"] = ec2conn
state["hook"] = hook
state["ui"] = ui
// Build the steps
steps := []multistep.Step{
&stepKeyPair{},
&stepSecurityGroup{},
&stepRunSourceInstance{},
&stepConnectSSH{},
&stepProvision{},
&stepStopInstance{},
&stepCreateAMI{},
}
// Run!
if b.config.PackerDebug {
b.runner = &multistep.DebugRunner{
Steps: steps,
PauseFn: common.MultistepDebugFn(ui),
}
} else {
b.runner = &multistep.BasicRunner{Steps: steps}
}
b.runner.Run(state)
// If there was an error, return that
if rawErr, ok := state["error"]; ok {
return nil, rawErr.(error)
}
// If there are no AMIs, then just return
if _, ok := state["amis"]; !ok {
return nil, nil
}
// Build the artifact and return it
artifact := &artifact{
amis: state["amis"].(map[string]string),
conn: ec2conn,
}
return artifact, nil
}
示例12: Run
func (s *StepAMIRegionCopy) Run(state multistep.StateBag) multistep.StepAction {
ec2conn := state.Get("ec2").(*ec2.EC2)
ui := state.Get("ui").(packer.Ui)
amis := state.Get("amis").(map[string]string)
ami := amis[ec2conn.Region.Name]
if len(s.Regions) == 0 {
return multistep.ActionContinue
}
ui.Say(fmt.Sprintf("Copying AMI (%s) to other regions...", ami))
for _, region := range s.Regions {
ui.Message(fmt.Sprintf("Copying to: %s", region))
// Connect to the region where the AMI will be copied to
regionconn := ec2.New(ec2conn.Auth, aws.Regions[region])
resp, err := regionconn.CopyImage(&ec2.CopyImage{
SourceRegion: ec2conn.Region.Name,
SourceImageId: ami,
})
if err != nil {
err := fmt.Errorf("Error Copying AMI (%s) to region (%s): %s", ami, region, err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
stateChange := StateChangeConf{
Conn: regionconn,
Pending: []string{"pending"},
Target: "available",
Refresh: AMIStateRefreshFunc(regionconn, resp.ImageId),
StepState: state,
}
ui.Say(fmt.Sprintf("Waiting for AMI (%s) in region (%s) to become ready...",
resp.ImageId, region))
if _, err := WaitForState(&stateChange); err != nil {
err := fmt.Errorf("Error waiting for AMI (%s) in region (%s): %s", resp.ImageId, region, err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
amis[region] = resp.ImageId
}
state.Put("amis", amis)
return multistep.ActionContinue
}
示例13: TestSignatureWithEndpointPath
func (s *S) TestSignatureWithEndpointPath(c *C) {
ec2.FakeTime(true)
defer ec2.FakeTime(false)
testServer.Response(200, nil, RebootInstancesExample)
// https://bugs.launchpad.net/goamz/+bug/1022749
ec2 := ec2.New(s.ec2.Auth, aws.Region{EC2Endpoint: testServer.URL + "/services/Cloud"})
_, err := ec2.RebootInstances("i-10a64379")
c.Assert(err, IsNil)
req := testServer.WaitRequest()
c.Assert(req.Form["Signature"], DeepEquals, []string{"klxs+VwDa1EKHBsxlDYYN58wbP6An+RVdhETv1Fm/os="})
}
示例14: getInstances
func getInstances(name string) (instances []ec2.Instance, err error) {
auth, err := aws.EnvAuth()
if err != nil {
panic(err.Error())
}
e := ec2.New(auth, aws.USEast)
filter := ec2.NewFilter()
filter.Add("instance-state-name", "running")
filter.Add("instance-state-name", "stopped")
filter.Add("tag:Name", name)
resp, err2 := e.Instances(nil, filter)
instances = make([]ec2.Instance, 0, 5)
for _, reservation := range resp.Reservations {
instances = append(instances, reservation.Instances...)
}
return instances, err2
}
示例15: Configure
func (p *ResourceProvider) Configure(c *terraform.ResourceConfig) error {
if _, err := config.Decode(&p.Config, c.Config); err != nil {
return err
}
// Get the auth and region. This can fail if keys/regions were not
// specified and we're attempting to use the environment.
var errs []error
log.Println("[INFO] Building AWS auth structure")
auth, err := p.Config.AWSAuth()
if err != nil {
errs = append(errs, err)
}
log.Println("[INFO] Building AWS region structure")
region, err := p.Config.AWSRegion()
if err != nil {
errs = append(errs, err)
}
if len(errs) == 0 {
log.Println("[INFO] Initializing EC2 connection")
p.ec2conn = ec2.New(auth, region)
log.Println("[INFO] Initializing ELB connection")
p.elbconn = elb.New(auth, region)
log.Println("[INFO] Initializing AutoScaling connection")
p.autoscalingconn = autoscaling.New(auth, region)
log.Println("[INFO] Initializing S3 connection")
p.s3conn = s3.New(auth, region)
log.Println("[INFO] Initializing RDS connection")
p.rdsconn = rds.New(auth, region)
log.Println("[INFO] Initializing Route53 connection")
p.route53 = route53.New(auth, region)
}
if len(errs) > 0 {
return &multierror.Error{Errors: errs}
}
// Create the provider, set the meta
p.p = Provider()
p.p.SetMeta(p)
return nil
}