Skip to content

Instantly share code, notes, and snippets.

@anderssonjohan
Created September 13, 2017 18:13
Show Gist options
  • Save anderssonjohan/fa88e6ddf883fd161698caac68912394 to your computer and use it in GitHub Desktop.
Save anderssonjohan/fa88e6ddf883fd161698caac68912394 to your computer and use it in GitHub Desktop.
user data script to initialize, partition and format ebs volume /dev/xvd[drive letter]
function setup-volume {
param(
[parameter(mandatory=$true,helpmessage="drive letter")]
[string] $driveletter,
[parameter(mandatory=$false,helpmessage="file system label")]
[string] $label = ""
)
$driveletter = $driveletter.ToLower()
# Assume last character of the device name = drive letter
# SCSI targets for device names:
# http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-windows-volumes.html#windows-volume-mapping
$letters = @("b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z")
# I.e. /dev/xvdb = scsi target 1
$scsitarget = 1 + $letters.IndexOf( $driveletter )
if( -not $scsitarget) {
throw "Invalid drive letter. Could not look up scsitarget for $driveletter"
}
$disk = Get-Disk | ?{ $_.Location.EndsWith(("Target {0} : LUN 0" -f $scsitarget)) -and $_.OperationalStatus -eq "Offline" }
if( -not $disk ) {
throw "Could not find disk with SCSI target $scsitarget"
}
try {
Initialize-Disk -Number $disk.Number -PartitionStyle "MBR"
} catch {
throw "Failed to initialize disk $_"
}
try {
$part = New-Partition -DiskNumber $disk.Number -UseMaximumSize -IsActive -DriveLetter $driveletter
} catch {
throw "Failed to create partition $_"
}
try {
Format-Volume -DriveLetter $part.DriveLetter -NewFileSystemLabel $label -Confirm
} catch {
throw "Failed to format drive $driveletter $_"
}
}
template = <<EOF
<powershell>
${file("${path.module}/setup-volume.ps1")}
setup-volume -driveLetter L -label Log
setup-volume -driveLetter W -label Web
</powershell>
EOF
@duhaas2015
Copy link

duhaas2015 commented Jan 30, 2018

appreciate the script, curious, I run and only see the following for "location"
https://i.imgur.com/FwXJCBi.png

which never finds a scsitarget

@earljon
Copy link

earljon commented Mar 3, 2020

That's because the $letters should not include "b", "c" like so:

$letters = @("d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z")

Drive D will be: Target ID 1 and xvdb

Bus Number 0, Target ID 1, LUN 0 | xvdb

@praneethng
Copy link

can you please guide me how to invoke this from my existing Terraform code

@praneethng
Copy link

@anderssonjohan can you please guide me how to invoke this from my existing Terraform code

@earljon
Copy link

earljon commented Feb 16, 2021

HI @praneethng, you can simply create a powershell file and assign it in user_data property in your terraform main.tf file.

<powershell> YOUR CODE HERE ... </powershell>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment