Manage Linux virtual machines in Azure using Ansible
Ansible allows you to automate the deployment and configuration of resources in your environment. In this article, you use an Ansible playbook to start and stop a Linux virtual machine.
Prerequisites
- Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Install Ansible: Do one of the following options:
- Install and configure Ansible on a Linux virtual machine
- Configure Azure Cloud Shell and - if you don't have access to a Linux virtual machine - create a virtual machine with Ansible.
Stop a virtual machine
In this section, you use Ansible to deallocate (stop) an Azure virtual machine.
Sign in to the Azure portal.
Open Cloud Shell.
Create a file named
azure-vm-stop.yml
, and open it in the editor:code azure-vm-stop.yml
Paste the following sample code into the editor:
- name: Stop Azure VM hosts: localhost connection: local tasks: - name: Stop virtual machine azure_rm_virtualmachine: resource_group: {{ resource_group_name }} name: {{ vm_name }} allocated: no
Replace the
{{ resource_group_name }}
and{{ vm_name }}
placeholders with your values.Save the file and exit the editor.
Run the playbook using ansible-playbook
ansible-playbook azure-vm-stop.yml
After running the playbook, you see output similar to the following results:
PLAY [Stop Azure VM] ******************************************************** TASK [Gathering Facts] ****************************************************** ok: [localhost] TASK [Deallocate the Virtual Machine] *************************************** changed: [localhost] PLAY RECAP ****************************************************************** localhost : ok=2 changed=1 unreachable=0 failed=0
Start a virtual machine
In this section, you use Ansible to start a deallocated (stopped) Azure virtual machine.
Sign in to the Azure portal.
Open Cloud Shell.
Create a file named
azure-vm-start.yml
, and open it in the editor:code azure-vm-start.yml
Paste the following sample code into the editor:
- name: Start Azure VM hosts: localhost connection: local tasks: - name: Start virtual machine azure_rm_virtualmachine: resource_group: {{ resource_group_name }} name: {{ vm_name }} started: yes
Replace the
{{ resource_group_name }}
and{{ vm_name }}
placeholders with your values.Save the file and exit the editor.
Run the playbook using ansible-playbook
ansible-playbook azure-vm-start.yml
After running the playbook, you see output similar to the following results:
PLAY [Start Azure VM] ******************************************************** TASK [Gathering Facts] ****************************************************** ok: [localhost] TASK [Start the Virtual Machine] ******************************************** changed: [localhost] PLAY RECAP ****************************************************************** localhost : ok=2 changed=1 unreachable=0 failed=0