Passing credential to DSC from arm template - azure

I am trying to pass a user credential to my DSC script via arm template.Its seem template is not passing credential correctly to the dsc.
DSC and MOF
Thanks

Here's whats working for me. Powershell:
Param(
[System.Management.Automation.PSCredential]$Admincreds,
xxx
)
xxx
Arm template:
"properties": {
"publisher": "Microsoft.Powershell",
"type": "DSC",
"typeHandlerVersion": "2.20",
"autoUpgradeMinorVersion": true,
"settings": {
"configuration": {
"url": "https://url.zip",
"script": "file.ps1",
"function": "configuration"
},
"configurationArguments": {
"param": "something"
}
},
"protectedSettings": {
"configurationArguments": {
"adminCreds": {
"userName": "actualusername",
"password": "actualpassword"
}
}
}
}

Related

Get VirtualMachineScaleSet instanceview for a ResourceGroup

I am trying to get instanceview objects(VirtualMachineScaleSetInstanceViewInner) of all Azure's VirtualMachineScaleSets under a Subscription and this requires both ResourceGroup Name and Vmss name together.
azureResourceManager.virtualMachines().manager().serviceClient().getVirtualMachineScaleSets().getInstanceView(resourceGroupName, virtualMachineScaleSet.name(), Context.NONE);
How do I get specific VirtualMachineScaleSets under a ResourceGroup? I only see AzureResourceManager.ResourceGroups() and AzureResourceManager.virtualMachineScaleSets(), but nothing that gets virtualMachineScaleSets under a ResourceGroup.
Thanks
I have tried to get the VMSS instance in a Resource group by using the below RestApi:
GET https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}?api-version=2022-08-01
output:
Body:
{
"name": "rajtestVMSS",
"id": "/subscriptions/*********/resourceGroups/abcaaaa/providers/Microsoft.Compute/virtualMachineScaleSets/rajtestVMSS",
"type": "Microsoft.Compute/virtualMachineScaleSets",
"location": "westus2",
"tags": {
"azsecpack": "nonprod",
"platformsettings.host_environment.service.platform_optedin_for_rootcerts": "true"
},
"sku": {
"name": "Standard_D2s_v3",
"tier": "Standard",
"capacity": 2
},
"properties": {
"singlePlacementGroup": false,
"upgradePolicy": {
"mode": "Manual"
},
"scaleInPolicy": {
"rules": [
"Default"
]
},
"virtualMachineProfile": {
"osProfile": {
"computerNamePrefix": "rajtestvm",
"adminUsername": "rajtest",
"windowsConfiguration": {
"provisionVMAgent": true,
"enableAutomaticUpdates": true,
"enableVMAgentPlatformUpdates": false
------------------
------------------
------------------
You can use the below java code to get the VirtualMachine ScaleSet instanceview for a ResourceGroup.
import com.azure.core.util.Context;
public final class Main {
public static void getAVirtualMachineScaleSet(com.azure.resourcemanager.AzureResourceManager azure) {
azure
.virtualMachines()
.manager()
.serviceClient()
.getVirtualMachineScaleSets()
.getByResourceGroupWithResponse("myResourceGroup", "myVirtualMachineScaleSet", null, Context.NONE);
}
}
Thanks to #XiaofeiCao for the github link to know more about Azure Resource Manager client library for Java.

Azure IoT Hub - create policy with supplied keys

I'm looking for a way to create access policy in Azure IoT hub but I'd like to supply my own keys.
I can see there is a command in Azure CLI:
az iot hub policy create --hub-name
--name
--permissions
[--resource-group]
[--subscription]
but it does not allow to provide my own keys.
I couldn't find anything interesting on PowerShell as well - seems like there is no command for creating shared access policy at all using PowerShell.
There is a way to use ARM template (seems like it is possible to provide primary and secondary key (https://learn.microsoft.com/en-us/azure/templates/microsoft.devices/iothubs?tabs=json#iothubproperties):
...
"properties": {
"allowedFqdnList": [ "string" ],
"authorizationPolicies": [
{
"keyName": "string",
"primaryKey": "string",
"rights": "string",
"secondaryKey": "string"
}
],
...
but it brings some hassle in terms how to provide the keys and I'm looking for something simple and preety much one-timer.
You can use the below sample arm template which create a basic iot hub & a shared access policy with our own keys. You need to create two files parameters.json & template.json.
template.json file contains the code which resources are going to deploy.
parameters.json file contains the value of those parameters that you have used in the template.json.
Template.json file:
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"IotHubs_IotHub_connectionString": {
"type": "SecureString"
},
"IotHubs_IotHub_containerName": {
"type": "SecureString"
},
"IotHubs_IotHub_name": {
"defaultValue": "vedodIotHub",
"type": "String"
},
"IotHubs_Key_Name" : {
"defaultValue" : "newkeyname",
"type": "string"
},
"IotHubs_Key_Primary_value" : {
"type": "string"
},
"IotHubs_Key_Secondary_value":{
"type": "string"
}
},
"variables": {},
"resources": [
{
"type": "Microsoft.Devices/IotHubs",
"apiVersion": "2021-07-02",
"name": "[parameters('IotHubs_IotHub_name')]",
"location": "eastus",
"sku": {
"name": "S1",
"tier": "Standard",
"capacity": 2
},
"identity": {
"type": "None"
},
"properties": {
"ipFilterRules": [],
"authorizationPolicies": [
{
"keyName": "[parameters('IotHubs_Key_Name')]",
"primaryKey": "[parameters('IotHubs_Key_Primary_value')]",
"secondaryKey" : "[parameters('IotHubs_Key_Secondary_value')]",
"rights": "RegistryRead, RegistryWrite, DeviceConnect"
}
],
"eventHubEndpoints": {
"events": {
"retentionTimeInDays": 1,
"partitionCount": 4
}
},
"routing": {
"endpoints": {
"serviceBusQueues": [],
"serviceBusTopics": [],
"eventHubs": [],
"storageContainers": []
},
"routes": [],
"fallbackRoute": {
"name": "$fallback",
"source": "DeviceMessages",
"condition": "true",
"endpointNames": [
"events"
],
"isEnabled": true
}
},
"storageEndpoints": {
"$default": {
"sasTtlAsIso8601": "PT1H",
"connectionString": "[parameters('IotHubs_IotHub_connectionString')]",
"containerName": "[parameters('IotHubs_IotHub_containerName')]"
}
},
"messagingEndpoints": {
"fileNotifications": {
"lockDurationAsIso8601": "PT1M",
"ttlAsIso8601": "PT1H",
"maxDeliveryCount": 10
}
},
"enableFileUploadNotifications": false,
"cloudToDevice": {
"maxDeliveryCount": 10,
"defaultTtlAsIso8601": "PT1H",
"feedback": {
"lockDurationAsIso8601": "PT1M",
"ttlAsIso8601": "PT1H",
"maxDeliveryCount": 10
}
},
"features": "None"
}
}
]
}
parameters.json file :
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"IotHubs_IotHub_connectionString": {
"value": ""
},
"IotHubs_IotHub_containerName": {
"value": ""
},
"IotHubs_IotHub_name": {
"value": "<IotHubName>"
},
"IotHubs_Key_Name":{
"value" : "<sharedaccesspolicyKeyName>"
},
"IotHubs_Key_Primary_value": {
"value" : "<accesspolicyPrimaryKeyValue>"
},
"IotHubs_Key_Secondary_value":{
"value" : "<accesspolicySecondaryKeyValue>"
}
}
}
Using the below Powershell cmdlets to deploy the create a Iot hub & passing the above template.json & parameters.json file as parameters :
New-AzResourceGroupDeployment -ResourceGroupName <resourcegroupName> -TemplateFile '<pathfortemplate.jsonfile>' -TemplateParameterFile '<Pathforparameters.jsonfile>'
Here is the sample output screenshot for reference:

Deployment Script ARM template in Azure

I am using Deployment Script to run powershell with ARM. It needs user-manged identity with contributor role. I have followed steps in below link but it always gives same error.
https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/deployment-script-template?tabs=PowerShell
Invalid value for the identities '/subscriptions/<subID>/resourcegroups/<rgname>/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test_manged_identity'. The 'UserAssignedIdentities' property keys should only be empty json objects, null or the resource exisiting property.
I have extracted principalId and client Id with below command.
Get-AzUserAssignedIdentity -ResourceGroupName 'rGname'
Below is the template
<pre>
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"name": {
"type": "string",
"defaultValue": "'ds test'"
},
"utcValue": {
"type": "string"
},
"subscriptionId": {
"type": "string",
"defaultValue": ""
}
},
"resources": [
{
"type": "Microsoft.Resources/deploymentScripts",
"apiVersion": "2019-10-01-preview",
"identity": {
"type": "userAssigned",
"userAssignedIdentities": {
"/subscriptions/subid/resourcegroups/rGname/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test_manged_identity": {
"ClientId": "value",
"PrincipalId": "value"
}
}
},
"kind": "AzurePowerShell", // or "AzureCLI"
"location": "[resourceGroup().location]",
"name": "runPowerShellInlineWithOutput",
"properties": {
"containerSettings": {
"containerGroupName": "deployscriptrun"
},
"storageAccountSettings": {
"storageAccountName": "allscriptstorage",
"storageAccountKey": "key"
},
"azPowerShellVersion": "3.0", // or "azCliVersion": "2.0.80"
"environmentVariables": [
{
"name": "someSecret",
"secureValue": "if this is really a secret, don't put it here... in plain text..."
}
],
"scriptContent" : "write-host 'hello world'",
"supportingScriptUris": [],
//"timeout": "PT30M",
"cleanupPreference": "OnSuccess",
"retentionInterval": "P1D"
}
}
],
"outputs": {
}
}
</pre>
With
"userAssignedIdentities": {
"/subscriptions/subid/resourcegroups/rGname/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test_manged_identity": {}
}
I get below error
{
"code": "DeploymentScriptOperationFailed",
"message": "The client 'id' with object id 'id' does not have authorization to perform action 'Microsoft.Resources/subscriptions/providers/read' over scope '/subscriptions/id' or the scope is invalid. If access was recently granted, please refresh your credentials."
}
according to the article linked it should look like this:
"userAssignedIdentities": {
"/subscriptions/subid/resourcegroups/rGname/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test_manged_identity": {}
}

Using secret from Azure KeyVault in Azure ARM Template

I have a template of container instance with container in azurecr.io
Is it possible to use an Azure Key Vault secret in an ARM Template?
The following examples do not work:
"imageRegistryCredentials": [
{
"server": "***.azurecr.io",
"username": "***",
"password": {
"reference": {
"keyVault": {
"id": "[resourceId(parameters('vaultSubscription'), parameters('vaultResourceGroupName'), 'Microsoft.KeyVault/vaults', parameters('vaultName'))]"
},
"secretName": "[parameters('secretName')]"
}
}
}
],
I have tried it with:
"resources": [
{
...
"properties": {
"parameters":{
"secretPassword": {
"type": "securestring",
"reference": {
"keyVault": {
"id": "[resourceId(parameters('vaultSubscription'), parameters('vaultResourceGroupName'), 'Microsoft.KeyVault/vaults', parameters('vaultName'))]"
},
"secretName": "[parameters('secretName')]"
}
}
},
And:
"imageRegistryCredentials": [
{
"server": "**.azurecr.io",
"username": "**",
"password": "[parameters('secretPassword')]"
}
],
Result:
"error": {
"code": "InvalidTemplate",
"message": "Unable to process template language expressions for resource '/subscriptions/**/resourceGroups/**/providers/Microsoft.ContainerInstance/containerGroups/**' at line '28' and co
lumn '9'. 'The template parameter 'secretPassword' is not found. Please see https://aka.ms/arm-template/#parameters for
usage details.'"
}
}'
So, I've created a workaround, which enables you to relatively simply use any keyvault secret in your template by using a publicly available template on github. See https://github.com/bobvandevijver/azure-arm-keyvault-secret-output for the example.
It would obviously be better if Microsoft just fixed this implementation, but it's something!
You can only use key vault reference in the parameters of the template (or nested template).
so you either need to move this part to the parameters section or move it to the nested template and use this as a parameter to the nested template. here is the sample to pass values from the kv to the nested template:
{
"apiVersion": "2017-05-10",
"name": "[concat('kvReference-', copyIndex())]",
"type": "Microsoft.Resources/deployments",
"copy": {
"name": "kvReference",
"count": 2
},
"properties": {
"mode": "Incremental",
"templateLink": {
"uri": "nested_template_uri"
},
"parameters": {
"cer": {
"reference": {
"keyVault": {
"id": "keyvaultId"
},
"secretName": "secretname"
}
}
}
}
},
and you can just use those inputs as parameters inside nested template

Join VMSS VM's to domain

It says here: https://learn.microsoft.com/en-us/azure/virtual-machine-scale-sets/virtual-machine-scale-sets-faq
That I can join a virtual machine scale set to an Azure AD domain, but I dont understand how you implement the JSON extension they state to use, I cant work out where I put it.
I have created the VMSS but cannot see an Extensions bit on it.
You can use script\dsc extensión as you normally would on a regular VM.
Sample DSC extensión:
{
"name": "Microsoft.Powershell.DSC",
"properties": {
"publisher": "Microsoft.Powershell",
"type": "DSC",
"typeHandlerVersion": "2.19",
"autoUpgradeMinorVersion": true,
"settings": {
"configuration": {
"url": "url_goes_here.ps1",
"script": "script.ps1",
"function": "function"
},
"configurationArguments": {
"domainName": "domain.name"
}
},
"protectedSettings": {
"configurationArguments": {
"adminCreds": {
"userName": "User",
"password": "Password"
}
}
}
}
}

Resources