proxmox_cloud-init.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. <?php
  2. /**
  3. * cloud-init script for pfSense on Proxmox VE
  4. *
  5. * The script does a pfSense configuration in that manner:
  6. * 1. looks for an available cloud-init drive and mount it to /etc/cloud-init
  7. * 2. compares the cloud-init files on the cloud-init drive by a local copy placed in /etc/cloud-init
  8. * and ends without changing anything if the files on both location are similar
  9. * 3. parses the cloud-init YAML files and prepare and set the given values to pfSense config array
  10. * 4. write the pfSense configuration and reboot the instance
  11. * HowTo install:
  12. * 1. get a copy of the YAML parse from https://github.com/mustangostang/spyc/ and place it to /usr/local/sbin
  13. * 2. place a copy of proxmox_cloud-init.php also to /usr/local/sbin
  14. * HowTo use:
  15. * 1. attach a cloud-init drive to the pfSense VM
  16. * 2. create a startupscript
  17. *
  18. * @version 0.9
  19. * @author Andre Genrich andre.genrich@thurdata.ch
  20. */
  21. require_once('Spyc.php'); // yaml parser
  22. require_once('config.inc'); // pfSense configuration structures
  23. require_once('system.inc'); // pfSense system utilities
  24. $cloudInitFiles = array('meta-data', 'network-config', 'user-data'); // provided by Proxmox
  25. $cloudInitLocalPath = '/etc/cloud-init';
  26. $cloudInitMountPoint = '/mnt/cloud-init';
  27. /**
  28. * compares the cloud-init files
  29. *
  30. * conpares the cloud-init drive by a local copy and
  31. * update the local copy in case of changes
  32. * or if the local copy does not exist
  33. *
  34. * @param array $cloudInitFiles an array of filenames created by Proxmox
  35. * @param string $cloudInitLocalPath the local path to place the copy of cloud-init files
  36. * @param string $cloudInitMountPoint the location where the cloud-init image is mounted
  37. * @return bool true in case of updates, false in case of all is up to date
  38. */
  39. function updateCloudInitFiles( $cloudInitFiles, $cloudInitLocalPath, $cloudInitMountPoint) {
  40. $cloudInitFileDiff = false;
  41. // create /etc/cloud-init if not exist
  42. if (!is_dir("$cloudInitLocalPath")) {
  43. if (!mkdir ( "$cloudInitLocalPath", 0770, TRUE)) {
  44. $sys_err= error_get_last();
  45. echo "cloud-init failed: $sys_err[type] $sys_err[message]\n";
  46. syslog(LOG_ERR,"cloud-init failed: $sys_err[type] $sys_err[message]");
  47. exit(1);
  48. }
  49. }
  50. // check for updated config files and update the local copy in case of differs
  51. foreach ( $cloudInitFiles as $cloudInitFile ) {
  52. if (!((sha1_file("$cloudInitLocalPath/$cloudInitFile")) == (sha1_file("$cloudInitMountPoint/$cloudInitFile")))) {
  53. if (!copy("$cloudInitMountPoint/$cloudInitFile", "$cloudInitLocalPath/$cloudInitFile")) {
  54. $sys_err = error_get_last();
  55. syslog(LOG_ERR,"cloud-init failed: $sys_err[type] $sys_err[message]");
  56. exit(1);
  57. } else {
  58. $cloudInitFileDiff = true;
  59. }
  60. }
  61. }
  62. return $cloudInitFileDiff;
  63. }
  64. /**
  65. * probes existence of all necessary cloud-init files
  66. *
  67. * @param array $cloudInitFiles an array of filenames created by Proxmox
  68. * @param string $cloudInitPath the location where the cloud-init files should be
  69. * @return bool true in case of all files are in place or false if something missing
  70. */
  71. function checkCloudInitFiles( $cloudInitFiles, $cloudInitPath) {
  72. foreach($cloudInitFiles as $cloudInitFile) {
  73. if (!file_exists("$cloudInitPath/$cloudInitFile")) {
  74. return false;
  75. }
  76. }
  77. return true;
  78. }
  79. /**
  80. * search for a cloud-init drive
  81. *
  82. * probes any attached cd device for existing cloud-init files
  83. * mounts the drive to /mnt/cloud-init and probes that all neccessary cloud-init files exist
  84. *
  85. * @param array $cloudInitFiles an array of filenames created by Proxmox
  86. * @param string $cloudInitMountPoint the mountpoint for cloud-init drive
  87. * @return bool true in case of success, fals in case of no cloud-init drive could found
  88. */
  89. function checkCloudInitDevice( $cloudInitFiles, $cloudInitMountPoint) {
  90. // get attached cd devices
  91. preg_match_all( "/.*cd[0-9] /", file_get_contents('/var/run/dmesg.boot'), $cdDeviceList);
  92. if (empty($cdDeviceList[0])) {
  93. syslog(LOG_ERR,"cloud-init failed: No cloud-init drive found");
  94. exit(1);
  95. }
  96. if(!is_dir($cloudInitMountPoint)) {
  97. if(!mkdir($cloudInitMountPoint)) {
  98. syslog(LOG_ERR,"cloud-init failed: Cloud not create mountpoint $cloudInitMountPoint");
  99. exit(1);
  100. }
  101. }
  102. // check cloud-init iso is mounted or try to mount the cloud-init medium
  103. foreach($cdDeviceList[0] as $cdDevice) {
  104. // is a cd mounted on /mnt/cloud-init ?
  105. $sys_err_msg = exec("df $cloudInitMountPoint | grep -q /dev/$cdDevice 2>&1", $sys_msg, $sys_err_no);
  106. if ($sys_err_no) { // not mounted
  107. // try to mount the cd
  108. $mount_err = exec("mount_cd9660 /dev/$cdDevice $cloudInitMountPoint", $sys_msg, $sys_err_no);
  109. if (!$sys_err_no) {
  110. if (checkCloudInitFiles( $cloudInitFiles, $cloudInitMountPoint)) {
  111. syslog(LOG_INFO,"cloud-init: found cloud init drive on $cdDevice mounted at $cloudInitMountPoint/");
  112. return true;
  113. } else {
  114. $umount_err = exec("umount $cloudInitMountPoint", $sys_msg, $sys_err_no);
  115. if ($sys_err_no) {
  116. syslog(LOG_ERR,"cloud-init: mounted a wrong device $cdDevice but not able to umount because $sys_msg");
  117. return false;
  118. }
  119. }
  120. }
  121. } else { //already mounted (but not by us)
  122. if (checkCloudInitFiles( $cloudInitFiles, $cloudInitMountPoint)) {
  123. syslog(LOG_INFO,"cloud-init: found cloud init drive on $cdDevice at $cloudInitMountPoint/");
  124. return true;
  125. } else {
  126. syslog(LOG_ERR,"cloud-init: expected files on cloud init drive not found");
  127. return false;
  128. }
  129. }
  130. }
  131. return false;
  132. }
  133. /**
  134. * does a case insensitive search for a network device by given hardware address
  135. *
  136. * @param string $mac hardware address
  137. * @return string $if[1] device name or false if no device could be found
  138. */
  139. function searchIfDevice( $mac) {
  140. exec("ifconfig -a | awk '/^[a-z]/ { gsub(/\:/,\"\", $1); iface=$1; next } /hwaddr/ { mac=$2; print mac, iface}'", $ifMacList, $sys_err_no);
  141. foreach($ifMacList as $ifMac) {
  142. $if = explode(" ",$ifMac);
  143. if (strcasecmp("$if[0]", "$mac") == 0) { // case insensitive
  144. return $if[1];
  145. }
  146. }
  147. return false;
  148. }
  149. // search and mount the cloud-init image or exit 1
  150. if (!checkCloudInitDevice( $cloudInitFiles, $cloudInitMountPoint)) {
  151. syslog(LOG_ERR,"cloud-init: no cloud init drive available, skipping...\n");
  152. exit(1);
  153. }
  154. // update the local copy of cloud-init files if there are any changes or exit 0
  155. if (!(updateCloudInitFiles( $cloudInitFiles, $cloudInitLocalPath, $cloudInitMountPoint))) {
  156. syslog(LOG_INFO,"cloud-init: cloud init files up to date, skipping...\n");
  157. exit(0);
  158. }
  159. // parse cloud init configurations
  160. // $metaData = Spyc::YAMLLoad("$cloudInitLocalPath/$cloudInitFiles[0]"); // meta-data (actually not in use)
  161. $netData = Spyc::YAMLLoad("$cloudInitLocalPath/$cloudInitFiles[1]"); // network-config
  162. $userData = Spyc::YAMLLoad("$cloudInitLocalPath/$cloudInitFiles[2]"); // user-data
  163. // configure nameserver if set
  164. $ifLastNr=(count($netData['config'])-1); // the YAML parser reurns a crappy array like this
  165. if (reset($netData['config'][$ifLastNr]) == 'nameserver') { // (
  166. next($netData['config'][$ifLastNr]); // [type] => nameserver
  167. $dnsServerCount = 0; // [address] =>
  168. while($nameserverIP=next($netData['config'][$ifLastNr])) { // [0] => 1.2.3.4
  169. $config['system']['dnsserver'][$dnsServerCount] = $nameserverIP; // [1] => 4.3.2.1
  170. $dnsServerCount++; // [search] =>
  171. } // [2] => mydomain.local
  172. $config['system']['domain'] = next($netData['config'][$ifLastNr]); // )
  173. }
  174. // configure WAN interface
  175. $wanDevice = searchIfDevice( $netData['config'][0]['mac_address']);
  176. if (!$wanDevice) {
  177. syslog(LOG_ERR,"cloud-init: no WAN device found");
  178. exit(1);
  179. } else {
  180. $config['interfaces']['wan']['if'] = $wanDevice;
  181. }
  182. if ($netData['config'][0][0]['type'] == 'static') {
  183. $config['interfaces']['wan']['ipaddr'] = $netData['config'][0][0]['address'];
  184. $config['interfaces']['wan']['subnet'] = 32 - log((ip2long($netData['config'][0][0]['netmask']) ^ ip2long('255.255.255.255')) + 1 ,2);
  185. $config['interfaces']['wan']['gateway'] = $netData['config'][0][0]['gateway'];
  186. }
  187. // configure primary LAN device
  188. $lanDevice = searchIfDevice( $netData['config'][1]['mac_address']);
  189. if (!$lanDevice) {
  190. syslog(LOG_ERR,"cloud-init: no LAN device found");
  191. exit(1);
  192. } else {
  193. $config['interfaces']['lan']['if'] = $lanDevice;
  194. }
  195. if ($netData['config'][1][0]['type'] == 'static') {
  196. $config['interfaces']['lan']['ipaddr'] = $netData['config'][1][0]['address'];
  197. $config['interfaces']['lan']['subnet'] = 32 - log((ip2long($netData['config'][1][0]['netmask']) ^ ip2long('255.255.255.255')) + 1 ,2);
  198. $config['interfaces']['lan']['gateway'] = $netData['config'][1][0]['gateway'];
  199. }
  200. // configure additional network devices
  201. if ($ifLastNr > 2) {
  202. for ($ifNr=2;$ifNr<$ifLastNr;$ifNr++) {
  203. $optDeviceName = "opt" . strval($ifNr-1);
  204. $optDevice = searchIfDevice( $netData['config'][$ifNr]['mac_address']);
  205. if (!$optDevice) {
  206. syslog(LOG_WARN,"cloud-init: given network device {$netData['config'][$ifNr]['mac_address']} not found");
  207. break;
  208. } else {
  209. $config['interfaces'][$optDeviceName]['if'] = $optDevice;
  210. }
  211. if ($netData['config'][$ifNr][0]['type'] == 'static') {
  212. $config['interfaces'][$optDeviceName]['ipaddr'] = $netData['config'][$ifNr][0]['address'];
  213. $config['interfaces'][$optDeviceName]['subnet'] = 32 - log((ip2long($netData['config'][$ifNr][0]['netmask']) ^ ip2long('255.255.255.255')) + 1 ,2);
  214. $config['interfaces'][$optDeviceName]['gateway'] = $netData['config'][$ifNr][0]['gateway'];
  215. }
  216. }
  217. }
  218. // add ssh keys
  219. if (isset($userData['ssh_authorized_keys'])) {
  220. foreach ($userData[ssh_authorized_keys] as $sshKey) {
  221. $sshKeys .= "$sshKey\n";
  222. }
  223. $config['system']['user'][0]['authorizedkeys'] = base64_encode("$sshKeys");
  224. }
  225. $config['system']['hostname'] = $userData['hostname'];
  226. $config['system']['user'][0]['bcrypt-hash'] = $userData['password'];
  227. // write the configuration
  228. write_config();
  229. // finally reboot the system
  230. system_reboot_sync();