How to assign content trust policy to container registry resource azure powershell - azure

I have created container registry as below through powershell.
$prop = #{
Location = "..."
ResourceName = "Resource1"
ResourceType = "Microsoft.ContainerRegistry/registries"
ResourceGroupName = "ResourceGroup.."
Force = $true
Sku = #{"Name"="Premium"}
}
$registry = New-AzResource #prop"
It gets created successfully, but the content trust policy set for this is "disabled"
How can i make it enabled during creation through powershell

The content trust policy for the ACR is in its properties, so you need to set it in the commands. Finally, the commands will like this:
$prop = #{
Location ="location"
ResourceName ="resourceName"
ResourceType ="Microsoft.ContainerRegistry/registries"
ResourceGroupName ="groupName"
Sku =#{"Name"="Premium"}
Properties =#{"Policies"=#{"TrustPolicy"=#{"Type"="Notary";"Status"="enabled"}}}
}
$registry = New-AzResource #prop

Related

Getting Subscription ID with Resource Group without setting az context

I have a tenant with multiple subscriptions.
When I first login using Connect-AzAccount, it shows a message "TenantId 'xxxxx-xxxxx-xxx-xxx' contains more than one active subscription. First one will be selected for further use. To select another subscription, use Set-AzContext."
But I want to be able to do Get-AzResourceGroup -name 'abcd'.
The problem is resource group abcd is not under the first selected subscription selected from the login command.
I want to progromatically Get-AzResourceGroup -Name "ResourcegroupName" to retrieve the subscriptionID without setting az context as it defeats the purpose.
tried to clear the context clear-azContext but that signs me out.
I want to progromatically Get-AzResourceGroup -Name "ResourcegroupName" to retrieve the subscriptionID without setting az context as it defeats the purpose.
After reproducing from my end, Using the below script I could able to achieve your requirement.
$ResourceGroupName = Read-Host "Enter the resource group name you are searching for"
Get-AzSubscription | ForEach-Object {
$subscriptionName = $_.Name
$subscriptionId = $_.SubscriptionId
Set-AzContext -SubscriptionId $subscriptionId
(Get-AzResourceGroup).ResourceGroupName | ForEach-Object {
If ($ResourceGroupName -eq $_) {
[PSCustomObject] #{
Subscription = $subscriptionName
SubscriptionId = $subscriptionId
ResourceGroup = $_
}
}
}
}
RESULTS:

Storage Account vnet details

I am trying to create a report to find all the storage account and its associated vnet details.
& {
foreach ($storageAccount in Get-AzStorageAccount) {
$storageAccountName = $storageAccount.StorageAccountName
$resourceGroupName = $storageAccount.ResourceGroupName
$context = (Get-AzStorageAccount -StorageAccountName $storageAccountName -ResourceGroupName $resourceGroupName).NetworkRuleSet.VirtualNetworkRules.VirtualNetworkResourceId
$splitarray = $context.Split('/')
$vnetid = $splitarray[8]
$subscriptionid = $splitarray[2]
New-Object psobject -Property #{
Name = $storageAccountName;
Context = $vnetid;
ResourceGroupName = $resourceGroupName
Subscriptionid = $subscriptionid
}
}
} | Format-Table Name, Context, subscriptionid, ResourceGroupName
I am currently getting the below output:
storage account vnet report
As you can see from the output the vnet name is not properly fetched for the storage accounts.
Storage account testfnapp2oct16 has vnet testfnvnet attached, this is correct.
Storage accounts unz2versvaultea, cs1f7b27d61e31e, win10guestdiag954 doesn't have any vnet attached but 'testfnvnet' is repeated until the value changes for a different storage account.
Storage account testfnapp9eb7 has two vnets but only testvnet1 is shown and the value 'testvnet1' is repeated for next storage account.
Any help is much appreciated.
I tried to reproduce the same in my environment it's work me successfully.
I have created sample storage account fetched with vnet and without attached with vnet when I tried, your code I got the same error as below.
To resolve this issue Please utilise the condition I have changed in the code below to execute this issue's solution properly.
& {
foreach ($storageAccount in Get-AzStorageAccount) {
$storageAccountName = $storageAccount.StorageAccountName
$resourceGroupName = $storageAccount.ResourceGroupName
$context = (Get-AzStorageAccount -StorageAccountName $storageAccountName -ResourceGroupName $resourceGroupName).NetworkRuleSet.VirtualNetworkRules.VirtualNetworkResourceId
$ErrorActionPreference = ‘SilentlyContinue’
if ($context -eq $null){
New-Object psobject -Property #{
Name = $storageAccountName;
Context = "Empty" ;
ResourceGroupName = $resourceGroupName
Subscriptionid = $subscriptionid
}
}
else {
$splitarray = $context.Split('/')
$vnetid = $splitarray[8]
$subscriptionid = $splitarray[2]
New-Object psobject -Property #{
Name = $storageAccountName;
Context = $vnetid;
ResourceGroupName = $resourceGroupName
Subscriptionid = $subscriptionid
}
}
}
} | Format-Table Name, Context, subscriptionid, ResourceGroupName
Result:
Now, whichever vnet are not fetched in my storage account it's show Empty like below.

