This is the jenkins file. The execution fails because the subnetid does not get its value in the second bat command to add subnet to storage account firewall. The complete scenario is that I am deploying infrastrucutre(one vm inside a vnet) to Azure using terraform via jenkins pipeline, once this is deployed, in the next stages the workflow is to whitelist the same subnet to the storage account firewall.
pipeline {
agent any
environment {
AZURE_RG = 'myrg'
VNET_NAME = 'myvnet'
STORAGE_ACCOUNT_RG = 'str_rg'
STORAGE_ACCOUNT_NAME = 'str_name'
SUBNET_ID = '' // Initialize SUBNET_ID variable
}
stages {
stage('Get Subnet ID') {
steps {
script {
// Construct Azure CLI command dynamically with Groovy string interpolation
def azCliCommand = "az network vnet subnet show -g ${AZURE_RG} -n default --vnet-name ${VNET_NAME} --query id --output tsv"
// Get subnet ID
SUBNET_ID = bat(script: azCliCommand, returnStdout: true).trim()
// Add subnet to storage account network rules
bat "az storage account network-rule add -g ${STORAGE_ACCOUNT_RG} --account-name ${STORAGE_ACCOUNT_NAME} --subnet ${SUBNET_ID} --bypass AzureServices"
}
}
}
}
}
The execution fails because the subnetid does not get its value in the second bat command to add subnet to storage account firewall. The complete scenario is that I am deploying infrastrucutre(one vm inside a vnet) to Azure using terraform via jenkins pipeline, once this is deployed, in the next stages the workflow is to whitelist the same subnet to the storage account firewall.
Expected Results: the value of subnetid must be passed as an argument in the second bat command and the subnet must get whitelisted to the storage account.
2
Answers
This is because:
SUBNET_ID
is defined in theenvironment
block – once it’s defined there, it cannot be updated within the stage;SUBNET_ID
defined in thescript
block is a different variable. If you want to use the environment variable in Groovy, you need to refer it asenv.SUBNET_ID
.If you only need the
SUBNET_ID
variable value within thebat
script, try to delete the environment variable definition.If you need the same variable to be shared between the stages, define it before the
pipeline
block.you can define it as a global environment variable outside of any stage block
try this