Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add virtual machines data sources #2463

Merged
merged 6 commits into from
Dec 14, 2018
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions azurerm/data_source_arm_virtual_machine.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package azurerm

import (
"fmt"

"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)

func dataSourceArmVirtualMachine() *schema.Resource {
return &schema.Resource{
Read: dataSourceArmVMRead,
Schema: map[string]*schema.Schema{
"resource_group_name": resourceGroupNameForDataSourceSchema(),

"name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.NoZeroValues,
},
},
}
}

func dataSourceArmVMRead(d *schema.ResourceData, meta interface{}) error {
inkel marked this conversation as resolved.
Show resolved Hide resolved
client := meta.(*ArmClient).vmClient
ctx := meta.(*ArmClient).StopContext

resGroup := d.Get("resource_group_name").(string)
name := d.Get("name").(string)

resp, err := client.Get(ctx, resGroup, name, "")
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
return fmt.Errorf("Error: Virtual Machine %q (Resource Group %q) was not found", name, resGroup)
}

return fmt.Errorf("Error making Read request on Virtual Machine %q (Resource Group %q): %+v", name, resGroup, err)
}

d.SetId(*resp.ID)

return nil
}
117 changes: 117 additions & 0 deletions azurerm/data_source_arm_virtual_machine_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package azurerm

import (
"fmt"
"testing"

"github.com/hashicorp/terraform/helper/resource"

"github.com/hashicorp/terraform/helper/acctest"
)

func TestAccDataSourceVirtualMachine_basic(t *testing.T) {
dataSourceName := "data.azurerm_virtual_machine.test"
ri := acctest.RandInt()

name := fmt.Sprintf("acctvm-%d", ri)
config := testAccDataSourceVirtualMachine_basic(ri, testLocation())

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: config,
Check: resource.TestCheckResourceAttr(dataSourceName, "name", name),
},
},
})
}

func testAccDataSourceVirtualMachine_basic(rInt int, location string) string {
return fmt.Sprintf(`
resource "azurerm_resource_group" "test" {
name = "acctestRG-%[1]d"
location = "%[2]s"
}

resource "azurerm_virtual_network" "test" {
name = "acctvn-%[1]d"
address_space = ["10.0.0.0/16"]
location = "${azurerm_resource_group.test.location}"
resource_group_name = "${azurerm_resource_group.test.name}"
}

resource "azurerm_subnet" "test" {
name = "acctsub-%[1]d"
resource_group_name = "${azurerm_resource_group.test.name}"
virtual_network_name = "${azurerm_virtual_network.test.name}"
address_prefix = "10.0.2.0/24"
}

resource "azurerm_network_interface" "test" {
name = "acctni-%[1]d"
location = "${azurerm_resource_group.test.location}"
resource_group_name = "${azurerm_resource_group.test.name}"

ip_configuration {
name = "testconfiguration1"
subnet_id = "${azurerm_subnet.test.id}"
private_ip_address_allocation = "dynamic"
}
}

resource "azurerm_storage_account" "test" {
name = "accsa%[1]d"
resource_group_name = "${azurerm_resource_group.test.name}"
location = "${azurerm_resource_group.test.location}"
account_tier = "Standard"
account_replication_type = "LRS"
}

resource "azurerm_storage_container" "test" {
name = "vhds"
resource_group_name = "${azurerm_resource_group.test.name}"
storage_account_name = "${azurerm_storage_account.test.name}"
container_access_type = "private"
}

resource "azurerm_virtual_machine" "test" {
name = "acctvm-%[1]d"
location = "${azurerm_resource_group.test.location}"
resource_group_name = "${azurerm_resource_group.test.name}"
network_interface_ids = ["${azurerm_network_interface.test.id}"]
vm_size = "Standard_D1_v2"

storage_image_reference {
publisher = "MicrosoftWindowsServer"
offer = "WindowsServer"
sku = "2012-Datacenter"
version = "latest"
}

storage_os_disk {
name = "myosdisk1"
vhd_uri = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd"
caching = "ReadWrite"
create_option = "FromImage"
}

os_profile {
computer_name = "winhost01"
admin_username = "testadmin"
admin_password = "Password1234!"
}

os_profile_windows_config {
timezone = "Pacific Standard Time"
}
}

data "azurerm_virtual_machine" "test" {
resource_group_name = "${azurerm_resource_group.test.name}"
name = "${azurerm_virtual_machine.test.name}"
}

`, rInt, location)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it'd be better to use a Linux VM here (since they tend to boot faster)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just copied the same definition from azurerm/data_source_arm_virtual_network_test.go, but sure, I can do that 👌

}
71 changes: 71 additions & 0 deletions azurerm/data_source_arm_virtual_machines.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package azurerm
inkel marked this conversation as resolved.
Show resolved Hide resolved