How to customize the image with Log Analytics virtual machine extension using Azure Image Builder

I have created a Windows VM with Azure Image Builder using PowerShell by following this documentation.
param (
[Parameter(Mandatory = $true)]
[string]
$imageResourceGroup,
[Parameter(Mandatory = $true)]
[string]
$location,
[Parameter(Mandatory = $true)]
[string]
$imageTemplateName,
[Parameter(Mandatory = $true)]
[string]
$runOutputName,
[Parameter(Mandatory = $true)]
[string]
$myGalleryName,
[Parameter(Mandatory = $true)]
[string]
$imageDefName
)
## Register features
Get-AzResourceProvider -ProviderNamespace Microsoft.Compute, Microsoft.KeyVault, Microsoft.Storage, Microsoft.VirtualMachineImages, Microsoft.Network |
Where-Object RegistrationState -ne Registered |
Register-AzResourceProvider
## Install modules
#Install-Module -Name Az.ManagedServiceIdentity -RequiredVersion 0.7.2 -Force
#Install-Module -Name Az.ImageBuilder -Force
## Your Azure Subscription ID
$subscriptionID = (Get-AzContext).Subscription.Id
Write-Output $subscriptionID
## Create a resource group
New-AzResourceGroup -Name $imageResourceGroup -Location $location
## Create user identity and set role permissions
[int]$timeInt = $(Get-Date -UFormat '%s')
$imageRoleDefName = "Azure Image Builder Image Def $timeInt"
$identityName = "myIdentity$timeInt"
## Create a user identity.
New-AzUserAssignedIdentity -ResourceGroupName $imageResourceGroup -Name $identityName
## Store the identity resource and principal IDs in variables.
$identityNameResourceId = (Get-AzUserAssignedIdentity -ResourceGroupName $imageResourceGroup -Name $identityName).Id
$identityNamePrincipalId = (Get-AzUserAssignedIdentity -ResourceGroupName $imageResourceGroup -Name $identityName).PrincipalId
## Assign permissions for identity to distribute images
$myRoleImageCreationUrl = 'https://raw.githubusercontent.com/azure/azvmimagebuilder/master/solutions/12_Creating_AIB_Security_Roles/aibRoleImageCreation.json'
$myRoleImageCreationPath = "$env:TEMP\myRoleImageCreation.json"
Invoke-WebRequest -Uri $myRoleImageCreationUrl -OutFile $myRoleImageCreationPath -UseBasicParsing
$Content = Get-Content -Path $myRoleImageCreationPath -Raw
$Content = $Content -replace '<subscriptionID>', $subscriptionID
$Content = $Content -replace '<rgName>', $imageResourceGroup
$Content = $Content -replace 'Azure Image Builder Service Image Creation Role', $imageRoleDefName
$Content | Out-File -FilePath $myRoleImageCreationPath -Force
## Create the role definition.
New-AzRoleDefinition -InputFile $myRoleImageCreationPath
## Grant the role definition to the image builder service principal.
$RoleAssignParams = #{
ObjectId = $identityNamePrincipalId
RoleDefinitionName = $imageRoleDefName
Scope = "/subscriptions/$subscriptionID/resourceGroups/$imageResourceGroup"
}
New-AzRoleAssignment #RoleAssignParams
## Create an Azure Compute Gallery
## Create the gallery.
#$myGalleryName = 'myImageGallery'
#$imageDefName = 'winSvrImages'
New-AzGallery -GalleryName $myGalleryName -ResourceGroupName $imageResourceGroup -Location $location
## Create a gallery definition.
$GalleryParams = #{
GalleryName = $myGalleryName
ResourceGroupName = $imageResourceGroup
Location = $location
Name = $imageDefName
OsState = 'generalized'
OsType = 'Windows'
Publisher = 'myCo'
Offer = 'Windows'
Sku = 'Win2019'
}
New-AzGalleryImageDefinition #GalleryParams
## Create an image
## Create an Azure image builder source object.
$SrcObjParams = #{
SourceTypePlatformImage = $true
Publisher = 'MicrosoftWindowsServer'
Offer = 'WindowsServer'
Sku = '2019-Datacenter'
Version = 'latest'
}
$srcPlatform = New-AzImageBuilderSourceObject #SrcObjParams
## Create an Azure image builder distributor object.
$disObjParams = #{
SharedImageDistributor = $true
ArtifactTag = #{tag = 'dis-share' }
GalleryImageId = "/subscriptions/$subscriptionID/resourceGroups/$imageResourceGroup/providers/Microsoft.Compute/galleries/$myGalleryName/images/$imageDefName"
ReplicationRegion = $location
RunOutputName = $runOutputName
ExcludeFromLatest = $false
}
$disSharedImg = New-AzImageBuilderDistributorObject #disObjParams
## Create an Azure image builder customization object.
$ImgCustomParams01 = #{
PowerShellCustomizer = $true
CustomizerName = 'settingUpMgmtAgtPath'
RunElevated = $false
Inline = #("mkdir c:\\buildActions", "mkdir c:\\buildArtifacts", "echo Azure-Image-Builder-Was-Here > c:\\buildActions\\buildActionsOutput.txt")
}
$Customizer01 = New-AzImageBuilderCustomizerObject #ImgCustomParams01
## Create a second Azure image builder customization object.
$ImgCustomParams02 = #{
FileCustomizer = $true
CustomizerName = 'downloadBuildArtifacts'
Destination = 'c:\\buildArtifacts\\index.html'
SourceUri = 'https://raw.githubusercontent.com/azure/azvmimagebuilder/master/quickquickstarts/exampleArtifacts/buildArtifacts/index.html'
}
$Customizer02 = New-AzImageBuilderCustomizerObject #ImgCustomParams02
## Create an Azure image builder template.
$ImgTemplateParams = #{
ImageTemplateName = $imageTemplateName
ResourceGroupName = $imageResourceGroup
Source = $srcPlatform
Distribute = $disSharedImg
Customize = $Customizer01, $Customizer02
Location = $location
UserAssignedIdentityId = $identityNameResourceId
}
New-AzImageBuilderTemplate #ImgTemplateParams
## To determine if the template creation process was successful, you can use the following example.
Get-AzImageBuilderTemplate -ImageTemplateName $imageTemplateName -ResourceGroupName $imageResourceGroup |
Select-Object -Property Name, LastRunStatusRunState, LastRunStatusMessage, ProvisioningState
## Start the image build
## Submit the image configuration to the VM image builder service.
Start-AzImageBuilderTemplate -ResourceGroupName $imageResourceGroup -Name $imageTemplateName
## Create a VM
## Store login credentials for the VM in a variable. The password must be complex.
$Cred = Get-Credential
## Create the VM using the image you created.
$ArtifactId = (Get-AzImageBuilderRunOutput -ImageTemplateName $imageTemplateName -ResourceGroupName $imageResourceGroup).ArtifactId
New-AzVM -ResourceGroupName $imageResourceGroup -Image $ArtifactId -Name myWinVM01 -Credential $Cred
## Verify the customizations
Get-Content -Path C:\buildActions\buildActionsOutput.txt
Get-ChildItem c:\buildArtifacts\
## Delete the image builder template
#Remove-AzImageBuilderTemplate -ResourceGroupName $imageResourceGroup -Name $imageTemplateName
## Delete the image resource group
#Remove-AzResourceGroup -Name $imageResourceGroup
I want to add the Log Analytics virtual machine extension for Windows to the custom image.
Did you tried the same custom params that I see in your script, something in inline (Silent installation commands) comments with workid or key?
however, the easiest way is to enabled log analytics auto provisioning in security center now it's called microsoft defender for cloud (I am using it)

