Deploy with Terraform on Azure via BitBucket Pipelines

Deploy with Terraform on Azure via BitBucket Pipelines BitBucket is another very interesting alternative for automating our CI/CD pipelines. In this case, we will integrate, with this tool, a pipeline for automatic deployment of Terraform i

Source comparison and review notes
  • Automated pair-review warning (AI bilingual content review): The English pipeline code changes case-sensitive values from image: hashicorp/terraform:latest, step, terraform init, and terraform plan to Hashicorp/Terraform:Latest, Step, Terraform Init, and Terraform Plan; copying that rendering can invalidate the Docker image, YAML key, or commands.

BitBucket is another very interesting alternative for automating our CI/CD pipelines. In this case, we will integrate, with this tool, a pipeline for automatic deployment of Terraform in Azure.

For the CI/CD deployment we will use BitBucket Pipelines, which is a tool that gives us free execution minutes to be able to test our code.

We will use the following repo: https://bitbucket.org/mb-terraform-proj/bb-terraform-lab/

What is BitBucket?

Bitbucket is another platform like Azure Repos or GitHub that offers version control and allows teams to collaborate on code, with support for Git and Mercurial. This platform is from Atlassian and offers streamlined integration with products like Jira and Trello.

Bitbucket Pipelines

Bitbucket Pipelines is a tool built into Bitbucket that allows you to implement continuous integration and deployment (CI/CD) processes. This functionality automates the process of testing and deploying software, allowing teams to release versions faster and more efficiently.

It offers tighter integration with Docker, including the ability to build and upload images to Docker Hub and other Docker registries directly from pipelines.

bitbucket-pipelines.yml file

The bitbucket-pipelines.yml file is a key configuration file for Bitbucket Pipelines, a continuous integration and deployment (CI/CD) tool provided by Bitbucket. This file, written in YAML format, defines how Bitbucket should build, test, and deploy your code.

To use BitBucket pipelines we must:

  • Generate the bitbucket-pipelines.yml file at the root of our file directory.
  • Write our pipeline in YAML.

Basic components of bitbucket-pipelines.yml

The file has 2 main components:

  • Image: here we need to place the container image on which the pipeline will run. We can use our own Runners or those provided in BitBucket Cloud.
  • Pipelines: here we will specify the name and steps of the pipelines.

Let’s take a look at the conditions of pipeline execution. We have different types of Pipeline Start:

  • By “Default:” the pipeline is automatically triggered whenever a commit is made to any branch of the repository.
  • By “Branches:” Specifies specific branches on which the pipeline will be activated. For example, you could configure the pipeline to only run on the main branch or specific feature branches. This is useful for controlling which branches you want to perform CI/CD on.
  • By “Pull Requests:” This condition focuses on pull requests. The pipeline will fire when a pull request is created or updated that targets specific branches. This is particularly useful for validating and testing changes before they merge into your main branch.
  • By “Tags:” With this condition, the pipeline runs when a Git tag is created. This is useful for scenarios such as deployments, where you may want to trigger a deployment process when you mark a specific version with a tag.
  • Custom Start: This option allows you to start the pipeline manually. It’s useful for running workflows that you don’t need to run with every change, such as manual deployments, cleanups, or administrative tasks.

Demo Pipeline

Here is the example we will use in this case:

Plain text
image: Hashicorp/Terraform:Latest
YAML
pipelines:
branches:
main:
- Step:
name: Security Scan
script:
- pipe: atlassian/git-secrets-scan:0.5.1
- Step:
name: Deploy to Production
deployment: Production
script:
- Terraform Init
- Terraform Plan
- terraform apply -auto-approve

Docker Image

Plain text
image: Hashicorp/Terraform:Latest
  • This line specifies that the pipeline will use the Docker image hashicorp/terraform:latest. This means that all pipeline operations will run in a Docker container that has the latest version of Terraform installed.

Pipelines for Branches

YAML
pipelines:
branches:
main:
  • Defines that the following pipeline configurations will apply to the main branch of the repository.

Security Scan

YAML
- Step:
name: Security Scan
script:
- pipe: atlassian/git-secrets-scan:0.5.1
  • Within this step, a script is executed that uses atlassian/git-secrets-scan:0.5.1. This is a Bitbucket pipe, a pre-configured tool used to scan code for sensitive data or secrets that shouldn't be exposed.
  • It incorporates an additional step “integrated” with Bitbucket to scan the security of our code.

