To create multiple local users in an Azure VM using Terraform, you can utilize the Azure Resource Manager (ARM) provider. Here's an example of how you can achieve this:
1. Set up your Terraform environment and configure the Azure provider with the necessary credentials.
2. Create a new Terraform configuration file (e.g., `main.tf`) and add the following code:
```hcl
provider "azurerm" {
# Configure the Azure provider here
}
resource "azurerm_virtual_machine_extension" "user_extension" {
name = "add-users-extension"
location = azurerm_virtual_machine.example.location
resource_group_name = azurerm_virtual_machine.example.resource_group_name
virtual_machine_name = azurerm_virtual_machine.example.name
publisher = "Microsoft.Compute"
type = "CustomScriptExtension"
type_handler_version = "1.10"
settings = <<SETTINGS
{
"commandToExecute": "powershell.exe -ExecutionPolicy Unrestricted -File add_users.ps1"
}
SETTINGS
depends_on = [azurerm_virtual_machine.example]
}
resource "azurerm_virtual_machine" "example" {
# Configure the VM resource here
}
data "azurerm_virtual_machine" "example" {
name = azurerm_virtual_machine.example.name
resource_group_name = azurerm_virtual_machine.example.resource_group_name
}
```
3. Create a PowerShell script file (e.g., `add_users.ps1`) in the same directory as your Terraform configuration file. The script should contain the logic to create the local users. Here's an example script:
```powershell
# Create user accounts
$usernames = @("user1", "user2", "user3")
foreach ($username in $usernames) {
$password = ConvertTo-SecureString -String "password123" -AsPlainText -Force
$user = New-LocalUser -Name $username -Password $password -PasswordNeverExpires:$true
Add-LocalGroupMember -Group "Administrators" -Member $user.Name
}
```
4. Run `terraform init` to initialize your Terraform configuration.
5. Run `terraform apply` to create the Azure VM and execute the custom script extension. Terraform will provision the VM and execute the PowerShell script to create the local user accounts.
Make sure to replace the placeholders (`azurerm_virtual_machine.example`) with your actual resource names or variables as needed.
By utilizing Terraform and the Azure provider, you can automate the process of creating multiple local user accounts in an Azure VM.
No comments:
Post a Comment