0
0
GCPcloud~15 mins

Variables and outputs in GCP - Deep Dive

Choose your learning style9 modes available
Overview - Variables and outputs
What is it?
Variables and outputs are ways to pass information into and out of your cloud infrastructure configurations. Variables let you customize settings before creating resources, like choosing a server size or region. Outputs show important information after deployment, such as IP addresses or resource names. Together, they make your cloud setup flexible and informative.
Why it matters
Without variables and outputs, every cloud setup would be fixed and hard to change, forcing you to rewrite configurations for every small change. This would slow down work and cause mistakes. Variables and outputs let you reuse and share setups easily, saving time and reducing errors. They also help teams understand what resources were created and how to connect to them.
Where it fits
Before learning variables and outputs, you should understand basic cloud resources and how to write simple infrastructure code. After mastering them, you can learn about modules and automation to build complex, reusable cloud systems.
Mental Model
Core Idea
Variables are input knobs you turn before building cloud resources, and outputs are display windows showing key results after building.
Think of it like...
Imagine baking a cake: variables are the ingredients you choose before baking, like sugar or flour amounts, and outputs are the finished cake’s size and taste you share after baking.
┌─────────────┐      ┌─────────────┐      ┌─────────────┐
│  Variables  │─────▶│  Deployment │─────▶│   Outputs   │
│ (Inputs)    │      │ (Build Cloud│      │ (Results)   │
│             │      │  Resources) │      │             │
└─────────────┘      └─────────────┘      └─────────────┘
Build-Up - 7 Steps
1
FoundationWhat are variables in cloud configs
🤔
Concept: Variables let you set values that change how cloud resources are created.
Variables are placeholders in your cloud setup files. Instead of hardcoding a value like a server name or size, you use a variable name. When you run your setup, you provide the actual value. This makes your setup flexible and reusable.
Result
You can create the same cloud setup with different settings without rewriting code.
Understanding variables helps you avoid repeating work and makes your cloud setups adaptable to different needs.
2
FoundationWhat are outputs in cloud configs
🤔
Concept: Outputs show important information about created resources after deployment.
After your cloud resources are created, outputs let you see key details like IP addresses, resource IDs, or URLs. These outputs help you connect to or use the resources you made.
Result
You get clear information about your cloud resources without searching through the cloud console.
Knowing outputs helps you quickly find and use your cloud resources after deployment.
3
IntermediateDefining variables with types and defaults
🤔Before reading on: do you think variables always need a value provided, or can they have defaults? Commit to your answer.
Concept: Variables can have types and default values to control what input is allowed and provide fallback values.
You can specify variable types like string, number, or boolean to ensure correct input. You can also set default values so if no input is given, the default is used. This prevents errors and simplifies usage.
Result
Your cloud setup becomes safer and easier to use because it checks inputs and fills in missing values.
Knowing how to type and default variables prevents mistakes and makes your setups friendlier for others.
4
IntermediateUsing outputs to expose resource info
🤔Before reading on: do you think outputs can only show static info or can they show dynamic info from created resources? Commit to your answer.
Concept: Outputs can display dynamic information generated during deployment, like resource addresses or IDs.
You define outputs that reference properties of created resources. For example, after creating a virtual machine, you output its IP address. This info updates automatically each time you deploy.
Result
You always get current, useful information about your cloud resources after deployment.
Understanding dynamic outputs helps you automate workflows that depend on resource details.
5
IntermediatePassing variables between modules
🤔Before reading on: do you think variables can be shared between different parts of your cloud setup? Commit to your answer.
Concept: Variables can be passed into modules to customize reusable parts of your cloud setup.
Modules are like building blocks. You pass variables into them to control their behavior. This lets you reuse modules with different settings in multiple places.
Result
Your cloud infrastructure becomes modular and easier to maintain.
Knowing variable passing unlocks powerful reuse and organization in cloud setups.
6
AdvancedSensitive variables and secure outputs
🤔Before reading on: do you think all variables and outputs are safe to show openly? Commit to your answer.
Concept: Some variables and outputs contain sensitive data and need special handling to keep them secure.
You can mark variables as sensitive so their values are hidden in logs and outputs. Similarly, outputs can be marked sensitive to avoid exposing secrets. This protects passwords, keys, and private info.
Result
Your cloud setup keeps secrets safe while still using variables and outputs.
Understanding sensitivity prevents accidental leaks of critical information.
7
ExpertOutputs for cross-stack communication
🤔Before reading on: do you think outputs can be used to share info between separate cloud deployments? Commit to your answer.
Concept: Outputs can be exported and imported between separate deployments to connect resources across stacks.
You can export outputs from one deployment and import them into another. This lets different teams or projects share resource info like network IDs or database endpoints securely and reliably.
Result
Complex cloud systems can be built by linking independent parts through outputs.
Knowing cross-stack outputs enables scalable, team-friendly cloud architectures.
Under the Hood
Variables are placeholders replaced by actual values during the deployment plan phase. The deployment engine reads variable definitions and inputs, then uses these values to configure resource creation. Outputs are expressions evaluated after resources are created, extracting live data from resource states. Sensitive flags trigger masking in logs and UI to protect secrets.
Why designed this way?
Variables and outputs were designed to separate configuration from code, enabling reuse and flexibility. Early cloud setups hardcoded values, causing duplication and errors. Introducing typed variables with defaults improved safety. Outputs provide a clean way to expose resource info without manual lookup. Sensitivity controls were added to address security concerns.
┌─────────────┐       ┌───────────────┐       ┌─────────────┐
│ Variable    │──────▶│ Deployment    │──────▶│ Resource    │
│ Definitions │       │ Engine        │       │ Creation    │
└─────────────┘       └───────────────┘       └─────────────┘
       │                      │                      │
       ▼                      ▼                      ▼
