Add support for injecting public key with cloud-init

Ref. https://github.com/churchers/vm-bhyve/issues/289
This commit is contained in:
Mateusz Kwiatkowski
2019-01-28 11:52:06 +01:00
parent 960f95a34c
commit 6df1c74a7d

View File

@@ -1,4 +1,3 @@
#!/bin/sh
#-------------------------------------------------------------------------+
# Copyright (C) 2016 Matt Churchyard (churchers@gmail.com)
# All rights reserved
@@ -97,9 +96,10 @@ core::list(){
#
core::create(){
local _name _opt _size _vmdir _disk _disk_dev _num=0
local _zfs_opts _disk_size _template="default" _ds="default" _ds_path _img _cpu _memory
local _zfs_opts _disk_size _template="default" _ds="default" _ds_path _img _cpu _memory _uuid
local _cloud_init_dir _ssh_public_key _ssh_key_file
while getopts d:t:s:i:c:m: _opt ; do
while getopts d:t:s:i:c:m:k: _opt ; do
case $_opt in
t) _template=${OPTARG} ;;
s) _size=${OPTARG} ;;
@@ -107,6 +107,8 @@ core::create(){
c) _cpu=${OPTARG} ;;
m) _memory=${OPTARG} ;;
i) _img=${OPTARG} ;;
k) _ssh_key_file=${OPTARG} ;;
*) util::usage ;;
esac
done
@@ -134,6 +136,12 @@ core::create(){
# make sure template has a disk before we start creating anything
[ -z "${_disk}" ] && util::err "template is missing disk0_name specification"
# get ssh public key for cloud-init from file
if [ -n "${_ssh_key_file}" ]; then
[ ! -r "${_ssh_key_file}" ] && util::err "can't read file with public key (${_ssh_key_file})"
_ssh_public_key="$(cat "${_ssh_key_file}")"
fi
# if we're on zfs, make a new filesystem
zfs::make_dataset "${VM_DS_ZFS_DATASET}/${_name}" "${_zfs_opts}"
@@ -144,7 +152,8 @@ core::create(){
[ $? -eq 0 ] || util::err "unable to copy template to virtual machine directory"
# generate a uuid
config::set "${_name}" "uuid" $(uuidgen)
_uuid=$(uuidgen)
config::set "${_name}" "uuid" ${_uuid}
# get any zvol options
config::get "_zfs_opts" "zfs_zvol_opts"
@@ -186,6 +195,32 @@ core::create(){
config::get "_disk_size" "disk${_num}_size" "20G"
done
# create disk with metadata for cloud-init
_cloud_init_dir="${VM_DS_PATH}/${_name}/.cloud-init"
mkdir -p "${_cloud_init_dir}"
cat << EOF > "${_cloud_init_dir}/meta-data"
instance-id: ${_uuid}
local-hostname: ${_name}
EOF
if [ -n "${_ssh_public_key}" ]; then
cat << EOF > "${_cloud_init_dir}/user-data"
#cloud-config
ssh_authorized_keys:
- ${_ssh_public_key}
resize_rootfs: True
manage_etc_hosts: localhost
EOF
fi
genisoimage -output "${VM_DS_PATH}/${_name}/seed.iso" -volid cidata -joliet -rock "${_cloud_init_dir}/meta-data" "${_cloud_init_dir}/user-data" > /dev/null 2>&1 || util:err "Can't write seed.iso for cloud-init"
config::set "${_name}" "disk${_num}_type" "ahci-cd"
config::set "${_name}" "disk${_num}_name" "seed.iso"
config::set "${_name}" "disk${_num}_dev" "file"
exit 0
}