Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions builder/ibmcloud/vpc/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package vpc

import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
Expand Down Expand Up @@ -371,7 +370,7 @@ func (client IBMCloudClient) createSSHKeyVPC(state multistep.StateBag) (*vpcv1.K
config := state.Get("config").(Config)

file := state.Get("PUBLIC_KEY").(string)
content, err := ioutil.ReadFile(file)
content, err := os.ReadFile(file)
if err != nil {
err := fmt.Errorf("[ERROR] Error reading SSH Public Key. Error: %s", err)
ui.Error(err.Error())
Expand Down
154 changes: 85 additions & 69 deletions builder/ibmcloud/vpc/step_create_instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package vpc
import (
"context"
"fmt"
"io/ioutil"
"os"
"time"

"github.com/IBM/vpc-go-sdk/vpcv1"
Expand Down Expand Up @@ -99,7 +99,7 @@ func (step *stepCreateInstance) Run(_ context.Context, state multistep.StateBag)
userDataFilePath := config.VSIUserDataFile
userDataString := config.VSIUserDataString
if userDataFilePath != "" {
content, err := ioutil.ReadFile(userDataFilePath)
content, err := os.ReadFile(userDataFilePath)
if err != nil {
err := fmt.Errorf("[ERROR] Error reading user data file. Error: %s", err)
state.Put("error", err)
Expand Down Expand Up @@ -177,7 +177,7 @@ func (step *stepCreateInstance) Run(_ context.Context, state multistep.StateBag)
userDataFilePath := config.VSIUserDataFile
userDataString := config.VSIUserDataString
if userDataFilePath != "" {
content, err := ioutil.ReadFile(userDataFilePath)
content, err := os.ReadFile(userDataFilePath)
if err != nil {
err := fmt.Errorf("[ERROR] Error reading user data file. Error: %s", err)
state.Put("error", err)
Expand Down Expand Up @@ -244,7 +244,7 @@ func (step *stepCreateInstance) Run(_ context.Context, state multistep.StateBag)
userDataFilePath := config.VSIUserDataFile
userDataString := config.VSIUserDataString
if userDataFilePath != "" {
content, err := ioutil.ReadFile(userDataFilePath)
content, err := os.ReadFile(userDataFilePath)
if err != nil {
err := fmt.Errorf("[ERROR] Error reading user data file. Error: %s", err)
state.Put("error", err)
Expand Down Expand Up @@ -318,7 +318,7 @@ func (step *stepCreateInstance) Run(_ context.Context, state multistep.StateBag)
userDataFilePath := config.VSIUserDataFile
userDataString := config.VSIUserDataString
if userDataFilePath != "" {
content, err := ioutil.ReadFile(userDataFilePath)
content, err := os.ReadFile(userDataFilePath)
if err != nil {
err := fmt.Errorf("[ERROR] Error reading user data file. Error: %s", err)
state.Put("error", err)
Expand Down Expand Up @@ -370,7 +370,7 @@ func (step *stepCreateInstance) Cleanup(state multistep.StateBag) {

// Delete Floating IP if it was created (VSI Interface was set as public)
if config.VSIInterface == "public" {
if state.Get("floating_ip") != nil {
if state.Get("floating_ip") != nil && state.Get("floating_ip_id") != nil {
floatingIP := state.Get("floating_ip").(string)
ui.Say(fmt.Sprintf("Releasing the Floating IP: %s ...", floatingIP))

Expand All @@ -385,105 +385,121 @@ func (step *stepCreateInstance) Cleanup(state multistep.StateBag) {
// log.Fatalf(err.Error())
return
}
status := floatingIPresponse.Status
if *status == "available" {
options := vpcService.NewDeleteFloatingIPOptions(floatingIPID)
result, err := vpcService.DeleteFloatingIP(options)

if err != nil {
err := fmt.Errorf("[ERROR] Error releasing the Floating IP. Please release it manually: %s", err)
state.Put("error", err)
ui.Error(err.Error())
// log.Fatalf(err.Error())
return
}
if result.StatusCode == 204 {
ui.Say("The Floating IP was successfully released!")
// Only proceed if the Floating IP still exists (not 404)
if response.StatusCode != 404 && floatingIPresponse.Status != nil {
status := floatingIPresponse.Status
if *status == "available" {
options := vpcService.NewDeleteFloatingIPOptions(floatingIPID)
result, err := vpcService.DeleteFloatingIP(options)

if err != nil {
err := fmt.Errorf("[ERROR] Error releasing the Floating IP. Please release it manually: %s", err)
state.Put("error", err)
ui.Error(err.Error())
// log.Fatalf(err.Error())
return
}
if result.StatusCode == 204 {
ui.Say("The Floating IP was successfully released!")
}
}
} else if response.StatusCode == 404 {
ui.Say("The Floating IP was already deleted or does not exist.")
}
}
}

// Wait a couple of seconds before attempting to delete the instance.
time.Sleep(2 * time.Second)
instanceData := state.Get("instance_data").(*vpcv1.Instance)
instanceID := *instanceData.ID
ui.Say(fmt.Sprintf("Deleting Instance ID: %s ...", instanceID))

options := &vpcv1.DeleteInstanceOptions{}
options.SetID(instanceID)
_, err := vpcService.DeleteInstance(options)

if err != nil {
err := fmt.Errorf("[ERROR] Error deleting the instance. Please delete it manually: %s", err)
state.Put("error", err)
ui.Error(err.Error())
// log.Fatalf(err.Error())
return
}
instanceDeleted := false
for !instanceDeleted {
options := &vpcv1.GetInstanceOptions{}

// Check if instance_data exists in state before attempting deletion
if state.Get("instance_data") != nil {
instanceData := state.Get("instance_data").(*vpcv1.Instance)
instanceID := *instanceData.ID
ui.Say(fmt.Sprintf("Deleting Instance ID: %s ...", instanceID))

options := &vpcv1.DeleteInstanceOptions{}
options.SetID(instanceID)
instance, response, err := vpcService.GetInstance(options)
_, err := vpcService.DeleteInstance(options)

if err != nil {
if response != nil && response.StatusCode == 404 {
ui.Say("Instance deleted Succesfully")
instanceDeleted = true
break
}
err := fmt.Errorf("[ERROR] Error getting the instance to check delete status. %s", err)
err := fmt.Errorf("[ERROR] Error deleting the instance. Please delete it manually: %s", err)
state.Put("error", err)
ui.Error(err.Error())
} else if instance != nil {
ui.Say(fmt.Sprintf("Instance status :- %s", *instance.Status))
// log.Fatalf(err.Error())
return
}
instanceDeleted := false
for !instanceDeleted {
options := &vpcv1.GetInstanceOptions{}
options.SetID(instanceID)
instance, response, err := vpcService.GetInstance(options)
if err != nil {
if response != nil && response.StatusCode == 404 {
ui.Say("Instance deleted Successfully")
instanceDeleted = true
break
}
err := fmt.Errorf("[ERROR] Error getting the instance to check delete status. %s", err)
state.Put("error", err)
ui.Error(err.Error())
} else if instance != nil {
ui.Say(fmt.Sprintf("Instance status :- %s", *instance.Status))
}
time.Sleep(10 * time.Second)
}
time.Sleep(10 * time.Second)
}

// Deleting Security Group's rule
if state.Get("security_group_rule_id") != nil {
if state.Get("security_group_rule_id") != nil && state.Get("security_group_id") != nil {
ruleID := state.Get("security_group_rule_id").(string)
securityGroupID := state.Get("security_group_id").(string)
ui.Say(fmt.Sprintf("Deleting Security Group's rule %s ...", ruleID))
sgRuleOptions := &vpcv1.DeleteSecurityGroupRuleOptions{}
sgRuleOptions.SetSecurityGroupID(state.Get("security_group_id").(string))
sgRuleOptions.SetSecurityGroupID(securityGroupID)
sgRuleOptions.SetID(ruleID)
sgRuleResponse, sgRuleErr := vpcService.DeleteSecurityGroupRule(sgRuleOptions)

if sgRuleErr != nil {
sgRuleErr := fmt.Errorf("[ERROR] Error deleting Security Group's rule %s. Please delete it manually: %s", ruleID, sgRuleErr)
state.Put("error", sgRuleErr)
ui.Error(err.Error())
// log.Fatalf(err.Error())
return
}

if sgRuleResponse.StatusCode == 204 {
// Check if it's a 404 (resource already deleted)
if sgRuleResponse != nil && sgRuleResponse.StatusCode == 404 {
ui.Say("The Security Group's rule was already deleted or does not exist.")
} else {
sgRuleErr := fmt.Errorf("[ERROR] Error deleting Security Group's rule %s. Please delete it manually: %s", ruleID, sgRuleErr)
state.Put("error", sgRuleErr)
ui.Error(sgRuleErr.Error())
// log.Fatalf(err.Error())
return
}
} else if sgRuleResponse.StatusCode == 204 {
ui.Say("The Security Group's rule was successfully deleted!")
}
}

// Wait a couple of seconds before attempting to delete the security group.
time.Sleep(10 * time.Second)

// Deleting Security Group
// Deleting Security Group (only if we created it, not if user provided one)
if config.SecurityGroupID == "" {
if state.Get("security_group_name") != nil {
if state.Get("security_group_name") != nil && state.Get("security_group_id") != nil {
securityGroupName := state.Get("security_group_name").(string)
ui.Say(fmt.Sprintf("Deleting Security Group %s ...", securityGroupName))
securityGroupID := state.Get("security_group_id").(string)
ui.Say(fmt.Sprintf("Deleting Security Group %s ...", securityGroupName))
sgOptions := &vpcv1.DeleteSecurityGroupOptions{}
sgOptions.SetID(securityGroupID)
sgResponse, err := vpcService.DeleteSecurityGroup(sgOptions)
if err != nil {
err := fmt.Errorf("[ERROR] Error deleting Security Group %s. Please delete it manually: %s", securityGroupName, err)
state.Put("error", err)
ui.Error(err.Error())
// log.Fatalf(err.Error())
return
}

if sgResponse.StatusCode == 204 {
// Check if it's a 404 (resource already deleted)
if sgResponse != nil && sgResponse.StatusCode == 404 {
ui.Say("The Security Group was already deleted or does not exist.")
} else {
err := fmt.Errorf("[ERROR] Error deleting Security Group %s. Please delete it manually: %s", securityGroupName, err)
state.Put("error", err)
ui.Error(err.Error())
// log.Fatalf(err.Error())
return
}
} else if sgResponse.StatusCode == 204 {
ui.Say("The Security Group was successfully deleted!")
}
}
Expand Down
9 changes: 4 additions & 5 deletions builder/ibmcloud/vpc/step_create_ssh_key_pair.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
mathrand "math/rand"
"os"
"strconv"
Expand Down Expand Up @@ -58,14 +57,14 @@ func (s *stepCreateSshKeyPair) Run(_ context.Context, state multistep.StateBag)
privatefilepath = keysDirectory + "id_ed25519"
publicfilepath = keysDirectory + "id_ed25519.pub"

err := ioutil.WriteFile(privatefilepath, privateKey, 0600)
err := os.WriteFile(privatefilepath, privateKey, 0600)
if err != nil {
err := fmt.Errorf("[ERROR] Failed to edit ed25519 private SSH Key's permission: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
err = ioutil.WriteFile(publicfilepath, authorizedKey, 0644)
err = os.WriteFile(publicfilepath, authorizedKey, 0644)
if err != nil {
err := fmt.Errorf("[ERROR] Failed to write ed25519 public SSH Key to file: %s", err)
state.Put("error", err)
Expand Down Expand Up @@ -100,7 +99,7 @@ func (s *stepCreateSshKeyPair) Run(_ context.Context, state multistep.StateBag)
ui.Say(fmt.Sprintf("Writing Private SSH Key to a file %s", privatefilepath))
privatekey := string(pem.EncodeToMemory(&privBlk))
privateKey := []byte(fmt.Sprintf("%s\n", privatekey))
err = ioutil.WriteFile(privatefilepath, privateKey, 0600)
err = os.WriteFile(privatefilepath, privateKey, 0600)
if err != nil {
err := fmt.Errorf("[ERROR] Failed to write Private SSH Key to file: %s", err)
state.Put("error", err)
Expand Down Expand Up @@ -131,7 +130,7 @@ func (s *stepCreateSshKeyPair) Run(_ context.Context, state multistep.StateBag)
ui.Say(fmt.Sprintf("Writing Public SSH Key to a file %s", publicfilepath))
pubkey := string(publicKey)
pubKey := []byte(fmt.Sprintf("%s\n", pubkey))
err = ioutil.WriteFile(publicfilepath, pubKey, 0600)
err = os.WriteFile(publicfilepath, pubKey, 0600)
if err != nil {
err := fmt.Errorf("[ERROR] Failed to write Public SSH Key to file: %s", err)
state.Put("error", err)
Expand Down
30 changes: 21 additions & 9 deletions builder/ibmcloud/vpc/step_create_ssh_key_vpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,25 +41,37 @@ func (s *stepCreateSshKeyVPC) Run(_ context.Context, state multistep.StateBag) m
func (s *stepCreateSshKeyVPC) Cleanup(state multistep.StateBag) {
ui := state.Get("ui").(packer.Ui)

ui.Say(fmt.Sprintf("Deleting SSH key for VPC %s ...", state.Get("vpc_ssh_key_name").(string)))
// Check if VPC SSH key exists in state before attempting deletion
if state.Get("vpc_ssh_key_name") == nil || state.Get("vpc_ssh_key_id") == nil {
return
}

vpcSSHKeyName := state.Get("vpc_ssh_key_name").(string)
vpcSSHKeyID := state.Get("vpc_ssh_key_id").(string)

ui.Say(fmt.Sprintf("Deleting SSH key for VPC %s ...", vpcSSHKeyName))
// Wait half minute before deleting SSH key - otherwise wouldn't be deleted.
time.Sleep(30 * time.Second)
var vpcService *vpcv1.VpcV1
if state.Get("vpcService") != nil {
vpcService = state.Get("vpcService").(*vpcv1.VpcV1)
}
deleteKeyOptions := &vpcv1.DeleteKeyOptions{}
deleteKeyOptions.SetID(state.Get("vpc_ssh_key_id").(string))
deleteKeyOptions.SetID(vpcSSHKeyID)
response, err := vpcService.DeleteKey(deleteKeyOptions)

if err != nil {
err := fmt.Errorf("[ERROR] Error deleting SSH key for VPC %s. Please delete it manually: %s", state.Get("vpc_ssh_key_name").(string), err)
state.Put("error", err)
ui.Error(err.Error())
// log.Fatalf(err.Error())
return
}
if response.StatusCode == 204 {
// Check if it's a 404 (resource already deleted)
if response != nil && response.StatusCode == 404 {
ui.Say("The SSH key was already deleted or does not exist.")
} else {
err := fmt.Errorf("[ERROR] Error deleting SSH key for VPC %s. Please delete it manually: %s", vpcSSHKeyName, err)
state.Put("error", err)
ui.Error(err.Error())
// log.Fatalf(err.Error())
return
}
} else if response.StatusCode == 204 {
ui.Say("The Key was successfully deleted!")
} else {
ui.Say("The key could not be deleted. Please delete it manually!")
Expand Down
3 changes: 1 addition & 2 deletions builder/ibmcloud/vpc/step_get_ip.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package vpc
import (
"context"
"fmt"
"io/ioutil"
"os"

"github.com/IBM/vpc-go-sdk/vpcv1"
Expand Down Expand Up @@ -78,7 +77,7 @@ func (step *stepGetIP) Run(_ context.Context, state multistep.StateBag) multiste
}

ipAddressBytes := []byte(fmt.Sprintf("%s\n", ipAddress))
err := ioutil.WriteFile(hostsFilePath, ipAddressBytes, 0644)
err := os.WriteFile(hostsFilePath, ipAddressBytes, 0644)
if err != nil {
err := fmt.Errorf("[ERROR] Failed to write IP address to file: %s", err)
state.Put("error", err)
Expand Down
Loading