首页 > 其他分享 >VCSA基于ansible批量创建虚拟机

VCSA基于ansible批量创建虚拟机

时间:2024-09-12 17:35:47浏览次数:10  
标签:name linetest 虚拟机 hostname hw item ansible VCSA guest

基于ansible批量创建虚拟机

安装模块

pip install --upgrade ansible
pip install PyVmomi

ansible-galaxy collection install community.vmware

ansible vmware_guest 如果需要配置IP和计算机名需要安装VMware tools

---
- hosts: localhost   ## 在本机执行
  gather_facts: No
  connection: local  ## 本地连接
  vars_files:
    - myvars.yml
    - vcenter.yml
  tasks:
  - name: Create a virtual machine from a template
    vmware_guest:
      hostname: "{{hostname}}"
      username: "{{username}}"
      password: "{{password}}"
      validate_certs: no
      folder: /
      datacenter: "{{datacenter}}"
      name: "{{item.name}}"
      state: poweredon
      esxi_hostname: "{{item.esxi_hostname}}"
      template: "{{item.sys_ver}}"
      disk:
      - size_gb: 51
        type: eagerzeroedthick    ## eagerzeroedthick厚置备零延迟   thin 精简置备
        datastore: "{{item.datastore}}"  ##存储
      - size_gb: "{{ item.d2_size_gb}}"
        #type: eagerzeroedthick
        datastore: "{{item.datastore}}"
      hardware:
        hotadd_cpu: true
        hotremove_cpu: true
        hotadd_memory: true
        memory_mb: "{{item.memory_mb}}"
        num_cpus: "{{item.num_cpus}}"
        scsi: lsilogic  ##linux用lsilogic,win用lsilogicsas,  默认使用paravirtual  这是VMware自己的准虚拟
      networks:
      - name: "{{item.vlan}}"  ##网络名
        device_type: vmxnet3  ## win使用e1000e
        ip: "{{item.ip}}"
        netmask: 255.255.255.0
        gateway: "{{item.gw}}"
      customization:
        hostname: "{{item.hostname}}"
        dns_servers:
        - "{{item.dns1}}"
        - "{{item.dns2}}"
    with_items:
      - "{{myvms}}"
    delegate_to: localhost
    register: deploy

  

vcenter.yml 存放vcenter验证信息

# vcenter.yml
hostname: "www.qq.com"  # Replace with your vCenter server hostname or IP address
username: "[email protected]"         # Replace with your vCenter username
password: "Raywing@host8."         # Replace with your vCenter password
datacenter: "Datacenter"     # Replace with your vCenter datacenter name

myvars.yml 是需要创建的虚拟机信息

myvars.yml 示例如下

---
datacenter: center
myvms:
 
  - name: x.x.x.x_xx #vcenter上显示的机器名
    esxi_hostname: x.x.x.x
    datastore: x
    d1_size_gb: 50
    d2_size_gb: 100
    memory_mb: 16384
    num_cpus: 8
    ip:
    gw:
    dns1:
    dns2:
    vlan: vlan14
    hostname: xxxx #克隆后机器的主机名
    sys_ver: centos6_moban
 
  - name: xxx
    esxi_hostname: xx
    datastore: xx
    d1_size_gb: 50
    d2_size_gb: 100
    memory_mb: 8192
    num_cpus: 4
    ip:
    gw:
    dns1:
    dns2:
    vlan: vlan14
    hostname: x
    sys_ver: centos7_moban

  

myvars.yml 可以直接用Python脚本生成

import re
 
