Hello All,
I am new to Ansiable .my requirement is to Create VM from dynamic JSON Values …For example below is output from my API
“Server_details”: [
{
“IP”: “192.168.1.1”,
“Server_Name”: “TestVM1”
“HDD”: “300GB”
“memory”:“4GB”
},
{
“IP”: “192.168.1.2”,
“Server_Name”: “TestVM2”
“HDD”: “200GB”
“memory”:“4GB”
},
{
“IP”: “192.168.1.3”,
“Server_Name”: “TestVM3”
“HDD”: “100GB”
“memory”: “4GB”
}
]
}
}
Now I want to create 3 VM and Clone from template , question is how i setup VMname , VMIP address, VM memory and VM cpU from about data …
Thanks …HeM
hello,
Yes, this functionality can be implemented using the feature of dynamic inventory.
Ansible can accept any kind of executable file as an inventory file, as long as you can pass it to Ansible as a JSON. You could create a script that can be run and will output JSON to stdout. Ansible will internally call this script with the argument --list.
The JSON structure should however fulfill below requirements for ansible to correctly interpret it as an inventory file:
- JSON should have a dictionary of groups with each group containing
a) A list of hosts
b) Group variables
- JSON should contain a _meta dictionary that stores host variables for all hosts individually inside a hostvars dictionary.
Below is the sample JSON example:
{
“group”: {
“hosts”: [
“192.168.1.1”,
“192.168.1.2”,
“192.168.1.3”
],
“vars”: {
“ansible_user”: “admin”
}
},
“_meta”: {
“hostvars”: {
“192.168.1.1”: {
“Server_Name”: “TestVM1”
“HDD”: “300GB”
“memory”:“6GB”
},
“192.168.1.2”: {
“Server_Name”: “TestVM2”
“HDD”: “200GB”
“memory”:“4GB”
},
“192.168.1.3”: {
“Server_Name”: “TestVM3”
“HDD”: “100GB”
“memory”: “2GB”
}
}
}
}
Steps to create and verify a custom dynamic inventory:
-
Create a python script (let’s say, myscript.py) that will generate a JSON output in above structure.
-
Run the script manually to verify it returns the proper JSON response in above structure when run with --list argument.
$ ./myscript.py --list
- Verify using ping if Ansible is able to interpret hosts from the JSON output.
$ ansible all -i myscript.py -m ping
- Create a playbook to create and clone VM and provide this script as inventory.
$ansible-playbook -i myscript.py main.yml
This inventory file can further be consumed in below playbook to create virtual machines.
$main.yml
hosts: all
gather_facts: False
tasks:
- name: Deploy guest from template
vmware_guest
hostname"{{ hostvars.Server_Name }}"
disk:
- size_gb: “{{ hostvars.HDD }}”
hardware:
memory_mb: “{{ hostvars.memory }}”
template: “{{ template }}”
with_items: “{{ hosts }}”
Thanks
Soniya