Update vmcreate1.sh

This commit is contained in:
2025-10-28 08:16:10 +00:00
parent 5a795e1c0b
commit 7f44fd6c50

View File

@@ -14,17 +14,11 @@ size=50
# Далее объявляю переменные, в цикле getopts это не получается # Далее объявляю переменные, в цикле getopts это не получается
harule="" harule=""
use_harule=false
pubkey="" pubkey=""
use_pubkey=false
username="" username=""
use_username=false
password="" password=""
use_password=false
tag="" tag=""
use_tag=false
file="" file=""
use_file=false
# Конец костыля # Конец костыля
show_help () { show_help () {
@@ -38,6 +32,7 @@ show_help () {
echo "-u - specify user instead of default 'root'." echo "-u - specify user instead of default 'root'."
echo "-p - specify password instead of default." echo "-p - specify password instead of default."
echo "-d - add custom disk space (in gibibytes, integer). Default is 50." echo "-d - add custom disk space (in gibibytes, integer). Default is 50."
echo "-n - specify target node NUMBER to migrate VM to after creating. Default is '3'"
echo "-t - add additional proxmox tag. Default is only pve node number." echo "-t - add additional proxmox tag. Default is only pve node number."
echo "-f - get IP addresses and Hostnames from 'flilename'." echo "-f - get IP addresses and Hostnames from 'flilename'."
echo echo
@@ -100,49 +95,47 @@ mksnippet () {
snippet="${path}${vmid}_user.yaml" snippet="${path}${vmid}_user.yaml"
cp ./user.yaml "$snippet" cp ./user.yaml "$snippet"
sed -i "s/HOSTNAME/$hostname/g" "$snippet" sed -i "s/HOSTNAME/$hostname/g" "$snippet"
if [[ -n $username ]]; then if [ $username ]; then
sed -i "s|user: root|user: ${username}\nsudo: ALL=(ALL) NOPASSWD:ALL|" "$snippet" sed -i "s|user: root|user: ${username}\nsudo: ALL=(ALL) NOPASSWD:ALL|" "$snippet"
fi fi
if [[ -n $password ]]; then if [ $password ]; then
phash=$(cat $password | mkpasswd -m sha-256 -s) phash=$(cat $password | mkpasswd -m sha-256 -s)
sed -i "s|.*password.*| - ${phash}|" "$snippet" sed -i "s|.*password.*| - ${phash}|" "$snippet"
fi fi
if [[ -v $pubkey ]]; then if [ $pubkey ]; then
sed -i "s|.*ssh-rsa.*| - (cat ${pubkey})|" "$snippet" sed -i "s|.*ssh-rsa.*| - (cat ${pubkey})|" "$snippet"
fi fi
echo "Snippet $snippet created" echo "Snippet $snippet created"
} }
# Обрабатываем опции # Обрабатываем опции
while getopts "a:f:hk:u:p:d:t:" opt; do while getopts "a:f:hk:u:p:d:n:t:" opt; do
case $opt in case $opt in
a) harule=${OPTARG}; use_harule=true;; a) harule=${OPTARG};;
f) file=${OPTARG}; use_file=true;; f) file=${OPTARG};;
h) show_help; exit 0;; h) show_help; exit 0;;
k) pubkey=${OPTARG}; use_pubkey=true;; k) pubkey=${OPTARG};;
u) username=${OPTARG}; use_username=true;; u) username=${OPTARG};;
p) password=${OPTARG}; use_password=true;; p) password=${OPTARG};;
d) size=${OPTARG};; d) size=${OPTARG};;
t) tag=${OPTARG}; use_tag=true;; n) node=${OPTARG};;
t) tag=${OPTARG};;
\?) echo "Invalid option."; show_help; exit 1;; \?) echo "Invalid option."; show_help; exit 1;;
esac esac
done done
if [[ $node -lt 1 || $node -gt 4 ]]; then
echo "Node number is not in [1..4]. Please specify correct node number. Aborting"
fi
# DEBUG Print specified options # DEBUG Print specified options
# if [[ -v $harule ]]; then echo "harule: $harule"; fi if [ $harule ]; then echo "harule: $harule"; fi
# if [[ -v $file ]]; then echo "file: $file"; fi if [ $file ]; then echo "file: $file"; fi
# if [[ -v $pubkey ]]; then echo "pubkey: $pubkey"; fi if [ $pubkey ]; then echo "pubkey: $pubkey"; fi
# if [[ -v $username ]]; then echo "username: $username"; fi if [ $username ]; then echo "username: $username"; fi
# if [[ -v $password ]]; then echo "password: $password"; fi if [ $password ]; then echo "password: $password"; fi
# if [[ -v $size ]]; then echo "size: $size"; fi if [ $size ]; then echo "size: $size"; fi
# if [[ -v $tag ]]; then echo "tag: $tag"; fi if [ $tag ]; then echo "tag: $tag"; fi
echo $harule
echo $file
echo $pubkey
echo $username
echo $password
echo $size
echo $tag
exit 102 exit 102
# END DEBUG # END DEBUG
@@ -153,18 +146,6 @@ echo "DEBUG arguments amount: $#"
### Проверка допустимости опций ### Проверка допустимости опций
if ! [[ $size -ge 10 && $size -le 500 ]]; then echo "Disk size increment shoud be in range of 10..500. Aborting."; exit 2; fi if ! [[ $size -ge 10 && $size -le 500 ]]; then echo "Disk size increment shoud be in range of 10..500. Aborting."; exit 2; fi
# Вывод переменных для дебага:
#if [[ -v file ]]; then echo "File: $file"; fi
#if [[ -v pubkey ]]; then echo "Public key: $pubkey"; fi
#if [[ -v username ]]; then echo "User: $file"; fi
#echo "END DEBUG 1"; exit 101
# Если нет аргументов, то пробуем файл
# if [[ $# -eq 0 && ! -e "$file" ]]; then
# echo "File $file does not exist. Aborting."
# exit 1
# fi
# Создаём hosts.tmp из аргументов/файла, попутно проверяя данные # Создаём hosts.tmp из аргументов/файла, попутно проверяя данные
# Если заданы И аргументы, И файл - сразу нахуй # Если заданы И аргументы, И файл - сразу нахуй
if [[ $# -ne 0 && $use_file ]]; then if [[ $# -ne 0 && $use_file ]]; then
@@ -174,7 +155,7 @@ else
# Если файл задан # Если файл задан
if $use_file; then if $use_file; then
# Но не существует, то нахуй # Но не существует, то нахуй
if [[ ! -e "$file" ]];then if [ ! -f "$file" ];then
echo "File $file does not exist. Aborting." echo "File $file does not exist. Aborting."
exit 4 exit 4
fi fi
@@ -183,7 +164,7 @@ else
file="hosts" file="hosts"
fi fi
# Если заданы аргументы # Если заданы аргументы
if [[ $# -ne 0 ]]; then if [ $# -ne 0 ]; then
echo "DEBUG using arguments" echo "DEBUG using arguments"
touch hosts.tmp touch hosts.tmp
echo -n "" > hosts.tmp echo -n "" > hosts.tmp
@@ -232,8 +213,8 @@ fi
# Закончили с вводными данными # Закончили с вводными данными
# Проверяем ключ # Проверяем ключ
if $use_pubkey; then if [ $pubkey ]; then
if ! [[ -e "$pubkey" ]]; then if [[ ! -f "$pubkey" ]]; then
input=y input=y
echo "You sbecified public key but it does not exist. Generate new pair? y/n" echo "You sbecified public key but it does not exist. Generate new pair? y/n"
read input read input
@@ -258,7 +239,7 @@ do
if qm status "$vmid"; then if qm status "$vmid"; then
echo "VM $vmid exists. Aborting" echo "VM $vmid exists. Aborting"
exit 7 exit 7
elif [[ -e "$snippet" ]]; then elif [[ -f "$snippet" ]]; then
echo "Snippet $snippet exists. Aborting" echo "Snippet $snippet exists. Aborting"
exit 7 exit 7
fi fi
@@ -269,6 +250,8 @@ done
echo "DEBUG cat hosts.tmp:" echo "DEBUG cat hosts.tmp:"
cat hosts.tmp; echo cat hosts.tmp; echo
### ###
# Подготовительные операции закончены, приступаем к выполнению.
read -p "Script is ready to create $(cat hosts.tmp | wc -l) VMs. Press Enter" read -p "Script is ready to create $(cat hosts.tmp | wc -l) VMs. Press Enter"
for line in $(cat hosts.tmp) for line in $(cat hosts.tmp)
@@ -315,8 +298,16 @@ do
cat /etc/pve/qemu-server/${vmid}.conf cat /etc/pve/qemu-server/${vmid}.conf
exit 102 exit 102
### ###
echo -n "Migrating VM $vmid to pve${node}....."
qm migrate $vmid pve${node} &&
if [ $? -eq 0 ]; then
echo "OK"
else
echo "ERROR"
exit 9
fi
# qm start $vmid ВРЕМЕННО ОТКЛЮЧЕНО # qm start $vmid ВРЕМЕННО ОТКЛЮЧЕНО
if $use_harule; then if [ $harule ]; then
ha-manager add vm:$vmid --state started --max_relocate 2 ha-manager add vm:$vmid --state started --max_relocate 2
ha-manager rules add node-affinity $harule --resources vm:$vmid --nodes pve1,pve2,pve3 --strict 1 ha-manager rules add node-affinity $harule --resources vm:$vmid --nodes pve1,pve2,pve3 --strict 1
echo "HA rule added" echo "HA rule added"
@@ -326,7 +317,7 @@ done
# Финальная часть # Финальная часть
rm hosts.tmp rm hosts.tmp
if [ -v $privkey ]; then if [ $privkey ]; then
echo echo
echo "Generated private key: ./$privkey" echo "Generated private key: ./$privkey"
echo "SAVE IT IMMEDIATELY!!!" echo "SAVE IT IMMEDIATELY!!!"