DEV Community

Msaghu
Msaghu

Posted on

Terraform Cloud Project Bootcamp with Andrew Brown - Creating a command alias

Hi guys , in this piece we will learn how to create an alias for the terraform command i.e instead of using terraform init, we use tf init.

This article is part of my Terraform journey with Terraform Bootcamp by Andrew Brown and Andrew Bayko, together with Chris Williams(I am also using his resources that he published here and the beloved Shala Warner. I am also using some other resources from Aaron Brooks so that I can better explain new terms. And a special shout out to Gwen Leigh for such a helpful outline that I used as a guide to create this series so that the documentation is easy to read!

As I learn more about Terraform, feel free to follow Andrew Brown on Youtube and see their free (and paid) content . Now let's jump in.

Table of Contents

  • [Shortening commands ; creating tf instead of Terraform](#shortening-commands-ccreating-tf-instead-of-ter

Shortening commands ; creating tf instead of Terraform

  • Set an alias for terraform to be tf in terraform, this can be replicated across other projects as you may like.

  • Open ~/.bash_profile for the terminal where we can set bash configurations/bash commands.

  • Add in a line
    alias tf="terraform"

  • We need to reload the file, therefore we will run source ~/.bash_profile

  • To make sure that it is set, type tf in the terminal to test it.

  • To persist it, we need to create a bash script for it;
    Create a new file set_tf_alias and paste in;

#!/usr/bin/env bash

#Checks if the alias already exists in the .bash_profile
grep -q 'alias tf="terraform"' ~/.bash_profile

# $? is a special variable in bash that holds the exit status of the last
if [ $? -ne 0 ]; then
    #if the alias does not exist, append it
    echo 'alias tf="terraform"' >> ~/.bash_profile
    echo "Alias added successfully."
else
    # inform the user if the alias already exists
    echo "Alias already exists in .bash_profile"
fi 

#Optional: source the .bash_profile to make the alias variable immediately
source ~/.bash_profile
Enter fullscreen mode Exit fullscreen mode
  • Change its permissions in the terminal;
    chmod u+x ./bin/set_tf_alias

  • Execute it in the terminal(it should say that its already created`

  • Add it to gitpod.yml and add it for both terraform and aws.
    `
    tasks:

    • name: terraform before: | source ./bin/set_tf_alias source ./bin/install_terraform_cli source ./bin/generate_tfrc_credentials
    • name: aws-cli env: AWS_CLI_AUTO_PROMPT: on-partial before: | source ./bin/set_tf_alias source ./bin/install_aws_cli

vscode:
extensions:
- amazonwebservices.aws-toolkit-vscode
- hashicorp.terraform
`

  • Restart the workspace to make sure that it loads as expected.

Top comments (0)