Reputation: 37
I'm trying to create a loop script that will create multiple RG's with different owners. I have problem with adding different owner into resource groups.
$RGNamesUSE = "RG-01", "RG-02", "RG-03"
$Owner = "[email protected]","[email protected]", "[email protected]"
foreach($rg in $RGNamesUSE)
{
New-AzResourceGroup -Name $rg -Location westeurope
}
I need to add for each RG the owner. It should be like RG-01 will have owner user1, RG-02 will have owner user2 etc... How can i do this?
Upvotes: 0
Views: 1828
Reputation: 2970
Jagrati posted a correct answer, and it fulfills your requirements. Instead, I would like to challenge your requirements :)
I have seen codes like yours. If it is part of a solution and not a just-one-time run, then they get very hard to maintain and very easy to make mistakes.
For example, if somebody adds a new RG in the future, they need to remember to add the owner in the proper place or everything will be broken, and the problem can be even worse since you might not even notice the error neither at build time nor run time.
That is why I prefer these type of structures, where all the details are in the same place and related to each other: (try it here)
$ResourceGroups = @(
@{
"Name"="RG-01";
"Owners"="[email protected]"
},
@{
"Name"="RG-02";
"Owners"="[email protected]"
}
)
Then the code to deploy is very easy, without any index or any other magic to relate multiple data sources by position
foreach($rg in $ResourceGroups)
{
Write-Host "Creating resource group Name: $($rg.Name) with Owners: $($rg.Owners)"
# Create the Resource group
New-AzResourceGroup -Name $rg.Name -Location westeurope
# Assign roles.
New-AzRoleAssignment -SignInName $rg.Owners -RoleDefinitionName "Owner" -ResourceGroupName $rg.Name
}
This will also work much better in cases where you need to add more role assignments per groups, or other properties like each resource group in a different region
Upvotes: 0
Reputation: 2088
You can try the script below, that will create a resource group and assign the user as "Owner" of the resource group:
$RGNamesUSE = "RG-01", "RG-02", "RG-03"
$Owner = "[email protected]","[email protected]","[email protected]"
For ($i=0; $i -le ($RGNamesUSE.length - 1); $i++) {
$rg = $RGNamesUSE[$i];
$userName = $Owner[$i];
New-AzResourceGroup -Name $rg -Location westeurope
New-AzRoleAssignment -SignInName $userName -RoleDefinitionName "Owner" -ResourceGroupName $rg
}
Upvotes: 1