outfile2 = open('myvars.yml', 'w')
file_head = '''
---
datacenter: center
myvms:
'''
outfile2.write(file_head)
with open('vm_list', 'r') as f:
    while 1:
        line = f.readline()
        if not line:
            break
        linetest = re.split(r'[;,\s]+', line)
        if linetest[12] is not None and linetest[12] != '' and linetest[12] == 'centos6':
            sys_version = 'centos6_moban'
        elif linetest[12] is not None and linetest[12] != '' and linetest[12] == 'centos7':
            sys_version = 'centos7_moban'
        else:
            sys_version = 'win2012_moban'
        if linetest[5] is not None and linetest[5].isdigit():
            memory = int(linetest[5]) * 1024
        host2text = '''
  - name: {0}_{1}
    esxi_hostname: {2}
    datastore: {3}
    d1_size_gb: {4}
    d2_size_gb: {5}
    memory_mb: {6}
    num_cpus: {7}
    ip: {8}
    gw: {9}
    dns1: {10}
    dns2: {11}
    vlan: {12}
    hostname: {13}
    sys_ver: {14}'''.format(linetest[0], linetest[1], linetest[2], linetest[3], linetest[6], linetest[7], memory, linetest[4], linetest[0], linetest[8], linetest[9], linetest[10], linetest[11], linetest[1], sys_version)
        print >> outfile2, host2text

安装完后的机器截图

查看虚拟机信息

[root@localhost vmware]# ansible-playbook -C test.yaml 
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'

PLAY [localhost] *********************************************************************************************************************************************************************************************

TASK [Get VM information] ************************************************************************************************************************************************************************************
ok: [localhost]

TASK [debug] *************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "vm_info": {
        "changed": false,
        "changes": {},
        "failed": false,
        "instance": {
            "advanced_settings": {
                "RemoteDisplay.maxConnections": "-1",
                "cpuid.coresPerSocket.cookie": "1",
                "ethernet0.pciSlotNumber": "192",
                "hpet0.present": "TRUE",
                "migrate.hostLog": "VM1-62db1586.hlog",
                "migrate.hostLogState": "none",
                "migrate.migrationId": "0",
                "monitor.phys_bits_used": "45",
                "numa.autosize.cookie": "10012",
                "numa.autosize.vcpu.maxPerVirtualNode": "1",
                "nvram": "VM1.nvram",
                "pciBridge0.pciSlotNumber": "17",
                "pciBridge0.present": "TRUE",
                "pciBridge4.functions": "8",
                "pciBridge4.pciSlotNumber": "21",
                "pciBridge4.present": "TRUE",
                "pciBridge4.virtualDev": "pcieRootPort",
                "pciBridge5.functions": "8",
                "pciBridge5.pciSlotNumber": "22",
                "pciBridge5.present": "TRUE",
                "pciBridge5.virtualDev": "pcieRootPort",
                "pciBridge6.functions": "8",
                "pciBridge6.pciSlotNumber": "23",
                "pciBridge6.present": "TRUE",
                "pciBridge6.virtualDev": "pcieRootPort",
                "pciBridge7.functions": "8",
                "pciBridge7.pciSlotNumber": "24",
                "pciBridge7.present": "TRUE",
                "pciBridge7.virtualDev": "pcieRootPort",
                "sata0.pciSlotNumber": "32",
                "sched.cpu.latencySensitivity": "normal",
                "scsi0.pciSlotNumber": "160",
                "scsi0.sasWWID": "50 05 05 6b cd 57 fa 70",
                "softPowerOff": "FALSE",
                "svga.guestBackedPrimaryAware": "TRUE",
                "svga.present": "TRUE",
                "tools.guest.desktop.autolock": "TRUE",
                "tools.remindInstall": "TRUE",
                "viv.moid": "1e091526-9d10-4572-9544-c0de1009e712:vm-17:FkTEKnLaZpO68ge8P5LN6ssRcpTvxlsW8QDA037ERdc=",
                "vmotion.checkpointFBSize": "8388608",
                "vmotion.checkpointSVGAPrimarySize": "8388608",
                "vmotion.svga.graphicsMemoryKB": "8192",
                "vmotion.svga.mobMaxSize": "8388608",
                "vmware.tools.internalversion": "0",
                "vmware.tools.requiredversion": "12384",
                "vmxstats.filename": "centos7.scoreboard"
            },
            "annotation": "",
            "current_snapshot": null,
            "customvalues": {},
            "guest_consolidation_needed": false,
            "guest_question": null,
            "guest_tools_status": "guestToolsNotRunning",
            "guest_tools_version": "0",
            "hw_cluster": null,
            "hw_cores_per_socket": 1,
            "hw_datastores": [
                "data"
            ],
            "hw_esxi_host": "192.168.17.5",
            "hw_eth0": {
                "addresstype": "assigned",
                "ipaddresses": null,
                "label": "Network adapter 1",
                "macaddress": "00:50:56:b9:42:aa",
                "macaddress_dash": "00-50-56-b9-42-aa",
                "portgroup_key": null,
                "portgroup_portkey": null,
                "summary": "VM Network"
            },
            "hw_files": [
                "[data] VM1/VM1.vmx",
                "[data] VM1/VM1.nvram",
                "[data] VM1/VM1.vmsd",
                "[data] VM1/VM1.vmdk"
            ],
            "hw_folder": "/Datacenter/vm",
            "hw_guest_full_name": null,
            "hw_guest_ha_state": null,
            "hw_guest_id": null,
            "hw_interfaces": [
                "eth0"
            ],
            "hw_is_template": false,
            "hw_memtotal_mb": 2048,
            "hw_name": "VM1",
            "hw_power_status": "poweredOff",
            "hw_processor_count": 1,
            "hw_product_uuid": "42392d62-ccc0-bf90-bde8-186ec267d492",
            "hw_version": "vmx-21",
            "instance_uuid": "50394019-b544-53c7-2f59-649dfa65551d",
            "ipv4": null,
            "ipv6": null,
            "module_hw": true,
            "moid": "vm-17",
            "snapshots": [],
            "tpm_info": {
                "provider_id": null,
                "tpm_present": false
            },
            "vimref": "vim.VirtualMachine:vm-17",
            "vnc": {}
        }
    }
}

