DEV Community

StackOverflowWarrior
StackOverflowWarrior

Posted on

Day 15 of 100 Days of Cloud: Getting Started with OpenTofu

OpenTofu is an open-source infrastructure as code tool forked from Terraform. It allows you to define and manage cloud resources using a declarative language. This tutorial will guide you through installing OpenTofu and creating a simple configuration.

Step 1: Install OpenTofu

  1. Visit the official OpenTofu GitHub releases page: https://github.com/opentofu/opentofu/releases

  2. Download the appropriate version for your operating system (Windows, macOS, or Linux).

  3. Extract the downloaded archive.

  4. Add the extracted directory to your system's PATH.

  5. Verify the installation by opening a terminal and running:

   tofu version
Enter fullscreen mode Exit fullscreen mode

Step 2: Set Up a Working Directory

  1. Create a new directory for your OpenTofu project:
   mkdir opentofu-demo
   cd opentofu-demo
Enter fullscreen mode Exit fullscreen mode
  1. Create a new file named main.tf:
   touch main.tf
Enter fullscreen mode Exit fullscreen mode

Step 3: Configure the Provider

  1. Open main.tf in your text editor.

  2. Add the following code to configure the AWS provider (replace with your preferred cloud provider if different):

   terraform {
     required_providers {
       aws = {
         source  = "hashicorp/aws"
         version = "~> 4.0"
       }
     }
   }

   provider "aws" {
     region = "us-west-2"
   }
Enter fullscreen mode Exit fullscreen mode

Step 4: Define Resources

  1. In the same main.tf file, add the following code to create an S3 bucket:
   resource "aws_s3_bucket" "demo_bucket" {
     bucket = "opentofu-demo-bucket-${random_id.bucket_id.hex}"
   }

   resource "random_id" "bucket_id" {
     byte_length = 8
   }
Enter fullscreen mode Exit fullscreen mode
  1. This creates an S3 bucket with a unique name using a random ID.

Step 5: Initialize OpenTofu

  1. In your terminal, run:
   tofu init
Enter fullscreen mode Exit fullscreen mode
  1. This command initializes the working directory, downloads the required provider plugins, and sets up the backend.

Step 6: Plan the Changes

  1. Run the following command to see what changes OpenTofu will make:
   tofu plan
Enter fullscreen mode Exit fullscreen mode
  1. Review the planned changes carefully.

Step 7: Apply the Changes

  1. If you're satisfied with the plan, apply the changes:
   tofu apply
Enter fullscreen mode Exit fullscreen mode
  1. Type 'yes' when prompted to confirm the action.

Step 8: Verify the Resources

  1. Log in to your AWS console and check that the S3 bucket has been created.

  2. Alternatively, use the AWS CLI to list your buckets:

   aws s3 ls
Enter fullscreen mode Exit fullscreen mode

Step 9: Clean Up (Optional)

  1. To remove the created resources, run:
   tofu destroy
Enter fullscreen mode Exit fullscreen mode
  1. Type 'yes' when prompted to confirm the action.

Happy Clouding!!

Top comments (0)