Ansible Part 0.4 - Destroy target host
Preparing your environment to start using Ansible
Destroy Target Host - remove Azure VM
This tutorial covers cleaning up the Target Hosts created in earlier steps in this tutorial.
You will want to remove the VM to stop incurring costs from your cloud provider and ensure there are no more exposed endpoints.
The Ansible Code will be run on your Control Host and you will need a personal Azure Subscription with some credit in it.
This tutorial is based on this Microsoft Guide
Dependencies
- If you have followed the previous tutorials then you will have all the required dependencies
- A control host to run the Ansible Commands
- A service principle for your Azure Subscription. See the previous part 0.2 and follow the guidance there.
- If you have not stored the service principle details and secrets for consumption by Ansible then you will need to export them as variables in Step 2.
Tutorial using Azure Portal to Destroy VM
Login into Azure
Navigate to your Resource Group
Click Delete in the Resource Group overview tab.
You will need to confirm deletion.
This will remove all resources in that Resource Group
Tutorial using Ansible to Destroy VM
1.
Create the playbook delete_rg.yml
Create the playbook to remove the VM
1
nano ~/create_vm_ansible/delete_rg.yml
Copy the below playbook and update the name
variable on line 4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
---
- hosts: localhost
vars:
name: learnAnsibleRG
tasks:
- name: Deleting resource group - "{{ name }}"
azure.azcollection.azure_rm_resourcegroup:
name: "{{ name }}"
state: absent
force_delete_nonempty: true
register: rg
- name: Print Resource Group Deletion Output
ansible.builtin.debug:
var: rg
LEARN: you can override defined variables in several ways, including on the command line. See the guide on variable precedence to understand how to do this: Link
2.
Run the playbook
- Export your Azure Service Principle Credentials as Variables if you have not created a configuration file as outlined in the Dependencies.
1
2
3
4
export AZURE_SUBSCRIPTION_ID=<subscription_id>
export AZURE_CLIENT_ID=<service_principal_app_id>
export AZURE_SECRET=<service_principal_password>
export AZURE_TENANT=<service_principal_tenant_id>
2. Run the below command on your control host.
You can also override the name variable in the playbook using the –extra-vars flag. Try it out.
1
2
3
# If you want to use extra vars include the --extra-vars command
RG_NAME=learnAnsibleRG
ansible-playbook ~/create_vm_ansible/delete_rg.yml --extra-vars "name=$RG_NAME"