Skip to content

Instantly share code, notes, and snippets.

@alexproca
Last active November 23, 2020 17:15
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 14 You must be signed in to fork a gist
  • Save alexproca/2324c60c86380b59001f to your computer and use it in GitHub Desktop.
Save alexproca/2324c60c86380b59001f to your computer and use it in GitHub Desktop.
Rename docker-machine
#!/usr/bin/env bash
#copy this in a folder from path ex: /usr/local/bin
#usage: docker-machine-rename default my-default
# Authors
#
# alexproca initial script
# eurythmia sed magic
OLD_MACHINE_NAME=${1:-default};
NEW_MACHINE_NAME=${2:-my-default-2};
STORE_PATH=$(docker-machine inspect ${OLD_MACHINE_NAME} | sed -n 's/^ *"StorePath": "\(.*\)",/\1/p')
# 1. rename the directory of your docker-machine from docker machine store
mv "$STORE_PATH/machines/$OLD_MACHINE_NAME" "$STORE_PATH/machines/$NEW_MACHINE_NAME";
# 2. update config.json with the new name and new path (always backup your configs)
sed -i.bak "s/${OLD_MACHINE_NAME}/${NEW_MACHINE_NAME}/g" ${STORE_PATH}/machines/${NEW_MACHINE_NAME}/config.json
# 3. rename machine in the virtual machine provider
vboxmanage modifyvm "$OLD_MACHINE_NAME" --name "$NEW_MACHINE_NAME"
@Ch4ni
Copy link

Ch4ni commented Sep 2, 2016

STORE_PATH=`docker-machine inspect $OLD_MACHINE_NAME | grep -m 1 StorePath | cut -d ':' -f 2 | cut -c 3- | rev | cut -c 3- | rev;`

is better written as:

STORE_PATH=$(docker-machine inspect ${OLD_MACHINE_NAME} | sed -n 's/^ *"StorePath": "\(.*\)",/\1/p')

and:

cp "$STORE_PATH/machines/$NEW_MACHINE_NAME/config.json" "$STORE_PATH/machines/$NEW_MACHINE_NAME/config.json.bak"
sed -e "s/$OLD_MACHINE_NAME/$NEW_MACHINE_NAME/g" "$STORE_PATH/machines/$NEW_MACHINE_NAME/config.json.bak" > "$STORE_PATH/machines/$NEW_MACHINE_NAME/config.json";

is better written as:

sed -i.bak "s/${OLD_MACHINE_NAME}/${NEW_MACHINE_NAME}/g" ${STORE_PATH}/machines/${NEW_MACHINE_NAME}/config.json

... in finding the $STORE_PATH sed can do all of the text manipulation without needing to be 'clever' or build a whole pipeline. It only matches the first StorePath because the last one in the file isn't followed by a comma, so it doesn't match anyways.

The final sed does an in-place text replacement and creates a backup file prior to operating. There's really no need to use cp when sed will do the work for you and you're already using it.

Another note: vboxmanage needs to be run prior to the copy/modification of config.json, otherwise vboxmanage has trouble finding and configuring the vm.

Thanks for the Gist though, this is exactly what I was looking for!

@LeonFedotov
Copy link

@eurythmia nice!

@alexproca
Copy link
Author

Thanks @eurythmia for sed magic

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment