Skip to content

Instantly share code, notes, and snippets.

@vigindian
Created April 27, 2023 06:49
Show Gist options
  • Save vigindian/723e4463494bb762877fc248a0376e1e to your computer and use it in GitHub Desktop.
Save vigindian/723e4463494bb762877fc248a0376e1e to your computer and use it in GitHub Desktop.
lxc scripts to create new container and take container snapshot
#!/bin/bash
###############################################
# lxc: Script to create a new Ubuntu container
#
# Vignesh Narasimhulu
###############################################
#Validate user
user=$(whoami)
if [ $user != "root" ];then
echo "ERROR: This script should be triggered as root. Exiting."
exit 99
fi
#Validate syntax
if [ "$#" -ne 1 ]; then
echo -e "\nERROR: Invalid syntax.\n\nUSAGE: $0 newcontainer_name\n"
exit 1
fi
#Assign input to variable
name=$1
echo -e "\nCreating container $name based on Ubuntu template\n"
#Create xenial Ubuntu container
#lxc-create -t ubuntu -n $name -- template-options -r xenial
lxc-create -t ubuntu -n $name
if [ "$?" -ne 0 ];then
echo "Container creation failed. Exiting."
exit 2
else
echo "Checking the container info.."
lxc-info -n $name
fi
#Update container config with auto-start and time, before container is started
echo "lxc.start.auto = 1" >> /var/lib/lxc/$name/config
echo "lxc.start.delay = 5" >> /var/lib/lxc/$name/config
#Start the container
lxc-start -n $name -d
#Validate if container running fine
lxc-info -n $name | grep -w RUNNING > /dev/null
if [ "$?" -ne 0 ];then
echo "Container not running. Exiting."
exit 3
fi
sleep 5 #fail-safe
#Update the container and install some utils
lxc-attach -n $name -- sudo apt-get update -y
lxc-attach -n $name -- sudo apt-get upgrade -y
lxc-attach -n $name -- sudo apt-get install wget curl -y
#!/usr/bin/env bash
################################################
# lxc: Script to create an offline lxc snapshot
#
# Vignesh Narasimhulu
################################################
#script needs elevated privileges
if [ ${UID} != 0 ];then
echo "ERROR: This script should be triggered as root. Exiting."
exit 99
fi
#Validate syntax
if [ "$#" -ne 1 ]; then
echo -e "\nERROR: Invalid syntax.\n\nUSAGE: $0 container_name\n"
exit 1
fi
#Assign input to variable
name=$1
echo -e "\nCreating container snapshot for ${name}\n"
#before: list snapshots
lxc-snapshot -n ${name} -L
#stop the container
lxc-stop -n ${name}
#take snapshot: this copies config file and the rootfs directory from /var/lib/lxc/container-name/ to /var/lib/lxc/container-name/snaps/snapname/
lxc-snapshot -n ${name} -o output #this only works on stopped containers
#after: list snapshots
lxc-snapshot -n ${name} -L
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment