Deploy Azure resource with Terraform
This guide demonstrates how to create a Port self-service action that deploys an Azure storage account with Terraform.
You can run the Terraform workflow with:
- GitHub Actions.
- Azure DevOps.
- Jenkins.
The examples use the same Port blueprint and Terraform templates. Choose the backend that matches your CI/CD setup.
Prerequisites
Before you start, make sure you have:
- An active Azure subscription.
- A resource group where Terraform can create the storage account.
- A service principal for Terraform to authenticate to Azure. See create a service principal.
- Port credentials. See find your Port credentials.
You can also import Azure resources into Port with the Azure integration.
Set up data model
Create the Azure storage blueprint
Follow the steps below to create the azureStorage blueprint💡 Port Concepts
Blueprint - A schema definition used to model any type of asset in your software catalog. Learn more in Port.
-
Go to the Data model page in Port.
-
Click + Blueprint.
-
Click Edit JSON.
-
Copy and paste the following JSON configuration into the editor.
Azure storage account blueprint (click to expand)
{"identifier": "azureStorage","title": "Azure Storage Account","icon": "Azure","schema": {"properties": {"storage_name": {"title": "Account Name","type": "string","minLength": 3,"maxLength": 63,"icon": "DefaultProperty"},"storage_location": {"icon": "DefaultProperty","title": "Location","type": "string"},"url": {"title": "URL","format": "url","type": "string","icon": "DefaultProperty"}},"required": ["storage_name","storage_location"]},"mirrorProperties": {},"calculationProperties": {},"relations": {}} -
Click on Save.
Create the Terraform templates
Create a terraform folder at the root of your repository.
You can also fork the example Terraform Azure repository to get started.
Add the following files:
main.tf- defines the Azure storage account and the Port entity.variables.tf- defines Terraform variables for Azure, Port, and the action run.output.tf- exposes the storage account endpoint URL.
main.tf (click to expand)
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "~> 3.0.2"
}
port = {
source = "port-labs/port-labs"
version = "~> 2.32"
}
}
required_version = ">= 1.1.0"
}
provider "azurerm" {
features {}
}
provider "port" {
client_id = var.port_client_id
secret = var.port_client_secret
base_url = var.base_url
}
resource "azurerm_storage_account" "storage_account" {
name = var.storage_account_name
resource_group_name = var.resource_group_name
location = var.location
account_tier = "Standard"
account_replication_type = "LRS"
account_kind = "StorageV2"
}
resource "port_entity" "azure_storage_account" {
count = length(azurerm_storage_account.storage_account) > 0 ? 1 : 0
identifier = var.storage_account_name
title = var.storage_account_name
blueprint = "azureStorage"
run_id = var.port_run_id
properties = {
string_props = {
"storage_name" = var.storage_account_name,
"storage_location" = var.location,
"endpoint" = azurerm_storage_account.storage_account.primary_web_endpoint
}
}
depends_on = [azurerm_storage_account.storage_account]
}
variables.tf (click to expand)
Replace the default resource_group_name with a resource group from your Azure account. See manage Azure resource groups.
variable "resource_group_name" {
type = string
default = "myTFResourceGroup"
description = "Resource group name in Azure"
}
variable "location" {
type = string
default = "westus2"
description = "Resource group location in Azure"
}
variable "storage_account_name" {
type = string
description = "Storage account name in Azure"
default = "demo"
}
variable "port_run_id" {
type = string
description = "The run ID of the action run that created the entity"
}
variable "port_client_id" {
type = string
description = "The Port client ID"
}
variable "port_client_secret" {
type = string
description = "The Port client secret"
}
variable "base_url" {
type = string
description = "The Port API URL"
}
The port_region, port.baseUrl, portBaseUrl, port_base_url and OCEAN__PORT__BASE_URL parameters select which Port API instance to use:
- EU (app.port.io) →
https://api.port.io - US (app.us.port.io) →
https://api.us.port.io
output.tf (click to expand)
output "endpoint_url" {
value = azurerm_storage_account.storage_account.primary_web_endpoint
}
Deploy with GitHub Actions
Use this option when you want Port to dispatch a GitHub workflow that runs Terraform.
Set up GitHub
-
Install the GitHub integration:
Install GitHub Ocean.
-
Add the following GitHub Actions secrets to the repository that contains the workflow:
PORT_CLIENT_ID- your Port client ID. See get API token.PORT_CLIENT_SECRET- your Port client secret. See get API token.ARM_CLIENT_ID- service principal application client ID.ARM_CLIENT_SECRET- service principal password.ARM_SUBSCRIPTION_ID- Azure subscription ID.ARM_TENANT_ID- Azure tenant ID.AZURE_RESOURCE_GROUP- Azure resource group.
Set up self-service action
Follow the steps below to create a self-service action that triggers the GitHub workflow.
-
Go to the Self-service page in Port.
-
Click on the
+ New Actionbutton. -
Click on the
{...} Edit JSONbutton. -
Copy and paste the following JSON configuration into the editor:
GitHub Ocean action (click to expand)
Replace the following placeholders:
<GITHUB_ORG>- your GitHub organization or user name.<GITHUB_REPO>- your GitHub repository name.<YOUR_GITHUB_OCEAN_INTEGRATION_ID>- your GitHub Ocean integration installation ID.
{"identifier": "service_create_azure_storage","title": "Create Azure Storage","icon": "Github","description": "Create an Azure storage account with Terraform","trigger": {"type": "self-service","operation": "CREATE","userInputs": {"properties": {"storage_name": {"title": "Storage Name","icon": "Azure","type": "string"},"storage_location": {"title": "Storage Location","icon": "Azure","type": "string","default": "westus2"}},"required": ["storage_name"],"order": ["storage_name","storage_location"]},"blueprintIdentifier": "azureStorage"},"invocationMethod": {"type": "INTEGRATION_ACTION","installationId": "<YOUR_GITHUB_OCEAN_INTEGRATION_ID>","integrationActionType": "dispatch_workflow","integrationActionExecutionProperties": {"org": "<GITHUB_ORG>","repo": "<GITHUB_REPO>","workflow": "terraform-azure.yml","workflowInputs": {"storage_name": "{{ .inputs.\"storage_name\" }}","storage_location": "{{ .inputs.\"storage_location\" }}","port_context": {"entity": "{{ .entity }}","blueprint": "{{ .action.blueprint }}","runId": "{{ .run.id }}","trigger": "{{ .trigger }}"}},"reportWorkflowStatus": true}},"requiredApproval": false} -
Click Save to create the action.
Create the GitHub workflow
Create .github/workflows/terraform-azure.yml with the following content:
GitHub workflow (click to expand)
name: Deploy Azure resource
on:
workflow_dispatch:
inputs:
storage_name:
required: true
type: string
storage_location:
required: true
type: string
port_context:
required: true
description: Action and general context from Port.
env:
TF_LOG: INFO
TF_INPUT: false
jobs:
terraform:
name: Terraform infrastructure change management
runs-on: ubuntu-latest
defaults:
run:
shell: bash
working-directory: ./terraform
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Set up Terraform
uses: hashicorp/setup-terraform@v2
with:
terraform_version: 1.6.0
- name: Terraform init
run: terraform init
- name: Terraform format
run: terraform fmt -check
- name: Terraform validate
run: terraform validate
- name: Run Terraform plan and apply for Azure
id: plan-azure
env:
ARM_CLIENT_ID: ${{ secrets.ARM_CLIENT_ID }}
ARM_CLIENT_SECRET: ${{ secrets.ARM_CLIENT_SECRET }}
ARM_TENANT_ID: ${{ secrets.ARM_TENANT_ID }}
ARM_SUBSCRIPTION_ID: ${{ secrets.ARM_SUBSCRIPTION_ID }}
TF_VAR_port_client_id: ${{ secrets.PORT_CLIENT_ID }}
TF_VAR_port_client_secret: ${{ secrets.PORT_CLIENT_SECRET }}
TF_VAR_port_run_id: ${{ fromJson(inputs.port_context).runId }}
TF_VAR_resource_group_name: ${{ secrets.AZURE_RESOURCE_GROUP }}
run: |
terraform plan \
-input=false \
-out=tfazure-${GITHUB_RUN_NUMBER}.tfplan \
-var="storage_account_name=${{ github.event.inputs.storage_name }}" \
-var="location=${{ github.event.inputs.storage_location }}" \
-target=azurerm_storage_account.storage_account
terraform apply -auto-approve -input=false tfazure-${GITHUB_RUN_NUMBER}.tfplan
- name: Terraform Azure status
if: steps.plan-azure.outcome == 'failure'
run: exit 1
- name: Run Terraform plan and apply for Port
id: plan-port
env:
ARM_CLIENT_ID: ${{ secrets.ARM_CLIENT_ID }}
ARM_CLIENT_SECRET: ${{ secrets.ARM_CLIENT_SECRET }}
ARM_TENANT_ID: ${{ secrets.ARM_TENANT_ID }}
ARM_SUBSCRIPTION_ID: ${{ secrets.ARM_SUBSCRIPTION_ID }}
TF_VAR_port_client_id: ${{ secrets.PORT_CLIENT_ID }}
TF_VAR_port_client_secret: ${{ secrets.PORT_CLIENT_SECRET }}
TF_VAR_port_run_id: ${{ fromJson(inputs.port_context).runId }}
TF_VAR_resource_group_name: ${{ secrets.AZURE_RESOURCE_GROUP }}
run: |
terraform plan \
-input=false \
-out=tfport-${GITHUB_RUN_NUMBER}.tfplan \
-var="storage_account_name=${{ github.event.inputs.storage_name }}" \
-var="location=${{ github.event.inputs.storage_location }}"
terraform apply -auto-approve -input=false tfport-${GITHUB_RUN_NUMBER}.tfplan
- name: Terraform Port status
if: steps.plan-port.outcome == 'failure'
run: exit 1
- name: Create a log message
uses: port-labs/port-github-action@v1
with:
clientId: ${{ secrets.PORT_CLIENT_ID }}
clientSecret: ${{ secrets.PORT_CLIENT_SECRET }}
baseUrl: https://api.port.io
operation: PATCH_RUN
status: SUCCESS
runId: ${{ fromJson(inputs.port_context).runId }}
logMessage: Created ${{ inputs.storage_name }}.
Test the flow
- Go to the self-service hub.
- Select the Create Azure Storage action.
- Fill in the storage account name and location.
- Click Execute.
Deploy with Azure DevOps
Use this option when you want Port to trigger an Azure pipeline that runs Terraform.
Set up Azure DevOps
- Create the Port credentials as variables in your Azure DevOps project with the group ID
port-credentials:PORT_CLIENT_ID- your Port client ID. See get API token.PORT_CLIENT_SECRET- your Port client secret. See get API token.
- Create the Azure credentials as variables with the group ID
azure-service-principal:ARM_CLIENT_ID- Azure client ID of the application.ARM_CLIENT_SECRET- Azure client secret of the application.ARM_SUBSCRIPTION_ID- Azure subscription ID.ARM_TENANT_ID- Azure tenant ID.
- Configure an incoming webhook for the Azure pipeline.
Set up self-service action
Follow the steps below to create a self-service action that triggers the Azure DevOps pipeline.
-
Go to the Self-service page in Port.
-
Click on the
+ New Actionbutton. -
Click on the
{...} Edit JSONbutton. -
Copy and paste the following JSON configuration into the editor:
Azure DevOps action (click to expand)
Replace the following placeholders:
<AZURE_DEVOPS_ORG>- your Azure DevOps organization name. You can find it in your Azure DevOps URL:https://dev.azure.com/{AZURE_DEVOPS_ORG}.<AZURE_DEVOPS_WEBHOOK_NAME>- the name you gave to the webhook resource in the Azure pipeline YAML file.
{"identifier": "azureStorage_azure_pipelines_create_azure","title": "Azure Pipelines Create Azure","icon": "Azure","description": "Create an Azure storage account with Azure Pipelines and Terraform","trigger": {"type": "self-service","operation": "CREATE","userInputs": {"properties": {"storage_name": {"icon": "Azure","title": "Storage Name","description": "The Azure storage account name","type": "string"},"storage_location": {"title": "Storage Location","icon": "Azure","type": "string","default": "westus2"}},"required": ["storage_name"],"order": ["storage_name","storage_location"]},"blueprintIdentifier": "azureStorage"},"invocationMethod": {"type": "AZURE_DEVOPS","webhook": "<AZURE_DEVOPS_WEBHOOK_NAME>","org": "<AZURE_DEVOPS_ORG>","payload": {"{{ spreadValue() }}": "{{ .inputs }}","port_context": {"entity": "{{ .entity }}","blueprint": "{{ .action.blueprint }}","runId": "{{ .run.id }}","trigger": "{{ .trigger }}"}}},"requiredApproval": false} -
Click Save to create the action.
Create the Azure pipeline
Create azure-pipelines.yml with the following content:
Azure DevOps pipeline (click to expand)
trigger: none
pool:
vmImage: ubuntu-latest
resources:
webhooks:
- webhook: PortWebhook
connection: PortWebhook
variables:
- group: port-credentials
- group: azure-service-principal
- name: STORAGE_NAME
value: ${{ parameters.PortWebhook.storage_name }}
- name: STORAGE_LOCATION
value: ${{ parameters.PortWebhook.storage_location }}
- name: PORT_RUN_ID
value: ${{ parameters.PortWebhook.port_context.runId }}
jobs:
- job: DeployJob
displayName: Deploy to Azure and Port
steps:
- checkout: self
displayName: Checkout repository
- bash: |
startedAt=$(date -u +%Y-%m-%dT%H:%M:%S.000Z)
echo "##vso[task.setvariable variable=startedAt]$startedAt"
echo "Started at $startedAt"
displayName: Set start time
- script: |
sudo apt-get update
sudo apt-get install -y jq
displayName: Install jq
- script: |
accessToken=$(curl -X POST \
-H 'Content-Type: application/json' \
-d '{"clientId": "$(PORT_CLIENT_ID)", "clientSecret": "$(PORT_CLIENT_SECRET)"}' \
-s 'https://api.port.io/v1/auth/access_token' | jq -r '.accessToken')
echo "##vso[task.setvariable variable=accessToken;isOutput=true]$accessToken"
displayName: Fetch access token
name: getToken
- bash: |
terraform init -input=false
displayName: Initialize configuration
failOnStderr: true
workingDirectory: terraform
- script: |
terraform validate
displayName: Terraform validate
workingDirectory: terraform
- script: |
tf_plan_and_apply() {
local plan_type=$1
local target_option=""
if [ "$plan_type" == "azure" ]; then
target_option="-target=azurerm_storage_account.storage_account"
fi
terraform plan \
-input=false \
-out=tf${plan_type}-${BUILD_BUILDNUMBER}.tfplan \
-var="storage_account_name=${STORAGE_NAME}" \
-var="location=${STORAGE_LOCATION}" \
$target_option
terraform apply -auto-approve -input=false tf${plan_type}-${BUILD_BUILDNUMBER}.tfplan
}
tf_plan_and_apply azure
tf_plan_and_apply port
displayName: Terraform changes to Azure and Port
workingDirectory: terraform
env:
TF_VAR_resource_group_name: arete-resources
TF_VAR_port_client_id: $(PORT_CLIENT_ID)
TF_VAR_port_client_secret: $(PORT_CLIENT_SECRET)
TF_VAR_port_run_id: $(PORT_RUN_ID)
- script: |
completedAt=$(date -u +%Y-%m-%dT%H:%M:%S.000Z)
terraform_output=$(terraform output endpoint_url | sed 's/"//g')
echo ${terraform_output}
curl -X PATCH \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer $(getToken.accessToken)' \
-d '{
"status": "SUCCESS",
"message": {"run_status":"Completed resource creation at $(completedAt)", "url":"$(terraform_output)" }
}' \
"https://api.port.io/v1/actions/runs/$(PORT_RUN_ID)"
displayName: Update run status
workingDirectory: terraform
Test the flow
- Go to the self-service hub.
- Select the Azure Pipelines Create Azure action.
- Fill in the storage account name and location.
- Click Execute.
Having issues with Azure DevOps integration or pipelines? See the Azure DevOps Troubleshooting Guide for step-by-step help.
Deploy with Jenkins
Use this option when you want Port to trigger a Jenkins pipeline that runs Terraform.
Set up Jenkins
- Install the following Jenkins plugins:
- Azure Credentials - provides the
Azure Service Principalcredential kind. - Terraform - simplifies Terraform command execution.
- Generic Webhook Trigger - receives Port webhook requests and extracts payload values.
- Azure Credentials - provides the
- Create the Port credentials using the
Username with passwordkind and the IDport-credentials:PORT_CLIENT_ID- your Port client ID. See get API token.PORT_CLIENT_SECRET- your Port client secret. See get API token.
- Create the Azure credentials using the
Azure Service Principalkind and the IDazure:ARM_CLIENT_ID- Azure client ID of the application.ARM_CLIENT_SECRET- Azure client secret of the application.ARM_SUBSCRIPTION_ID- Azure subscription ID.ARM_TENANT_ID- Azure tenant ID.
- Create
WEBHOOK_TOKENto secure the Jenkins webhook trigger. - Enable webhook trigger for a pipeline.
- Define variables for a pipeline.
- Set up the token.
Set up self-service action
Follow the steps below to create a self-service action that triggers the Jenkins pipeline.
-
Go to the Self-service page in Port.
-
Click on the
+ New Actionbutton. -
Click on the
{...} Edit JSONbutton. -
Copy and paste the following JSON configuration into the editor:
Jenkins action (click to expand)
Replace the following placeholders:
<JENKINS_HOST>- your Jenkins host.<JOB_TOKEN>- the webhook token configured in Jenkins.
{"identifier": "azureStorage_create_azure_storage","title": "Create Azure Storage","icon": "Azure","trigger": {"type": "self-service","operation": "CREATE","userInputs": {"properties": {"storage_name": {"title": "Storage Name","type": "string","minLength": 3,"maxLength": 63},"storage_location": {"icon": "DefaultProperty","title": "Storage Location","description": "Storage account geo region","type": "string"}},"required": ["storage_name"],"order": ["storage_name"]},"blueprintIdentifier": "azureStorage"},"invocationMethod": {"type": "WEBHOOK","url": "https://<JENKINS_HOST>/generic-webhook-trigger/invoke?token=<JOB_TOKEN>","agent": false,"synchronized": false,"method": "POST","body": {"action": "{{ .action.identifier[(\"azureStorage_\" | length):] }}","resourceType": "run","status": "TRIGGERED","trigger": "{{ .trigger | {by, origin, at} }}","context": {"entity": "{{ .entity.identifier }}","blueprint": "{{ .action.blueprint }}","runId": "{{ .run.id }}"},"payload": {"entity": "{{ (if .entity == {} then null else .entity end) }}","action": {"invocationMethod": {"type": "WEBHOOK","agent": false,"url": "https://<JENKINS_HOST>/generic-webhook-trigger/invoke?token=<JOB_TOKEN>","synchronized": false,"method": "POST"},"trigger": "{{ .trigger.operation }}"},"properties": {"{{ if (.inputs | has(\"storage_name\")) then \"storage_name\" else null end }}": "{{ .inputs.\"storage_name\" }}","{{ if (.inputs | has(\"storage_location\")) then \"storage_location\" else null end }}": "{{ .inputs.\"storage_location\" }}"},"censoredProperties": "{{ .action.encryptedProperties }}"}}},"requiredApproval": false} -
Click Save to create the action.
Create the Jenkins pipeline
Create a Jenkins pipeline with the following script.
Jenkins pipeline (click to expand)
Replace <YOUR_USERNAME> and <YOUR_REPO> in the Checkout stage. You can also use the example Terraform Azure repository.
import groovy.json.JsonSlurper
pipeline {
agent any
tools {
"org.jenkinsci.plugins.terraform.TerraformInstallation" "terraform"
}
environment {
TF_HOME = tool('terraform')
TF_IN_AUTOMATION = "true"
PATH = "$TF_HOME:$PATH"
PORT_ACCESS_TOKEN = ""
endpoint_url = ""
}
triggers {
GenericTrigger(
genericVariables: [
[key: 'STORAGE_NAME', value: '$.payload.properties.storage_name'],
[key: 'STORAGE_LOCATION', value: '$.payload.properties.storage_location'],
[key: 'PORT_RUN_ID', value: '$.context.runId'],
[key: 'BLUEPRINT_ID', value: '$.context.blueprint']
],
causeString: 'Triggered by Port',
allowSeveralTriggersPerBuild: true,
tokenCredentialId: "WEBHOOK_TOKEN",
regexpFilterExpression: '',
regexpFilterText: '',
printContributedVariables: true,
printPostContent: true
)
}
stages {
stage('Checkout') {
steps {
git branch: 'main', credentialsId: 'github', url: 'git@github.com:<YOUR_USERNAME>/<YOUR_REPO>.git'
}
}
stage('Get access token') {
steps {
withCredentials([usernamePassword(
credentialsId: 'port-credentials',
usernameVariable: 'PORT_CLIENT_ID',
passwordVariable: 'PORT_CLIENT_SECRET')]) {
script {
def result = sh(returnStdout: true, script: """
accessTokenPayload=\$(curl -X POST \
-H "Content-Type: application/json" \
-d '{"clientId": "${PORT_CLIENT_ID}", "clientSecret": "${PORT_CLIENT_SECRET}"}' \
-s "https://api.port.io/v1/auth/access_token")
echo \$accessTokenPayload
""")
def jsonSlurper = new JsonSlurper()
def payloadJson = jsonSlurper.parseText(result.trim())
PORT_ACCESS_TOKEN = payloadJson.accessToken
}
}
}
}
stage('Terraform Azure') {
steps {
withCredentials([azureServicePrincipal(
credentialsId: 'azure',
subscriptionIdVariable: 'ARM_SUBSCRIPTION_ID',
clientIdVariable: 'ARM_CLIENT_ID',
clientSecretVariable: 'ARM_CLIENT_SECRET',
tenantIdVariable: 'ARM_TENANT_ID'
), usernamePassword(credentialsId: 'port-credentials', usernameVariable: 'TF_VAR_port_client_id', passwordVariable: 'TF_VAR_port_client_secret')]) {
dir('terraform') {
script {
sh 'terraform init'
sh 'terraform validate'
sh """
terraform plan -out=tfazure -var storage_account_name=$STORAGE_NAME -var location=$STORAGE_LOCATION -var port_run_id=$PORT_RUN_ID -target=azurerm_storage_account.storage_account
"""
sh 'terraform apply -auto-approve -input=false tfazure'
sh """
terraform plan -out=tfport -var storage_account_name=$STORAGE_NAME -var location=$STORAGE_LOCATION -var port_run_id=$PORT_RUN_ID
"""
sh 'terraform apply -auto-approve -input=false tfport'
}
}
}
}
}
stage('Notify Port') {
steps {
script {
def logs_report_response = sh(script: """
curl -X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${PORT_ACCESS_TOKEN}" \
-d '{"message": "Created Port entity"}' \
"https://api.port.io/v1/actions/runs/$PORT_RUN_ID/logs"
""", returnStdout: true)
println(logs_report_response)
}
}
}
stage('Update run status') {
steps {
script {
def status_report_response = sh(script: """
curl -X PATCH \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${PORT_ACCESS_TOKEN}" \
-d '{"status":"SUCCESS", "message": {"run_status": "Jenkins CI/CD run completed successfully."}}' \
"https://api.port.io/v1/actions/runs/${PORT_RUN_ID}"
""", returnStdout: true)
println(status_report_response)
}
}
}
}
post {
failure {
script {
def status_report_response = sh(script: """
curl -X PATCH \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${PORT_ACCESS_TOKEN}" \
-d '{"status":"FAILURE", "message": {"run_status": "Failed to create Azure resource ${STORAGE_NAME}"}}' \
"https://api.port.io/v1/actions/runs/${PORT_RUN_ID}"
""", returnStdout: true)
println(status_report_response)
}
}
always {
cleanWs(cleanWhenNotBuilt: false,
deleteDirs: true,
disableDeferredWipeout: false,
notFailBuild: true,
patterns: [[pattern: '.gitignore', type: 'INCLUDE'], [pattern: '.propsfile', type: 'EXCLUDE']])
}
}
}
Test the flow
- Go to the self-service hub.
- Select the Create Azure Storage action.
- Fill in the storage account name and location.
- Click Execute.
Create pull requests for follow-up infrastructure changes
Use this optional flow to add infrastructure code to a service repository through a GitHub pull request. The action appends an Azure storage account resource to main.tf; you can replace the Terraform template with another resource.
Before you start, make sure you have a service blueprint and a service entity whose github_url property points to the target GitHub repository. For the GitHub Actions backend, install the GitHub integration and note its installation ID.
Set up self-service action
Follow the steps below to create a self-service action that triggers your GitHub Actions workflow or Jenkins pipeline.
-
Go to the Self-service page of your factory.
-
Click on the + New Action button.
-
Click on the
{...} Edit JSONbutton. -
Copy and paste the JSON configuration for your backend into the editor:
- GitHub Actions
- Jenkins
Open GitHub PR action (click to expand)
Replace the variables<GITHUB_ORG>- Your GitHub organization or user name.<GITHUB_REPO>- The repository where the workflow file is stored.<YOUR_GITHUB_OCEAN_INTEGRATION_ID>- Your GitHub Ocean integration installation ID.
{"identifier": "open_github_pr","title": "Open GitHub PR","icon": "Microservice","description": "Open a pull request after modifying a Terraform file.","trigger": {"type": "self-service","operation": "DAY-2","userInputs": {"properties": {"storage_name": {"type": "string","title": "Storage name"},"storage_location": {"type": "string","title": "Storage location"}},"required": ["storage_name","storage_location"],"order": ["storage_name","storage_location"]},"blueprintIdentifier": "service"},"invocationMethod": {"type": "INTEGRATION_ACTION","installationId": "<YOUR_GITHUB_OCEAN_INTEGRATION_ID>","integrationActionType": "dispatch_workflow","integrationActionExecutionProperties": {"org": "<GITHUB_ORG>","repo": "<GITHUB_REPO>","workflow": "create-github-pr.yml","workflowInputs": {"storage_name": "{{ .inputs.storage_name }}","storage_location": "{{ .inputs.storage_location }}","repo_url": "{{ .entity.properties.github_url }}","port_context": {"blueprint": "{{ .action.blueprint }}","entity": "{{ .entity }}","runId": "{{ .run.id }}","trigger": "{{ .trigger }}"}},"reportWorkflowStatus": true}},"requiredApproval": false}Open GitHub PR with Jenkins action (click to expand)
Replace the variablesYOUR_JENKINS_URL- The URL of your Jenkins server.JOB_TOKEN- The token of the Jenkins job.
{"identifier": "open_github_pr_with_jenkins","title": "Open GitHub PR with Jenkins","icon": "Microservice","description": "Open a pull request after modifying a Terraform file using Jenkins.","trigger": {"type": "self-service","operation": "DAY-2","userInputs": {"properties": {"storage_name": {"type": "string","title": "Storage name"},"storage_location": {"type": "string","title": "Storage location"}},"required": ["storage_name","storage_location"],"order": ["storage_name","storage_location"]},"blueprintIdentifier": "service"},"invocationMethod": {"type": "JENKINS","url": "http://YOUR_JENKINS_URL/generic-webhook-trigger/invoke?token=<JOB_TOKEN>","agent": false,"body": {"{{ spreadValue() }}": "{{ .inputs }}","port_context": {"runId": "{{ .run.id }}","blueprint": "{{ .action.blueprint }}","entity": "{{ .entity }}"}}},"requiredApproval": false} -
Click Save to create the action.
Create Terraform templates
In the target service repository, create a templates/create-azure-storage.tf file:
Azure storage account template (click to expand)
resource "azurerm_storage_account" "storage_account" {
name = "{{ storage_name }}"
resource_group_name = "YourResourcesGroup"
location = "{{ storage_location }}"
account_tier = "Standard"
account_replication_type = "LRS"
account_kind = "StorageV2"
}
Add a main.tf file in the root of the repository if it does not already exist:
Terraform provider configuration (click to expand)
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "~> 3.0.2"
}
}
required_version = ">= 1.1.0"
}
provider "azurerm" {
features {}
}
Create the GitHub pull request workflow
Create .github/workflows/create-github-pr.yml in the workflows repository. Add the following repository secrets before running it:
PORT_CLIENT_ID- Your Port client ID.PORT_CLIENT_SECRET- Your Port client secret.GH_TOKEN- A classic personal access token with thereposcope.
Create GitHub PR workflow (click to expand)
name: Create GitHub PR
on:
workflow_dispatch:
inputs:
storage_name:
required: true
type: string
storage_location:
required: true
type: string
repo_url:
required: true
type: string
port_context:
required: true
type: string
jobs:
create-pr:
runs-on: ubuntu-latest
steps:
- name: Inform starting
uses: port-labs/port-github-action@v1
with:
clientId: ${{ secrets.PORT_CLIENT_ID }}
clientSecret: ${{ secrets.PORT_CLIENT_SECRET }}
operation: PATCH_RUN
runId: ${{ fromJson(inputs.port_context).runId }}
logMessage: |
Creating a GitHub pull request for a new Terraform resource.
- name: Extract repository information
run: |
REPO_PATH=$(echo "${{ inputs.repo_url }}" | sed 's|https://github.com/||' | sed 's|git@github.com:||' | sed 's|.git||')
echo "REPO_PATH=$REPO_PATH" >> $GITHUB_ENV
- name: Checkout target repository
uses: actions/checkout@v6
with:
repository: ${{ env.REPO_PATH }}
token: ${{ secrets.GH_TOKEN }}
ref: main
- name: Make Terraform changes
run: |
sed "s/{{ storage_name }}/${{ inputs.storage_name }}/g; s/{{ storage_location }}/${{ inputs.storage_location }}/g" templates/create-azure-storage.tf >> main.tf
- name: Create branch and push
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git checkout -b "infra/new-resource-${{ inputs.storage_name }}"
git add main.tf
git commit -m "Add a new Terraform resource block"
git push origin "infra/new-resource-${{ inputs.storage_name }}"
- name: Create pull request
run: |
gh pr create --base main --head "infra/new-resource-${{ inputs.storage_name }}" \
--title "Add resource block ${{ inputs.storage_name }}" \
--body "This pull request adds a new Terraform resource block to the project."
env:
GH_TOKEN: ${{ secrets.GH_TOKEN }}
- name: Notify Port
uses: port-labs/port-github-action@v1
with:
clientId: ${{ secrets.PORT_CLIENT_ID }}
clientSecret: ${{ secrets.PORT_CLIENT_SECRET }}
operation: PATCH_RUN
runId: ${{ fromJson(inputs.port_context).runId }}
status: SUCCESS
logMessage: |
Created GitHub pull request for new Terraform resource ${{ inputs.storage_name }}.
Create the Jenkins pull request pipeline
Configure Jenkins credentials:
port-credentials- A Jenkins Username with password credential where the username isPORT_CLIENT_IDand the password isPORT_CLIENT_SECRET.WEBHOOK_TOKEN- The webhook token used by the Generic Webhook Trigger plugin.GITHUB_TOKEN- A GitHub personal access token with permissions to create pull requests.
Create the GitHub personal access token from your GitHub tokens page, and grant it the repo and admin:org scopes.
Before adding the Jenkinsfile, configure the Jenkins job:
- Enable the webhook trigger for the pipeline.
- Define variables for the pipeline:
STORAGE_NAME,STORAGE_LOCATION,REPO_URL, andPORT_RUN_ID. - Set the job token to match the
JOB_TOKENconfigured in the Port action.
Create a Jenkins pipeline that receives the Port payload, appends the Terraform template to main.tf, opens a pull request, and reports the run status back to Port:
Jenkins pipeline (click to expand)
import groovy.json.JsonSlurper
pipeline {
agent any
environment {
GITHUB_TOKEN = credentials("GITHUB_TOKEN")
NEW_BRANCH_PREFIX = "infra/new-resource"
NEW_BRANCH_NAME = "${NEW_BRANCH_PREFIX}-${STORAGE_NAME}"
TEMPLATE_FILE = "templates/create-azure-storage.tf"
PORT_ACCESS_TOKEN = ""
REPO = ""
}
triggers {
GenericTrigger(
genericVariables: [
[key: "STORAGE_NAME", value: "$.storage_name"],
[key: "STORAGE_LOCATION", value: "$.storage_location"],
[key: "REPO_URL", value: "$.port_context.entity.properties.github_url"],
[key: "PORT_RUN_ID", value: "$.port_context.runId"]
],
causeString: "Triggered by Port",
allowSeveralTriggersPerBuild: true,
regexpFilterExpression: "",
regexpFilterText: "",
printContributedVariables: true,
printPostContent: true
)
}
stages {
stage("Checkout") {
steps {
script {
def path = REPO_URL.substring(REPO_URL.indexOf("/") + 1)
REPO = path.replace("/github.com/", "")
}
git branch: "main", credentialsId: "github", url: "git@github.com:${REPO}.git"
}
}
stage("Make changes") {
steps {
script {
sh """cat ${TEMPLATE_FILE} | sed "s/{{ storage_name }}/${STORAGE_NAME}/g; s/{{ storage_location }}/${STORAGE_LOCATION}/g" >> main.tf"""
}
}
}
stage("Create branch and commit") {
steps {
script {
sh "git checkout -b ${NEW_BRANCH_NAME}"
sh "git add main.tf"
sh "git commit -m 'Add a new Terraform resource block'"
sh "git push origin ${NEW_BRANCH_NAME}"
}
}
}
stage("Create pull request") {
steps {
script {
createPullRequestCurl(
REPO,
NEW_BRANCH_NAME,
"main",
"Add resource block ${STORAGE_NAME}",
"This pull request adds a new Terraform resource block to the project."
)
}
}
}
stage("Get access token") {
steps {
withCredentials([usernamePassword(
credentialsId: "port-credentials",
usernameVariable: "PORT_CLIENT_ID",
passwordVariable: "PORT_CLIENT_SECRET"
)]) {
script {
def result = sh(returnStdout: true, script: """
accessTokenPayload=\$(curl -X POST \
-H "Content-Type: application/json" \
-d '{"clientId": "${PORT_CLIENT_ID}", "clientSecret": "${PORT_CLIENT_SECRET}"}' \
-s "https://api.port.io/v1/auth/access_token")
echo \$accessTokenPayload
""")
def jsonSlurper = new JsonSlurper()
def payloadJson = jsonSlurper.parseText(result.trim())
PORT_ACCESS_TOKEN = payloadJson.accessToken
}
}
}
}
stage("Notify Port") {
steps {
script {
sh """
curl -X PATCH \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${PORT_ACCESS_TOKEN}" \
-d '{"status":"SUCCESS", "message": {"run_status": "Jenkins run completed successfully"}}' \
"https://api.port.io/v1/actions/runs/${PORT_RUN_ID}"
"""
}
}
}
}
post {
failure {
script {
sh """
curl -X PATCH \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${PORT_ACCESS_TOKEN}" \
-d '{"status":"FAILURE", "message": {"run_status": "Failed to create Terraform resource ${STORAGE_NAME}"}}' \
"https://api.port.io/v1/actions/runs/${PORT_RUN_ID}"
"""
}
}
always {
cleanWs(cleanWhenNotBuilt: false, deleteDirs: true, disableDeferredWipeout: false, notFailBuild: true)
}
}
}
def createPullRequestCurl(repo, headBranch, baseBranch, title, body) {
curlCommand = "curl -X POST https://api.github.com/repos/$repo/pulls -H 'Authorization: Bearer ${GITHUB_TOKEN}' -d '{ \"head\": \"$headBranch\", \"base\": \"$baseBranch\", \"title\": \"$title\", \"body\": \"$body\", \"draft\": false }'"
try {
response = sh(script: curlCommand)
if (response.contains("201 Created")) {
println "Pull request created successfully"
} else {
println "Failed to create pull request"
println response
}
} catch (Exception e) {
println "Error occurred during CURL request: ${e.getMessage()}"
}
}
Test the pull request flow
-
Go to the Self-service page in Port.
-
Click the Open GitHub PR action, or Open GitHub PR with Jenkins if you use the Jenkins path.
-
Enter a name for the Azure storage account and a location.
-
Select the relevant service and click Execute.
-
Open the action run details and verify that the run succeeded.
-
Check the GitHub repository and confirm that the pull request was created with the Terraform changes.
To trigger resource deployment after the pull request is merged, use the Jenkins Terraform Azure pipeline example.