page_type | languages | name | description | products | urlFragment | |||||
---|---|---|---|---|---|---|---|---|---|---|
sample |
|
Using Azure DevOps Pipelines Workload identity federation (OIDC) with Azure for Terraform Deployments |
A sample showing how to configure Azure DevOps Workload identity federation (OIDC) connection to Azure with Terraform and then use that configuration to deploy resources with Terraform. The sample also demonstrates bootstrapping CI / CD with Terraform and how to implement a number of best practices. |
|
azure-devops-terraform-oidc-ci-cd |
Using Azure DevOps Pipelines Workload identity federation (OIDC) or Managed Identity with Azure for Terraform Deployments
This is a two part sample. The first part demonstrates how to configure Azure and Azure DevOps for credential free deployment with Terraform. The second part demonstrates an end to end Continuous Delivery Pipeline for Terraform.
File/folder | Description |
---|---|
bootstrap |
The Terraform to configure Azure and Azure DevOps ready for Workload identity federation (OIDC) or Managed Identity authenticaton. |
example-module |
Some Terraform with Azure Resources for the demo to deploy. |
pipelines |
The templated Azure DevOps Pipelines for the demo. |
.gitignore |
Define what to ignore at commit time. |
CHANGELOG.md |
List of changes to the sample. |
CONTRIBUTING.md |
Guidelines for contributing to the sample. |
README.md |
This README file. |
LICENSE.md |
The license for the sample. |
This sample includes the following features:
- Setup 6 Azure User Assigned Managed Identities with Federation ready for Azure DevOps Workload identity federation (OIDC).
- Setup an Azure Storage Account for State file management.
- Setup Azure DevOps repository and environments ready to deploy Terraform with Workload identity federation (OIDC).
- Run a Continuous Delivery pipeline for Terraform using Workload identity federation (OIDC) auth for state and deploying resources to Azure.
- Run a Pull Request workflow with some basic static analysis.
- HashiCorp Terraform CLI: Download
- Azure CLI: Download
- An Azure Subscription: Free Account
- An Azure DevOps Organization and Project: Free Organization
- Clone the repository locally and then follow the Demo / Lab.
The instructions for this sample are in the form of a Lab. Follow along with them to get up and running.
This lab has the following phases:
- Bootstrap Azure and Azure DevOps for Terraform CI / CD.
- Run the Continuous Delivery pipeline for Terraform.
- Make a change and submit a Pull Request and see the CI pipeline run.
This demo lab creates and is scoped to resource groups. This is to ensure the lab only requires a single subscription and can be run by anyone without the overhead of creating multiple subscriptions. However, for a production scenario we recommend scoping to subscriptions and using subscription demoncratization.
The boostrap implements a number of best practices for Terraform in Azure DevOps that you should take note of as you run through the lab:
- Governed pipelines: The pipelines are stored in a separate repository to the code they deploy. This allows you to govern the pipelines and ensure that only approved templates are used. This is enforced by the required template setting on the service connections.
- Approvals: The production environment requires approval to apply to it. This is enforeced on the prod-apply service connection. This is not configured on the environment by design to ensure that the approval is to use the identity and cannot be bypassed.
- Environment locks: The environments are locked with an exclusive to prevent parralel deployments from running at the same time. The pipeline includes the
lockBehavior: sequential
setting to ensure that the pipeline will wait for the lock to be released before running, so it queues rather just failing. - Workload Identity Federation (OIDC): The service connections and User Assigned Managed Identities are configured to use Workload Identity Federation (OIDC)authenticate to Azure. This means that you don't need to store any secrets in Azure DevOps.
- Pipeline Stages: By default the pipeline is configured with dependencies between the environments. This means that the pipeline will run the dev stage, then the test stage and finally the prod stage. We also provide a parameter to target a specific environment to demonstrate a GitOps type approach too.
- Separate Plan and Apply Identities: The bootstrap creates separate plan and apply identities and service connections per environment. This is to implement the principal of least privilege. The plan identity has read only access to the resource group and the apply identity has contributor access to the resource group.
- Navigate to dev.azure.com.
- Login and select the
User Settings
icon in the top right and thenPersonal access tokens
. - Click
New token
. - Type
Demo_OIDC
into theName
field. - Click
Show all scopes
down at the bottom of the dialog. - Check these scopes:
Agent Pools
:Read & manage
Build
:Read & execute
Code
:Full
Environment
:Read & manage
Service Connections
:Read, query, & manage
Project and Team
:Read, write, & manage
Variable Groups
:Read, create, & manage
- Click
Create
-
IMPORTANT: Copy the token and save it somewhere.
-
Clone this repository to your local machine if you haven't already.
-
Open the repo in Visual Studio Code. (Hint: In a terminal you can open Visual Studio Code by navigating to the folder and running
code .
). -
Navigate to the
bootstrap
folder and create a new file calledterraform.tfvars
. -
In the
terraform.tfvars
file add the following:postfix = "<your_initials>-<date_as_YYYYMMDD>" organization_name = "<your_azure_devops_organisation_name>" azure_devops_project = "<your_azure_devops_project_name>" approvers = ["<your_azure_devops_username>"] # You can omit this is you don't want to demo approvals on the production environment. Remove this line to omit.
e.g.
postfix = "JFH-20221208" organization_name = "my-organization" azure_devops_project = "my-project" approvers = ["demouser@example.com"]
If you wish to use Microsoft-hosted agents and public networking add this setting to
terraform.tfvars
:use_self_hosted_agents = false
If you wish to use Container Apps (scale to zero) add this setting to
terraform.tfvars
:NOTE: Container App takes longer to provision than Container Instances.
self_hosted_agent_type = "azure_container_app"
- Open the Visual Studio Code Terminal and navigate the
bootstrap
folder. - Run
az login -T "<tenant_id>"
and follow the prompts to login to Azure with your account. - Run
az account show
. If you are not connected to you test subscription, change it by runningaz account set --subscription "<subscription-id>"
- Run
$env:ARM_SUBSCRIPTION_ID = $(az account show --query id -o tsv)
to set the subscription id required by azurerm provider v4. - Run
$env:TF_VAR_personal_access_token = "<your_pat>"
to set the PAT you generated earlier. - Run
terraform init
. - Run
terraform plan -out tfplan
. - The plan will complete. Review the plan and see what is going to be created.
- Run
terraform apply tfplan
. - Wait for the apply to complete.
- You will see three outputs from this run. These are the Service Principal Ids that you will require in the next step. Save them somewhere.
- Login to the Azure Portal with your Global Administrator account.
- Navigate to your Subscription and select
Resource groups
. - Click the resource group post-fixed
identity
(e.g.rg-JFH-20221208-identity
). - You should see 6 newly created User Assigned Managed Identities, 2 per environment.
- Look for a
Managed Identity
resource post-fixed withdev-plan
and click it.
- Click on
Federated Credentials
. - There should only be one credential in the list, select that and take a look at the configuration.
- Examine the
Subject identifier
and ensure you understand how it is built up.
- Navigate to your Subscription and select
Resource groups
. - You should see four newly created resource groups.
- Click the resource group post-fixed
dev
(e.g.rg-JFH-20221208-env-dev
). - Select
Access control (IAM)
and selectRole assignments
. - Under the
Reader
role, you should see that yourdev-plan
Managed Identity has been granted access directly to the resource group. - Under the
Contributor
role, you should see that yourdev-apply
Managed Identity has been granted access directly to the resource group.
- Navigate to your Subscription and select
Resource groups
. - Click the resource group post-fixed
state
(e.g.rg-JFH-20221208-state
). - You should see a single storage account in there, click on it.
- Select
Containers
. You should see adev
,test
andprod
container. - Select the
dev
container. - Click
Access Control (IAM)
and selectRole assignments
. - Scroll down to
Storage Blob Data Owner
. You should see yourdev-plan
anddev-apply
Managed Identities have been assigned that role.
- Open Azure DevOps in your browser (login if you need to).
- Navigate to your organisation and project.
- Click
Repos
, then select your new repo in the drop down at the top of the page (e.g.JFH-20221208-demo
). Click on it. - You should see some files under source control.
- Navigate to your organisation and project.
- Click
Repos
, then select your new repo in the drop down at the top of the page (e.g.JFH-20221208-demo-template
). Click on it. - You should see some files under source control.
- Hover over
Pipelines
, then selectEnvironments
. - You should see 3 environments called
dev
,test
andprod
. - Click on the
dev
environment and take a look at the settings. - Note the exclusive lock on the environment, this stops parralel deployments from planning at the same time as another plan and apply.
- Hover over
Pipelines
, then selectLibrary
. - You should see 3 variable groups called
dev
,test
andprod
. - Click on the
dev
environment and take a look at the variables.
- Click
Project Settings
in the bottom left corner. - Click
Service connections
under thePipelines
section. - There should be 3 service connections configured for Managed Identity or Workload Identity Federation depending on the option you choose.
- Click on one of the service connections and click
Edit
to look at the settings. - Look at the approvals and required template check. The required template check will ensure that the pipeline is using the template specified in the template repository.
- Click
Project Settings
in the bottom left corner. - Click
Agent pools
under thePipelines
section. - There 1 new agent pool configured.
- Click on it and navigate to the
Agents
tab, you should see 4 agents in the pool ready to accept runs. (You may only see 1 placeholder agent if you chose the Container Apps option).
- Click on
Pipelines
- You should see 2 pipeline in the list. Click on each in turn.
- Click on
Edit
and examine the pipeline code.
- Select
Pipelines
, then click on the02 - Continuous Delivery
pipeline you created. - Click the
Run pipeline
in the top right, then clickRun
in the dialog. - Wait for the run to appear or refresh the screen, then click on the run to see the details.
- You will see each environment being deployed one after the other.
- If you added approver, you'll need to appove the Production apply stage.
- Drill into the log for one of the environments and look at the steps that were run.
- Run the workflow again and take a look at the log to compare what happens on the Day 2 run.
-
Clone your new repository and open it in Visual Studio Code.
-
Create a new branch, call it whatever you want.
-
Open the
main.tf
file. -
Add tags to the virtual network resource.
resource "azurerm_virtual_network" "example" { name = "example-network" address_space = ["10.0.0.0/16"] location = data.azurerm_resource_group.example.location resource_group_name = data.azurerm_resource_group.example.name tags = { environment = "dev" costcentre = "1234" } }
-
Commit and push the change.
-
Raise a pull request.
-
You'll see the Azure DevOps Pipeline running in the pull request. This is because we created a branch policy to enforce this.
-
The
Terraform Format Check
step will fail formain.tf
. Fix it, commit and push your change. -
Wait for the CI Pipeline to run again and pass.
-
Examine the
Terraform Plan Check
step and see what is going to be changed. -
Merge the Pull Request.
-
Navigate to
Pipelines
and watch the run.
- Run
terraform destroy
in thebootstrap
folder to clean up the resources created by the bootstrap.
NOTE: The destroy may fail the first time due to dependency between service connections and federated credentials. If this happens, run
terraform destroy
again and it should succeed.