Create-virtual-machine-esxi.yml

---
- hosts: localhost
  gather_facts: no
  vars:
    vcenter_hostname: 'www.qq.com'
    vcenter_username: '[email protected]'
    vcenter_password: 'Raywing@host8.'
    datacenter_name: 'Datacenter' #中心名称
    esxi_hostname: '192.168.17.5' #esxi主机
  tasks:
  - name: Create a virtual machine on given ESXi hostname
    vmware_guest:
      hostname: '{{ vcenter_hostname }}'
      username: '{{ vcenter_username }}'
      password: '{{ vcenter_password }}'
      validate_certs: False
      name: vm-03
      guest_id: centos7_64Guest #虚拟机模板
      datacenter: '{{ datacenter_name }}'
      folder: /
      datastore: data
      disk:
      - size_gb: 10
        type: thin  #磁盘精简模式
        datastore: data  #硬盘名称
      hardware:
        memory_mb: 2048
        num_cpus: 2
        scsi: paravirtual
      networks:
      - name: VM Network
        mac: aa:bb:dd:aa:00:14
        ip: 192.168.17.27
        netmask: 255.255.255.0
        gateway: 192.168.17.254
        type: static
        domain:
        dns_servers:
        - 8.8.8.8
        - 9.9.9.9
        device_type: vmxnet3
        state: poweredoff
      wait_for_ip_address: yes
    delegate_to: localhost
    

vms_create.yaml

---
- hosts: localhost
  #connection: localhost
  gather_facts: false
    #collections:
    # - community.vmware
  tasks:
    - name: Create Virtual Machines
      vmware_guest:
        hostname: www.qq.com
        username: [email protected]
        password: Raywing@host8.
        validate_certs: false
        datacenter: Datacenter
        folder: /
        name: "{{ item.name }}"
        state: poweredoff
        guest_id: "{{ item.guest_id }}"
        hardware:
          memory_mb: "{{ item.memory }}"
          num_cpus: "{{ item.cpus }}"
        networks:
          - name: "{{ item.network }}"
        disk:
          - size_gb: "{{ item.disk_size }}"
            datastore: "{{ item.datastore }}"
      with_items:
          - { name: "vm-02", guest_id: "centos7_64Guest", memory: 2048, cpus: 2, network: "VM Network", disk_size: 10, datastore: "data" }

标签:name,linetest,虚拟机,hostname,hw,item,ansible,VCSA,guest
From: https://www.cnblogs.com/suixinnan/p/18410698

