Ansible - пометка Azure работающих виртуальных машин - PullRequest
0 голосов
/ 31 августа 2018

Сегодня я работаю над поиском лучшего способа автоматически помечать работающие виртуальные машины в Azure из Ansible.

Первый подход заключался в использовании модуля azure_rm_virtualmachine, но он прекрасно работает во время развертывания новой виртуальной машины. Когда виртуальная машина запущена и работает, это другая история, в основном, когда развертывание было выполнено с использованием пользовательских образов.

  - name: Tag my VM
    azure_rm_virtualmachine:
      resource_group: myresourcegroup
      name: myvm
      admin_username: ansible
      admin_password: mypassword
      virtual_network_name: myvnet
      virtual_network_resource_group: myvnetrsg
      vm_size: Standard_D2_v2
      state: present
      started: no
      append_tags: True
      image:
        name: mycustomimage
        resource_group: myimagesrsg
      tags:
        env: "dev"

См .: https://github.com/ansible/ansible/issues/35235 решено в 2.7, но все еще не работает с пользовательскими изображениями.

Итак, вопрос в том, как это сделать с запущенными виртуальными машинами? Как изменить старые теги и добавить новые?

1 Ответ

0 голосов
/ 31 августа 2018

Вопрос использует azure_rm_deployment вместе с azure_rm_virtualmachine.

С помощью azure_rm_virtualmachine мы регистрируем факты и добавляем их в переменную:

  - name: Azure Facts
    azure_rm_virtualmachine:
      name: myvm
      resource_group: myrsg
    register: myvm

Затем разверните ВМ, используя шаблон JSON с azure_rm_deployment, но сохраняя важные значения для ВМ:

Примечание: переменные для справки, работайте с ними должным образом, чтобы они оставались чистыми и управляемыми:

- name: Create Azure VM from ARM template with public IP
    azure_rm_deployment:
      state: present
      deployment_name: mydeployment
      location: mylocation
      resource_group_name: myresorcegroup
      wait_for_deployment_completion: yes
      template: "{{ lookup('template', 'azure.json') }}"
      parameters:
        tags:
          value: "{{ vmtags }}"
        adminUsername:
          value: "{{ myvm.ansible_facts.azure_vm.properties.osProfile.adminUsername }}"
        adminPassword:
          value: mypassword
        imageName:
          value: "{{ myvm.ansible_facts.azure_vm.properties.storageProfile.imageReference.id | basename }}"
        imageResourceGroup:
          value: myimagesrsg
        dnsLabelPrefix:
          value: "{{ myvm.ansible_facts.azure_vm.properties.networkProfile.networkInterfaces[0].properties.ipConfigurations[0].properties.publicIPAddress.properties.dnsSettings.domainNameLabel }}"
        vmName:
          value: myvm
        ComputerName:
          value: "{{ myvm.ansible_facts.azure_vm.properties.osProfile.computerName }}"
        vmResourceGroup:
          value: myrsg
        nicName:
          value: "{{ myvm.ansible_facts.azure_vm.properties.networkProfile.networkInterfaces[0].name }}"
        virtualNetworkName:
          value: "{{myvm.ansible_facts.azure_vm.properties.networkProfile.networkInterfaces[0].properties.ipConfigurations[0].properties.subnet.id.split('/')[-3] }}"
        publicIPAddressName:
          value: "{{ myvm.ansible_facts.azure_vm.properties.networkProfile.networkInterfaces[0].properties.ipConfigurations[0].properties.publicIPAddress.name }}"
        subnetName:
          value: "{{ myvm.ansible_facts.azure_vm.properties.networkProfile.networkInterfaces[0].properties.ipConfigurations[0].properties.subnet.id | basename }}"
        vmSize:
          value: "{{ myvm.ansible_facts.azure_vm.properties.hardwareProfile.vmSize }}"
        storageAccountType:
          value: "{{ myvm.ansible_facts.azure_vm.properties.storageProfile.osDisk.managedDisk.storageAccountType }}"

Пароль не изменится, имя виртуальной машины и группы ресурсов уже известны, а теги - это словарь, подобный следующему:

  vars:
    vmtags:
        MyFirstDay: "Saturday"
        Env: "dev"

А шаблон JSON?

JSON - это стандартный шаблон Azure, но с тегами, добавленными как объект :

