Can you deallocate a VM without logging in (non-interactively)?

mikey 5 Reputation points
2024-03-29T10:58:06.1533333+00:00

Hi,

I'm running a VM non-interactively and I need to shut it down (and deallocate resources) once the process is complete. If I were to run az login first, I'd then be able to run az vm deallocate. But my process needs to run non-interactively, so I can't do az login because that requires an unfortunate verification step.

How can I deallocate the VM if I am not logged in? (This is a Ubuntu VM.)

Azure Virtual Machines
Azure Virtual Machines
An Azure service that is used to provision Windows and Linux virtual machines.
9,053 questions
{count} votes

4 answers

Sort by: Most helpful
  1. Konstantinos Passadis 19,591 Reputation points MVP
    2024-03-29T11:08:08.2466667+00:00

    Hello @mikey

    Welcome to Microsoft QnA!

    The only way i can think of is by API Call

    https://learn.microsoft.com/en-us/rest/api/compute/virtual-machines/deallocate?view=rest-compute-2024-03-01&tabs=HTTP

    https://learn.microsoft.com/en-us/rest/api/azure/?view=rest-compute-2024-03-01

    Azure will never allow you to access Subscriptions without explicitly authenticating , one way or another !

    --

    I hope this helps!

    Kindly mark the answer as Accepted and Upvote in case it helped!

    Regards

    1 person found this answer helpful.
    0 comments No comments

  2. deherman-MSFT 38,021 Reputation points Microsoft Employee Moderator
    2024-03-29T16:58:42.02+00:00

    @mikey
    The proper way is highlighted by @Marcin Policht . I just wanted to add an alternative. in case someone might find it helpful. If you have SSH access, you can run a simple shutdown command via ssh without need for interaction. This format allows you to send your command and immediately exit without need for interaction or waiting for the shutdown to complete.

    ssh -i mykey.pem azureuser@10.0.0.4 -q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null 'hostname;uptime;nohup sudo shutdown -h now < /dev/null > std.out 2> std.err &' 
    

    If you still have questions, please let us know in the "comments" and we would be happy to help you. Comment is the fastest way of notifying the experts.

    If the answer has been helpful, we appreciate hearing from you and would love to help others who may have the same question. Accepting answers helps increase visibility of this question for other members of the Microsoft Q&A community.

    Thank you for helping to improve Microsoft Q&A!

    User's image

    0 comments No comments

  3. Marcin Policht 50,895 Reputation points MVP Volunteer Moderator
    2024-03-29T11:10:42.6533333+00:00

    You have to be authenticated to access your Azure subscription and deallocate any Azure VM.

    If you want to do this programmatically, you'd need to configure the application to sign in to Entra ID non-interactively (also known as service principal authentication). To do so, you'd follow these steps:

    Register the Application:

    Go to the Azure portal and navigate to "Azure Active Directory" > "App registrations".
    
    Click on "New registration" and provide a name for your application.
    
    Choose the appropriate supported account types (e.g., single tenant or multi-tenant).
    
    Specify the Redirect URI if your application requires it. For non-interactive authentication, this is typically not needed.
    
    Click on "Register" to create the application.
    

    Create Client Secret:

       Once the application is registered, navigate to the "Certificates & secrets" section.
      
          Click on "New client secret" and enter a description.
         
             Choose the expiration duration for the secret (recommended to choose a long expiration time for service principals).
            
                Click on "Add" to generate the client secret. Make sure to copy and securely store the secret value, as it will not be displayed again.
               
               **Assign Required Permissions**:
               
                   Navigate to the "API permissions" section of your registered application.
                  
                      Click on "Add a permission" and select the required APIs or Microsoft Graph permissions that your application needs to access.
                     
                         Grant admin consent if necessary.
                        
                        **Retrieve Tenant ID and Application ID**:
                        
                            Note down the "Directory (tenant) ID" and the "Application (client) ID" of your registered application. You'll need these values for authentication.
                           
                           **Use Client Credentials Flow**:
                           
                               In your application code, use the Client Credentials OAuth 2.0 flow to authenticate using the client ID and client secret.
                              
                                  Make a POST request to the token endpoint (**`https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token`**) with the following parameters:
                                 
                                        **`client_id`**: Application (client) ID of your registered application.
                                       
                                              **`client_secret`**: The client secret generated earlier.
                                             
                                                    **`grant_type`**: Set to "client_credentials".
                                                   
                                                          **`scope`**: Set to the desired scope (e.g., **`"https://graph.microsoft.com/.default"`** for Microsoft Graph API).
                                                         
                                                             Upon successful authentication, you'll receive an access token that can be used to access the requested resources on behalf of the application.
                                                            
    

    If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.

    hth

    Marcin

    1 person found this answer helpful.
    0 comments No comments

  4. kobulloc-MSFT 26,811 Reputation points Microsoft Employee Moderator
    2024-03-29T17:05:54.6433333+00:00

    Hello, @mikey !

    Can you deallocate a VM without logging in?

    No. As other have stated, you cannot deallocate a VM without authenticating your access to the subscription (this is different than managing resources without interaction--see question below). The Azure portal, Azure PowerShell, Azure CLI, REST clients, and SDKs all require authentication:

    https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/overview#consistent-management-layer

    Diagram that shows the role of Azure Resource Manager in handling Azure requests.

    Can I deallocate a VM without human interaction (programmatically)?

    Yes. There are several ways to do this when looking at SDKs and REST clients:


    I hope this has been helpful! Your feedback is important so please take a moment to accept answers.

    If you still have questions, please let us know what is needed in the comments so the question can be answered. Thank you for helping to improve Microsoft Q&A!

    User's image

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.