Creating an Azure Virtual Network with Ansible Playbook

As organizations continue to adopt cloud technologies, the need for automated infrastructure provisioning and configuration management becomes more important than ever. Ansible, a popular open-source automation tool, has several modules for working with Microsoft Azure Cloud. In this article, we will explore how to use Ansible’s Azure modules to automate the creation of a virtual network with subnets and a public IP address in Microsoft Azure Cloud.

Prerequisites

To follow along with this tutorial, you will need the following:

  • An Azure account with the necessary permissions to create virtual networks and subnets.
  • Ansible is installed on your local machine or server.
  • Azure modules for Ansible installed.

``bash

ansible-galaxy collection install azure.azcollection

`

Creating an Azure Virtual Network with Ansible

Let’s start by creating an Ansible playbook to create a virtual network with subnets and a public IP address in Azure.

Links

  • [azure.azcollection.azure_rm_virtualnetwork](https://docs.ansible.com/ansible/latest/collections/azure/azcollection/azure_rm_virtualnetwork_module.html)
  • [azure.azcollection.azure_rm_subnet](https://docs.ansible.com/ansible/latest/collections/azure/azcollection/azure_rm_subnet_module.html)
  • [azure.azcollection.azure_rm_publicipaddress](https://docs.ansible.com/ansible/latest/collections/azure/azcollection/azure_rm_publicipaddress_module.html)

Code

1. Define Variables First.

We need to define the variables that will be used throughout the playbook. Open a new file and add the following code:

`yaml

---

  • name: Azure Virtual Network

hosts: all

vars:

resource_group_name: "aznetwork-rg"

location: westeurope

tags:

environment: dev

department: infrastructure

network:

name: "aznetwork-vnet"

address: "10.210.0.0/16"

subnets:

- name: "aznetwork-vnet-frontend"

address: "10.210.1.0/24"

- name: "aznetwork-vnet-backend"

address: "10.210.2.0/24"

publicip:

name: "aznetwork-public-ip"

domain: aznetwork-labs

`

In this code, we define the following variables:

  • resource_group_name: The name of the resource group where the virtual network will be created.
  • location: The Azure region where the resource group will be created.
  • tags: Custom tags to be added to the virtual network.
  • network: The details of the virtual network, including its name, address space, and subnets.
  • publicip: The details of the public IP address.

2. Create Virtual Network Next.

We will use the azure_rm_virtualnetwork module to create the virtual network. Add the following task to the playbook:

``yaml

  • name: VNet - Create virtual network

azure.azcollection.azure_rm_virtualnetwork:

resource_group: "{{ resource_group_name }}"

name: "{{ network.name }}"

address_prefixes:

- "{{ network.address }}"

tags:

environment: "{{ tags.envi