Production Deployment Ste

YAML
- Step:
name: Deploy to Production
deployment: Production
script:
- Terraform Init
- Terraform Plan
- terraform apply -auto-approve
  • After the dedicated Security Scan, the deployment step in the production environment begins.
  • The script for this step consists of three Terraform commands.
  • terraform init: Initializes the Terraform working directory, installing the necessary plugins.
  • terraform plan: Creates an execution plan, showing what actions will be taken when the infrastructure change is implemented.
  • terraform apply -auto-approve: Applies the infrastructure changes defined in Terraform. The -auto-approve option prevents you from being asked for manual confirmation to apply changes.

Considerations for logging in to Azure using the Terraform image

As indicated in the following documentation:

Service Principal Client Secret in Terraform

We need to build a core service in Azure, give it the necessary permissions, and use the data from that SP for Azure login. It’s important that we use Least Privilege in production environments. For this lab case we won’t focus on this point and for simplicity we will give Contributor permissions on the subscription. It is important to note that this SHOULD NOT be done in production environments.

Then we must:

  • Create Service Principal:
Bash
az ad sp create-for-rbac --name {principalname} --role {role|Contributor} --scopes {scope|/subscriptions/{subscription}/resourceGroups/{resourcegroup}}
  • As a result of this command we will get the following outpu
JSON
{
"appId": "...",
"displayName": "test-main",
"password": "...",
"tenant": "..."
}
  • With this information, we must configure the following repository variables in BitBucket.
  • We need to go to the Repository > Repository Configurations > Repository Variables
  • Configure the following variables:

Repository Variables

We need to create the following variables with the exact names:

  • ARM_CLIENT_ID: Assign the “appId” value of the SP output.
  • ARM_CLIENT_SECRET: Assign the “password” value of the SP output.
  • ARM_TENANT_ID: Assign the “tenant” value of the SP output.
  • ARM_SUBSCRIPTION_ID: Assign the value of the subscription ID, which is not in the output of the SP.

Once these steps are complete, we can start with the deployment 🙂

Azure Deployment Demo with Terraform

Repo: https://bitbucket.org/mb-terraform-proj/bb-terraform-lab/

I recommend doing the repo fork!

Localize the Repository to Fork:

Plain text
https://bitbucket.org/mb-terraform-proj/bb-terraform-lab/

Fork the Repository:

  • On the repository page, look for the “Fork” button (it may appear as a fork icon). This button is usually located at the top right of the page.
  • Click on the “Fork” button.

Configure the Fork:

  • Clicking “Fork” will prompt you to set up your new forked repository.
  • You can change the name of the repository and adjust other settings, such as description or visibility (public or private).
  • Once you’ve finished setting up your fork, click the button to create the fork.

Clone the Forked Repository:

Bash
git clone https://bitbucket.org/tu-usuario/tu-fork-repo.git
cd tu-fork-repo

Then we need to create the Service Principal for Terraform

Make some minimal code changes and configure the repository variables (named above in this post!). We must configure the variables:

Bash
az ad sp create-for-rbac --name Terraform-sp --role Contributor --scopes /subscriptions/{subscription}

The output will look something like this:

JSON
{
"appId": "...",
"displayName": "test-main",
"password": "...",
"tenant": "..."
}
  • ARM_CLIENT_ID. Assign the “appId” value of the SP output.
  • ARM_CLIENT_SECRET. Assign the “password” value of the SP output.
  • ARM_TENANT_ID. Assign the “tenant” value of the SP output.
  • ARM_SUBSCRIPTION_ID. Assign the value of the subscription ID, which is not in the output of the SP.

Once we push the change to our repo, the BitBucket Pipeline will start.

  • In the first instance, we will see that the
  • Then we will be able to see that it starts running Terraform Init.
  • Second, you will see the result of Terraform Plan
  • Finally, Terraform Apply will be executed without manual approval.
  • We can see how our AKS is created.
  • After creation, we’ll see our resource created in Azure 🙂

Mateo Di Loreto

Thanks for reading. The learning continues in the next article.