Azure deployment slots - Adding it to a virtual network using powershell

I'm trying to add an azure deployment slot to a virtual network. Below is the powershell script I'm currently using for adding the webapp to the Vnet, which is working fine:
#Property array with the SubnetID
$properties = #{
subnetResourceId = "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/resourceGroupName/providers/Microsoft.Network/virtualNetworks/vnetName/subnets/subnetName"
}
#Creation of the VNet integration
$vnetParams = #{
ResourceName = "WebappName/VirtualNetwork"
Location = "South Central US"
ResourceGroupName = "resourceGroupName"
ResourceType = "Microsoft.Web/sites/networkConfig"
PropertyObject = $properties
}
New-AzResource #vnetParams -Force
How do I change the above script to work with the deployment slot of the same webapp?
Thanks in advance.
You could change your code like this. Note the change of ResourceName and ResourceType.
#Property array with the SubnetID
$properties = #{
subnetResourceId = "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/resourceGroupName/providers/Microsoft.Network/virtualNetworks/vnetName/subnets/subnetName"
}
#Creation of the VNet integration
$vnetParams = #{
ResourceName = "WebappName/slot/VirtualNetwork"
Location = "South Central US"
ResourceGroupName = "resourceGroupName"
ResourceType = "Microsoft.Web/sites/slots/networkConfig"
PropertyObject = $properties
}
New-AzResource #vnetParams -Force