┌─────────────┐       ┌───────────────┐       ┌─────────────┐
│ Input Values│       │ Resource State│       │ Outputs     │
│ Provided by │       │ Updated after │       │ Evaluated   │
│ User or Env │       │ Creation      │       │ from State  │
└─────────────┘       └───────────────┘       └─────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think variables must always be provided by the user? Commit to yes or no.
Common Belief:Variables always require the user to provide a value before deployment.
Tap to reveal reality
Reality:Variables can have default values, so users don’t have to provide them every time.
Why it matters:Believing this causes unnecessary input prompts and complicates automation.
Quick: Do you think outputs can be used to change resource configurations? Commit to yes or no.
Common Belief:Outputs can modify or control how resources are created.
Tap to reveal reality
Reality:Outputs only display information after resources are created; they don’t affect creation.
Why it matters:Confusing outputs with inputs leads to deployment errors and confusion.
Quick: Do you think sensitive variables are hidden everywhere automatically? Commit to yes or no.
Common Belief:Marking a variable sensitive hides it in all places, including code and logs.
Tap to reveal reality
Reality:Sensitive variables are hidden in logs and UI but still appear in code files unless managed carefully.
Why it matters:Assuming full secrecy can cause accidental exposure of secrets in code repositories.
Quick: Do you think outputs can only be used within the same deployment? Commit to yes or no.
Common Belief:Outputs are only useful inside the deployment where they are defined.
Tap to reveal reality
Reality:Outputs can be exported and imported across deployments to share information.
Why it matters:Missing this limits building complex, multi-stack cloud architectures.
Expert Zone
1
Variables can be overridden by environment variables or CLI flags, which affects deployment behavior subtly.
2
Outputs can be sensitive but still appear in state files, requiring careful state management to avoid leaks.
3
Using outputs for cross-stack references requires careful dependency management to avoid deployment order issues.
When NOT to use
Avoid using variables and outputs for very large or complex data structures; instead, use external configuration files or secret management services. For secret data, prefer dedicated secret managers over sensitive variables to enhance security.
Production Patterns
In production, variables are used to parameterize environments like dev, test, and prod. Outputs are used to feed resource info into CI/CD pipelines or other automation tools. Cross-stack outputs enable multi-team collaboration by sharing resource endpoints securely.
Connections
Function Parameters and Return Values
Variables are like function parameters (inputs), and outputs are like return values (outputs).
Understanding this connection helps grasp how cloud configurations behave like small programs with inputs and outputs.
Database Query Parameters and Results
Variables act like query parameters that customize database queries, while outputs are like query results.
This analogy clarifies how inputs control what is created and outputs show what was made.
Supply Chain Management
Variables are like order specifications before manufacturing, and outputs are the finished goods delivered.
Seeing cloud configs as supply chains helps understand the flow from input decisions to final products.
Common Pitfalls
#1Forgetting to provide a required variable value.
Wrong approach:variable "region" { type = string } # Deployment command without region input terraform apply
Correct approach:variable "region" { type = string default = "us-central1" } # Deployment command uses default or explicit input terraform apply
Root cause:Not setting a default or providing input causes deployment to fail due to missing values.
#2Exposing sensitive data in outputs openly.
Wrong approach:output "db_password" { value = var.db_password } # This shows password in plain text after deployment
Correct approach:output "db_password" { value = var.db_password sensitive = true } # Password is hidden in logs and UI
Root cause:Not marking outputs sensitive leads to accidental secret exposure.
#3Trying to use outputs as inputs to change resource creation in the same deployment.
Wrong approach:resource "vm_instance" "example" { name = output.instance_name } output "instance_name" { value = "my-vm" }
Correct approach:variable "instance_name" { type = string } resource "vm_instance" "example" { name = var.instance_name } output "instance_name" { value = var.instance_name }
Root cause:Outputs are only available after deployment, so they cannot be used as inputs in the same run.
Key Takeaways
Variables let you customize cloud setups by providing flexible inputs before deployment.
Outputs reveal important information about created resources after deployment, helping you connect and manage them.
Using types and defaults in variables improves safety and ease of use.
Sensitive variables and outputs protect secrets but require careful handling to avoid leaks.
Outputs can link separate deployments, enabling complex, modular cloud architectures.