Creating Azure Recovery Service Vault - Python SDK - bad request - azure

I am trying to create a Recovery Service Vault in Azure using Python SDK.
Package version: azure-mgmt-recoveryservices==2.0.0
Code snippet:
client=RecoveryServicesClient(client_secret_credential, subscription_id)
client.vaults.begin_create_or_update(
resource_group_name="my-custom-rg",
vault_name="name_of_the_vault",
vault={
"location": "centralus",
"sku": {
"name": "Standard",
},
"identity": {
"type": "SystemAssigned",
}
}
)
I got the following error:
File "/<my-computer-path>/azure/lib/python3.8/site-packages/azure/mgmt/recoveryservices/operations/_vaults_operations.py", line 293, in _create_or_update_initial
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
azure.core.exceptions.HttpResponseError: Operation returned an invalid status 'Bad Request'
What am I doing wrong? How could I do more "error investigation"?

Thank you Robert. Posting your suggestion as an answer to help other community members.
This error azure.core.exceptions.HttpResponseError: Operation returned an invalid status 'Bad Request' is caused by missing backup_policy_resource properties.
policy_resource = BaseBackupPolicyResource(properties=backup_policy)
poller = client.backup_policies.create_or_update(
vault_name="my-vault-name",
resource_group_name="my-resource-group",
backup_policy_name="my-daily-backup",
parameters=policy_resource
)
You can refer to How to create disk Backup Policy using azure python SDK?

Related

Azure assign group and device to script using Graph API

