APURV
  • Home
  • Journey
  • Projects
  • Blogs
  • Interview
  • Exams
Resume
APURV

Building scalable, secure, and production-ready cloud infrastructure. Automation first.

NAVIGATION

HomeExperienceProjectsCertificationsSkills

TECH STACK

AWSGCPK8sCI/CDLinuxDocker

CONNECT

LinkedInGitHubEmailResume

© 2026 Apurv Gujjar. All rights reserved.
Apurv Gujjar
Apurv GujjarDevOps & Cloud Engineer
|Interview Documentation
Portfolio
Handbooks
🎯Linux🐙Git & GitHub🤖GitHub Actions🌐Networking☁AWS🛠Terraform🐳Docker☸Kubernetes📊Monitoring🛡DevSecOps💰Cost Optimization🚨Incident Scenarios👤HR & Behavioral☁GCP🐍Python
Interview DocumentationPythonScenario 3: Write a script that executes a Terraform workspace deployment, captures the stdout logs, and logs success/failure status.
Back to all Python questions
Q3

Scenario 3: Write a script that executes a Terraform workspace deployment, captures the stdout logs, and logs success/failure status.

💬Answer
import subprocess
import os

tf_dir = "/home/dev/DevOps/DevOps/12-Python-for-DevOps/terra-automate/terraform"
log_path = "/var/log/terraform_deploy.log"

def run_terraform():
    print("Initiating Terraform deployment...")
    try:
        # Run apply command
        process = subprocess.run(
            f"terraform -chdir={tf_dir} apply -auto-approve",
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            check=True
        )
        
        # Log success
        with open(log_path, "a") as log:
            log.write(f"\n--- SUCCESS: {os.uname()[1]} ---\n")
            log.write(process.stdout.decode())
        print("Terraform applied successfully.")
        
    except subprocess.CalledProcessError as e:
        # Log failure details
        with open(log_path, "a") as log:
            log.write(f"\n--- FAILURE: {os.uname()[1]} ---\n")
            log.write(e.stderr.decode())
        print(f"Terraform deployment failed. Error logged to {log_path}.")

run_terraform()

Related Python Questions

View All PythonQuestions →
Q1

What is the difference between a List and a Tuple?

Q2

What is the difference between the `==` and `is` operators?

Q3

What are the primary Python data types?

Q4

What is a dictionary and why is it heavily used in DevOps?

Apurv Gujjar - DevOps & Cloud Engineer
Created by

Apurv Gujjar

DevOps & Cloud Engineer

Specialized in:DevOpsAWSGCPKubernetesTerraformDocker
View Portfolio