import (
"fmt"
"strings"
"time"

"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
)

func dataSourceArmVirtualMachines() *schema.Resource {
return &schema.Resource{
Read: dataSourceArmVMsRead,
Schema: map[string]*schema.Schema{
"resource_group_name": resourceGroupNameForDataSourceSchema(),

"name_prefix": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.NoZeroValues,
},

"ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},

"names": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}

func dataSourceArmVMsRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).vmClient
ctx := meta.(*ArmClient).StopContext

resGroup := d.Get("resource_group_name").(string)
namePrefix := d.Get("name_prefix").(string)

resp, err := client.List(ctx, resGroup)
if err != nil {
return fmt.Errorf("Error listing Virtual Machines in the Resource Group %q: %v", resGroup, err)
}

var ids []string
var names []string

for _, vm := range resp.Values() {
if strings.HasPrefix(*vm.Name, namePrefix) {
ids = append(ids, *vm.ID)
names = append(names, *vm.Name)
}
}

d.SetId(time.Now().UTC().String())

if err := d.Set("ids", ids); err != nil {
return fmt.Errorf("Error setting `ids`: %+v", err)
}
if err := d.Set("names", names); err != nil {
return fmt.Errorf("Error setting `names`: %+v", err)
}

return nil
}
2 changes: 2 additions & 0 deletions azurerm/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,8 @@ func Provider() terraform.ResourceProvider {
"azurerm_subscription": dataSourceArmSubscription(),
"azurerm_subscriptions": dataSourceArmSubscriptions(),
"azurerm_traffic_manager_geographical_location": dataSourceArmTrafficManagerGeographicalLocation(),
"azurerm_virtual_machine": dataSourceArmVirtualMachine(),
"azurerm_virtual_machines": dataSourceArmVirtualMachines(),
"azurerm_virtual_network": dataSourceArmVirtualNetwork(),
"azurerm_virtual_network_gateway": dataSourceArmVirtualNetworkGateway(),
},
Expand Down
33 changes: 33 additions & 0 deletions website/docs/d/virtual_machine.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
---
inkel marked this conversation as resolved.
Show resolved Hide resolved
layout: "azurerm"
page_title: "Azure Resource Manager: azurerm_virtual_machine"
sidebar_current: "docs-azurerm-datasource-virtual-machine-x"
inkel marked this conversation as resolved.
Show resolved Hide resolved
description: |-
Gets information about an existing Virtual Machine.
---

# Data Source: azurerm_virtual_machine

Use this data source to access information about an existing Virtual Machine.

## Example Usage

```hcl
data "azurerm_virtual_machine" "test" {
name = "production"
resource_group_name = "networking"
}

output "virtual_machine_id" {
value = "${data.azurerm_virtual_machine.test.id}"
}
```

## Argument Reference

* `name` - (Required) Specifies the name of the Virtual Machine.
* `resource_group_name` - (Required) Specifies the name of the resource group the Virtual Machine is located in.

## Attributes Reference

* `id` - The ID of the Virtual Machine.
38 changes: 38 additions & 0 deletions website/docs/d/virtual_machines.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
---
inkel marked this conversation as resolved.
Show resolved Hide resolved
layout: "azurerm"
page_title: "Azure Resource Manager: azurerm_virtual_machines"
sidebar_current: "docs-azurerm-datasource-virtual-machines-x"
description: |-
Gets information about existing Virtual Machines.
---

# Data Source: azurerm_virtual_machines

Use this data source to access information about existing Virtual Machines.

## Example Usage

```hcl
data "azurerm_virtual_machines" "test" {
name_prefix = "prod-"
resource_group_name = "networking"
}

output "virtual_machine_ids" {
value = "${join(", ", data.azurerm_virtual_machine.test.ids)}"
}

output "virtual_machine_names" {
value = "${join(", ", data.azurerm_virtual_machine.test.names)}"
}
```

## Argument Reference

* `name_prefix` - (Optional) Specifies the prefix to match the name of the Virtual Machines.
* `resource_group_name` - (Required) Specifies the name of the resource group the Virtual Machines are located in.

## Attributes Reference

* `ids` - List of IDs of the Virtual Machines.
* `names` - List of names of the Virtual Machines.