I am writing a program in Java that creates a VM instance in Azure, uploads a script to a container, and downloads and executes the script in the VM. However, I am currently facing a difficulty in granting the machine access to the container. I added
.withSystemAssignedManagedServiceIdentity()
to the machine creation. This however was not enough and apparently I also have to add Roles (in my case Storage Reader) to the VM. When I do it manually in the portal, after the machine has been setup, I then see via SSH that I have the access. But is there a way to do it in the VM creation process in my Java program?
It is possible, you can use withSystemAssignedIdentityBasedAccessTo(String resourceId, BuiltInRole role)
method.
Here is the sample:
VirtualMachine virtualMachine = azureResourceManager.virtualMachines()
.define(linuxVMName)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withNewPrimaryPublicIPAddress(pipName)
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername(userName)
.withRootPassword(password)
.withSize(VirtualMachineSizeTypes.STANDARD_DS2_V2)
.withOSDiskCaching(CachingTypes.READ_WRITE)
.withSystemAssignedManagedServiceIdentity()
.withSystemAssignedIdentityBasedAccessTo("<storage-account-resource-id>", BuiltInRole.READER)
.create();