I am trying to assign groups and devices to a PowerShell script in Microsoft Intune using the following POST request:
URL: https://graph.microsoft.com/beta/deviceManagement/deviceManagementScripts/%7Bid%7D/Assign
Body:
{
"deviceManagementScriptGroupAssignments": [
{
"#odata.type": "#microsoft.graph.deviceManagementScriptGroupAssignment",
"id": "{ScriptId:GroupId}",
"targetGroupId": "{GroupId}"
}
],
"deviceManagementScriptAssignments": [
{
"#odata.type": "#microsoft.graph.deviceManagementScriptAssignment",
"id": "{ScriptID:DeviceID}",
"target": {
"#odata.type": "#microsoft.graph.allDevicesAssignmentTarget",
"deviceAndAppManagementAssignmentFilterId": null,
"deviceAndAppManagementAssignmentFilterType": "none"
}
}
]
}
However, I am getting a 400 error with the following message:
"{ "_version": 3, "Message": "An error has occurred - Operation ID (for customer support): 00000000-0000-0000-0000-000000000000 - Activity ID: 615c3437-bd99-2193-9d4b-d9a61deb0340 - Url: https://fef.amsua0102.manage.microsoft.com/DeviceFE/StatelessDeviceFEService/deviceManagement/deviceManagementScripts('{id}')/microsoft.management.services.api.assign?api-version=5022-11-08", "CustomApiErrorPhrase": "", "RetryAfter": null, "ErrorSourceService": "", "HttpHeaders": "{}"}"
I base on this document of Microsoft https://learn.microsoft.com/en-us/graph/api/intune-shared-devicemanagementscript-assign?view=graph-rest-beta
I tried to reproduce the same in my environment.
Received the same error:
{
"error": {
"code": "UnknownError",
"message": "{\"ErrorCode\":\"Forbidden\",\"Message\":\"{\\ \\\"_version\\\": 3,\\ \\\"Message\\\": \\\"An error has occurred - Operation ID (for customer support): xxxx –
}
When I followed the url in the error and queried, I got that the api version is not supported.
Make sure the authorization header is given with bearer token which has proper permissions to work with intune and device management
Omit the parameter #odata.type in the post request body.
{
"#odata.type": "#microsoft.graph.deviceManagementScript",
…
"runAs32Bit": true
}
Make sure you have DeviceManagementConfiguration.ReadWrite.All Application and delegated permissions.
Note that Intune requires an active Intune license for the tenant.

Failed to send query to service connection API when using Azure devops api serviceendpoint to create kubernetes service connection

I am trying to use the https://dev.azure.com/<orgname>/_apis/serviceendpoint/endpoints?api-version=6.0-preview.4 api to create a new kubernetes service connection.
I want to use AzureSubscription auth, and as far as I know, it creates the service account and role binding for you. I have done this in portal and it works fine, but am struggling to replicate through the api.
I am able to create the Service Connection, and it sits in my service connection list in the project settings no problem.
When I pull it back down to check the status (with the GET service endpoint) , I have an operation status of 'failed' with a status message of 'An error occurred while creating the service account. Internal error: Failed to query service connection API: 'https://management.azure.com/api/v1/namespaces/default/serviceaccounts?pretty=false'. Error Message: 'An error occurred while sending the request.'
Here is what I am sending in the body, I am using a PAT to auth.
{
"data": {
"authorizationType": "AzureSubscription",
"clusterAdmin": "true",
"azureSubscriptionId": "00000000-0000-0000-0000-000000000000",
"azureSubscriptionName": "SomeSubscriptionName",
"clusterId": "/subscriptions/"00000000-0000-0000-0000-000000000000"/resourceGroups/someresourcegroupname/providers/Microsoft.ContainerService/managedClusters/someclustername",
"namespace": "default"
},
"name": "TestK8sEndpoint",
"type": "Kubernetes",
"url": "https://management.azure.com/",
"authorization": {
"parameters": {
"azureTenantId": ""00000000-0000-0000-0000-000000000000"",
"azureEnvironment": "AzureCloud"
},
"scheme": "Kubernetes"
},
"isShared": false,
"isReady": true,
"serviceEndpointProjectReferences": [
{
"projectReference": {
"id": ""00000000-0000-0000-0000-000000000000"",
"name": "someprojectname"
},
"name": "TestK8sEndpoint"
}
]
}
Any help is much appreciated
I have since realised that I made a mistake in my body.
The 4th property url should have been the url of my cluster - aka, someclustername-dns-0a0a0a0a.hcp.northeurope.0a0a0a.io

How to create a fork of a parent repository using Azure DevOps REST API?

How can we create a new repository copying all the contents from a parent repository? I have tried forking an existing repository, but the REST API is throwing 400 Bad Request exception.
The sample request provided in the Microsoft document here is not working as expected and is throwing below exception.
{
"$id": "1",
"innerException": null,
"message": "A team project ID or name is required in the URL or request body.\r\nParameter name: ProjectReference",
"typeName": "Microsoft.TeamFoundation.SourceControl.WebServer.InvalidArgumentValueException, Microsoft.TeamFoundation.SourceControl.WebServer",
"typeKey": "InvalidArgumentValueException",
"errorCode": 0,
"eventId": 0
}
How to create a fork of a parent repository using Azure DevOps REST API?
I could reproduce this issue with the sample request body.
To resolve this issue, please try to replace the name with ID of the project:
{
"name": "forkRepository",
"project": {
"id": "MyFirstProject_ID"
},
"parentRepository": {
"name": "MyFirstRepo",
"project": {
"id": "MyFirstProject_ID"
}
}
}
My test result:
And the fork repo:

Azure VM creation failed using downloaded template (The entity name 'vmImageName' is invalid according to its validation rule)

I want to create a vm on azure using az cli.
So I created interactively a VM and downloaded the template and its parameters.
I added some missing parameters, the final script is
az deployment group create --resource-group my-rg --template-file ./azure-32Go.template.json --parameters #./azure-32Go.template.parameters --parameters publicIpAddressName=my-ip networkInterfaceName=my-nic adminPublicKey="$(cat ~/.ssh/id_rsa.pub)" imageName=MsOps-Demo1-image-20210212-175858 --debug
I get an error
msrestazure.azure_exceptions.CloudError: Azure Error: DeploymentFailed
Message: At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/DeployOperations for usage details.
Exception Details:
Error Code: BadRequest
Message: {'error': {'code': 'InvalidParameter', 'message': "The entity name 'vmImageName' is invalid according to its validation rule: ^[^_\\W][\\w-._]{0,79}(?<![-.])$.", 'target': 'vmImageName'}}
Googling did not point me to someone to get the same issue.
I looked in azur portal Resource Group / Activity log to look at more information, but I only see the same above issue with no more information
How can I fix my code ?
I auto answer this question.
I have redone the whole process, and starting the vm with the template works fine.
As I wanted to set a specific image name. I added a parameter imageName
Now I updated the template.json by adding a parameter
"parameters": {
"location": {
"type": "string"
},
"imageName": {
"type": "string"
},
"networkInterfaceName": {
Updated where it is used
"storageProfile": {
"osDisk": {
"createOption": "fromImage",
"managedDisk": {
"storageAccountType": "[parameters('osDiskType')]"
}
},
"imageReference": {
"id": "/subscriptions/14b6e880-753e-4a5f-8618-c0786702aa1c/resourceGroups/MsOps-Horizon-rg/providers/Microsoft.Compute/images/[parameters('imageName')]"
}
},
But when doing the creation process fails with the same reason
Deployment failed. Correlation ID: 39b18e50-ff0d-4ecd-a3e8-e40b988a341b. {
"error": {
"code": "InvalidParameter",
"message": "The entity name 'vmImageName' is invalid according to its validation rule: ^[^_\\W][\\w-._]{0,79}(?<![-.])$.",
"target": "vmImageName"
}
}
Creation of vm failed
My workaround is therefore to do a sed in the template.json to insert the image name I want :(
My guess is that the [parameter('imageName')] is not expanded early enough which makes the process fails as the name does not match the matching rule

Unable to create LambdaPermission with Terraform and LocalStack combination: creation: unexpected state '', wanted target 'Active'

I am adding resource aws_lambda_permission to send events from S3 to Lambda. But Terraform is complaining with following error message.
Error: error waiting for Lambda Function (py-lambda-foo) creation: unexpected state '', wanted target 'Active'. last error: %!s(<nil>)
Using Terraform:
Terraform v0.12.17
provider.aws v2.41.0
Localstack 0.10.5
I am able to verify that function has been created successfully
By checking this command
awslocal lambda list-functions
I see this problem as AWS Provider has created the lambda function however, localstack is not returning status which is expected for provider.aws to work on. Hence, it is failing with this error.
I switched on the TRACE logs and I could see these aws.provider logs that it is waiting for state of Lambda to change to ACTIVE and it is constantly pinging lambda/GetFunction
2019-12-07T08:16:24.328Z [DEBUG] plugin.terraform-provider-aws_v2.41.0_x4: 2019/12/07 08:16:24 [DEBUG] Waiting for state to become: [Active]
2019-12-07T08:16:29.336Z [DEBUG] plugin.terraform-provider-aws_v2.41.0_x4: 2019/12/07 08:16:29 [DEBUG] [aws-sdk-go] DEBUG: Request lambda/GetFunction Details:
This is response we receive for createFunction
{
"CodeSha256": "xnITd7GQzVtuke7kOR5LP7iprBAmgz5iu15WISiVd0U=",
"CodeSize": 5503941,
"Description": "",
"Environment": {
"Variables": {
"foo": "bar"
}
},
"FunctionArn": "arn:aws:lambda:eu-west-1:000000000000:function:py-lambda-foo",
"FunctionName": "py-lambda-foo",
"Handler": "app.lambda_handler",
"LastModified": "2019-12-07T08:16:21.097+0000",
"MemorySize": 128,
"RevisionId": "f04d5dad-5e1e-41f0-9c96-387b7ab2313f",
"Role": "arn:aws:iam::000000000000:role/iam_for_lambda",
"Runtime": "python3.7",
"Timeout": 3,
"TracingConfig": {
"Mode": "PassThrough"
},
"Version": "$LATEST"
}
This has been an issue with the Localstack compatibility with the Terraform's AWS Provider. Take a look at issue description here https://github.com/localstack/localstack/issues/1835
Finally, Localstack developers applied the fix https://github.com/localstack/localstack/pull/1838 by adding state as ACTIVE and now this has been picked up aws-provider of Terraform.

Resources