page_type | languages | name | description | products | urlFragment | |||||
---|---|---|---|---|---|---|---|---|---|---|
sample |
|
Using GitHub Actions Workload identity federation (OIDC) with Azure for Terraform Deployments |
A sample showing how to configure GitHub 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. |
|
github-terraform-oidc-ci-cd |
This is a two part sample. The first part demonstrates how to configure Azure and GitHub for OIDC ready for Terraform deployments. The second part demonstrates an end to end Continuous Delivery Pipeline for Terraform.
File/folder | Description |
---|---|
bootstrap |
The Terraform to configure Azure and GitHub ready for Workload identity federation (OIDC) or Managed Identity authentication. |
example-module |
Some Terraform with Azure Resources for the demo to deploy. |
workflows |
The templated GitHub Actions 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 GitHub Workload identity federation (OIDC).
- Setup an Azure Storage Account for State file management.
- Setup GitHub 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
- A GitHub Organization: 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 GitHub 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 bootstrap 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 (
job_workflow_ref
) claim on the federated credentials. - Approvals: The production environment requires approval to apply to it. This is enforced on the prod-apply environment as GitHub only supports approvals on environments.
- Concurrent locks: The actions are locked using a concurrency setting to prevent parallel deployments from running at the same time. The pipeline includes the
concurrency: <storage container>
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 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 GitHub.
- 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 github.com.
- Login and select the account icon in the top right and then
Settings
. - Click
Developer settings
. - Click
Personal access tokens
and selectTokens (classic)
. - Click
Generate new token
and select theclassic
option. - Type
Demo_OIDC
into theNote
field. - Check these scopes:
repo
workflow
admin:org
user
:read:user
user
:user:email
delete_repo
- Click
Generate token
-
IMPORTANT: Copy the token and save it somewhere.
-
Clone this repository to your local machine.
-
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 config file add the following:
postfix = "<your_initials>-<date_as_YYYYMMDD>" organization_name = "<your_github_organisation_name>" approvers = ["<your_github_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" approvers = ["[email protected]"]
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 github.com (login if you need to).
- Navigate to your organization and select
Repositories
. - You should see a newly created repository in there (e.g.
JFH-20221208-demo
). Click on it. - You should see some files under source control.
- Navigate to
Settings
, then selectEnvironments
. - You should see 6 environments called
dev-plan
,dev-apply
,test-plan
,test-apply
,prod-plan
, andprod-apply
. - Click on the
dev-plan
environment. - You should see that the environment has 7 Environment variables. These secrets are all used in the Action for deploying Terraform.
- Click on the
prod-apply
environment and take a look at the approval settings.
- Navigate to
Settings
. - Click
Action
and thenRunners
. - You should see 4 runners ready to accept runs. (You may not see any if you chose the Container Apps option, as they are created on demand).
- Navigate to
Code
. - Select
.github
,workflows
and open theci.yml
file. - Examine the file and ensure you understand all the steps in there.
- Select
.github
,workflows
and open thecd.yml
file. - Examine the file and ensure you understand all the steps in there.
- Select
Actions
, then click on the02 - Continuous Delivery
action in the left menu. - Click the
Run workflow
drop-down and hit theRun workflow
button. - 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.
- You'll be prompted from approval fro the prod apply job.
- Drill into the log for one of the environments and look at the
Terraform Apply
step. You should see the output of the plan and apply. - 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 GitHub Action running in the pull request.
-
The
Terraform Format Check
step will fail formain.tf
. Fix it, commit and push your change. -
Wait for the Action to run again.
-
Examine the
Terraform Plan Check
step and see what is going to be changed. -
Merge the Pull Request.
-
Navigate to
Actions
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.