This PowerShell script is designed to isolate a specific Azure Virtual Machine (VM) by moving it to a new subnet and setting up Azure Bastion for secure access. It is crafted to work both as a standalone script for local execution and as part of a GitLab CI/CD pipeline.
The script performs the following actions:
- Authenticates with Azure using a service principal or interactive login.
- Retrieves the virtual network address space associated with the VM.
- Creates a new subnet for isolation purposes.
- Creates a separate subnet for the Azure Bastion host.
- Generates a new Network Security Group (NSG) and configures it to allow Bastion Host access only.
- Associates the NSG with the isolation subnet.
- Provisions a new public IP address for the Bastion host.
- Quarantines the target VM by moving it into the isolation subnet.
- Establishes a new Bastion host for secure connectivity.
- Azure PowerShell Module (Az Module)
- An active Azure subscription with appropriate permissions.
- For CI/CD pipeline execution: GitLab with a configured runner.
- Authentication: The script checks for an existing Azure session and prompts for authentication if needed.
- Subscription and Resource Group: Input your Azure Subscription ID and the name of the resource group containing the VM.
- Virtual Machine Selection: Specify the VM name you intend to isolate.
- Network Configuration: Provide CIDR blocks for the isolation and Bastion subnets.
- Execution: Run the script in a PowerShell environment. The script creates network resources and reconfigures the VM.
- Configuration: Set the necessary environment variables in your GitLab CI/CD settings.
- Automation: The
gitlab-ci.yml
file orchestrates the script execution based on the provided variables.
subscriptionId
: Azure Subscription ID.VMresourceGroupName
: Resource Group name containing the VM.vmName
: Name of the VM to isolate.subnetRange
: CIDR for the new isolation subnet.bastionSubnet
: CIDR for the Bastion subnet.
Execute the script in a PowerShell environment with the Azure PowerShell module installed.
# Example command to execute the script, it will ask the user for the values it requires
.\IsolateVM.ps1
# Alternatively, you can pass in those values at runtime as follows
.\IsolateVM.ps1 -subscriptionId "your-subscription-id" -VMresourceGroupName "your-rg-name" -vmName "your-vm-name" -subnetRange "your-subnet-range" -bastionSubnet "your-bastion-subnet"
When running the pipeline manually, it will ask for user input parameters for use within the script. GitLab CI/CD pipeline will then automatically execute the script based on the defined stages in gitlab-ci.yml
.
The script maintains a hashtable to track the creation of resources. In case of an error, it provides information about which resources were created and might need to be manually cleaned up.
Feel free to fork this repository and submit pull requests or issues for any enhancements or fixes.