how to associate floating ip address to a instance in openstack using terraform - terraform-provider-openstack

I am using terraform to create couple of instances in openstack and I would like to automatically assign floatings ip address to them without any manual intervention.
My .tf file is as below:
resource "openstack_networking_floatingip_v2" "floating-ip" {
count = 4
pool = "floating-ip-pool"
}
resource "openstack_compute_floatingip_associate_v2" "fip-associate" {
floating_ip = openstack_networking_floatingip_v2.floating-ip.address[count.0]
instance_id = openstack_compute_instance_v2.terraform-vm.id[count.0]
}`
I am getting an error
"Error: Missing resource instance key
on image-provisioning.tf line 33, in resource "openstack_compute_floatingip_associate_v2" "fip-associate":
33: instance_id = openstack_compute_instance_v2.terraform-vm.id[count.0]"
My terraform version is : Terraform v0.12.24
+ provider.openstack 1.26.0

able to resolve using for_each option in terraform :
resource "openstack_compute_instance_v2" "terraform_vm" {
image_id = "f8b9189d-2518-4a32-b1ba-2046ea8d47fd"
for_each = var.instance_name
name = each.key
flavor_id = "3"
key_pair = "openstack vm key"
security_groups = ["default"]
network {
name = "webapps-network"
}
}
resource "openstack_networking_floatingip_v2" "floating_ip" {
pool = "floating-ip-pool"
for_each = var.instance_name
}
resource "openstack_compute_floatingip_associate_v2" "fip_associate" {
for_each = var.instance_name
floating_ip = openstack_networking_floatingip_v2.floating_ip[each.key].address
instance_id = openstack_compute_instance_v2.terraform_vm[each.key].id
}

Related

Terraform - reference different variable within resource or data source dependent on some logic

With this code, I'm planning on having mulitple variables like "vms". These are key/value maps of VMs and resource groups where I for_each on the data source lookup (backupvm) to get their id. Then I can add these VMs, using id, as a backup item in vault.
data "azurerm_virtual_machine" "backupvm" {
for_each = var.vms
name = each.key
resource_group_name = each.value
}
variable "vms" {
type = map
default = {
# "vm name" = "resource group name"
"vaulttestvm1" = "vaulttestrg"
"vaulttestvm2" = "vaulttestrg"
"vaulttestvm4" = "vaulttestrg"
}
}
resource "azurerm_resource_group" "rg" {
name = var.rg_name
location = var.location
}
resource "azurerm_recovery_services_vault" "vault" {
name = var.vault_name
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
sku = "Standard"
# change later
soft_delete_enabled = false
}
resource "azurerm_backup_protected_vm" "vms" {
for_each = var.vms
recovery_vault_name = azurerm_recovery_services_vault.vault.name
resource_group_name = azurerm_recovery_services_vault.vault.resource_group_name
source_vm_id = data.azurerm_virtual_machine.backupvm[each.key].id
backup_policy_id = azurerm_backup_policy_vm.VMBackupPolicy.id
}
I need a way to reference var.vms, in both the data source & resource, so I could interchange using some logic for another map type variable. So if it was PowerShell, it would be something like:
name = if ($env -eq "prod") { $var.vms } elseif ($env -eq "stage") { $var.vmsstage } elseif ($env -eq "dev") { $var.vmsdev }
I've spent a day trying different things but haven't really got close. I may be somewhat restricted as I need to lookup the vm id using the data source first then loop through my resource (azurerm_backup_protected_vm) dropping that ID in. A solution to this would prevent me from having to use multiple data sources and resources of the same type. Thanks!

VM creation using terraform in vsphere gives An error occurred while customizing VM

provider "vsphere" {
vsphere_server = "myserver"
user = "myuser"
password = "mypass"
allow_unverified_ssl = true
version = "v1.21.0"
}
data "vsphere_datacenter" "dc" {
name = "pcloud-datacenter"
}
data "vsphere_datastore_cluster" "datastore_cluster" {
name = "pc-storage"
datacenter_id = data.vsphere_datacenter.dc.id
}
data "vsphere_compute_cluster" "compute_cluster" {
name = "pcloud-cluster"
datacenter_id = data.vsphere_datacenter.dc.id
}
data "vsphere_network" "network" {
name = "u32c01p26-1514"
datacenter_id = data.vsphere_datacenter.dc.id
}
data "vsphere_virtual_machine" "vm_template" {
name = "first-terraform-vm"
datacenter_id = data.vsphere_datacenter.dc.id
}
resource "vsphere_virtual_machine" "vm" {
count = 1
name = "first-terraform-vm-1"
resource_pool_id = data.vsphere_compute_cluster.compute_cluster.resource_pool_id
datastore_cluster_id = data.vsphere_datastore_cluster.datastore_cluster.id
num_cpus = 2
memory = 1024
wait_for_guest_ip_timeout = 2
wait_for_guest_net_timeout = 0
guest_id = data.vsphere_virtual_machine.vm_template.guest_id
scsi_type = data.vsphere_virtual_machine.vm_template.scsi_type
network_interface {
network_id = data.vsphere_network.network.id
adapter_type = data.vsphere_virtual_machine.vm_template.network_interface_types[0]
}
disk {
name = "disk0.vmdk"
size = data.vsphere_virtual_machine.vm_template.disks.0.size
eagerly_scrub = data.vsphere_virtual_machine.vm_template.disks.0.eagerly_scrub
thin_provisioned = data.vsphere_virtual_machine.vm_template.disks.0.thin_provisioned
}
folder = "virtual-machines"
clone {
template_uuid = data.vsphere_virtual_machine.vm_template.id
customize {
linux_options {
host_name = "first-terraform-vm-1"
domain = "localhost.localdomain"
}
network_interface {
ipv4_address = "10.10.14.100"
ipv4_netmask = 24
}
ipv4_gateway = "10.10.14.1"
}
}
}
The command terraform script throws the below error
Error:
Virtual machine customization failed on "/pcloud-datacenter/vm/virtual-machines/first-terraform-vm-1":
An error occurred while customizing VM first-terraform-vm-1. For details reference the log file <No Log> in the guest OS.
The virtual machine has not been deleted to assist with troubleshooting. If
corrective steps are taken without modifying the "customize" block of the
resource configuration, the resource will need to be tainted before trying
again. For more information on how to do this, see the following page:
https://www.terraform.io/docs/commands/taint.html
on create_vm.tf line 34, in resource "vsphere_virtual_machine" "vm":
34: resource "vsphere_virtual_machine" "vm" {
Some how the generated vm "first-terraform-vm-1" doesn't have the connected box checked-in in network settings. While i checked my template "first-terraform-vm" it has network connected box checked-in.
I see similar post in github https://github.com/hashicorp/terraform-provider-vsphere/issues/951
But not sure why this issue is still surfacing?
Vsphere version: 6.7
Terraform v0.12.28
provider.vsphere v1.21.0
Is there anything wrong with my template? Or am i missing something? Can anyone help please? Stuck with this for last 2 days.
The problem looks to be with the template that i have used. The linux template should have Network Manager installed and running. It looks like terraform uses the network manager to assign IPaddress for newly created vm.

Declaring list and map variable values in terraform.tfvars

I recently moved over the values for my variables within my terraform code to terraform.tfvars. I am now getting an error that is due to how I am declaring my list and map variables. The code where I am getting the error is replicated below:
image_id = var.web_amis[var.region]
this is how I have these variables specified in terraform.tfvars:
web_amis = ["ami-0dacb0c129b49f529", "ami-00068cd7555f543d5", ]
this is the error code I am getting:
Error: Invalid index
on autoscaling.tf line 3, in resource "aws_launch_configuration" "web_lc":
3: image_id = var.web_amis[var.region]
|----------------
| var.region is "us-east-2"
| var.web_amis is tuple with 2 elements
The given key does not identify an element in this collection value: a number
is required.
You're trying to access a list element with a non index key instead of by position.
What you probably want instead is to have your web_amis variable be a map that is keyed by the region name:
main.tf
variable "region" {}
variable "web_amis" {}
resource "foo_bar" "baz" {
# ...
image_id = var.web_amis[var.region]
}
terraform.tfvars
web_amis = {
us-east-2 = "ami-0dacb0c129b49f529"
us-west-2 = "ami-00068cd7555f543d5"
}
But, this is a very old school and inelegant way of doing things with Terraform nowadays. Instead you could use the aws_ami data source to look up the AMI for the region based on filters such as tags or the name of the AMI.
A basic example is given in the aws_instance resource documentation:
provider "aws" {
region = "us-west-2"
}
data "aws_ami" "ubuntu" {
most_recent = true
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-trusty-14.04-amd64-server-*"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
owners = ["099720109477"] # Canonical
}
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t2.micro"
tags = {
Name = "HelloWorld"
}
}

Terraform 0.12.5 | Bigquery table resource doesn't support external data configuration block

I'm creating a module to make easy to provision a BigQuery table in GCP.
My module is working, but now I'm trying to add the option to create the table based in external data, like a GCS bucket.
In the doc (https://www.terraform.io/docs/providers/google/r/bigquery_table.html#external_data_configuration) are saying this configuration is supported, but I get only this error:
Acquiring state lock. This may take a few moments...
Error: Unsupported block type
on ../../modules/bq_table/main.tf line 24, in resource "google_bigquery_table" "default":
24: external_data_configuration {
Blocks of type "external_data_configuration" are not expected here.
Im using the last Terraform version (0.12.5) and google provider v2.10.0 in Mac OS.
Here is my module code in HCL2:
resource "google_bigquery_table" "default" {
dataset_id = "${terraform.workspace}_${var.bq_dataset_id}"
table_id = "${terraform.workspace}_${var.bq_table_id}"
project = (var.project_id != "" ? var.project_id : null)
description = (var.bq_table_description != "" ? var.project_id : null)
expiration_time = (var.bq_table_expiration_time != null ? var.project_id : null)
friendly_name = (var.bq_table_name != "" ? var.project_id : null)
dynamic "external_data_configuration" {
for_each = var.bq_table_external_data_configuration
content {
autodetect = true
source_format = "NEWLINE_DELIMITED_JSON"
source_uris = [external_data_configuration.value]
}
}
time_partitioning {
type = "DAY"
field = var.bq_table_partition_field
}
labels = var.bq_table_labels
schema = (var.bq_table_schema != "" ? var.bq_table_schema : null)
dynamic "view" {
for_each = (var.bq_table_view_query != "" ? {query = var.bq_table_view_query} : {})
content {
query = view.value
}
}
depends_on = ["null_resource.depends_on"]
}
Above im using Dynamic blocks, but tried to use normally and the error is the same.
The for_each property inside your dynamic block expects an array value. Try wrapping the input variable in an array:
dynamic "external_data_configuration" {
for_each = var.bq_table_external_data_configuration ? [var.bq_table_external_data_configuration] : []
content {
autodetect = true
source_format = "NEWLINE_DELIMITED_JSON"
source_uris = [external_data_configuration.value]
}
}
Conditional blocks are still a bit of a hassle even after Terraform 0.12; read here for more.

Terraform Variables prompting me when defined in tfvars

There is something that I am not understanding about terraform variables. I am getting prompted for two variables in when I run "terraform apply". I don't think that I should be prompted for any as I defined a terraform.tfvars. I am getting prompted for (applicationNamespace, and staticIpName) but I am not sure why. What am I misunderstanding?
I created a file (terraform.tfvars):
#--------------------------------------------------------------
# General
#--------------------------------------------------------------
cluster = "reddiyo-development"
project = "<MYPROJECTID>"
region = "us-central1"
credentialsLocation = "<MYCERTLOCATION>"
bucket = "reddiyo-terraform-state"
vpcLocation = "us-central1-b"
network = "default"
staticIpName = "dev-env-ip"
#--------------------------------------------------------------
# Specific To NODE
#--------------------------------------------------------------
terraformPrefix = "development"
mainNodeName = "primary-pool"
nodeMachineType = "n1-standard-1"
#--------------------------------------------------------------
# Specific To Application
#--------------------------------------------------------------
applicationNamespace = "application"
I also have a terrform script:
variable "cluster" {}
variable "project" {}
variable "region" {}
variable "bucket" {}
variable "terraformPrefix" {}
variable "mainNodeName" {}
variable "vpcLocation" {}
variable "nodeMachineType" {}
variable "credentialsLocation" {}
variable "network" {}
variable "applicationNamespace" {}
variable "staticIpName" {}
data "terraform_remote_state" "remote" {
backend = "gcs"
config = {
bucket = "${var.bucket}"
prefix = "${var.terraformPrefix}"
}
}
provider "google" {
//This needs to be updated to wherever you put your credentials
credentials = "${file("${var.credentialsLocation}")}"
project = "${var.project}"
region = "${var.region}"
}
resource "google_container_cluster" "gke-cluster" {
name = "${var.cluster}"
network = "${var.network}"
location = "${var.vpcLocation}"
remove_default_node_pool = true
# node_pool {
# name = "${var.mainNodeName}"
# }
node_locations = [
"us-central1-a",
"us-central1-f"
]
//Get your credentials for the newly created cluster so that microservices can be deployed
provisioner "local-exec" {
command = "gcloud config set project ${var.project}"
}
provisioner "local-exec" {
command = "gcloud container clusters get-credentials ${var.cluster} --zone ${var.vpcLocation}"
}
}
resource "google_container_node_pool" "primary_pool" {
name = "${var.mainNodeName}"
cluster = "${var.cluster}"
location = "${var.vpcLocation}"
node_count = "2"
node_config {
machine_type = "${var.nodeMachineType}"
oauth_scopes = [
"https://www.googleapis.com/auth/logging.write",
"https://www.googleapis.com/auth/monitoring",
"https://www.googleapis.com/auth/devstorage.read_only",
"https://www.googleapis.com/auth/service.management.readonly",
"https://www.googleapis.com/auth/servicecontrol",
"https://www.googleapis.com/auth/trace.append",
]
}
management {
auto_repair = true
auto_upgrade = true
}
autoscaling {
min_node_count = 2
max_node_count = 10
}
}
# //Reserve a Static IP
resource "google_compute_address" "ip_address" {
name = "${var.staticIpName}"
}
//Install Ambassador
module "ambassador" {
source = "modules/ambassador"
applicationNamespace = "${var.applicationNamespace}"
}
You can try to force it to read your variables by using:
terraform apply -var-file=<path_to_your_vars>
For reference, read below, if anybody face the similar issue.
“terraform.tfvars” is the default variable file name, from where terraform will read variables.
If any other file name is used, it needs to be passed in the command line i.e: “terraform plan –var=whateverName.tfvars
Also, order of Loading for variables by Terraform program.
Environment Variables
terraform.tfvars
terraform.tfvars.json
Any .auto.tfvars
Any –var or –var-file options