SlideShare a Scribd company logo
1
Desplegar Cosmos DB usando Terraform
Introducción
En este ejercicio se desplegarán recursos de Azure utilizando Terraform, en concreto se van a crear los
siguientes elementos:
• Grupo de recursos.
• Cuenta Cosmos DB.
• Base de datos.
• Colección.
Diagrama conceptual de tarea a realizar.
Prerrequisitos.
• Suscripción Azure activa.
o Si no posee una, crear en: https://azure.microsoft.com/es-mx/free/
• Conocimiento previo de Azure, Cosmos DB, Git y Terraform.
Entorno.
• Windows 10 Home – Core I5 – 12GB RAM.
• Visual Studio Code v1.51.1.
• Chocolatey v0.10.15
• Azure CLI v2.15.1
• Terraform v0.13.5
Algunos conceptos.
Azure CLI es la interfaz de comandos de Azure que se utiliza para crear y administrar recursos de Azure, está
disponible para instalar en entornos Linux, MacOS y Windows.
Chocolatey es un gestor/administrador de paquetes para Windows similar a apt-get.
Cosmos DB es un servicio de bases de datos multimodelo distribuido y con escalado horizontal, permite de
forma nativa modelos de datos de columnas (Cassandra), documentos (SQL y MongoDB), grafos (Gremlin) y
pares clave-valor (Azure Table Storage)
Terraform es un software de código libre que permite el despliegue de infraestructura como código (IaC), fue
creado por HashiCorp, está escrito en Go y soporta una serie de proveedores de nube, entre ellos Azure.
Terraform Cosmos DB| Moisés Elías Araya
[2]
Características de Cosmos DB.
Procedimiento
Iniciar consola Power Shell y ejecutar el comando az login, esto abrirá el navegador donde se deben ingresar
las credenciales de la cuenta, una vez ingresado anotar los valores de “homeTenantId” e “id”
PS C:WINDOWSsystem32> az login
The default web browser has been opened at https://login.microsoftonline.com/common/oauth2/authorize.
Please continue the login in the web browser. If no web browser is available or if the web browser
fails to open, use device code flow with `az login --use-device-code`.
You have logged in. Now let us find all the subscriptions to which you have access...
[
{
"cloudName": "AzureCloud",
"homeTenantId": "f8bad4ef-a9e1-4186-bcf2-2351494523da",
"id": "29831166-1ec2-4121-b6ca-7d0b5190218",
"isDefault": true,
"managedByTenants": [],
"name": "Azure subscription 1",
"state": "Enabled",
"tenantId": "f8bad4ef-a9e1-4186-bcf2-2351494523da",
"user": {
"name": "eliasarayam@outlook.cl",
"type": "user"
}
}
]
Terraform Cosmos DB| Moisés Elías Araya
[3]
También es posible encontrar estos valores desde Suscripciones y Azure Active Directory.
Archivos de configuración.
La configuración está presente en el siguiente repositorio de Github:
https://github.com/EliasGH/terraformcosmosdb y este consta de 3 archivos; main.tf, variables.tf y output.tf.
Variables.tf
Este archivo contiene las variables del grupo de recursos, ubicación y nombre de cuenta cosmosdb, todos
estos valores son modificables según preferencias.
También están presentes las variables “homeTenantId” e “id”, acá es donde se deben copiar los valores
extraídos del paso anterior.
variable "resource_group_name" {
default = "cosmosdb-rg"
}
variable "resource_group_location" {
default = "eastus"
}
variable "subscription_id" {
default = "29831166-1ec2-4121-b6ca-7d0b5190218c"
}
variable "tenant_id" {
default = "f8bad4ef-a9e1-4186-bcf2-2351494523da"
}
variable "cosmos_db_account_name" {
default = "cosmostf"
}
variable "failover_location" {
default = "eastus2"
}
Terraform Cosmos DB| Moisés Elías Araya
[4]
Main.tf
Este archivo contiene las configuraciones principales; se definen el proveedor, el grupo de recursos, la cuenta
cosmos, la base de datos y la colección.
provider "azurerm" {
version = "~> 1.34.0"
subscription_id = "${var.subscription_id}"
tenant_id = "${var.tenant_id}"
}
resource "azurerm_resource_group" "rg" {
name = "${var.resource_group_name}"
location = "${var.resource_group_location}"
}
resource "azurerm_cosmosdb_account" "acc" {
name = "${var.cosmos_db_account_name}"
location = "${azurerm_resource_group.rg.location}"
resource_group_name = "${azurerm_resource_group.rg.name}"
offer_type = "Standard"
kind = "GlobalDocumentDB"
enable_automatic_failover = true
consistency_policy {
consistency_level = "Session"
}
geo_location {
location = "${var.failover_location}"
failover_priority = 1
}
geo_location {
location = "${var.resource_group_location}"
failover_priority = 0
}
}
resource "azurerm_cosmosdb_sql_database" "db" {
name = "servicios"
resource_group_name = "${azurerm_cosmosdb_account.acc.resource_group_name}"
account_name = "${azurerm_cosmosdb_account.acc.name}"
}
resource "azurerm_cosmosdb_sql_container" "coll" {
name = "viajes"
resource_group_name = "${azurerm_cosmosdb_account.acc.resource_group_name}"
account_name = "${azurerm_cosmosdb_account.acc.name}"
database_name = "${azurerm_cosmosdb_sql_database.db.name}"
partition_key_path = "/viajesId"
}
Primeramente, se define el proveedor Azure, luego se definen los ids que sirven para informar a Terraform en
que suscripción se van a implementar los recursos de Cosmos DB.
Luego se crea un grupo de recursos el cual es necesario para alojar todos los recursos que se van a crear, se
define un nombre y una ubicación, ambos valores son referenciados al archivo de variables.
A continuación, se configura la cuenta Cosmos DB por medio del recurso azurerm_cosmosdb_account, se
definen el nombre, ubicación, grupo de recursos, tipo de oferta, tipo de cuenta y nivel de consistencia, se
habilita la geo-localización para la replicación geográfica y las prioridades de ubicación ante un error.
Luego se crea una base de datos dentro de esa cuenta, la base de datos se llama servicios y se usa el mismo
grupo de recursos creado anteriormente, el recurso utilizado es azurerm_cosmosdb_sql_database
Finalmente se crea una colección con el nombre de viajes y una clave de partición “/viajesId”, estos recursos
están creados bajo el grupo, cuenta y base de datos.
Terraform Cosmos DB| Moisés Elías Araya
[5]
Output.tf
El archivo de salida se utiliza para mostrar información útil al finalizar el proceso de despliegue de recursos,
en este caso se mostrarán los valores de base de datos, connection string, id y el endpoint.
output "databases" {
value = azurerm_cosmosdb_sql_database.db.name
}
output "endpoint" {
description = "The endpoint used to connect to the CosmosDB account."
value = azurerm_cosmosdb_account.acc.endpoint
}
output "id" {
description = "The ID of the CosmosDB Account."
value = azurerm_cosmosdb_account.acc.id
}
output "cosmos_db_connection_string" {
value = "${azurerm_cosmosdb_account.acc.connection_strings}"
}
Está todo listo para iniciar la implementación.
Inicializar proceso.
El primer paso necesario es ejecutar el comando terraform init.
Este comando crea un nuevo entorno y descarga e instala los binarios necesarios para utilizar el proveedor
seleccionado.
PS C:RepoGITCosmosDB> terraform init
Initializing the backend…
Initializing provider plugins…
- Finding hashicorp/azurerm versions matching “~> 1.34.0”…
- Installing hashicorp/azurerm v1.34.0…
- Installed hashicorp/azurerm v1.34.0 (signed by HashiCorp)
Warning: Interpolation-only expressions are deprecated
on main.tf line 3, in provider “azurerm”:
3: subscription_id = “${var.subscription_id}”
Terraform 0.11 and earlier required all non-constant expressions to be
provided via interpolation syntax, but this pattern is now deprecated. To
silence this warning, remove the “${ sequence from the start and the }”
sequence from the end of this 5ill5e5rm, leaving just the inner 5ill5e5rm.
Template interpolation syntax is still used to construct strings from
expressions when the template includes multiple interpolation sequences or a
mixture of literal strings and interpolations. This deprecation applies only
to templates that consist entirely of a single interpolation sequence.
(and 13 more similar warnings elsewhere)
Terraform has been successfully initialized!
You may now begin working with Terraform. Try running “5ill5e5rm plan” 5ill5e
any changes that are required for your infrastructure. All Terraform commands
should now work.
If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands 5ill detect it and remind you to do so if necessary.
Respuesta de comando Terraform init.
Terraform Cosmos DB| Moisés Elías Araya
[6]
El segundo paso es crear un plan de ejecución, acá se le indica que acciones y el orden que Terraform
ejecutara las mismas para desplegar recursos, también se valida la sintaxis y como buena práctica, podemos
guardar el plan en un archivo para luego ejecutarlo en el paso siguiente.
Ejecutar el comando Terraform plan con la opción –out plan.out
PS C:RepoGITCosmosDB> terraform plan --out plan.out
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.
------------------------------------------------------------------------
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# azurerm_cosmosdb_account.acc will be created
+ resource "azurerm_cosmosdb_account" "acc" {
+ connection_strings = (sensitive value)
+ enable_automatic_failover = true
+ enable_multiple_write_locations = false
+ endpoint = (known after apply)
+ id = (known after apply)
+ is_virtual_network_filter_enabled = false
+ kind = "GlobalDocumentDB"
+ location = "eastus"
+ name = "cosmostf"
+ offer_type = "Standard"
+ primary_master_key = (sensitive value)
+ primary_readonly_master_key = (sensitive value)
+ read_endpoints = (known after apply)
+ resource_group_name = "cosmosdb-rg"
+ secondary_master_key = (sensitive value)
+ secondary_readonly_master_key = (sensitive value)
+ tags = (known after apply)
+ write_endpoints = (known after apply)
+ consistency_policy {
+ consistency_level = "Session"
+ max_interval_in_seconds = 5
+ max_staleness_prefix = 100
}
+ geo_location {
+ failover_priority = 0
+ id = (known after apply)
+ location = "eastus"
}
+ geo_location {
+ failover_priority = 1
+ id = (known after apply)
+ location = "eastus2"
}
}
# azurerm_cosmosdb_sql_container.coll will be created
+ resource "azurerm_cosmosdb_sql_container" "coll" {
+ account_name = "cosmostf"
+ database_name = "servicios"
+ id = (known after apply)
+ name = "viajes"
+ partition_key_path = "/viajesId"
+ resource_group_name = "cosmosdb-rg"
}
# azurerm_cosmosdb_sql_database.db will be created
+ resource "azurerm_cosmosdb_sql_database" "db" {
+ account_name = "cosmostf"
+ id = (known after apply)
+ name = "servicios"
+ resource_group_name = "cosmosdb-rg"
}
# azurerm_resource_group.rg will be created
+ resource "azurerm_resource_group" "rg" {
+ id = (known after apply)
+ location = "eastus"
+ name = "cosmosdb-rg"
Terraform Cosmos DB| Moisés Elías Araya
[7]
+ tags = (known after apply)
}
Plan: 4 to add, 0 to change, 0 to destroy.
Changes to Outputs:
+ cosmosdb_connectionstrings = (sensitive value)
+ databases = "servicios"
+ endpoint = (known after apply)
+ id = (known after apply)
Warning: Interpolation-only expressions are deprecated
on main.tf line 3, in provider "azurerm":
3: subscription_id = "${var.subscription_id}"
Terraform 0.11 and earlier required all non-constant expressions to be
provided via interpolation syntax, but this pattern is now deprecated. To
silence this warning, remove the "${ sequence from the start and the }"
sequence from the end of this expression, leaving just the inner expression.
Template interpolation syntax is still used to construct strings from
expressions when the template includes multiple interpolation sequences or a
mixture of literal strings and interpolations. This deprecation applies only
to templates that consist entirely of a single interpolation sequence.
(and 13 more similar warnings elsewhere)
------------------------------------------------------------------------
This plan was saved to: plan.out
To perform exactly these actions, run the following command to apply:
terraform apply "plan.out"
El resultado del plan indica que se van a crear 4 recursos; el grupo de recursos, la cuenta, la base de datos y
la colección.
Ahora ejecutar el comando terraform apply, este comando es utilizado para aplicar los cambios mostrados en
el paso anterior.
PS C:RepoGITCosmosDB> terraform apply plan.out
azurerm_resource_group.rg: Creating...
azurerm_cosmosdb_account.acc: Creating...
azurerm_cosmosdb_account.acc: Still creating... [10s elapsed]
azurerm_cosmosdb_account.acc: Still creating... [40s elapsed]
azurerm_cosmosdb_sql_database.db: Creating...
azurerm_cosmosdb_sql_database.db: Still creating... [10s elapsed]
azurerm_cosmosdb_sql_database.db: Still creating... [20s elapsed]
azurerm_cosmosdb_sql_database.db: Still creating... [1m0s elapsed]
azurerm_cosmosdb_sql_container.coll: Creating...
azurerm_cosmosdb_sql_container.coll: Still creating... [10s elapsed]
azurerm_cosmosdb_sql_container.coll: Still creating... [50s elapsed]
azurerm_cosmosdb_sql_container.coll: Still creating... [1m0s elapsed]
azurerm_cosmosdb_sql_container.coll:
on main.tf line 3, in provider "azurerm":
3: subscription_id = "${var.subscription_id}"
Terraform 0.11 and earlier required all non-constant expressions to be
provided via interpolation syntax, but this pattern is now deprecated. To
silence this warning, remove the "${ sequence from the start and the }"
sequence from the end of this expression, leaving just the inner expression.
Template interpolation syntax is still used to construct strings from
expressions when the template includes multiple interpolation sequences or a
mixture of literal strings and interpolations. This deprecation applies only
to templates that consist entirely of a single interpolation sequence.
(and 13 more similar warnings elsewhere)
Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
Outputs:
cosmos_db_connection_string = [
"AccountEndpoint=https://cosmostf.documents.azure.com:443/;AccountKey=aYNg5E106z6HigfBSsFuJLYmouuqBVgIl
fMyYknSsrk2vSOQVt5UWDIXLcsaSuaVqy9LEQSL6H8TdawaQ85Xgg==;",
Terraform Cosmos DB| Moisés Elías Araya
[8]
"AccountEndpoint=https://cosmostf.documents.azure.com:443/;AccountKey=xyDd1FxRhjBYKxP52LzO1zjI7NMcRBuWe
YZyzA0c0DCeaUJ8XTTBIaB3fX0C2UEURwfLZOmJQaKiwQFxYYINTg==;",
"AccountEndpoint=https://cosmostf.documents.azure.com:443/;AccountKey=rkFH9Vs8053GeE2iqDYysNuF2iQP5gNW2
srtXWjMgEGZnGgVAKE7UvtakQ5e4RXmFr8rG3kke1N3BDFSMOkJHg==;",
"AccountEndpoint=https://cosmostf.documents.azure.com:443/;AccountKey=7ReLmKejxvjMK5izqvobz1FoCYlZjnxyF
AfOMyIxz762iUn8S9WVkgC2OGeVgg7RZZTQmh3xzjY79khzQrQfCg==;",
]
databases = servicios
endpoint = https://cosmostf.documents.azure.com:443/
id = /subscriptions/29831166-1ec2-4121-b6ca-7d0b5190218c/resourceGroups/cosmosdb-
rg/providers/Microsoft.DocumentDB/databaseAccounts/cosmostf
El resultado muestra las salidas que se indican en archivo output.tf
El proceso finaliza después de 15 – 20 minutos con el resultado mostrado arriba.
Revisar resultados.
Conectarse a consola web y revisar la creación de los recursos.
Terraform Cosmos DB| Moisés Elías Araya
[9]
También es posible acceder al explorador de datos de CosmosDB por medio de la siguiente URL:
https://cosmos.azure.com/
Limpiar/Eliminar recursos.
Para eliminar los recursos creados, ejecutar el comando terraform destroy (esta tarea tarda algunos minutos
en completarse).
PS C:RepoGITCosmosDB> terraform destroy -auto-approve
..salida omitida.
azurerm_resource_group.rg: Destruction complete after 51s
Destroy complete! Resources: 4 destroyed.
#El flag -auto-approve elimina sin confirmación previa.
Referencias y material complementario.
• Documentación Cosmos DB.
o https://docs.microsoft.com/en-us/azure/cosmos-db/introduction
o https://docs.microsoft.com/en-us/azure/cloud-adoption-framework/ready/azure-best-
practices/naming-and-tagging
o https://docs.microsoft.com/en-us/azure/developer/terraform/deploy-azure-cosmos-db-to-azure-
container-instances
• Documentación Terraform.
o https://learn.hashicorp.com/tutorials/terraform/install-cli
o https://learn.hashicorp.com/terraform
o https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/cosmosdb_account#c
onnection_strings
• Software de diagramado online.
o https://lucid.app/documents#/dashboard
• Instalación Chocolatey
o https://chocolatey.org/install
Terraform Cosmos DB| Moisés Elías Araya
[10]
Anexos.
a- Instalar Azure CLI.
Iniciar PowerShell como administrador y ejecutar el comando:
Invoke-WebRequest -Uri https://aka.ms/installazurecliwindows -OutFile .AzureCLI.msi;
Start-Process msiexec.exe -Wait -ArgumentList '/I AzureCLI.msi /quiet'; rm .AzureCLI.msi
Validar versión.
PS C:WINDOWSsystem32> az --version
azure-cli 2.15.1
Cerrar y volver a iniciar consola Power Shell.
b- Instalar Terraform.
PS C:WINDOWSsystem32> choco install terraform
Chocolatey v0.10.15
Installing the following packages:
terraform
By installing you accept licenses for the packages.
Progress: Downloading terraform 0.13.5... 100%
terraform v0.13.5 [Approved]
terraform package files install completed. Performing other installation steps.
The package terraform wants to run 'chocolateyInstall.ps1'.
Note: If you don't run this script, the installation will fail.
Note: To confirm automatically next time, use '-y' or consider:
choco feature enable -n allowGlobalConfirmation
Do you want to run the script?([Y]es/[A]ll - yes to all/[N]o/[P]rint): Y
Removing old terraform plugins
Downloading terraform 64 bit
from 'https://releases.hashicorp.com/terraform/0.13.5/terraform_0.13.5_windows_amd64.zip'
Progress: 100% - Completed download of
C:UsersUser1AppDataLocalTempchocolateyterraform0.13.5terraform_0.13.5_windows_amd64.zip (33.23
MB).
Download of terraform_0.13.5_windows_amd64.zip (33.23 MB) completed.
Hashes match.
Extracting
C:UsersUser1AppDataLocalTempchocolateyterraform0.13.5terraform_0.13.5_windows_amd64.zip to
exit
C:ProgramDatachocolateylibterraformtools...
C:ProgramDatachocolateylibterraformtools
ShimGen has successfully created a shim for terraform.exe
The install of terraform was successful.
Software installed to 'C:ProgramDatachocolateylibterraformtools'
Chocolatey installed 1/1 packages.
See the log for details (C:ProgramDatachocolateylogschocolatey.log).
Validar instalación consultado la versión instalada.
PS C:WINDOWSsystem32> terraform --version
Terraform v0.13.5
Your version of Terraform is out of date! The latest version
is 0.14.0. You can update by downloading from https://www.terraform.io/downloads.html
PS C:WINDOWSsystem32>
Terraform Cosmos DB| Moisés Elías Araya
[11]
c- Habilitar soporte lenguaje Terraform en Visual Studio Code.
Una extensión de código añade compatibilidad de sintaxis para el lenguaje de configuración, algunas
características son: resaltado de sintaxis, validación básica de sintaxis, funciones, etc.
Buscar las opciones disponibles en menú View - Extensions – Escribir Terraform – Seleccionar la extensión -
Instalar y Validar.
Resultado final.

