Ansible is a powerful tool for automating IT operations, including the creation of virtual machines (VMs) in cloud and on-premises environments. This article explores how Ansible can create VMs, its integration with virtualization platforms, and examples of playbooks for automating VM provisioning.
Can Ansible Create VMs?
Yes, Ansible can create virtual machines by interacting with virtualization platforms and cloud providers. Using platform-specific modules and collections, Ansible automates the provisioning of VMs, from defining configurations to deploying operating systems and managing resources.
Supported Platforms for VM Creation
Ansible integrates with a variety of platforms to create VMs:
1. Cloud Providers:
- AWS: Use the amazon.aws.ec2_instance module.
- Azure: Use the azure.azcollection.azure_rm_virtualmachine module.
- Google Cloud: Use the google.cloud.gcp_compute_instance module.
2. On-Premises Virtualization:
- VMware: Use the vmware.vmware_guest module.
- KVM/Libvirt: Use the community.libvirt.virt module.
- Hyper-V: Use the ansible.windows.win_hyperv_vm module.
3. Containerized Environments:
- Automate virtualized containers with tools like Kubernetes and Docker.
Examples of Creating VMs with Ansible
1. Creating an EC2 Instance on AWS
``yaml
- name: Create an EC2 instance
hosts: localhost
tasks:
- name: Launch an EC2 instance
amazon.aws.ec2_instance:
name: "WebServer"
key_name: "my-key-pair"
instance_type: "t2.micro"
image_id: "ami-12345678"
region: "us-east-1"
state: present
`
2. Creating a Virtual Machine on VMware
`yaml
- name: Create a VMware VM
hosts: localhost
tasks:
- name: Deploy a VM from a template
vmware.vmware_guest:
hostname: "vcenter.local"
username: "[email protected]"
password: "password"
validate_certs: no
datacenter: "Datacenter"
cluster: "Cluster"
template: "UbuntuTemplate"
name: "NewVM"
networks:
- name: "VM Network"
ip: "192.168.1.100"
disk:
- size_gb: 20
datastore: "Datastore1"
state: poweredon
`
3. Creating a VM on KVM/Libvirt
`yaml
- name: Create a KVM VM
hosts: localhost
tasks:
- name: Define and start a KVM virtual machine
community.libvirt.virt:
name: "test-vm"
memory_mb: 2048
vcpu: 2
disks:
- size: 20
pool: "default"
networks:
- name: "default"
state: running
`
4. Creating a Virtual Machine on Azure
``yaml
- name: Create an Azure VM
hosts: localhost
tasks:
- name: Create a virtual machine
azure.azcollection.azure_rm_virtualmachine:
resource_group: "MyResourceGroup"
name: "MyVM"
vm_size: "Standard_B1s"
admin_username: "azureuser"