Недопустимая символьная ошибка при выполнении инициализации terraform, плана terraform или применения - PullRequest
0 голосов
/ 25 апреля 2020

Я использую Terraform, используя редактор VScode, который использует PowerShell в качестве оболочки по умолчанию, и получаю ту же ошибку, когда пытаюсь проверить ее или запустить terraform init / plan / apply через VScode, внешний PowerShell или CMD.

Код работал без проблем, пока я не добавил код создания виртуальной машины. Я разбил переменныеs.tf, terraform.tfvars и основной код Terraform ниже.

terraform.tfvars

web_server_location       = "West US 2"
resource_prefix           = "web-server"
web_server_address_space  = "1.0.0.0/22"
web_server_address_prefix = "1.0.1.0/24"
Environment               = "Test"

variables.tf

variable "web_server_location" {
  type = string
}

variable "resource_prefix" {
  type = string
}

variable "web_server_address_space" {
  type = string
}

#variable for network range

variable "web_server_address_prefix" {
  type = string
}

#variable for Environment
variable "Environment" {
  type = string
}

terraform_example.tf

# Configure the Azure Provider
provider "azurerm" {
  # whilst the `version` attribute is optional, we recommend pinning to a given version of the Provider
  version = "=2.0.0"
  features {}
}

# Create a resource group
resource "azurerm_resource_group" "example_rg" {
  name     = "${var.resource_prefix}-RG"
  location = var.web_server_location
}

# Create a virtual network within the resource group
resource "azurerm_virtual_network" "example_vnet" {
  name                = "${var.resource_prefix}-vnet"
  resource_group_name = azurerm_resource_group.example_rg.name
  location            = var.web_server_location
  address_space       = [var.web_server_address_space]
}

# Create a subnet within the virtual network
resource "azurerm_subnet" "example_subnet" {
  name                  = "${var.resource_prefix}-subnet"
  resource_group_name   = azurerm_resource_group.example_rg.name
  virtual_network_name  = azurerm_virtual_network.example_vnet.name
  address_prefix        = var.web_server_address_prefix
}

# Create a Network Interface
resource "azurerm_network_interface" "example_nic" {
  name                = "${var.resource_prefix}-NIC"
  location            = azurerm_resource_group.example_rg.location
  resource_group_name = azurerm_resource_group.example_rg.name

  ip_configuration {
    name                          = "internal"
    subnet_id                     = azurerm_subnet.example_subnet.id
    private_ip_address_allocation = "Dynamic"
    public_ip_address_id          = azurerm_public_ip.example_public_ip.id
  }  
}

# Create a Public IP 
resource "azurerm_public_ip" "example_public_ip" {
  name = "${var.resource_prefix}-PublicIP"
  location = azurerm_resource_group.example_rg.location
  resource_group_name = azurerm_resource_group.example_rg.name
  allocation_method = var.Environment == "Test" ? "Static" : "Dynamic"

  tags = {
    environment = "Test"
  }
}

# Creating resource NSG
resource "azurerm_network_security_group" "example_nsg" {
  name = "${var.resource_prefix}-NSG"
  location = azurerm_resource_group.example_rg.location
  resource_group_name = azurerm_resource_group.example_rg.name

  # Security rule can also be defined with resource azurerm_network_security_rule, here just defining it inline. 
  security_rule {
    name       = "RDPInbound"
    priority   = 100
    direction  = "Inbound"
    access     = "Allow"
    protocol   = "Tcp"
    source_port_range = "*"
    destination_port_range = "3389"
    source_address_prefix  = "*"
    destination_address_prefix = "*"
  }
  tags = {
    environment = "Test"
  }
}

# NIC and NSG association 
resource "azurerm_network_interface_security_group_association" "example_nsg_association" {
   network_interface_id      = azurerm_network_interface.example_nic.id
   network_security_group_id = azurerm_network_security_group.example_nsg.id

}

