modulos
- Forma de encapsular y reutilizar bloques de configuración.
- Sirve para modularizar infraestructura.
- Se publican o se pueden crear propios.
Primer modulo en terraform
Crear carpeta con la siguiente estructura:
nginx_server_module
├── 00.variables.tf
├── 01.provider.tf
├── 02.gce.tf
├── 03-firewall.tf
└── 99-outputs.tf
- Crear
main.tf
##### modulos #####
module "nginx_server_dev" {
source = "./nginx_server_module"
image_id = "ubuntu-minimal-2210-kinetic-amd64-v20230126"
instance_type = "e2-micro"
server_name = "nginx-server"
environment = "dev"
}
terraform init
- Output
Initializing the backend...
Initializing modules...
- nginx_server_dev in nginx_server_module
Initializing provider plugins...
- Reusing previous version of hashicorp/google from the dependency lock file
- Using previously-installed hashicorp/google v6.40.0
Terraform has been successfully initialized!
You may now begin working with Terraform. Try running "terraform plan" to see
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 will detect it and remind you to do so if necessary. - Correr
terraform plan - Correr
terraform apply - Los outputs no se muestran porque se guardan por default en modules.
- Debo agregar el ouput en el main.tf (No borrar el archivo tf del modulo)
##### modulos #####
module "nginx_server_dev" {
source = "./nginx_server_module"
image_id = "ubuntu-minimal-2210-kinetic-amd64-v20230126"
instance_type = "e2-micro"
server_name = "nginx-server-dev"
environment = "dev"
}
output "public_ip" {
description = "Dirección IP pública de la instancia GCP"
value = module.nginx_server_dev.public_ip
} terraform planPara ver el output.
Creamos modulo QA
- Crear clave ssh
ssh-keygen -t rsa -b 2048 -f "ngnix-server-qa.key" - Agregar el modulo QA
##### modulos #####
module "nginx_server_dev" {
source = "./nginx_server_module"
image_id = "ubuntu-minimal-2210-kinetic-amd64-v20230126"
instance_type = "e2-micro"
server_name = "nginx-server-dev"
environment = "dev"
}
module "nginx_server_qa" {
source = "./nginx_server_module"
image_id = "ubuntu-minimal-2210-kinetic-amd64-v20230126"
instance_type = "e2-micro"
server_name = "nginx-server-qa"
environment = "qa"
}
output "dev_public_ip" {
description = "Dirección IP pública de la instancia GCP DEV"
value = module.nginx_server_dev.dev_public_ip
}
output "qa_public_ip" {
description = "Dirección IP pública de la instancia GCP QA"
value = module.nginx_server_dev.qa_public_ip
} terraform init- Algo extra, para guardar el output de un terraform plan para usarlo nuevo
terraform plan -out server_qa.tfplan - Esto crea un archivo para
server_qa.tfplan - Ahora implementar apply con ese archivo
terraform apply server_qa.tfplan