// IPAddress is an implementation of Instances.IPAddress. func (aws *AWSCloud) IPAddress(name string) (net.IP, error) { f := ec2.NewFilter() f.Add("private-dns-name", name) resp, err := aws.ec2.Instances(nil, f) if err != nil { return nil, err } if len(resp.Reservations) == 0 { return nil, fmt.Errorf("no reservations found for host: %s", name) } if len(resp.Reservations) > 1 { return nil, fmt.Errorf("multiple reservations found for host: %s", name) } if len(resp.Reservations[0].Instances) == 0 { return nil, fmt.Errorf("no instances found for host: %s", name) } if len(resp.Reservations[0].Instances) > 1 { return nil, fmt.Errorf("multiple instances found for host: %s", name) } ipAddress := resp.Reservations[0].Instances[0].PrivateIpAddress ip := net.ParseIP(ipAddress) if ip == nil { return nil, fmt.Errorf("invalid network IP: %s", ipAddress) } return ip, nil }
func getfilter(args []string) (*ec2.Filter, []string) { filter := ec2.NewFilter() for len(args) > 1 { if args[0][0] != '-' { break } switch args[0] { case "-image": filter.Add("image-id", args[1]) case "-type": filter.Add("instance-type", "*"+args[1]+"*") case "-state": filter.Add("instance-state-name", "*"+args[1]+"*") case "-name": filter.Add("tag:Name", "*"+args[1]+"*") case "-stage": filter.Add("tag:stage", "*"+args[1]+"*") default: filter.Add(args[0][1:], "*"+args[1]+"*") } if len(args) > 2 { args = args[2:] } else { args = nil break } //filter.Add("tag:Name", "*"+args[1]+"*") } return filter, args }
func testAccCheckRouteTableDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).ec2conn for _, rs := range s.RootModule().Resources { if rs.Type != "aws_route_table" { continue } // Try to find the resource resp, err := conn.DescribeRouteTables( []string{rs.Primary.ID}, ec2.NewFilter()) if err == nil { if len(resp.RouteTables) > 0 { return fmt.Errorf("still exist.") } return nil } // Verify the error is what we want ec2err, ok := err.(*ec2.Error) if !ok { return err } if ec2err.Code != "InvalidRouteTableID.NotFound" { return err } } return nil }
func testAccCheckRouteTableAssociationExists(n string, v *ec2.RouteTable) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } if rs.ID == "" { return fmt.Errorf("No ID is set") } conn := testAccProvider.ec2conn resp, err := conn.DescribeRouteTables( []string{rs.Attributes["route_table_id"]}, ec2.NewFilter()) if err != nil { return err } if len(resp.RouteTables) == 0 { return fmt.Errorf("RouteTable not found") } *v = resp.RouteTables[0] if len(v.Associations) == 0 { return fmt.Errorf("no associations") } return nil } }
func (s *S) TestDescribeSecurityGroupsExampleWithFilter(c *C) { testServer.Response(200, nil, DescribeSecurityGroupsExample) filter := ec2.NewFilter() filter.Add("ip-permission.protocol", "tcp") filter.Add("ip-permission.from-port", "22") filter.Add("ip-permission.to-port", "22") filter.Add("ip-permission.group-name", "app_server_group", "database_group") _, err := s.ec2.SecurityGroups(nil, filter) req := testServer.WaitRequest() c.Assert(req.Form["Action"], DeepEquals, []string{"DescribeSecurityGroups"}) c.Assert(req.Form["Filter.1.Name"], DeepEquals, []string{"ip-permission.from-port"}) c.Assert(req.Form["Filter.1.Value.1"], DeepEquals, []string{"22"}) c.Assert(req.Form["Filter.2.Name"], DeepEquals, []string{"ip-permission.group-name"}) c.Assert(req.Form["Filter.2.Value.1"], DeepEquals, []string{"app_server_group"}) c.Assert(req.Form["Filter.2.Value.2"], DeepEquals, []string{"database_group"}) c.Assert(req.Form["Filter.3.Name"], DeepEquals, []string{"ip-permission.protocol"}) c.Assert(req.Form["Filter.3.Value.1"], DeepEquals, []string{"tcp"}) c.Assert(req.Form["Filter.4.Name"], DeepEquals, []string{"ip-permission.to-port"}) c.Assert(req.Form["Filter.4.Value.1"], DeepEquals, []string{"22"}) c.Assert(err, IsNil) }
// 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 } }
func testAccCheckInternetGatewayDestroy(s *terraform.State) error { conn := testAccProvider.ec2conn for _, rs := range s.Resources { if rs.Type != "aws_internet_gateway" { continue } // Try to find the resource resp, err := conn.DescribeInternetGateways( []string{rs.ID}, ec2.NewFilter()) if err == nil { if len(resp.InternetGateways) > 0 { return fmt.Errorf("still exist.") } return nil } // Verify the error is what we want ec2err, ok := err.(*ec2.Error) if !ok { return err } if ec2err.Code != "InvalidInternetGatewayID.NotFound" { return err } } return nil }
func (client *Client) FindShip(name string) types.Ship { var ship types.Ship filter := ec2.NewFilter() filter.Add("tag-key", "docker") filter.Add("tag:Name", name) for _, region := range client.region { response, _ := region.Instances(nil, filter) for _, pool := range response.Reservations { for _, instance := range pool.Instances { ship = types.Ship{ instance.InstanceId, client.SearchTag(instance.Tags, "Name"), instance.DNSName, instance.PublicIpAddress, client.State(instance.State), "Ubuntu 14.04", instance.InstanceType, 27017, "http", 0, nil, false, } } } } return ship }
func (s *S) TestDescribeInstancesExample1(c *C) { testServer.Response(200, nil, DescribeInstancesExample1) filter := ec2.NewFilter() filter.Add("key1", "value1") filter.Add("key2", "value2", "value3") resp, err := s.ec2.Instances([]string{"i-1", "i-2"}, nil) req := testServer.WaitRequest() c.Assert(req.Form["Action"], DeepEquals, []string{"DescribeInstances"}) c.Assert(req.Form["InstanceId.1"], DeepEquals, []string{"i-1"}) c.Assert(req.Form["InstanceId.2"], DeepEquals, []string{"i-2"}) c.Assert(err, IsNil) c.Assert(resp.RequestId, Equals, "98e3c9a4-848c-4d6d-8e8a-b1bdEXAMPLE") c.Assert(resp.Reservations, HasLen, 2) r0 := resp.Reservations[0] c.Assert(r0.ReservationId, Equals, "r-b27e30d9") c.Assert(r0.OwnerId, Equals, "999988887777") c.Assert(r0.RequesterId, Equals, "854251627541") c.Assert(r0.SecurityGroups, DeepEquals, []ec2.SecurityGroup{{Name: "default", Id: "sg-67ad940e"}}) c.Assert(r0.Instances, HasLen, 1) r0i := r0.Instances[0] c.Assert(r0i.InstanceId, Equals, "i-c5cd56af") c.Assert(r0i.PrivateDNSName, Equals, "domU-12-31-39-10-56-34.compute-1.internal") c.Assert(r0i.DNSName, Equals, "ec2-174-129-165-232.compute-1.amazonaws.com") c.Assert(r0i.AvailZone, Equals, "us-east-1b") }
func testAccCheckInternetGatewayExists(n string, ig *ec2.InternetGateway) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } if rs.ID == "" { return fmt.Errorf("No ID is set") } conn := testAccProvider.ec2conn resp, err := conn.DescribeInternetGateways( []string{rs.ID}, ec2.NewFilter()) if err != nil { return err } if len(resp.InternetGateways) == 0 { return fmt.Errorf("InternetGateway not found") } *ig = resp.InternetGateways[0] return nil } }
func testAccCheckVpcExists(n string, vpc *ec2.VPC) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } if rs.ID == "" { return fmt.Errorf("No VPC ID is set") } conn := testAccProvider.ec2conn resp, err := conn.DescribeVpcs([]string{rs.ID}, ec2.NewFilter()) if err != nil { return err } if len(resp.VPCs) == 0 { return fmt.Errorf("VPC not found") } *vpc = resp.VPCs[0] return nil } }
func (s *StepSourceAMIInfo) Run(state multistep.StateBag) multistep.StepAction { ec2conn := state.Get("ec2").(*ec2.EC2) ui := state.Get("ui").(packer.Ui) ui.Say("Inspecting the source AMI...") imageResp, err := ec2conn.Images([]string{s.SourceAmi}, ec2.NewFilter()) if err != nil { err := fmt.Errorf("Error querying AMI: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } if len(imageResp.Images) == 0 { err := fmt.Errorf("Source AMI '%s' was not found!", s.SourceAmi) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } image := &imageResp.Images[0] // Enhanced Networking (SriovNetSupport) can only be enabled on HVM AMIs. // See http://goo.gl/icuXh5 if s.EnhancedNetworking && image.VirtualizationType != "hvm" { err := fmt.Errorf("Cannot enable enhanced networking, source AMI '%s' is not HVM", s.SourceAmi) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } state.Put("source_image", image) return multistep.ActionContinue }
func (s *StepSourceAMIInfo) Run(state map[string]interface{}) multistep.StepAction { config := state["config"].(*Config) ec2conn := state["ec2"].(*ec2.EC2) ui := state["ui"].(packer.Ui) ui.Say("Inspecting the source AMI...") imageResp, err := ec2conn.Images([]string{config.SourceAmi}, ec2.NewFilter()) if err != nil { err := fmt.Errorf("Error querying AMI: %s", err) state["error"] = err ui.Error(err.Error()) return multistep.ActionHalt } if len(imageResp.Images) == 0 { err := fmt.Errorf("Source AMI '%s' was not found!", config.SourceAmi) state["error"] = err ui.Error(err.Error()) return multistep.ActionHalt } image := &imageResp.Images[0] // It must be EBS-backed otherwise the build won't work if image.RootDeviceType != "ebs" { err := fmt.Errorf("The root device of the source AMI must be EBS-backed.") state["error"] = err ui.Error(err.Error()) return multistep.ActionHalt } state["source_image"] = image return multistep.ActionContinue }
func testAccCheckRouteTableAssociationDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).ec2conn for _, rs := range s.RootModule().Resources { if rs.Type != "aws_route_table_association" { continue } // Try to find the resource resp, err := conn.DescribeRouteTables( []string{rs.Primary.Attributes["route_table_Id"]}, ec2.NewFilter()) if err != nil { // Verify the error is what we want ec2err, ok := err.(*ec2.Error) if !ok { return err } if ec2err.Code != "InvalidRouteTableID.NotFound" { return err } return nil } rt := resp.RouteTables[0] if len(rt.Associations) > 0 { return fmt.Errorf( "route table %s has associations", rt.RouteTableId) } } return nil }
// 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") } }
func testAccCheckAWSNetworkAclDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).ec2conn for _, rs := range s.RootModule().Resources { if rs.Type != "aws_network" { continue } // Retrieve the network acl resp, err := conn.NetworkAcls([]string{rs.Primary.ID}, ec2.NewFilter()) if err == nil { if len(resp.NetworkAcls) > 0 && resp.NetworkAcls[0].NetworkAclId == rs.Primary.ID { return fmt.Errorf("Network Acl (%s) still exists.", rs.Primary.ID) } return nil } ec2err, ok := err.(*ec2.Error) if !ok { return err } // Confirm error code is what we want if ec2err.Code != "InvalidNetworkAclID.NotFound" { return err } } return nil }
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 }
// 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 } }
func (s *stepCreateAMI) Run(state map[string]interface{}) multistep.StepAction { config := state["config"].(config) ec2conn := state["ec2"].(*ec2.EC2) instance := state["instance"].(*ec2.Instance) ui := state["ui"].(packer.Ui) // Parse the name of the AMI amiNameBuf := new(bytes.Buffer) tData := amiNameData{ strconv.FormatInt(time.Now().UTC().Unix(), 10), } t := template.Must(template.New("ami").Parse(config.AMIName)) t.Execute(amiNameBuf, tData) amiName := amiNameBuf.String() // Create the image ui.Say(fmt.Sprintf("Creating the AMI: %s", amiName)) createOpts := &ec2.CreateImage{ InstanceId: instance.InstanceId, Name: amiName, } createResp, err := ec2conn.CreateImage(createOpts) if err != nil { err := fmt.Errorf("Error creating AMI: %s", err) state["error"] = err ui.Error(err.Error()) return multistep.ActionHalt } // Set the AMI ID in the state ui.Say(fmt.Sprintf("AMI: %s", createResp.ImageId)) amis := make(map[string]string) amis[config.Region] = createResp.ImageId state["amis"] = amis // Wait for the image to become ready ui.Say("Waiting for AMI to become ready...") for { imageResp, err := ec2conn.Images([]string{createResp.ImageId}, ec2.NewFilter()) if err != nil { err := fmt.Errorf("Error querying images: %s", err) state["error"] = err ui.Error(err.Error()) return multistep.ActionHalt } if imageResp.Images[0].State == "available" { break } log.Printf("Image in state %s, sleeping 2s before checking again", imageResp.Images[0].State) time.Sleep(2 * time.Second) } return multistep.ActionContinue }
func resource_aws_instance_refresh( s *terraform.ResourceState, meta interface{}) (*terraform.ResourceState, error) { p := meta.(*ResourceProvider) ec2conn := p.ec2conn resp, err := ec2conn.Instances([]string{s.ID}, ec2.NewFilter()) if err != nil { // If the instance was not found, return nil so that we can show // that the instance is gone. if ec2err, ok := err.(*ec2.Error); ok && ec2err.Code == "InvalidInstanceID.NotFound" { return nil, nil } // Some other error, report it return s, err } // If nothing was found, then return no state if len(resp.Reservations) == 0 { return nil, nil } instance := &resp.Reservations[0].Instances[0] // If the instance is terminated, then it is gone if instance.State.Name == "terminated" { return nil, nil } return resource_aws_instance_update_state(s, instance) }
func testAccCheckInstanceExists(n string, i *ec2.Instance) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } if rs.ID == "" { return fmt.Errorf("No ID is set") } conn := testAccProvider.ec2conn resp, err := conn.Instances( []string{rs.ID}, ec2.NewFilter()) if err != nil { return err } if len(resp.Reservations) == 0 { return fmt.Errorf("Instance not found") } *i = resp.Reservations[0].Instances[0] return nil } }
func testAccCheckRouteTableExists(n string, v *ec2.RouteTable) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } if rs.Primary.ID == "" { return fmt.Errorf("No ID is set") } conn := testAccProvider.Meta().(*AWSClient).ec2conn resp, err := conn.DescribeRouteTables( []string{rs.Primary.ID}, ec2.NewFilter()) if err != nil { return err } if len(resp.RouteTables) == 0 { return fmt.Errorf("RouteTable not found") } *v = resp.RouteTables[0] return nil } }
// Implementation of EC2.Instances func (self *goamzEC2) Instances(instanceIds []string, filter *ec2InstanceFilter) (resp *ec2.InstancesResp, err error) { var goamzFilter *ec2.Filter if filter != nil { goamzFilter = ec2.NewFilter() if filter.PrivateDNSName != "" { goamzFilter.Add("private-dns-name", filter.PrivateDNSName) } } return self.ec2.Instances(instanceIds, goamzFilter) }
func (s *StepRunSourceInstance) Run(state map[string]interface{}) multistep.StepAction { ec2conn := state["ec2"].(*ec2.EC2) keyName := state["keyPair"].(string) securityGroupId := state["securityGroupId"].(string) ui := state["ui"].(packer.Ui) runOpts := &ec2.RunInstances{ KeyName: keyName, ImageId: s.SourceAMI, InstanceType: s.InstanceType, MinCount: 0, MaxCount: 0, SecurityGroups: []ec2.SecurityGroup{ec2.SecurityGroup{Id: securityGroupId}}, SubnetId: s.SubnetId, } ui.Say("Launching a source AWS instance...") imageResp, err := ec2conn.Images([]string{s.SourceAMI}, ec2.NewFilter()) if err != nil { state["error"] = fmt.Errorf("There was a problem with the source AMI: %s", err) return multistep.ActionHalt } if s.ExpectedRootDevice != "" && imageResp.Images[0].RootDeviceType != s.ExpectedRootDevice { state["error"] = fmt.Errorf( "The provided source AMI has an invalid root device type.\n"+ "Expected '%s', got '%s'.", s.ExpectedRootDevice, imageResp.Images[0].RootDeviceType) return multistep.ActionHalt } runResp, err := ec2conn.RunInstances(runOpts) if err != nil { err := fmt.Errorf("Error launching source instance: %s", err) state["error"] = err ui.Error(err.Error()) return multistep.ActionHalt } s.instance = &runResp.Instances[0] log.Printf("instance id: %s", s.instance.InstanceId) ui.Say(fmt.Sprintf("Waiting for instance (%s) to become ready...", s.instance.InstanceId)) s.instance, err = WaitForState(ec2conn, s.instance, []string{"pending"}, "running") if err != nil { err := fmt.Errorf("Error waiting for instance (%s) to become ready: %s", s.instance.InstanceId, err) state["error"] = err ui.Error(err.Error()) return multistep.ActionHalt } state["instance"] = s.instance return multistep.ActionContinue }
func (s *StepAttachVolume) Run(state multistep.StateBag) multistep.StepAction { ec2conn := state.Get("ec2").(*ec2.EC2) device := state.Get("device").(string) instance := state.Get("instance").(*ec2.Instance) ui := state.Get("ui").(packer.Ui) volumeId := state.Get("volume_id").(string) // For the API call, it expects "sd" prefixed devices. attachVolume := strings.Replace(device, "/xvd", "/sd", 1) ui.Say(fmt.Sprintf("Attaching the root volume to %s", attachVolume)) _, err := ec2conn.AttachVolume(volumeId, instance.InstanceId, attachVolume) if err != nil { err := fmt.Errorf("Error attaching volume: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } // Mark that we attached it so we can detach it later s.attached = true s.volumeId = volumeId // Wait for the volume to become attached stateChange := awscommon.StateChangeConf{ Conn: ec2conn, Pending: []string{"attaching"}, StepState: state, Target: "attached", Refresh: func() (interface{}, string, error) { resp, err := ec2conn.Volumes([]string{volumeId}, ec2.NewFilter()) if err != nil { return nil, "", err } if len(resp.Volumes[0].Attachments) == 0 { return nil, "", errors.New("No attachments on volume.") } a := resp.Volumes[0].Attachments[0] return a, a.Status, nil }, } _, err = awscommon.WaitForState(&stateChange) if err != nil { err := fmt.Errorf("Error waiting for volume: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } state.Put("attach_cleanup", s) return multistep.ActionContinue }
// 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 } }
func (s *stepRunSourceInstance) Run(state map[string]interface{}) multistep.StepAction { config := state["config"].(config) ec2conn := state["ec2"].(*ec2.EC2) keyName := state["keyPair"].(string) securityGroupId := state["securityGroupId"].(string) ui := state["ui"].(packer.Ui) runOpts := &ec2.RunInstances{ KeyName: keyName, ImageId: config.SourceAmi, InstanceType: config.InstanceType, MinCount: 0, MaxCount: 0, SecurityGroups: []ec2.SecurityGroup{ec2.SecurityGroup{Id: securityGroupId}}, } ui.Say("Launching a source AWS instance...") imageResp, err := ec2conn.Images([]string{config.SourceAmi}, ec2.NewFilter()) if err != nil { state["error"] = fmt.Errorf("There was a problem with the source AMI: %s", err) return multistep.ActionHalt } if imageResp.Images[0].RootDeviceType != "ebs" { state["error"] = fmt.Errorf( "The provided source AMI is instance-store based. The\n" + "amazon-ebs bundler can only work with EBS based AMIs.") return multistep.ActionHalt } runResp, err := ec2conn.RunInstances(runOpts) if err != nil { err := fmt.Errorf("Error launching source instance: %s", err) state["error"] = err ui.Error(err.Error()) return multistep.ActionHalt } s.instance = &runResp.Instances[0] log.Printf("instance id: %s", s.instance.InstanceId) ui.Say(fmt.Sprintf("Waiting for instance (%s) to become ready...", s.instance.InstanceId)) s.instance, err = waitForState(ec2conn, s.instance, []string{"pending"}, "running") if err != nil { err := fmt.Errorf("Error waiting for instance (%s) to become ready: %s", s.instance.InstanceId, err) state["error"] = err ui.Error(err.Error()) return multistep.ActionHalt } state["instance"] = s.instance return multistep.ActionContinue }
func (s *StepSnapshot) Run(state multistep.StateBag) multistep.StepAction { ec2conn := state.Get("ec2").(*ec2.EC2) ui := state.Get("ui").(packer.Ui) volumeId := state.Get("volume_id").(string) ui.Say("Creating snapshot...") createSnapResp, err := ec2conn.CreateSnapshot( volumeId, fmt.Sprintf("Packer: %s", time.Now().String())) if err != nil { err := fmt.Errorf("Error creating snapshot: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } // Set the snapshot ID so we can delete it later s.snapshotId = createSnapResp.Id ui.Message(fmt.Sprintf("Snapshot ID: %s", s.snapshotId)) // Wait for the snapshot to be ready stateChange := awscommon.StateChangeConf{ Pending: []string{"pending"}, StepState: state, Target: "completed", Refresh: func() (interface{}, string, error) { resp, err := ec2conn.Snapshots([]string{s.snapshotId}, ec2.NewFilter()) if err != nil { return nil, "", err } if len(resp.Snapshots) == 0 { return nil, "", errors.New("No snapshots found.") } s := resp.Snapshots[0] return s, s.Status, nil }, } _, err = awscommon.WaitForState(&stateChange) if err != nil { err := fmt.Errorf("Error waiting for snapshot: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } state.Put("snapshot_id", s.snapshotId) return multistep.ActionContinue }
func testAccCheckSubnetIsAssociatedWithAcl(acl string, sub string) resource.TestCheckFunc { return func(s *terraform.State) error { networkAcl := s.RootModule().Resources[acl] subnet := s.RootModule().Resources[sub] conn := testAccProvider.Meta().(*AWSClient).ec2conn filter := ec2.NewFilter() filter.Add("association.subnet-id", subnet.Primary.ID) resp, err := conn.NetworkAcls([]string{networkAcl.Primary.ID}, filter) if err != nil { return err } if len(resp.NetworkAcls) > 0 { return nil } r, _ := conn.NetworkAcls([]string{}, ec2.NewFilter()) fmt.Printf("\n\nall acls\n %#v\n\n", r.NetworkAcls) conn.NetworkAcls([]string{}, filter) return fmt.Errorf("Network Acl %s is not associated with subnet %s", acl, sub) } }
// 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 }