How to configure azure storage lifecycle with terraform?

So I'm using terraform for azure provider in order to deploy my infrastructure. I just can't seem to be able to define the storage lifecycle. I'd like to add something like this, which i have found, but is not available as is.
So i've tried this https://github.com/terraform-providers/terraform-provider-azurerm/issues/3316, and i've look all over. I'm certain there's a way of telling azure to enable the lifecycle tiertoarchive and tiertodelete… Just can't seem to figure it out.
Thanks
What i'm looking for:
*the resource azurerm_storage_management_policy is a made up resource.
resource "azurerm_storage_account" "example" {
name = "myaccount"
resource_group_name = "myresourcegroup"
location = "westeurope"
account_tier = "Standard"
account_replication_type = "LRS"
}
resource "azurerm_storage_management_policy" "example" {
storage_account_name ="${azurerm_storage_account.example.name}"
rule {
name = "rule1"
enabled = true
type = "Lifecycle"
definition {
filters {
prefix_match = ["container1/wibble"]
blob_types = ["blockBlob"]
}
actions = {
base_blob {
tier_to_cool {
days_after_modification_greater_than = 30
}
tier_to_archive {
days_after_modification_greater_than = 90
}
delete {
days_after_modification_greater_than = 2555
}
snapshot {
delete {
days_after_creation_greater_than = 90
}
}
}
}
}
}
https://github.com/terraform-providers/terraform-provider-azurerm/issues/3316
I see in your comment, you ask for powershell to do that. Then yes, it's possible via powershell as per this doc.
The sample code from the doc(you can modify it to meet your need) works for me, and note that you should install azure powershell az module before run the script:
#Initialize the following with your resource group and storage account names
$rgname = ""
$accountName = ""
#Create a new action object
$action = Add-AzStorageAccountManagementPolicyAction -BaseBlobAction Delete -daysAfterModificationGreaterThan 2555
$action = Add-AzStorageAccountManagementPolicyAction -InputObject $action -BaseBlobAction TierToArchive -daysAfterModificationGreaterThan 90
$action = Add-AzStorageAccountManagementPolicyAction -InputObject $action -BaseBlobAction TierToCool -daysAfterModificationGreaterThan 30
$action = Add-AzStorageAccountManagementPolicyAction -InputObject $action -SnapshotAction Delete -daysAfterCreationGreaterThan 90
# Create a new filter object
# PowerShell automatically sets BlobType as “blockblob” because it is the only available option currently
$filter = New-AzStorageAccountManagementPolicyFilter -PrefixMatch ab,cd
#Create a new rule object
#PowerShell automatically sets Type as “Lifecycle” because it is the only available option currently
$rule1 = New-AzStorageAccountManagementPolicyRule -Name Test -Action $action -Filter $filter
#Set the policy
$policy = Set-AzStorageAccountManagementPolicy -ResourceGroupName $rgname -StorageAccountName $accountName -Rule $rule1
Please let me know if you issues when write / execute the code above.

Resources