Skip to content

Instantly share code, notes, and snippets.

@ScottJWalter
Last active December 18, 2024 15:11
Show Gist options
  • Save ScottJWalter/7a91cc2c4bcb9d79ff0871f1d3d830f8 to your computer and use it in GitHub Desktop.
Save ScottJWalter/7a91cc2c4bcb9d79ff0871f1d3d830f8 to your computer and use it in GitHub Desktop.
Generate a temporary cloud-init.yml file that is fed directly to multipass to launch a VM
#!/bin/sh
# WIP experiment
VM_NAME="$1"
$SSH_PUBLIC_KEY="Your Public SSH Key"
# The following method for handling temp files is adapted from
#
# https://unix.stackexchange.com/a/181938/458942
#
# Flow:
# 1. Create file in /tmp directory
# 2. Attach read and write descriptors to the file
# 3. Delete the file
#
# The descriptors keep the "file" open (as a stream) until the
# script closes (which automatically releases them). Deleting the
# file now removes it's entry from the directory list so that, even
# if the script errors out early, the file doesn't clutter up /tmp
# 1. Create temporary file
tmpfile=$(mktemp /tmp/cloud-init.$VM_NAME.yml.XXXXXX) || exit 1
# 2a. Create file descriptor 3 for writing to a temporary file so that
# echo ... >&3 writes to that file
exec 3>"$tmpfile"
# 2b. Create file descriptor 4 for reading from the same file so that
# the file seek positions for reading and writing can be different
exec 4<"$tmpfile"
# 3. Delete temp file; the directory entry is deleted at once; the reference
# counter of the inode is decremented only after the file descriptor has been
# closed. The file content blocks are deallocated (this is the real deletion)
# when the reference counter drops to zero.
rm "$tmpfile"
# At this point, we can reference our temp "file" via >&3 (to write) and
# <&4 (to read) and not have to worry about cleaning up /tmp
# "write" out the cloud-init.yml file we want to use. In this demo, we're
# prepping for a vscode-enabled VM
cat >&3 <<EOF
#cloud-config
groups:
- vscode
users:
- name: ubuntu
groups:
- vscode
sudo: ['ALL=(ALL) NOPASSWD:ALL']
ssh-authorized-keys:
- ssh-rsa $SSH_PUBLIC_KEY
EOF
# Launch Multipass, passing the cloud-init.yml data in via stdin
head -n 1 <&4 | \
multipass launch \
-n $VM_NAME \
... \
--cloud-init -
# close the file descriptor (done automatically when script exits)
# see section 2.7.6 of the POSIX definition of the Shell Command Language
exec 3>&-
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment