github.com/vijayrajah/packer@v1.3.2/post-processor/vagrant-cloud/step_create_provider.go (about) 1 package vagrantcloud 2 3 import ( 4 "context" 5 "fmt" 6 7 "github.com/hashicorp/packer/helper/multistep" 8 "github.com/hashicorp/packer/packer" 9 ) 10 11 type Provider struct { 12 Name string `json:"name"` 13 Url string `json:"url,omitempty"` 14 HostedToken string `json:"hosted_token,omitempty"` 15 UploadUrl string `json:"upload_url,omitempty"` 16 } 17 18 type stepCreateProvider struct { 19 name string // the name of the provider 20 } 21 22 func (s *stepCreateProvider) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { 23 client := state.Get("client").(*VagrantCloudClient) 24 ui := state.Get("ui").(packer.Ui) 25 box := state.Get("box").(*Box) 26 version := state.Get("version").(*Version) 27 providerName := state.Get("providerName").(string) 28 downloadUrl := state.Get("boxDownloadUrl").(string) 29 30 path := fmt.Sprintf("box/%s/version/%v/providers", box.Tag, version.Version) 31 32 provider := &Provider{Name: providerName} 33 34 if downloadUrl != "" { 35 provider.Url = downloadUrl 36 } 37 38 // Wrap the provider in a provider object for the API 39 wrapper := make(map[string]interface{}) 40 wrapper["provider"] = provider 41 42 ui.Say(fmt.Sprintf("Creating provider: %s", providerName)) 43 44 resp, err := client.Post(path, wrapper) 45 46 if err != nil || (resp.StatusCode != 200) { 47 cloudErrors := &VagrantCloudErrors{} 48 err = decodeBody(resp, cloudErrors) 49 state.Put("error", fmt.Errorf("Error creating provider: %s", cloudErrors.FormatErrors())) 50 return multistep.ActionHalt 51 } 52 53 if err = decodeBody(resp, provider); err != nil { 54 state.Put("error", fmt.Errorf("Error parsing provider response: %s", err)) 55 return multistep.ActionHalt 56 } 57 58 // Save the name for cleanup 59 s.name = provider.Name 60 61 state.Put("provider", provider) 62 63 return multistep.ActionContinue 64 } 65 66 func (s *stepCreateProvider) Cleanup(state multistep.StateBag) { 67 client := state.Get("client").(*VagrantCloudClient) 68 ui := state.Get("ui").(packer.Ui) 69 box := state.Get("box").(*Box) 70 version := state.Get("version").(*Version) 71 72 // If we didn't save the provider name, it likely doesn't exist 73 if s.name == "" { 74 ui.Say("Cleaning up provider") 75 ui.Message("Provider was not created, not deleting") 76 return 77 } 78 79 _, cancelled := state.GetOk(multistep.StateCancelled) 80 _, halted := state.GetOk(multistep.StateHalted) 81 82 // Return if we didn't cancel or halt, and thus need 83 // no cleanup 84 if !cancelled && !halted { 85 return 86 } 87 88 ui.Say("Cleaning up provider") 89 ui.Message(fmt.Sprintf("Deleting provider: %s", s.name)) 90 91 path := fmt.Sprintf("box/%s/version/%v/provider/%s", box.Tag, version.Version, s.name) 92 93 // No need for resp from the cleanup DELETE 94 _, err := client.Delete(path) 95 96 if err != nil { 97 ui.Error(fmt.Sprintf("Error destroying provider: %s", err)) 98 } 99 }