相关文章

  • ansible批量修改主机名
    (1)hosts文件[task]IP地址1 hostname=主机名1IP地址2 hostname=主机名2IP地址3 hostname=主机名3[task:vars]ansible_become=yesansible_become_method=sudoansible_become_user=rootansible_become_password=密码ansible_user=用户ansible_password=密码ansible_python_int......
  • 虚拟机热迁移技术介绍
    本文分享自天翼云开发者社区《虚拟机热迁移技术介绍》,作者:潘****东什么是虚拟机热迁移虚拟机热迁移(VirtualMachineLiveMigration)是一种技术,它允许在不中断虚拟机运行的情况下将虚拟机从一台物理主机迁移到另一台物理主机。传统上,当需要迁移虚拟机时,必须先将虚拟机关机,然后将......
  • 02-虚拟机克隆或复制后eth0不存在,不能上网的解决办法
    1.复制完虚拟机后,要正常上网,首先要重新生成新虚拟机的物理网卡地址,如下图所示,一次点击编辑虚拟机设置(1)-->选择网络适配器(2)-->点击高级选项(3)-->点击生成按钮(4),即可生成新的物理网卡地址,然后复制当前生成的网卡地址,以备后续使用。2.清空/etc/udev/rules.d/70-presistent-net.rule......
  • 05-kvm虚拟机克隆
    1、在克隆虚拟机之前,必须先暂停或者停掉kvm虚拟机第一种方法:针对虚拟机本身直接克隆(建议使用第二种方法)1执行命令virt-clonevirt-clone-ocentos6r10-ncentos6r10-c1-f/data/kvm/image/centos6r10-c1.qcow2参数说明:-o:指定源虚拟机-n:命名新克隆的虚拟机-f......
  • qumu虚拟机启动后无法远程连接
    通过virsh在启动qemu虚拟机,可以通过VNC访问虚拟机,但无法通过设置的SSH的外部映射端口登录。首先在宿主机上查看虚拟机(csv\tpm\name)的网络配置,可以看到端口映射情况和当前网络的网段(10.0.10.0/24)。$virsheditcsv_tpm_name在配置中包含访问虚拟机的VNC端口(5995),通过该......
  • centos7安装KVM虚拟机
    一、系统安装#系统下载地址(系统不能选择最小Minimal最小化版本,需要CentOS-7-x86_64-DVD-2009.iso版本)https://mirrors.aliyun.com/centos/7.9.2009/isos/x86_64/?spm=a2c6h.25603864.0.0.37a8f5adlbTtoj重要提醒:!!!1、安装系统分区目录/var/lib/libvirt/  虚拟机默认安装目录......
  • ansible模块编写
    目录1.程序为什么能识别模块a.模块是独立的脚本b.模块的路径与目录结构2.模块的工作特性a.ansible模块执行任务,会ssh到远程主机b.ansible.module_utils.basicc.核心模块(CoreModules)与插件(Plugins)的区别3.构建简单模块a.模块功能b.模块文档c.验证模块功能1.程序为什......
  • 深入理解java虚拟机---第 3 章 垃圾收集器与内存分配策略
    3.2.2可达性分析算法当前主流的商用程序语言(Java、C#,上溯至前面提到的古老的Lisp)的内存管理子系统,都是通过可达性分析(ReachabilityAnalysis)算法来判定对象是否存活的。这个算法的基本思路就是通过一系列称为“GCRoots”的根对象作为起始节点集,从这些节点开始,根据引用关......
  • 宿主机与qemu虚拟机互传文件
    ​原文:https://zhuanlan.zhihu.com/p/594235031 目录收起0背景1宿主机与qemu虚拟机互传文件2编写kodemo,做内核测试推荐阅读0背景当搭建好qemu调试arm64linux内核的环境(详见同事的文章VSCode+GDB+Qemu调试ARM64linux内......
  • 【Spark+Hive】基于大数据招聘数据分析预测推荐系统(完整系统源码+数据库+开发笔记+详
    文章目录【Spark+Hive】基于大数据招聘数据分析预测推荐系统(完整系统源码+数据库+开发笔记+详细部署教程+虚拟机分布式启动教程)源码获取方式在文章末尾一、 项目概述二、研究意义三、背景四、国内外研究现状五、开发技术介绍六、算法介绍 七、数据库设计八、系统......