More Related Content

Terraform Cosmos DB

  • 1. 1 Desplegar Cosmos DB usando Terraform Introducción En este ejercicio se desplegarán recursos de Azure utilizando Terraform, en concreto se van a crear los siguientes elementos: • Grupo de recursos. • Cuenta Cosmos DB. • Base de datos. • Colección. Diagrama conceptual de tarea a realizar. Prerrequisitos. • Suscripción Azure activa. o Si no posee una, crear en: https://azure.microsoft.com/es-mx/free/ • Conocimiento previo de Azure, Cosmos DB, Git y Terraform. Entorno. • Windows 10 Home – Core I5 – 12GB RAM. • Visual Studio Code v1.51.1. • Chocolatey v0.10.15 • Azure CLI v2.15.1 • Terraform v0.13.5 Algunos conceptos. Azure CLI es la interfaz de comandos de Azure que se utiliza para crear y administrar recursos de Azure, está disponible para instalar en entornos Linux, MacOS y Windows. Chocolatey es un gestor/administrador de paquetes para Windows similar a apt-get. Cosmos DB es un servicio de bases de datos multimodelo distribuido y con escalado horizontal, permite de forma nativa modelos de datos de columnas (Cassandra), documentos (SQL y MongoDB), grafos (Gremlin) y pares clave-valor (Azure Table Storage) Terraform es un software de código libre que permite el despliegue de infraestructura como código (IaC), fue creado por HashiCorp, está escrito en Go y soporta una serie de proveedores de nube, entre ellos Azure.
  • 2. Terraform Cosmos DB| Moisés Elías Araya [2] Características de Cosmos DB. Procedimiento Iniciar consola Power Shell y ejecutar el comando az login, esto abrirá el navegador donde se deben ingresar las credenciales de la cuenta, una vez ingresado anotar los valores de “homeTenantId” e “id” PS C:WINDOWSsystem32> az login The default web browser has been opened at https://login.microsoftonline.com/common/oauth2/authorize. Please continue the login in the web browser. If no web browser is available or if the web browser fails to open, use device code flow with `az login --use-device-code`. You have logged in. Now let us find all the subscriptions to which you have access... [ { "cloudName": "AzureCloud", "homeTenantId": "f8bad4ef-a9e1-4186-bcf2-2351494523da", "id": "29831166-1ec2-4121-b6ca-7d0b5190218", "isDefault": true, "managedByTenants": [], "name": "Azure subscription 1", "state": "Enabled", "tenantId": "f8bad4ef-a9e1-4186-bcf2-2351494523da", "user": { "name": "eliasarayam@outlook.cl", "type": "user" } } ]
  • 3. Terraform Cosmos DB| Moisés Elías Araya [3] También es posible encontrar estos valores desde Suscripciones y Azure Active Directory. Archivos de configuración. La configuración está presente en el siguiente repositorio de Github: https://github.com/EliasGH/terraformcosmosdb y este consta de 3 archivos; main.tf, variables.tf y output.tf. Variables.tf Este archivo contiene las variables del grupo de recursos, ubicación y nombre de cuenta cosmosdb, todos estos valores son modificables según preferencias. También están presentes las variables “homeTenantId” e “id”, acá es donde se deben copiar los valores extraídos del paso anterior. variable "resource_group_name" { default = "cosmosdb-rg" } variable "resource_group_location" { default = "eastus" } variable "subscription_id" { default = "29831166-1ec2-4121-b6ca-7d0b5190218c" } variable "tenant_id" { default = "f8bad4ef-a9e1-4186-bcf2-2351494523da" } variable "cosmos_db_account_name" { default = "cosmostf" } variable "failover_location" { default = "eastus2" }
  • 4. Terraform Cosmos DB| Moisés Elías Araya [4] Main.tf Este archivo contiene las configuraciones principales; se definen el proveedor, el grupo de recursos, la cuenta cosmos, la base de datos y la colección. provider "azurerm" { version = "~> 1.34.0" subscription_id = "${var.subscription_id}" tenant_id = "${var.tenant_id}" } resource "azurerm_resource_group" "rg" { name = "${var.resource_group_name}" location = "${var.resource_group_location}" } resource "azurerm_cosmosdb_account" "acc" { name = "${var.cosmos_db_account_name}" location = "${azurerm_resource_group.rg.location}" resource_group_name = "${azurerm_resource_group.rg.name}" offer_type = "Standard" kind = "GlobalDocumentDB" enable_automatic_failover = true consistency_policy { consistency_level = "Session" } geo_location { location = "${var.failover_location}" failover_priority = 1 } geo_location { location = "${var.resource_group_location}" failover_priority = 0 } } resource "azurerm_cosmosdb_sql_database" "db" { name = "servicios" resource_group_name = "${azurerm_cosmosdb_account.acc.resource_group_name}" account_name = "${azurerm_cosmosdb_account.acc.name}" } resource "azurerm_cosmosdb_sql_container" "coll" { name = "viajes" resource_group_name = "${azurerm_cosmosdb_account.acc.resource_group_name}" account_name = "${azurerm_cosmosdb_account.acc.name}" database_name = "${azurerm_cosmosdb_sql_database.db.name}" partition_key_path = "/viajesId" } Primeramente, se define el proveedor Azure, luego se definen los ids que sirven para informar a Terraform en que suscripción se van a implementar los recursos de Cosmos DB. Luego se crea un grupo de recursos el cual es necesario para alojar todos los recursos que se van a crear, se define un nombre y una ubicación, ambos valores son referenciados al archivo de variables. A continuación, se configura la cuenta Cosmos DB por medio del recurso azurerm_cosmosdb_account, se definen el nombre, ubicación, grupo de recursos, tipo de oferta, tipo de cuenta y nivel de consistencia, se habilita la geo-localización para la replicación geográfica y las prioridades de ubicación ante un error. Luego se crea una base de datos dentro de esa cuenta, la base de datos se llama servicios y se usa el mismo grupo de recursos creado anteriormente, el recurso utilizado es azurerm_cosmosdb_sql_database Finalmente se crea una colección con el nombre de viajes y una clave de partición “/viajesId”, estos recursos están creados bajo el grupo, cuenta y base de datos.
  • 5. Terraform Cosmos DB| Moisés Elías Araya [5] Output.tf El archivo de salida se utiliza para mostrar información útil al finalizar el proceso de despliegue de recursos, en este caso se mostrarán los valores de base de datos, connection string, id y el endpoint. output "databases" { value = azurerm_cosmosdb_sql_database.db.name } output "endpoint" { description = "The endpoint used to connect to the CosmosDB account." value = azurerm_cosmosdb_account.acc.endpoint } output "id" { description = "The ID of the CosmosDB Account." value = azurerm_cosmosdb_account.acc.id } output "cosmos_db_connection_string" { value = "${azurerm_cosmosdb_account.acc.connection_strings}" } Está todo listo para iniciar la implementación. Inicializar proceso. El primer paso necesario es ejecutar el comando terraform init. Este comando crea un nuevo entorno y descarga e instala los binarios necesarios para utilizar el proveedor seleccionado. PS C:RepoGITCosmosDB> terraform init Initializing the backend… Initializing provider plugins… - Finding hashicorp/azurerm versions matching “~> 1.34.0”… - Installing hashicorp/azurerm v1.34.0… - Installed hashicorp/azurerm v1.34.0 (signed by HashiCorp) Warning: Interpolation-only expressions are deprecated on main.tf line 3, in provider “azurerm”: 3: subscription_id = “${var.subscription_id}” Terraform 0.11 and earlier required all non-constant expressions to be provided via interpolation syntax, but this pattern is now deprecated. To silence this warning, remove the “${ sequence from the start and the }” sequence from the end of this 5ill5e5rm, leaving just the inner 5ill5e5rm. Template interpolation syntax is still used to construct strings from expressions when the template includes multiple interpolation sequences or a mixture of literal strings and interpolations. This deprecation applies only to templates that consist entirely of a single interpolation sequence. (and 13 more similar warnings elsewhere) Terraform has been successfully initialized! You may now begin working with Terraform. Try running “5ill5e5rm plan” 5ill5e any changes that are required for your infrastructure. All Terraform commands should now work. If you ever set or change modules or backend configuration for Terraform, rerun this command to reinitialize your working directory. If you forget, other commands 5ill detect it and remind you to do so if necessary. Respuesta de comando Terraform init.
  • 6. Terraform Cosmos DB| Moisés Elías Araya [6] El segundo paso es crear un plan de ejecución, acá se le indica que acciones y el orden que Terraform ejecutara las mismas para desplegar recursos, también se valida la sintaxis y como buena práctica, podemos guardar el plan en un archivo para luego ejecutarlo en el paso siguiente. Ejecutar el comando Terraform plan con la opción –out plan.out PS C:RepoGITCosmosDB> terraform plan --out plan.out Refreshing Terraform state in-memory prior to plan... The refreshed state will be used to calculate this plan, but will not be persisted to local or remote state storage. ------------------------------------------------------------------------ An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # azurerm_cosmosdb_account.acc will be created + resource "azurerm_cosmosdb_account" "acc" { + connection_strings = (sensitive value) + enable_automatic_failover = true + enable_multiple_write_locations = false + endpoint = (known after apply) + id = (known after apply) + is_virtual_network_filter_enabled = false + kind = "GlobalDocumentDB" + location = "eastus" + name = "cosmostf" + offer_type = "Standard" + primary_master_key = (sensitive value) + primary_readonly_master_key = (sensitive value) + read_endpoints = (known after apply) + resource_group_name = "cosmosdb-rg" + secondary_master_key = (sensitive value) + secondary_readonly_master_key = (sensitive value) + tags = (known after apply) + write_endpoints = (known after apply) + consistency_policy { + consistency_level = "Session" + max_interval_in_seconds = 5 + max_staleness_prefix = 100 } + geo_location { + failover_priority = 0 + id = (known after apply) + location = "eastus" } + geo_location { + failover_priority = 1 + id = (known after apply) + location = "eastus2" } } # azurerm_cosmosdb_sql_container.coll will be created + resource "azurerm_cosmosdb_sql_container" "coll" { + account_name = "cosmostf" + database_name = "servicios" + id = (known after apply) + name = "viajes" + partition_key_path = "/viajesId" + resource_group_name = "cosmosdb-rg" } # azurerm_cosmosdb_sql_database.db will be created + resource "azurerm_cosmosdb_sql_database" "db" { + account_name = "cosmostf" + id = (known after apply) + name = "servicios" + resource_group_name = "cosmosdb-rg" } # azurerm_resource_group.rg will be created + resource "azurerm_resource_group" "rg" { + id = (known after apply) + location = "eastus" + name = "cosmosdb-rg"
  • 7. Terraform Cosmos DB| Moisés Elías Araya [7] + tags = (known after apply) } Plan: 4 to add, 0 to change, 0 to destroy. Changes to Outputs: + cosmosdb_connectionstrings = (sensitive value) + databases = "servicios" + endpoint = (known after apply) + id = (known after apply) Warning: Interpolation-only expressions are deprecated on main.tf line 3, in provider "azurerm": 3: subscription_id = "${var.subscription_id}" Terraform 0.11 and earlier required all non-constant expressions to be provided via interpolation syntax, but this pattern is now deprecated. To silence this warning, remove the "${ sequence from the start and the }" sequence from the end of this expression, leaving just the inner expression. Template interpolation syntax is still used to construct strings from expressions when the template includes multiple interpolation sequences or a mixture of literal strings and interpolations. This deprecation applies only to templates that consist entirely of a single interpolation sequence. (and 13 more similar warnings elsewhere) ------------------------------------------------------------------------ This plan was saved to: plan.out To perform exactly these actions, run the following command to apply: terraform apply "plan.out" El resultado del plan indica que se van a crear 4 recursos; el grupo de recursos, la cuenta, la base de datos y la colección. Ahora ejecutar el comando terraform apply, este comando es utilizado para aplicar los cambios mostrados en el paso anterior. PS C:RepoGITCosmosDB> terraform apply plan.out azurerm_resource_group.rg: Creating... azurerm_cosmosdb_account.acc: Creating... azurerm_cosmosdb_account.acc: Still creating... [10s elapsed] azurerm_cosmosdb_account.acc: Still creating... [40s elapsed] azurerm_cosmosdb_sql_database.db: Creating... azurerm_cosmosdb_sql_database.db: Still creating... [10s elapsed] azurerm_cosmosdb_sql_database.db: Still creating... [20s elapsed] azurerm_cosmosdb_sql_database.db: Still creating... [1m0s elapsed] azurerm_cosmosdb_sql_container.coll: Creating... azurerm_cosmosdb_sql_container.coll: Still creating... [10s elapsed] azurerm_cosmosdb_sql_container.coll: Still creating... [50s elapsed] azurerm_cosmosdb_sql_container.coll: Still creating... [1m0s elapsed] azurerm_cosmosdb_sql_container.coll: on main.tf line 3, in provider "azurerm": 3: subscription_id = "${var.subscription_id}" Terraform 0.11 and earlier required all non-constant expressions to be provided via interpolation syntax, but this pattern is now deprecated. To silence this warning, remove the "${ sequence from the start and the }" sequence from the end of this expression, leaving just the inner expression. Template interpolation syntax is still used to construct strings from expressions when the template includes multiple interpolation sequences or a mixture of literal strings and interpolations. This deprecation applies only to templates that consist entirely of a single interpolation sequence. (and 13 more similar warnings elsewhere) Apply complete! Resources: 4 added, 0 changed, 0 destroyed. Outputs: cosmos_db_connection_string = [ "AccountEndpoint=https://cosmostf.documents.azure.com:443/;AccountKey=aYNg5E106z6HigfBSsFuJLYmouuqBVgIl fMyYknSsrk2vSOQVt5UWDIXLcsaSuaVqy9LEQSL6H8TdawaQ85Xgg==;",
  • 8. Terraform Cosmos DB| Moisés Elías Araya [8] "AccountEndpoint=https://cosmostf.documents.azure.com:443/;AccountKey=xyDd1FxRhjBYKxP52LzO1zjI7NMcRBuWe YZyzA0c0DCeaUJ8XTTBIaB3fX0C2UEURwfLZOmJQaKiwQFxYYINTg==;", "AccountEndpoint=https://cosmostf.documents.azure.com:443/;AccountKey=rkFH9Vs8053GeE2iqDYysNuF2iQP5gNW2 srtXWjMgEGZnGgVAKE7UvtakQ5e4RXmFr8rG3kke1N3BDFSMOkJHg==;", "AccountEndpoint=https://cosmostf.documents.azure.com:443/;AccountKey=7ReLmKejxvjMK5izqvobz1FoCYlZjnxyF AfOMyIxz762iUn8S9WVkgC2OGeVgg7RZZTQmh3xzjY79khzQrQfCg==;", ] databases = servicios endpoint = https://cosmostf.documents.azure.com:443/ id = /subscriptions/29831166-1ec2-4121-b6ca-7d0b5190218c/resourceGroups/cosmosdb- rg/providers/Microsoft.DocumentDB/databaseAccounts/cosmostf El resultado muestra las salidas que se indican en archivo output.tf El proceso finaliza después de 15 – 20 minutos con el resultado mostrado arriba. Revisar resultados. Conectarse a consola web y revisar la creación de los recursos.
  • 9. Terraform Cosmos DB| Moisés Elías Araya [9] También es posible acceder al explorador de datos de CosmosDB por medio de la siguiente URL: https://cosmos.azure.com/ Limpiar/Eliminar recursos. Para eliminar los recursos creados, ejecutar el comando terraform destroy (esta tarea tarda algunos minutos en completarse). PS C:RepoGITCosmosDB> terraform destroy -auto-approve ..salida omitida. azurerm_resource_group.rg: Destruction complete after 51s Destroy complete! Resources: 4 destroyed. #El flag -auto-approve elimina sin confirmación previa. Referencias y material complementario. • Documentación Cosmos DB. o https://docs.microsoft.com/en-us/azure/cosmos-db/introduction o https://docs.microsoft.com/en-us/azure/cloud-adoption-framework/ready/azure-best- practices/naming-and-tagging o https://docs.microsoft.com/en-us/azure/developer/terraform/deploy-azure-cosmos-db-to-azure- container-instances • Documentación Terraform. o https://learn.hashicorp.com/tutorials/terraform/install-cli o https://learn.hashicorp.com/terraform o https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/cosmosdb_account#c onnection_strings • Software de diagramado online. o https://lucid.app/documents#/dashboard • Instalación Chocolatey o https://chocolatey.org/install
  • 10. Terraform Cosmos DB| Moisés Elías Araya [10] Anexos. a- Instalar Azure CLI. Iniciar PowerShell como administrador y ejecutar el comando: Invoke-WebRequest -Uri https://aka.ms/installazurecliwindows -OutFile .AzureCLI.msi; Start-Process msiexec.exe -Wait -ArgumentList '/I AzureCLI.msi /quiet'; rm .AzureCLI.msi Validar versión. PS C:WINDOWSsystem32> az --version azure-cli 2.15.1 Cerrar y volver a iniciar consola Power Shell. b- Instalar Terraform. PS C:WINDOWSsystem32> choco install terraform Chocolatey v0.10.15 Installing the following packages: terraform By installing you accept licenses for the packages. Progress: Downloading terraform 0.13.5... 100% terraform v0.13.5 [Approved] terraform package files install completed. Performing other installation steps. The package terraform wants to run 'chocolateyInstall.ps1'. Note: If you don't run this script, the installation will fail. Note: To confirm automatically next time, use '-y' or consider: choco feature enable -n allowGlobalConfirmation Do you want to run the script?([Y]es/[A]ll - yes to all/[N]o/[P]rint): Y Removing old terraform plugins Downloading terraform 64 bit from 'https://releases.hashicorp.com/terraform/0.13.5/terraform_0.13.5_windows_amd64.zip' Progress: 100% - Completed download of C:UsersUser1AppDataLocalTempchocolateyterraform0.13.5terraform_0.13.5_windows_amd64.zip (33.23 MB). Download of terraform_0.13.5_windows_amd64.zip (33.23 MB) completed. Hashes match. Extracting C:UsersUser1AppDataLocalTempchocolateyterraform0.13.5terraform_0.13.5_windows_amd64.zip to exit C:ProgramDatachocolateylibterraformtools... C:ProgramDatachocolateylibterraformtools ShimGen has successfully created a shim for terraform.exe The install of terraform was successful. Software installed to 'C:ProgramDatachocolateylibterraformtools' Chocolatey installed 1/1 packages. See the log for details (C:ProgramDatachocolateylogschocolatey.log). Validar instalación consultado la versión instalada. PS C:WINDOWSsystem32> terraform --version Terraform v0.13.5 Your version of Terraform is out of date! The latest version is 0.14.0. You can update by downloading from https://www.terraform.io/downloads.html PS C:WINDOWSsystem32>
  • 11. Terraform Cosmos DB| Moisés Elías Araya [11] c- Habilitar soporte lenguaje Terraform en Visual Studio Code. Una extensión de código añade compatibilidad de sintaxis para el lenguaje de configuración, algunas características son: resaltado de sintaxis, validación básica de sintaxis, funciones, etc. Buscar las opciones disponibles en menú View - Extensions – Escribir Terraform – Seleccionar la extensión - Instalar y Validar. Resultado final.