Getting Started with OpenTofu: An Open-Source Alternative to Terraform

Introduction
Infrastructure as Code (IaC) is key in modern DevOps, helping teams manage infrastructure through code. While Terraform has been a leading tool, OpenTofu is a new open-source alternative that offers similar features with a focus on community development.
In this post, we’ll cover how to get started with OpenTofu, including how to manage resources, and show how to integrate it with GitHub Actions.
What is OpenTofu?
OpenTofu is an open-source tool for managing infrastructure with code. It works similarly to Terraform, allowing you to define and manage resources across different cloud providers.
Benefits of OpenTofu
Open-Source: Transparent and community-driven.
Familiar Syntax: Similar to Terraform, so it's easy to pick up.
Community Focused: Evolving with input from its users.
Steps to Use OpenTofu
Install OpenTofu on Ubuntu
wget https://github.com/opentofu/opentofu/releases/download/v1.6.0/tofu_1.6.0_amd64.deb
sudo dpkg --install tofu_1.6.0_amd64.deb
mv /usr/bin/tofu /usr/local/bin/opentofu
opentofu version
Create a Configuration
Create a directory and a file named main.tf
with:
provider "aws" {
region = "us-west-2"
}
resource "aws_s3_bucket" "example" {
bucket = "opentofu-example-pradeep"
acl = "private"
}
Initialize OpenTofu
opentofu init
Plan Configuration
opentofu plan
Validate Configuration
opentofu validate
Apply Configuration
opentofu apply
Destroy Resources
opentofu destroy
Integrating OpenTofu with GitHub Actions
To automate OpenTofu with GitHub Actions, create a workflow file .github/workflows/opentofu.yml
with:
name: OpenTofu CI
on: [workflow_dispatch]
jobs:
opentofu:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up OpenTofu
run: |
wget https://github.com/opentofu/opentofu/releases/download/v1.6.0/tofu_1.6.0_amd64.deb
sudo dpkg --install tofu_1.6.0_amd64.deb
sudo mv /usr/bin/tofu /usr/local/bin/opentofu
opentofu version
- name: Set up AWS CLI
uses: aws-actions/configure-aws-credentials@v2
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: us-west-2
- name: Run AWS Command
run: aws sts get-caller-identity
- name: Initialize OpenTofu
run: opentofu init
- name: Validate OpenTofu configuration
run: opentofu validate
- name: Apply OpenTofu configuration
run: opentofu apply -auto-approve
Set Up AWS Credentials
Add AWS credentials to GitHub Secrets under Settings > Secrets and variables > Actions with AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.
Conclusion
OpenTofu is a great open-source alternative to Terraform, with a familiar syntax and strong community support. Integrating it with GitHub Actions simplifies managing your infrastructure. Give OpenTofu a try and streamline your IaC processes!