# Creating Windows Virtual Machine
resource "azurerm_virtual_machine" "example_windows_vm" {
  name  = "${var.resource_prefix}-VM"
  location = azurerm_resource_group.example_rg.location
  resource_group_name = azurerm_resource_group.example_rg.name
  network_interface_ids = [azurerm_network_interface.example_nic.id]
  vm_size = "Standard_B1s"
  delete_os_disk_on_termination = true

  storage_image_reference {
    publisher = "MicrosoftWindowsServer"
    offer     = "WindowsServerSemiAnnual"
    sku       = "Datacenter-Core-1709-smalldisk"
    version   = "latest"  
  }

  storage_os_disk  {
    name                 = "myosdisk1"
    caching              = "ReadWrite"
    create_option        = "FromImage"
    storage_account_type = "Standard_LRS"
  }

  os_profile {
    computer_name  = "hostname"
    admin_username = "adminuser"
    admin_password = "Password1234!"
  }

  os_profile_windows_config {
    disable_password_authentication = false
  }

  tags = {
    environment = "Test"
  }
}

Ошибка:

PS C:\Users\e5605266\Documents\MyFiles\Devops\Terraform> terraform init

There are some problems with the configuration, described below.

The Terraform configuration must be valid before initialization so that
Terraform can determine which modules and providers need to be installed.

Error: Invalid character

  on terraform_example.tf line 89, in resource "azurerm_virtual_machine" "example_windows_vm":
  89:   location                      = azurerm_resource_group.example_rg.location

This character is not used within the language.


Error: Invalid expression

  on terraform_example.tf line 89, in resource "azurerm_virtual_machine" "example_windows_vm":
  89:   location                      = azurerm_resource_group.example_rg.location

Expected the start of an expression, but found an invalid expression token.


Error: Argument or block definition required

  on terraform_example.tf line 90, in resource "azurerm_virtual_machine" "example_windows_vm":
  90:   resource_group_name           = azurerm_resource_group.example_rg.name

An argument or block definition is required here. To set an argument, use the
equals sign "=" to introduce the argument value.


Error: Invalid character

  on terraform_example.tf line 90, in resource "azurerm_virtual_machine" "example_windows_vm":
  90:   resource_group_name           = azurerm_resource_group.example_rg.name

This character is not used within the language.
*

1 Ответ

0 голосов
/ 26 апреля 2020

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

Этот блок ресурсов, кажется, где это сталкивается с проблемами:

resource "azurerm_virtual_machine" "example_windows_vm" {
  name  = "${var.resource_prefix}-VM"
  location = azurerm_resource_group.example_rg.location
  resource_group_name = azurerm_resource_group.example_rg.name
  network_interface_ids = [azurerm_network_interface.example_nic.id]
  vm_size = "Standard_B1s"
  delete_os_disk_on_termination = true

  storage_image_reference {
    publisher = "MicrosoftWindowsServer"
    offer     = "WindowsServerSemiAnnual"
    sku       = "Datacenter-Core-1709-smalldisk"
    version   = "latest"  
  }

  storage_os_disk  {
    name                 = "myosdisk1"
    caching              = "ReadWrite"
    create_option        = "FromImage"
    storage_account_type = "Standard_LRS"
  }

  os_profile {
    computer_name  = "hostname"
    admin_username = "adminuser"
    admin_password = "Password1234!"
  }

  os_profile_windows_config {
    disable_password_authentication = false
  }

  tags = {
    environment = "Test"
  }
}

Попробуйте скопировать это обратно в ваш редактор, как есть. Я не вижу никаких проблемных символов c в нем, и по иронии судьбы StackOverflow мог сделать вам solid и отфильтровать их. Буквальное копирование / вставка его поверх существующего блока может исправить ситуацию.

Я видел примеры Terraform онлайн с двойными кавычками Styli sh (которые не являются двойными кавычками ASCII и не будут работать) много раз. Это может быть то, что вы видите.

Кроме того, вам нужно будет sh выложить свой код в GitHub или аналогичный, чтобы я мог видеть необработанные байты для себя.

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