After deploying an EC2 instance, there may be a need to add EBS volume to EC2 instance. You can add EBS volume to a running instance. This PowerShell script will automate the process of attaching additional EBS volume to Windows EC2 instance and after that, it will initialize, format the disk & assign a disk label.
To attach additional EBS volume, we need to use block device mapping. Block device mapping defines the block devices (EBS volumes) that attach to an instance. The root volume is always attached to "/dev/sda1", it is mounted as C:\ in the Windows instance. Subsequent volumes are attached as "xvdf" devices. For Windows instance, you should use "xvdf-z", in order: xvdf, xvdg, xvdh, and so on.
To get the device name, the script uses the function Get-Device. This function automates the generation of device names in sequence xvdf, xvdg. The function takes Instance Id as a parameter. It checks the current attached devices first and generates new device name & returns it. If the current device is "/dev/sda1" then it returns "xvdf" otherwise it calculates subsequent devices and returns.
The next script block is the main script block, which takes parameters- instance name, volume size, volume type (gp2, io1, etc) & device. Using the instance name it finds the instance id and gets the device name by calling the Get-Device function. Note, it also finds the availability zone for instance so that volume is created in that zone.
Next, it creates a new volume with the New-EC2Volume command. We wait till the volume becomes available & once it is available attach it to the instance. Further, we do tagging for volume.
Once the volume is attached to an instance, call another function Initialize-EC2Disk to initialize, format the disk & assign a drive letter to the volume. In this function, we use the AWS Systems Manager tool to run PowerShell commands remotely on an EC2 instance. Using the automation feature of Systems Manager you do not require remote PowerShell to execute commands on the instance. For this first, create IAM role which will be used to give Systems Manager permission to run commands on the instance.
We use Send-SSMCommand to send PowerShell commands to instances. These commands will be executed on instance & format the attached volume.
In this way, you can automate adding EBS volume to the Windows instance and initializing & formatting volume.
This comment has been removed by the author.
ReplyDeleteThe ability to swiftly attach an EBS volume to an active Windows EC2 instance using PowerShell exemplifies the robust automation capabilities within the Amazon ecosystem. This functionality, pivotal for scaling and adapting cloud resources on-demand, underscores the convenience and agility offered by the Amazon Automation Store.
ReplyDelete