{
    "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "tags": {
            "type": "object"
        },
        "adminUsername": {
            "type": "string"
        },
        "adminPassword": {
            "type": "securestring"
        },
        "vmName": {
            "type": "string"
        },
        "ComputerName": {
            "type": "string"
        },
        "imageName": {
            "type": "string"
        },
        "imageResourceGroup": {
            "type": "string"
        },
        "vmSize": {
            "type": "string"
        },
        "vmResourceGroup": {
            "type": "string"
        },
        "virtualNetworkName": {
            "type": "string"
        },
        "nicName": {
            "type": "string"
        },
        "subnetName": {
            "type": "string"
        },
        "dnsLabelPrefix": {
            "type": "string"
        },
        "publicIPAddressName": {
            "type": "string"
        },
        "storageAccountType": {
            "type": "string"
        }
    },
    "variables": {
        "apiVersion": "2015-06-15",
        "publicIPAddressType": "Dynamic",
        "privateIPAddressType": "Dynamic",
        "addressPrefix": "10.0.0.0/16",
        "subnetPrefix": "10.0.0.0/24",
        "vnetID": "[resourceId('Microsoft.Network/virtualNetworks',parameters('virtualNetworkName'))]",
        "subnetRef": "[concat(variables('vnetID'),'/subnets/',parameters('subnetName'))]",
        "sshKeyPath": "[concat('/home/',parameters('adminUsername'),'/.ssh/authorized_keys')]",
        "hostDNSNameScriptArgument": "[concat('*.',resourceGroup().location,'.cloudapp.azure.com')]"
    },
    "resources": [{
            "apiVersion": "[variables('apiVersion')]",
            "type": "Microsoft.Network/publicIPAddresses",
            "name": "[parameters('publicIPAddressName')]",
            "location": "[resourceGroup().location]",
            "properties": {
                "publicIPAllocationMethod": "[variables('publicIPAddressType')]",
                "dnsSettings": {
                    "domainNameLabel": "[parameters('dnsLabelPrefix')]"
                }
            }
        },
        {
            "apiVersion": "[variables('apiVersion')]",
            "type": "Microsoft.Network/virtualNetworks",
            "name": "[parameters('virtualNetworkName')]",
            "location": "[resourceGroup().location]",
            "properties": {
                "addressSpace": {
                    "addressPrefixes": [
                        "[variables('addressPrefix')]"
                    ]
                },
                "subnets": [{
                    "name": "[parameters('subnetName')]",
                    "properties": {
                        "addressPrefix": "[variables('subnetPrefix')]"
                    }
                }]
            }
        },
        {
            "apiVersion": "[variables('apiVersion')]",
            "type": "Microsoft.Network/networkInterfaces",
            "name": "[parameters('nicName')]",
            "location": "[resourceGroup().location]",
            "dependsOn": [
                "[concat('Microsoft.Network/publicIPAddresses/', parameters('publicIPAddressName'))]",
                "[concat('Microsoft.Network/virtualNetworks/', parameters('virtualNetworkName'))]"
            ],
            "properties": {
                "ipConfigurations": [{
                    "name": "ipconfig1",
                    "properties": {
                        "privateIPAllocationMethod": "[variables('privateIPAddressType')]",
                        "publicIPAddress": {
                            "id": "[resourceId('Microsoft.Network/publicIPAddresses',parameters('publicIPAddressName'))]"
                        },
                        "subnet": {
                            "id": "[variables('subnetRef')]"
                        }
                    }
                }]
            }
        },
        {
            "name": "[parameters('vmName')]",
            "type": "Microsoft.Compute/virtualMachines",
            "apiVersion": "2016-04-30-preview",
            "location": "[resourceGroup().location]",
            "tags": "[parameters('tags')]",
            "dependsOn": [
                "[concat('Microsoft.Network/networkInterfaces/', parameters('nicName'))]"
            ],
            "properties": {
                "osProfile": {
                    "computerName": "[parameters('ComputerName')]",
                    "adminUsername": "[parameters('adminUsername')]",
                    "adminPassword": "[parameters('adminPassword')]"
                },
                "hardwareProfile": {
                    "vmSize": "[parameters('vmSize')]"
                },
                "storageProfile": {
                    "imageReference": {
                        "id": "[resourceId(parameters('imageResourceGroup'),'Microsoft.Compute/images', parameters('imageName'))]"
                    },
                    "osDisk": {
                        "name": "[concat(parameters('vmName'),'_OsDisk')]",
                        "createOption": "FromImage",
                        "managedDisk": {
                            "storageAccountType": "[parameters('storageAccountType')]"
                        }
                    }
                },
                "networkProfile": {
                    "networkInterfaces": [{
                        "id": "[resourceId('Microsoft.Network/networkInterfaces', parameters('nicName'))]"
                    }]
                }
            }
        }
    ]
}

По сути, это первый подход, и переменные именования, способ применения и т. Д. Будут меняться более оптимизированным образом. Я буду обновлять это при улучшении.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...