Create a basic virtual machine in Azure with Ansible

Ansible allows you to automate the deployment and configuration of resources in your environment. You can use Ansible to manage your virtual machines (VMs) in Azure, the same as you would any other resource. This article shows you how to create a basic VM with Ansible. You can also learn how to Create a complete VM environment with Ansible.


To manage Azure resources with Ansible, you need the following:

Create supporting Azure resources

In this example, you create a runbook that deploys a VM into an existing infrastructure. First, create resource group with az group create. The following example creates a resource group named myResourceGroup in the eastus location:

az group create --name myResourceGroup --location eastus

Create a virtual network for your VM with az network vnet create. The following example creates a virtual network named myVnet and a subnet named mySubnet:

az network vnet create \
  --resource-group myResourceGroup \
  --name myVnet \
  --address-prefix \
  --subnet-name mySubnet \

Create and run Ansible playbook

Create an Ansible playbook named azure_create_vm.yml and paste the following contents. This example creates a single VM and configures SSH credentials. Enter your own complete public key data in the key_data pair as follows:

- name: Create Azure VM
  hosts: localhost
  connection: local
  - name: Create VM
      resource_group: myResourceGroup
      name: myVM
      vm_size: Standard_DS1_v2
      admin_username: azureuser
      ssh_password_enabled: false
        - path: /home/azureuser/.ssh/authorized_keys
          key_data: "ssh-rsa AAAAB3Nz{snip}hwhqT9h"
        offer: CentOS
        publisher: OpenLogic
        sku: '7.3'
        version: latest

To create the VM with Ansible, run the playbook as follows:

ansible-playbook azure_create_vm.yml

The output looks similar to the following example that shows the VM has been successfully created:

PLAY [Create Azure VM] ****************************************************

TASK [Gathering Facts] ****************************************************
ok: [localhost]

TASK [Create VM] **********************************************************
changed: [localhost]

PLAY RECAP ****************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0

Next steps

This example creates a VM in an existing resource group and with a virtual network already deployed. For a more detailed example on how to use Ansible to create supporting resources such as a virtual network and Network Security Group rules, see Create a complete VM environment with Ansible.