2

I successfull made the virtual machine in Azure with Terraform ( from a Packer image). After the Virtual machine created, I would run some commands remotely on the newly created machine.

The machine has a piblic ip but that ip attached dynamically to the new resource group what created by terrafrom. In this case I not know the puclic ip before the terraform starts.

Unfortunately the remote-exec provisioner needs an ip to connect for and ssh connect. How can I solva that issue?

1

You have two method could do this.

1.When you create VM, using DNS name. HOST is <dns name>.<location>.cloudapp.azure.com.

In tf file, Create public IP like below:

# create public IPs
resource "azurerm_public_ip" "ip" {
    name = "tfip"
    location = "ukwest"
    resource_group_name = "${azurerm_resource_group.rg.name}"
    public_ip_address_allocation = "dynamic"
    domain_name_label = "sometestdn"

    tags {
        environment = "staging"
    }
}

Create connection like below:

   connection {
        host = "sometestdn.ukwest.cloudapp.azure.com"
        user = "testuser"
        type = "ssh"
        private_key = "${file("~/.ssh/id_rsa_unencrypted")}"
        timeout = "1m"
        agent = true
    }

    provisioner "remote-exec" {
        inline = [
          "sudo apt-get update",
          "sudo apt-get install docker.io -y",
          "git clone https://github.com/somepublicrepo.git",
          "cd Docker-sample",
          "sudo docker build -t mywebapp .",
          "sudo docker run -d -p 5000:5000 mywebapp"
        ]
    }

2.Use Azure Custom Script Extension.

The Custom Script Extension downloads and executes scripts on Azure virtual machines. This extension is useful for post deployment configuration, software installation, or any other configuration / management task.

You could write your tf like below:

resource "azurerm_virtual_machine_extension" "helloterraformvm" {
  name                 = "hostname"
  location             = "West US"
  resource_group_name  = "${azurerm_resource_group.helloterraformvm.name}"
  virtual_machine_name = "${azurerm_virtual_machine.helloterraformvm.name}"
  publisher            = "Microsoft.OSTCExtensions"
  type                 = "CustomScriptForLinux"
  type_handler_version = "1.2"

  settings = <<SETTINGS
    {
        "commandToExecute": "apt-get install docker.io -y"
    }
SETTINGS
}

More information please refer to this similar question.

2
  • Works. thank you. The "Terraform" label would very helpful in superuser.com – GergA Nov 23 '17 at 10:11
  • Ofcourse I do that – GergA Nov 24 '17 at 9:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.