Coder Social home page Coder Social logo

azure / powershell Goto Github PK

View Code? Open in Web Editor NEW
58.0 13.0 36.0 32.72 MB

GH Action to run Az PowerShell scripts for developers and administrators to develop, deploy, and manage Microsoft Azure applications.

License: MIT License

JavaScript 1.04% TypeScript 98.96%

powershell's Introduction

GitHub action for Azure PowerShell

This repository contains GitHub action for Azure PowerShell to automate your GitHub workflows using Azure PowerShell scripts.

Get started today with a free Azure account!

The definition of this GitHub Action is in action.yml.

Note

Azure PowerShell action now supports macOS and self-hosted Runners!

Dependencies on other GitHub Actions

Login to Azure before running Azure PowerShell scripts using Azure Login. Refer Azure Login action on how to configure Azure credentials.

Both Azure Login and Azure PowerShell action uses Az module.

Once login is done, Azure PowerShell action will use the same session to run the script.

Sample Workflow

Sample workflow to run inlineScript

on: [push]

name: AzurePowerShellSample

jobs:

  build:
    runs-on: ubuntu-latest
    steps:
    
    - name: Login via Az module
      uses: azure/login@v2
      with:
        creds: ${{secrets.AZURE_CREDENTIALS}}
        enable-AzPSSession: true 
        
    - name: Run Azure PowerShell inline script
      uses: azure/powershell@v2
      with:
        inlineScript: |
          Get-AzVM -ResourceGroupName "ResourceGroup11"
        azPSVersion: "latest"

Azure PowerShell Script to be executed can be given under inlineScript as shown in the sample workflow.

Azure PowerShell action is now supported for the Azure public cloud as well as Azure government clouds (AzureUSGovernment or AzureChinaCloud) and Azure Stack (AzureStack) Hub. Before running Azure PowerShell scripts, login to the respective Azure Cloud using Azure Login action by setting appropriate value for the environment parameter.

Additionally the action supports two optional parameters:

  • errorActionPreference : select a suitable  value for the variable for executing the script. Allowed values are stop, continue, silentlyContinue. Default is Stop.
  • failOnStandardError : By default this is marked as false. But if this is marked as true, the action will fail if any errors are written to the error pipeline, or if any data is written to the Standard Error stream.

Sample workflow to run a script file in your repository

# File: ./scripts/run_azps_cmdlets.ps1
on: [push]

name: AzurePowerShellSampleWithFile

jobs:

  build:
    runs-on: ubuntu-latest
    steps:
    
    - name: Check Out
      uses: actions/checkout@v3

    - name: Login Azure
      uses: azure/login@v2
      with:
        creds: ${{secrets.AZURE_CREDENTIALS}}
        enable-AzPSSession: true 

    - name: Run Azure PowerShell Script File
      uses: azure/powershell@v2
      with:
        inlineScript: ./scripts/run_azps_cmdlets.ps1
        azPSVersion: "latest"

You have to check out the repository before running the script file. You can also run the script file with parameters. For example:

    - name: Run Azure PowerShell Script File
      uses: azure/powershell@v2
      with:
        inlineScript: ./scripts/run_azps_cmdlets.ps1 myresourcegroup myresourcename
        azPSVersion: "latest"

or

    - name: Run Azure PowerShell Script File
      uses: azure/powershell@v2
      with:
        inlineScript: ./scripts/run_azps_cmdlets.ps1 -ResourceGroupName myresourcegroup -ResourceName myresourcename
        azPSVersion: "latest"

Sample workflow to run Azure powershell actions in Azure US Government cloud

   - name: Login to Azure US Gov Cloud with Az Powershell 
        uses: azure/login@v2
        with:
          creds: ${{ secrets.AZURE_US_GOV_CREDENTIALS }}
          environment: 'AzureUSGovernment'
          enable-AzPSSession: true
    
      - name: Run powershell command in US Gov Cloud
        uses: azure/powershell@v2
        with:
          inlineScript: "Get-AzContext"
          azPSVersion: "latest"

Available versions of Az Module on runner

To use the latest Az module version, specify latest. You can find the latest Az module versions on different runner images from this table.

Or you can find all supported Az version on PowerShell Gallery.

Getting Help for Azure PowerShell Issues

If you encounter an issue related to the Azure PowerShell commands executed in your script, you can file an issue directly on the Azure PowerShell repository.

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

powershell's People

Contributors

aksm-ms avatar amit-avit avatar amrutakawade avatar balaga-gayatri avatar dependabot[bot] avatar dolauli avatar isra-fel avatar jamesc avatar jonas-lomholdt avatar kanika1894 avatar microsoft-github-operations[bot] avatar microsoftopensource avatar n-usha avatar veryearly avatar yanaxu avatar zainuvk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

powershell's Issues

New-AzResourceGroupDeployment - Bad JSON content found in the request

Hello,

when deploying a KeyVault via New-AzResourceGroupDeployment I get the error "Bad JSON content found in the request"

$kvDeployResult = New-AzResourceGroupDeployment -Name "addKeyVault" -ResourceGroupName $resourceGroupeName -TemplateFile ".\deploy_kv.json" -Verbose -Debug

I went through the whole process with the -Debug parameter to find the very point from where the error originates.
You can see, that the creation itself works just fine, but later in the process something bad happens, and I dont know why.

I am using PowerShell 5.1 with the Az 5.1 package which includes the Az.Resources 3.0.1. I did a clean uninstall of ALL Azure modules I had installed prior.

The template file:

{
    "$schema":  "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion":  "1.0.0.0",
    "parameters":  {
                       "name":  {
                                    "type":  "string",
                                    "defaultValue":  "kvname"
                                },
                       "location":  {
                                        "type":  "string",
                                        "defaultValue":  "[resourceGroup().location]"
                                    },
                       "sku":  {
                                   "type":  "string",
                                   "defaultValue":  "Standard"
                               },
                       "accessPolicies":  {
                                              "type":  "array",
                                              "defaultvalue":  [
                                                                   {
                                                                       "objectId":  "objid",
                                                                       "tenantId":  "[subscription().tenantId]",
                                                                       "permissions":  {
                                                                                           "keys":  "",
                                                                                           "secrets":  "Get List Set Delete Recover Backup Restore",
                                                                                           "certificates":  ""
                                                                                       },
                                                                       "applicationId":  null
                                                                   }
                                                               ]
                                          },
                       "tenantId":  {
                                        "type":  "string",
                                        "defaultValue":  "[subscription().tenantId]",
                                        "metadata":  {
                                                         "description":  "Specifies the Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. Get it by using Get-AzSubscription cmdlet."
                                                     }
                                    }
                   },
    "variables":  {

                  },
    "resources":  [
                      {
                          "type":  "Microsoft.KeyVault/vaults",
                          "name":  "[parameters('name')]",
                          "location":  "[parameters('location')]",
                          "apiVersion":  "2019-09-01",
                          "tags":  {
                                       "displayName":  "KeyVault"
                                   },
                          "properties":  {
                                             "enabledForDeployment":  false,
                                             "enabledForTemplateDeployment":  false,
                                             "enabledForDiskEncryption":  false,
                                             "enableSoftDelete":  true,
                                             "softDeleteRetentionInDays":  90,
                                             "tenantId":  "[parameters('tenantId')]",
                                             "accessPolicies":  "[parameters('accessPolicies')]",
                                             "sku":  {
                                                         "name":  "[parameters('sku')]",
                                                         "family":  "A"
                                                     },
                                             "networkAcls":  {
                                                                 "defaultAction":  "Allow",
                                                                 "bypass":  "AzureServices"
                                                             }
                                         }
                      }
                  ],
    "outputs":  {

                }
}
`DEBUG: 11:24:56 - NewAzureResourceGroupDeploymentCmdlet begin processing with ParameterSet 'ByTemplateFileWithNoParameters'.
Bestätigung
Vorgang fortsetzen?
[J] Ja [A] Ja, alle [B] Befehl anhalten [H] Anhalten [?] Help (default is "Ja"): j
DEBUG: 11:25:04 - using account id 'username'...     
Bestätigung
Vorgang fortsetzen?
[J] Ja [A] Ja, alle [B] Befehl anhalten [H] Anhalten [?] Help (default is "Ja"): j
Bestätigung
Möchten Sie diese Aktion wirklich ausführen?
Ausführen des Vorgangs "Creating Deployment" für das Ziel "resourcegroupname".
[J] Ja [A] Ja, alle [N] Nein [K] Nein, keine [H] Anhalten [?] Help (default is "Ja"): j
DEBUG: [Common.Authentication]: Authenticating using Account: 'username', environment: 'AzureCloud', tenant: 'tenantId'
Bestätigung
Vorgang fortsetzen?
[J] Ja [A] Ja, alle [B] Befehl anhalten [H] Anhalten [?] Help (default is "Ja"): j
DEBUG: SharedTokenCacheCredential.GetToken invoked. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId: 
Bestätigung
Vorgang fortsetzen?
[J] Ja [A] Ja, alle [B] Befehl anhalten [H] Anhalten [?] Help (default is "Ja"): j
DEBUG: SharedTokenCacheCredential.GetToken succeeded. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId:  ExpiresOn: 2020-12-01T11:24:48.0000000+00:00
Bestätigung
Vorgang fortsetzen?
[J] Ja [A] Ja, alle [B] Befehl anhalten [H] Anhalten [?] Help (default is "Ja"): j
DEBUG: SharedTokenCacheCredential.GetToken invoked. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId: 
Bestätigung
Vorgang fortsetzen?
[J] Ja [A] Ja, alle [B] Befehl anhalten [H] Anhalten [?] Help (default is "Ja"): j
DEBUG: SharedTokenCacheCredential.GetToken succeeded. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId:  ExpiresOn: 2020-12-01T11:24:48.0000000+00:00
Bestätigung
Vorgang fortsetzen?
[J] Ja [A] Ja, alle [B] Befehl anhalten [H] Anhalten [?] Help (default is "Ja"): j
DEBUG: [Common.Authentication]: Received token with LoginType 'User', Tenant: 'tenantId', UserId: 'userName'
Bestätigung
Vorgang fortsetzen?
[J] Ja [A] Ja, alle [B] Befehl anhalten [H] Anhalten [?] Help (default is "Ja"): j
DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
POST

Absolute Uri:
https://management.azure.com/subscriptions/subscriptionId/resourcegroups/resourcegroupname/providers/Microsoft.Resources/deployments/addKeyVault/validate?api-version=2020-06-01

Headers:
x-ms-client-request-id        : b880558b-302b-4b84-8b4d-efbab5489ebe
accept-language               : en-US

Body:
{
  "properties": {
    "template": {
      "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
      "contentVersion": "1.0.0.0",
      "parameters": {
        "name": {
          "type": "string",
          "defaultValue": "kvname"
        },
        "location": {
          "type": "string",
          "defaultValue": "[resourceGroup().location]"
        },
        "sku": {
          "type": "string",
          "defaultValue": "Standard"
        },
        "accessPolicies": {
          "type": "array",
          "defaultvalue": [
            {
              "objectId": "objectId",
              "tenantId": "[subscription().tenantId]",
              "permissions": {
                "keys": "",
                "secrets": "Get List Set Delete Recover Backup Restore",
                "certificates": ""
              },
              "applicationId": null
            }
          ]
        },
        "tenantId": {
          "type": "string",
          "defaultValue": "[subscription().tenantId]",
          "metadata": {
            "description": "Specifies the Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. Get it by using Get-AzSubscription cmdlet."
          }
        }
      },
      "variables": {},
      "resources": [
        {
          "type": "Microsoft.KeyVault/vaults",
          "name": "[parameters('name')]",
          "location": "[parameters('location')]",
          "apiVersion": "2019-09-01",
          "tags": {
            "displayName": "KeyVault"
          },
          "properties": {
            "enabledForDeployment": false,
            "enabledForTemplateDeployment": false,
            "enabledForDiskEncryption": false,
            "enableSoftDelete": true,
            "softDeleteRetentionInDays": 90,
            "tenantId": "[parameters('tenantId')]",
            "accessPolicies": "[parameters('accessPolicies')]",
            "sku": {
              "name": "[parameters('sku')]",
              "family": "A"
            },
            "networkAcls": {
              "defaultAction": "Allow",
              "bypass": "AzureServices"
            }
          }
        }
      ],
      "outputs": {}
    },
    "parameters": {},
    "mode": "Incremental"
  }
}


Bestätigung
Vorgang fortsetzen?
[J] Ja [A] Ja, alle [B] Befehl anhalten [H] Anhalten [?] Help (default is "Ja"): j
DEBUG: ============================ HTTP RESPONSE ============================

Status Code:
OK

Headers:
Pragma                        : no-cache
x-ms-ratelimit-remaining-subscription-writes: 1197
x-ms-request-id               : 7c16b74d-fff5-4d05-90e7-5b352f4f3781
x-ms-correlation-request-id   : 7c16b74d-fff5-4d05-90e7-5b352f4f3781
x-ms-routing-request-id       : GERMANYWESTCENTRAL:20201201T102506Z:7c16b74d-fff5-4d05-90e7-5b352f4f3781
Strict-Transport-Security     : max-age=31536000; includeSubDomains
X-Content-Type-Options        : nosniff
Cache-Control                 : no-cache
Date                          : Tue, 01 Dec 2020 10:25:05 GMT

Body:
{
  "id": "/subscriptions/subscriptionId/resourcegroups/resourcegroupname/providers/Microsoft.Resources/deployments/addKeyVault",
  "name": "addKeyVault",
  "type": "Microsoft.Resources/deployments",
  "properties": {
    "templateHash": "9468291095648279112",
    "parameters": {
      "name": {
        "type": "String",
        "value": "kvname"
      },
      "location": {
        "type": "String",
        "value": "westeurope"
      },
      "sku": {
        "type": "String",
        "value": "Standard"
      },
      "accessPolicies": {
        "type": "Array",
        "value": [
          {
            "objectId": "objid",
            "tenantId": "tenantId",
            "permissions": {
              "keys": "",
              "secrets": "Get List Set Delete Recover Backup Restore",
              "certificates": ""
            },
            "applicationId": null
          }
        ]
      },
      "tenantId": {
        "type": "String",
        "value": "tenantId"
      }
    },
    "mode": "Incremental",
    "provisioningState": "Succeeded",
    "timestamp": "2020-12-01T10:25:06.3031798Z",
    "duration": "PT0S",
    "correlationId": "7c16b74d-fff5-4d05-90e7-5b352f4f3781",
    "providers": [
      {
        "namespace": "Microsoft.KeyVault",
        "resourceTypes": [
          {
            "resourceType": "vaults",
            "locations": [
              "westeurope"
            ]
          }
        ]
      }
    ],
    "dependencies": [],
    "validatedResources": [
      {
        "id": "subscriptions/subscriptionId/resourcegroups/resourcegroupname/providers/Microsoft.KeyVault/vaults/psmccom-ti-cred"
      }
    ]
  }
}


Bestätigung
Vorgang fortsetzen?
[J] Ja [A] Ja, alle [B] Befehl anhalten [H] Anhalten [?] Help (default is "Ja"): j
VERBOSE: 11:25:06 - Template is valid.
DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
PUT

Absolute Uri:
https://management.azure.com/subscriptions/subscriptionId/resourcegroups/resourcegroupname/providers/Microsoft.Resources/deployments/addKeyVault?api-version=2020-06-01

Headers:
x-ms-client-request-id        : 68ef6731-a7db-40fa-b628-f5e47a53d10f
accept-language               : en-US

Body:
{
  "properties": {
    "template": {
      "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
      "contentVersion": "1.0.0.0",
      "parameters": {
        "name": {
          "type": "string",
          "defaultValue": "kvname"
        },
        "location": {
          "type": "string",
          "defaultValue": "[resourceGroup().location]"
        },
        "sku": {
          "type": "string",
          "defaultValue": "Standard"
        },
        "accessPolicies": {
          "type": "array",
          "defaultvalue": [
            {
              "objectId": "objId",
              "tenantId": "[subscription().tenantId]",
              "permissions": {
                "keys": "",
                "secrets": "Get List Set Delete Recover Backup Restore",
                "certificates": ""
              },
              "applicationId": null
            }
          ]
        },
        "tenantId": {
          "type": "string",
          "defaultValue": "[subscription().tenantId]",
          "metadata": {
            "description": "Specifies the Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. Get it by using Get-AzSubscription cmdlet."
          }
        }
      },
      "variables": {},
      "resources": [
        {
          "type": "Microsoft.KeyVault/vaults",
          "name": "[parameters('name')]",
          "location": "[parameters('location')]",
          "apiVersion": "2019-09-01",
          "tags": {
            "displayName": "KeyVault"
          },
          "properties": {
            "enabledForDeployment": false,
            "enabledForTemplateDeployment": false,
            "enabledForDiskEncryption": false,
            "enableSoftDelete": true,
            "softDeleteRetentionInDays": 90,
            "tenantId": "[parameters('tenantId')]",
            "accessPolicies": "[parameters('accessPolicies')]",
            "sku": {
              "name": "[parameters('sku')]",
              "family": "A"
            },
            "networkAcls": {
              "defaultAction": "Allow",
              "bypass": "AzureServices"
            }
          }
        }
      ],
      "outputs": {}
    },
    "parameters": {},
    "mode": "Incremental"
  }
}


Bestätigung
Vorgang fortsetzen?
[J] Ja [A] Ja, alle [B] Befehl anhalten [H] Anhalten [?] Help (default is "Ja"): j
DEBUG: ============================ HTTP RESPONSE ============================

Status Code:
OK

Headers:
Pragma                        : no-cache
Azure-AsyncOperation          : https://management.azure.com/subscriptions/subscriptionId/resourcegroups/resourcegroupname/providers/Microsoft.Resources/deployments/addKeyVault/operationStatuses/08585947885738533236?api-version=2020-06-01
x-ms-ratelimit-remaining-subscription-writes: 1198
x-ms-request-id               : fc6451a2-6540-46b2-88d1-a936dd626ca3
x-ms-correlation-request-id   : fc6451a2-6540-46b2-88d1-a936dd626ca3
x-ms-routing-request-id       : GERMANYWESTCENTRAL:20201201T102511Z:fc6451a2-6540-46b2-88d1-a936dd626ca3
Strict-Transport-Security     : max-age=31536000; includeSubDomains
X-Content-Type-Options        : nosniff
Cache-Control                 : no-cache
Date                          : Tue, 01 Dec 2020 10:25:11 GMT

Body:
{
  "id": "subscriptions/subscriptionId/resourcegroups/resourcegroupname/providers/Microsoft.Resources/deployments/addKeyVault",
  "name": "addKeyVault",
  "type": "Microsoft.Resources/deployments",
  "properties": {
    "templateHash": "9468291095648279112",
    "parameters": {
      "name": {
        "type": "String",
        "value": "kvName"
      },
      "location": {
        "type": "String",
        "value": "westeurope"
      },
      "sku": {
        "type": "String",
        "value": "Standard"
      },
      "accessPolicies": {
        "type": "Array",
        "value": [
          {
            "objectId": "objId",
            "tenantId": "tenantId",
            "permissions": {
              "keys": "",
              "secrets": "Get List Set Delete Recover Backup Restore",
              "certificates": ""
            },
            "applicationId": null
          }
        ]
      },
      "tenantId": {
        "type": "String",
        "value": "tenantId"
      }
    },
    "mode": "Incremental",
    "provisioningState": "Accepted",
    "timestamp": "2020-12-01T10:25:11.8564464Z",
    "duration": "PT0.2321564S",
    "correlationId": "fc6451a2-6540-46b2-88d1-a936dd626ca3",
    "providers": [
      {
        "namespace": "Microsoft.KeyVault",
        "resourceTypes": [
          {
            "resourceType": "vaults",
            "locations": [
              "westeurope"
            ]
          }
        ]
      }
    ],
    "dependencies": []
  }
}


Bestätigung
Vorgang fortsetzen?
[J] Ja [A] Ja, alle [B] Befehl anhalten [H] Anhalten [?] Help (default is "Ja"): j
VERBOSE: 11:25:12 - Create template deployment 'addKeyVault'
VERBOSE: 11:25:15 - Checking deployment status in 5 seconds
DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
GET

Absolute Uri:
https://management.azure.com/subscriptions/subscriptionId/resourcegroups/resourcegroupname/deployments/addKeyVault/operations?api-version=2020-06-01

Headers:
x-ms-client-request-id        : 90f688d0-52dd-42f9-843b-f90ea5029fb2
accept-language               : en-US

Body:



Bestätigung
Vorgang fortsetzen?
[J] Ja [A] Ja, alle [B] Befehl anhalten [H] Anhalten [?] Help (default is "Ja"): j
DEBUG: ============================ HTTP RESPONSE ============================

Status Code:
OK

Headers:
Pragma                        : no-cache
x-ms-ratelimit-remaining-subscription-reads: 11982
x-ms-request-id               : 12ca4085-1396-4531-a0f3-bcc47cc46fc3
x-ms-correlation-request-id   : 12ca4085-1396-4531-a0f3-bcc47cc46fc3
x-ms-routing-request-id       : GERMANYWESTCENTRAL:20201201T102519Z:12ca4085-1396-4531-a0f3-bcc47cc46fc3
Strict-Transport-Security     : max-age=31536000; includeSubDomains
X-Content-Type-Options        : nosniff
Cache-Control                 : no-cache
Date                          : Tue, 01 Dec 2020 10:25:19 GMT

Body:
{
  "value": [
    {
      "id": "subscriptions/subscriptionId/resourcegroups/resourcegroupname/providers/Microsoft.Resources/deployments/addKeyVault/operations/D5E656753912A57A",
      "operationId": "D5E656753912A57A",
      "properties": {
        "provisioningOperation": "Create",
        "provisioningState": "Failed",
        "timestamp": "2020-12-01T10:25:13.1328085Z",
        "duration": "PT1.048678S",
        "trackingId": "1f6559f5-f794-47e6-ac5c-a690460bf69f",
        "serviceRequestId": "c673774d-a445-4768-99e3-f638fe1adbe7",
        "statusCode": "BadRequest",
        "statusMessage": {
          "status": "Failed",
          "error": {
            "code": "BadRequest",
            "message": "Bad JSON content found in the request."
          }
        },
        "targetResource": {
          "id": "subscriptions/subscriptionId/resourcegroups/resourcegroupname/providers/Microsoft.KeyVault/vaults/psmccom-ti-cred",
          "resourceType": "Microsoft.KeyVault/vaults",
          "resourceName": "kvname"
        }
      }
    }
  ]
}


Bestätigung
Vorgang fortsetzen?
[J] Ja [A] Ja, alle [B] Befehl anhalten [H] Anhalten [?] Help (default is "Ja"): J
DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
GET

Absolute Uri:
https://management.azure.com/subscriptions/subscriptionId/resourcegroups/resourcegroupname/providers/Microsoft.Resources/deployments/addKeyVault?api-version=2020-06-01

Headers:
x-ms-client-request-id        : 7d2a911a-32f6-4419-a5ba-8c47525a94f3
accept-language               : en-US

Body:



Bestätigung
Vorgang fortsetzen?
[J] Ja [A] Ja, alle [B] Befehl anhalten [H] Anhalten [?] Help (default is "Ja"): J
DEBUG: ============================ HTTP RESPONSE ============================

Status Code:
OK

Headers:
Pragma                        : no-cache
x-ms-ratelimit-remaining-subscription-reads: 11981
x-ms-request-id               : 34572e39-4ca3-4cf0-af8d-fb8487c16f0a
x-ms-correlation-request-id   : 34572e39-4ca3-4cf0-af8d-fb8487c16f0a
x-ms-routing-request-id       : GERMANYWESTCENTRAL:20201201T102519Z:34572e39-4ca3-4cf0-af8d-fb8487c16f0a
Strict-Transport-Security     : max-age=31536000; includeSubDomains
X-Content-Type-Options        : nosniff
Cache-Control                 : no-cache
Date                          : Tue, 01 Dec 2020 10:25:19 GMT

Body:
{
  "id": "/subscriptions/subscriptionId/resourcegroups/resourcegroupname/providers/Microsoft.Resources/deployments/addKeyVault",
  "name": "addKeyVault",
  "type": "Microsoft.Resources/deployments",
  "properties": {
    "templateHash": "9468291095648279112",
    "parameters": {
      "name": {
        "type": "String",
        "value": "kvname"
      },
      "location": {
        "type": "String",
        "value": "westeurope"
      },
      "sku": {
        "type": "String",
        "value": "Standard"
      },
      "accessPolicies": {
        "type": "Array",
        "value": [
          {
            "objectId": "objId",
            "tenantId": "tenantId",
            "permissions": {
              "keys": "",
              "secrets": "Get List Set Delete Recover Backup Restore",
              "certificates": ""
            },
            "applicationId": null
          }
        ]
      },
      "tenantId": {
        "type": "String",
        "value": "tenantId"
      }
    },
    "mode": "Incremental",
    "provisioningState": "Failed",
    "timestamp": "2020-12-01T10:25:13.2609024Z",
    "duration": "PT1.6366124S",
    "correlationId": "fc6451a2-6540-46b2-88d1-a936dd626ca3",
    "providers": [
      {
        "namespace": "Microsoft.KeyVault",
        "resourceTypes": [
          {
            "resourceType": "vaults",
            "locations": [
              "westeurope"
            ]
          }
        ]
      }
    ],
    "dependencies": [],
    "error": {
      "code": "DeploymentFailed",
      "message": "At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/DeployOperations for usage details.",
      "details": [
        {
          "code": "BadRequest",
          "message": "Bad JSON content found in the request."
        }
      ]
    }
  }
}


Bestätigung
Vorgang fortsetzen?
[J] Ja [A] Ja, alle [B] Befehl anhalten [H] Anhalten [?] Help (default is "Ja"): J
Bestätigung
11:25:20 - The deployment 'addKeyVault' failed with error(s). Showing 1 out of 1 error(s).
Status Message: Bad JSON content found in the request. (Code:BadRequest)

CorrelationId: fc6451a2-6540-46b2-88d1-a936dd626ca3
[J] Ja [A] Ja, alle [B] Befehl anhalten [H] Anhalten [?] Help (default is "Ja"): J
New-AzResourceGroupDeployment : 11:25:20 - The deployment 'addKeyVault' failed with error(s). Showing 1 out of 1 error(s).
Status Message: Bad JSON content found in the request. (Code:BadRequest)
CorrelationId: fc6451a2-6540-46b2-88d1-a936dd626ca3
In C:\_dev\CANCOM%20Teams%20Intelligence\runbooks\createResources.ps1:182 Zeichen:23
+ ... loyResult = New-AzResourceGroupDeployment -Name "addKeyVault" -Resour ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [New-AzResourceGroupDeployment], Exception
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.NewAzureResourceGroupDeploymentCmdlet

DEBUG: AzureQoSEvent: CommandName - New-AzResourceGroupDeployment; IsSuccess - False; Duration - 00:05:32.0699732;; Exception - System.Exception: 11:25:20 - The deployment 'addKeyVault' failed with error(s). Showing 1 out of 1 error(s).    
Status Message: Bad JSON content found in the request. (Code:BadRequest)`

PowerShell/pwsh steps do not fail on command not found, parameter not found or parameter validation errors

Not sure if this is the correct repo for the GitHub/Azure DevOps powershell action that is used by PowerShell repo to build PowerShell. There's some inception level stuff going on here. :-) Anyway, this issue cropped on a PR build. We were having a hard time figuring out what was going wrong. It turns out that a PowerShell step was indicating it passed when it was clearly failing:

image

In fact, a few experiments with this repo's approach to executing PowerShell script shows that it fails in these other scenarios as well:

image

image

The fix is to execute the wrapper script using try { . 'path-to-ps1' } catch {throw} which causes these issues to return a non-zero exit code:

image

I recently made the same change to the Jenkins durable-task-plugin to fix the very same issue with the powershell/pwsh step in Jenkins pipelines. See my PR for that project.

I would suggest that the following tests for the PowerShell step be added to verify the current impl fails (red/green testing):

- pwsh: Get-CommandDoesNotExist

- pwsh: Get-Date -ParameterDoesNotExist

- pwsh Get-Date -Month 13 # invalid parameter value

- pwsh: Write-Host (1+)  # parse error - I think this works today but good to have a test if you don't already

Failed initializing Az Module

On self hosted runner Windows 10

`Run azure/powershell@v1
Validating inputs
Module Az latest installed from hostedAgentFolder
Initializing Az Module
"C:\Program Files\PowerShell\7\pwsh.exe" -NoLogo -NoProfile -NonInteractive -Command Test-Path (Join-Path C:\Modules az_)
"C:\Program Files\PowerShell\7\pwsh.exe" -NoLogo -NoProfile -NonInteractive -Command "try ***
$ErrorActionPreference = "Stop"
$WarningPreference = "SilentlyContinue"
$output = @
**
$data = Get-Module -Name Az -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
$output['AzVersion'] = $data.Version.ToString()
$output['Success'] = "true"
***
catch ***
$output['Error'] = $_.exception.Message
***
return ConvertTo-Json $output"
False

"Error": "You cannot call a method on a null-valued expression."

`

Question: Controlling the Log level

By default I get a lot of DEBUG logs in the action output. e.g.

DEBUG: Sought all Az modules and got latest version 6.1.0

Is it possible to control the log level?

Az.ImageBuilder module could not be loaded

modules are installed from PSGallery
Run azure/powershell@v1 using the shell PWSH

Calls an inline script and stops with error:
"The 'Get-AzImageBuilderTemplate' command was found in the module 'Az.ImageBuilder', but the module could not be
| loaded. For more information, run 'Import-Module Az.ImageBuilder'.
Error: Error: The process 'C:\Program Files\PowerShell\7\pwsh.exe' failed with exit code 1"

We have 3 separate workflows and all fails due to this error. Please guide.

Action does not use Azure context set by azure/login step

I created a workflow that simply connects to Azure and calls Get-AzSubscription. It follows the sample in the README.md file for this action almost exactly.

  • When I run the workflow on the windows-latest GitHub-hosted runner (installed software), it succeeds.

  • When I run the workflow on a self-hosted runner with the same (relevant) software, the azure/login step succeeds:

Azure PowerShell session successfully initialized
Login successful.

...but the azure/powershell step fails with this error:

Run Connect-AzAccount to login.

Here's the entire workflow:

name: Connect to Azure
on:
  push:
    branches: master
    paths: 
    - '.github/workflows/connect-to-azure.yml'
jobs:
  deploy:
    runs-on: windows-latest
    steps:
    - name: Login to Azure
      uses: azure/[email protected]
      with:
        creds: ${{secrets.AZURE_DEPLOYMENT_SERVICE_PRINCIPAL}}
        enable-AzPSSession: true
      
    - name: Deploy app package
      uses: azure/powershell@v1
      with:
        azPSVersion: latest
        inlineScript: Get-AzSubscription -SubscriptionId "<my-subscription-id>"

Both environments have the following software installed:

  • GitHub runner 2.262.1
  • PowerShell Core 7.0.1
  • Azure CLI 2.5.1
  • Az 3.8.0
  • Az.Accounts 1.7.5

What am I missing? This workflow should be trivial to get working on a self-hosted runner.

Additional info:

  • The self-hosted runner OS is Windows 10 Pro 18362.
  • I get the same error with the following software versions installed:
    • PowerShell Core 6.2.4
    • Azure CLI 2.6.0
    • Az 3.8.0
    • Az.Accounts 1.8.0
  • I can connect to Azure successfully on the self-hosted runner using this PS command, which is the same as what the azure/login action does:
Connect-AzAccount -ServicePrincipal -Tenant <tenant-id> -Credential <service-principal-creds> -Environment AzureCloud

Get-AzUserAssignedIdentity command not working

Get-AzVM, Get-AzResourceGroup and Get-AzUserAssignedIdentity commands are not working.

We are calling PS script from GitHub Actions, inside which we are calling these commands.

We are using below for yaml file:
runs-on: ubuntu-latest
steps:

  • name: Azure Login
    uses: Azure/[email protected]
    with:
    creds: '${{ secrets.xxx }}'
    enable-AzPSSession: true

    • name: Checkout source code
      uses: actions/checkout@v4

    • name: Group Policy
      uses: azure/powershell@v2

https://github.com/allscriptshealthcare/ALT-CDO-Azure/actions/runs/8690262646/job/23829783601

Get-AzResourceGroupDeployment does not correctly return deployment outputs

Running a Resource Group Deployment for some fairly simple Virtual Machine resources and need to send the VM names as output from the template. The output is defined as described the same way as in most examples. When looking at the Azure portal, the output of the VM names is correctly displayed as an array. However, when using PowerShell to get the deployment, the output does not show the array of VM names.

Output section from the ARM template:

"outputs": {
        "sessionHostNames": {
            "copy": {
                "count": "[parameters('az_vmNumberOfInstances')]",
                "input": "[wvdSessionHost.getName(parameters('az_vmNamePrefix'),copyIndex(variables('wvdshOffSet')))]"
            },
            "type": "Array"
        }
    }

arm_output

PowerShell Output:

$jobB = Get-AzResourceGroupDeployment -ResourceGroupName <redacted> -Name Deploy-WVD-SessionHosts-Group-B-a0df4c2b351b



DeploymentName          : Deploy-WVD-SessionHosts-Group-B-a0df4c2b351b
ResourceGroupName       : <redacted>
ProvisioningState       : Succeeded
Timestamp               : 9/29/2020 2:30:51 PM
Mode                    : Incremental
TemplateLink            : 
                          Uri            : <redacted>
                          ContentVersion : 1.0.0.0
                          
Parameters              : 
                          Name                       Type                       Value     
                          =========================  =========================  ==========
                          timeStamp                  String                     20200929T142925Z
                          az_vmSize                  String                     Standard_D8s_v4
                          az_vmNumberOfInstances     Int                        3         
                          az_vmStartingIncrement     Int                        3         
                          az_vmNamePrefix            String                     c30-wshp01
                          az_vmImageOffer            String                     windowsserver
                          az_vmImagePublisher        String                     microsoftwindowsserver
                          az_vmImageSKU              String                     2019-datacenter
                          az_vmDiskType              String                     Premium_LRS
                          wvd_groupReference         String                     B         
                          wvd_buildVersion           String                     1.2       
                          wvd_subnetId               String                       <redacted>
                          wvd_hostpoolName           String                     <redacted>
                          dj_adminAccountUPN         String                    <redacted>
                          dj_adminAccountPassword    SecureString                         
                          
Outputs                 : 
                          Name                Type                       Value     
                          ==================  =========================  ==========
                          sessionHostNames    Array                      [
                            "c30-wshp01sh006",
                            "c30-wshp01sh007",
                            "c30-wshp01sh008"
                          ]
                          
DeploymentDebugLogLevel : 
$jobB.Outputs.sessionHostNames

Type  Value
----  -----
Array {, , }

Trying to understand why the Portal clearly shows the array, but when trying to get the names programatically from PowerShell, it returns null values.

When should you use this action over normal bash?

Hey,

First of all, thanks for all the great open source contributions - I really appreciate it.
I was wondering, how a best practice for this action in combination with a normal powershell would look like. How is this action better suited for commands than the normal powershell?

Thanks,
Jan

Working directory

Would be nice to have a working directory to set, so when scripts are ie. referencing ARM templates in the script folder or a sub-folder it won't breake the action.

[docs] Old link to actions/virtual-environments#available-environments in README

Link https://github.com/actions/virtual-environments#available-environments from:

To use the latest Az module version, specify 'latest'. You can find the list of Az module versions that can be given as azPSVersion from this [table](https://github.com/actions/virtual-environments#available-environments).

should be updated to: https://github.com/actions/runner-images#available-images.

(Repo redirect works on GitHub level, but the HTML content ID in the linked README was changed from available-environments to available-images)

Copy files from one folder to another folder

I'm trying to copy files from one folder to another folder in github branch by ignoring one folder(trigger) using below powershell script

name: Azure PowerShell Action
uses: Azure/powershell@v1
with:

Specify the Az PowerShell script here.
inlineScript: |
[System.Collections.ArrayList]$E = (get-childitem -path ".\dev").name
$E.remove("trigger")
copy-item -path ".\dev*" -destination ".\prod" -Recurse -Force
Write-Output "File copy process completed."

Azure PS version to be used to execute the script, example: 1.8.0, 2.8.0, 3.4.0. To use the latest version, specify "latest".
azPSVersion: 5.1

Select the value of the ErrorActionPreference variable for executing the script. Options: stop, continue, silentlyContinue. Default is Stop.
errorActionPreference: Stop
From the above script my pipeline is running successfully but I'm unable to see content copied from one folder to another folder. Please help me on this issue.

Dependabot Pull Requests Merged

Curious if this action is still being maintained? I see dependabot pull requests from last fall that have not yet been merged into the master branch?

Can we use Desktop instead of Core

I want to run a Set-AzureWebsite command, but get this:
The 'Set-AzureWebsite' command was found in the module 'Azure', but the module could not be loaded.
| For more information, run 'Import-Module Azure'.

I add a command:
Import-Module -Name Azure -Verbose
now get this:
Could not load type 'System.Management.Automation.PSSnapIn' from assembly
| 'System.Management.Automation, Version=7.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.

according to this, it appears to be an issue of Powershell using dotnet core: seanmcne/Microsoft.Xrm.Data.PowerShell#443

How can I specify to use Powershell Desktop?

Make PS faster by removing the calls to get progress info

There is a feature request for Powershell -

The progress bar in PowerShell makes Invoke-WebRequest literally 50x slower. Downloading the .iso for building dev images would probably hit the default 60 minute timeout with progress enabled. With progress disabled it completes in a few minutes like you’d expect. This is especially galling because progress is not rendered by pipelines so it is wasted work.

Can we start a discussion with the ADO and GitHub Actions folks to see if their PowerShell tasks can disable progress automatically? That would be an immediate boost in pipeline performance with no downside that I’m aware of. Disabling progress in PowerShell just requires a single line of setup:
$ProgressPreference = 'SilentlyContinue';

For the above can we please check if any changes are needed in the powershell Action?
Related on ADO - https://dev.azure.com/mseng/AzureDevOps/_workitems/edit/1914047
Related - Azure/pipelines#53

Set environment variables from action

Hi, I'm trying to use this action get some details from Az Powershell cmdlets and send the information back to the workflow. Can this be done with this action?

Writable AzInstallFolder requirement breaks self-hosted runner

The following code was recently added to Utils.getDefaultAzInstallFolder() via PR #91:

        ...

        if(Utils.isFolderExistAndWritable(defaultAzInstallFolder)){
            return defaultAzInstallFolder;
        }
        if(Utils.isFolderExistAndWritable(process.env.RUNNER_TOOL_CACHE)){
            return process.env.RUNNER_TOOL_CACHE;
        }
        return process.cwd();

It is difficult to know for certain, but I believe this new "writable" requirement is causing my self-hosted, custom runners to not find the "latest" installed Az module. What I can say for certain, is that azure/[email protected] works as expected, but 1.4.0 fails to find any Az modules (Get-Module -Name Az -ListAvailable returns nothing).

The command we use to load the Az module on the runner image is Save-Module -Path /usr/share/az_7.1.0 -Name az -RequiredVersion 7.1.0 -Force, which is exactly where the azure/powershell action expects it to be. So, the only explanation I can come up with is /usr/share/ is not writable on my runners.

Any chance we can remove the "writeable" requirement? It should not be necessary.

Details

Workflow invocation:

  my_job:
    runs-on:
      - self-hosted
    steps:
      - uses: actions/checkout@v3
      - uses: azure/powershell@v1
        with:
          azPSVersion: latest
          inlineScript: ./scripts/foo.ps1

Self hosted runner details (very briefly):

FROM summerwind/actions-runner:ubuntu-20.04
.
.
.
# Cache the Azure Powershell modules. Based on https://github.com/actions/virtual-environments/blob/d3de894568d2662083e3515b884c86e9326ea255/images/linux/scripts/installers/Install-AzureModules.ps1#L18
# Use the [Azure/powershell@v1](https://github.com/Azure/powershell/tree/v1) action with `azPSVersion: latest` to activate it.
RUN sudo pwsh -c 'Save-Module -Path /usr/share/az_7.1.0 -Name az -RequiredVersion 7.1.0 -Force'
.
.
.

using Az.Resources module

Using azure/powershell@v1 module it gives error on using Get-AzResources:

The term 'Get-AzResource' is not recognized as the name of a
     | cmdlet, function, script file, or operable program. Check the
     | spelling of the name, or if a path was included, verify that
     | the path is correct and try again.

It seems like Az.Resource module is not installed in the powershell. How do i ensure that ? I have specified azPSVersion as 4.5.0 which should contain this module.

Cannot find type [Microsoft.Open.AzureAD.Model.AppRole]

Is there anyway to use AzureAD module in this? Seems that the module is installed but can not be used properly
AzureAD needs to run in powershell.exe v2 and actions run it as pwsh.exe v.7

Caught the exception System.Management.Automation.PSArgumentException: Cannot find type [Microsoft.Open.AzureAD.Model.AppRole]: verify that the assembly containing this type is loaded.
at System.Management.Automation.MshCommandRuntime.ThrowTerminatingError(ErrorRecord errorRecord)

https://docs.microsoft.com/en-us/answers/questions/903709/cloudshell.html

Specifying latest for the azPSVersion generates an exception on the Ubuntu hosted agent

On the Ubuntu runner, the following yaml snipped will generate an exception (burying the output) :

    steps:
    - name: checkout
      uses: actions/checkout@v2
    - name: 'Azure PowerShell script: Inline Script Version'
      continue-on-error: true
      uses: Azure/login@v1
      with:
        creds: "${{ secrets.AZURE_CREDENTIALS }}"
    - name: 'Azure PowerShell script: Inline Script Version'
      continue-on-error: true
      uses: azure/powershell@v1
      with:
        inlineScript: |-
          Write-Host "Testing 1.2..3..."
          Get-ChildItem
        errorActionPreference: Stop
        failOnStandardError: false
        azPSVersion: "latest"

The exception output is:

Run azure/powershell@v1
Validating inputs
Module Az latest installed from hostedAgentFolder
Initializing Az Module
/usr/bin/pwsh -NoLogo -NoProfile -NonInteractive -Command Test-Path (Join-Path /usr/share az_*)
/usr/bin/pwsh -NoLogo -NoProfile -NonInteractive -Command try ***
            $ErrorActionPreference = "Stop"
            $WarningPreference = "SilentlyContinue"
            $output = @***
            $data = Get-Module -Name Az -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
            $output['AzVersion'] = $data.Version.ToString()
            $output['Success'] = "true"
        ***
        catch ***
            $output['Error'] = $_.exception.Message
        ***
        return ConvertTo-Json $output
Process terminated. The type initializer for 'Microsoft.PowerShell.Telemetry.ApplicationInsightsTelemetry' threw an exception.
   at System.Environment.FailFast(System.String, System.Exception)
   at Microsoft.PowerShell.UnmanagedPSEntry.Start(System.String[], Int32)
   at Microsoft.PowerShell.ManagedPSEntry.Main(System.String[])
System.TypeInitializationException: The type initializer for 'Microsoft.PowerShell.Telemetry.ApplicationInsightsTelemetry' threw an exception.
 ---> System.IO.IOException: The system cannot open the device or file specified. : 'CreateUniqueUserId'
   at System.Threading.Mutex.CreateMutexCore(Boolean initiallyOwned, String name, Boolean& createdNew)
   at System.Threading.Mutex..ctor(Boolean initiallyOwned, String name)
   at Microsoft.PowerShell.Telemetry.ApplicationInsightsTelemetry.GetUniqueIdentifier() in /PowerShell/src/System.Management.Automation/utils/Telemetry.cs:line 802
   at Microsoft.PowerShell.Telemetry.ApplicationInsightsTelemetry..cctor() in /PowerShell/src/System.Management.Automation/utils/Telemetry.cs:line 548
   --- End of inner exception stack trace ---
   at Microsoft.PowerShell.Telemetry.ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry(String mode) in /PowerShell/src/System.Management.Automation/utils/Telemetry.cs:line 656
   at Microsoft.PowerShell.ConsoleHost.Start(String bannerText, String helpText) in /PowerShell/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs:line 248
(node:1671) UnhandledPromiseRejectionWarning: Error: The process '/usr/bin/pwsh' failed with exit code null
    at ExecState._setResult (/home/runner/work/_actions/azure/powershell/v1/node_modules/@actions/exec/lib/toolrunner.js:561:25)
    at ExecState.CheckComplete (/home/runner/work/_actions/azure/powershell/v1/node_modules/@actions/exec/lib/toolrunner.js:544:18)
    at ChildProcess.<anonymous> (/home/runner/work/_actions/azure/powershell/v1/node_modules/@actions/exec/lib/toolrunner.js:444:27)
    at ChildProcess.emit (events.js:210:5)
    at maybeClose (internal/child_process.js:1021:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)
(node:1671) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:1671) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
   at Microsoft.PowerShell.UnmanagedPSEntry.Start(String[] args, Int32 argc) in /PowerShell/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs:line 99***
  "AzVersion": "6.1.0",
  "Success": "true"
***
Initializing Az Module Complete
Running Az PowerShell Script
/usr/bin/pwsh -NoLogo -NoProfile -NonInteractive -Command /home/runner/work/_temp/f6af17b0-6b1e-4ebb-b04d-5a5cadbd0600.ps1
Testing 1.2..3...

    Directory: /home/runner/work/valet-testing/valet-testing

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-----          09/03/2021    01:07             37 README.md

This happens when azPSVersion is latest, 'latest', or "latest".

However it works if a specific azPSVersion is specified such as: 3.1.0 or 6.1.0.

That is, the following action.yml generates the appropriate output:

    steps:
    - name: checkout
      uses: actions/checkout@v2
    - name: 'Azure PowerShell script: Inline Script Version'
      continue-on-error: true
      uses: Azure/login@v1
      with:
        creds: "${{ secrets.AZURE_CREDENTIALS }}"
    - name: 'Azure PowerShell script: Inline Script Version'
      continue-on-error: true
      uses: azure/powershell@v1
      with:
        inlineScript: |-
          Write-Host "Testing 1.2..3..."
          Get-ChildItem
        errorActionPreference: Stop
        failOnStandardError: false
        azPSVersion: 6.1.0

In this case, the run succeeds without an exception:

Run azure/powershell@v1
Validating inputs
Module Az 6.1.0 installed from hostedAgentFolder
Initializing Az Module
Initializing Az Module Complete
Running Az PowerShell Script
/usr/bin/pwsh -NoLogo -NoProfile -NonInteractive -Command Test-Path (Join-Path /usr/share az_*)
/usr/bin/pwsh -NoLogo -NoProfile -NonInteractive -Command /home/runner/work/_temp/84acae14-92ca-479b-8ac8-08753b234257.ps1
Testing 1.2..3...
True

    Directory: /home/runner/work/valet-testing/valet-testing

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-----          09/03/2021    01:29             37 README.md

Script execution Complete

On a Windows runner, the azPSVersion works with either the latest or a numeric specification.

Process terminated. The type initializer for 'Microsoft.PowerShell.Telemetry.ApplicationInsightsTelemetry' threw an exception

I've started seeing this today.

Process terminated. The type initializer for 'Microsoft.PowerShell.Telemetry.ApplicationInsightsTelemetry' threw an exception.
   at System.Environment.FailFast(System.String, System.Exception)
   at Microsoft.PowerShell.UnmanagedPSEntry.Start(System.String[], Int32)
   at Microsoft.PowerShell.ManagedPSEntry.Main(System.String[])
System.TypeInitializationException: The type initializer for 'Microsoft.PowerShell.Telemetry.ApplicationInsightsTelemetry' threw an exception.
 ---> System.IO.IOException: The system cannot open the device or file specified. : 'CreateUniqueUserId'
   at System.Threading.Mutex.CreateMutexCore(Boolean initiallyOwned, String name, Boolean& createdNew)
   at System.Threading.Mutex..ctor(Boolean initiallyOwned, String name)
   at Microsoft.PowerShell.Telemetry.ApplicationInsightsTelemetry.GetUniqueIdentifier() in /PowerShell/src/System.Management.Automation/utils/Telemetry.cs:line 802
   at Microsoft.PowerShell.Telemetry.ApplicationInsightsTelemetry..cctor() in /PowerShell/src/System.Management.Automation/utils/Telemetry.cs:line 548
   --- End of inner exception stack trace ---
   at Microsoft.PowerShell.Telemetry.ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry(String mode) in /PowerShell/src/System.Management.Automation/utils/Telemetry.cs:line 656
   at Microsoft.PowerShell.ConsoleHost.Start(String bannerText, String helpText) in /PowerShell/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs:line 248
   at Microsoft.PowerShell.UnmanagedPSEntry.Start(String[] args, Int32 argc) in /PowerShell/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs:line 99True
Error: Error: The process '/usr/bin/pwsh' failed with exit code null

Action Fails after Login via Az module

I am using azure/login@v1 with enable-AzPSSession: true to login to azure but the next step azure/powershell@v1 fails with error:

     | Your Azure credentials have not been set up or have expired, please run
     | Connect-AzAccount to set up your Azure credentials. No certificate
     | thumbprint or secret provided for the given service principal
     | '***'.

My yml is: here

name: AzurePowerShellLoginSample
on:
  workflow_dispatch:

jobs:

  build:
    runs-on: ubuntu-latest
    steps:
    
    - name: Login via Az module
      uses: azure/login@v1
      with:
        creds: ${{secrets.POLICY_COMPLIANCE_SCAN}}
        allow-no-subscriptions: true
        enable-AzPSSession: true

    - name: Az PowerShell
      uses: azure/powershell@v1
      with:
        azPSVersion: "latest"
        inlineScript: |
          Get-AzContext
          if(-not (Get-Module Az.ResourceGraph -ListAvailable))
          {
            Install-Module Az.ResourceGraph -Scope CurrentUser -Force
          }
          $query = "resourcecontainers | where type == 'microsoft.resources/subscriptions' | project name, id | sort by name asc"
          $subscriptions = Search-AzGraph -Query $query -UseTenantScope
          $subscriptions

I found a workaround - add a ps cmdlet at the start of the inline script.

So, the following fails:

    - name: Az PowerShell
      uses: azure/powershell@v1
      with:
        azPSVersion: "latest"
        inlineScript: |
          if(-not (Get-Module Az.ResourceGraph -ListAvailable))
          {
            Install-Module Az.ResourceGraph -Scope CurrentUser -Force
          }
          $query = "resourcecontainers | where type == 'microsoft.resources/subscriptions' | project name, id | sort by name asc"
          $subscriptions = Search-AzGraph -Query $query -UseTenantScope
          $subscriptions

but his one succeeds:

    - name: Az PowerShell
      uses: azure/powershell@v1
      with:
        azPSVersion: "latest"
        inlineScript: |
          Get-AzContext
          if(-not (Get-Module Az.ResourceGraph -ListAvailable))
          {
            Install-Module Az.ResourceGraph -Scope CurrentUser -Force
          }
          $query = "resourcecontainers | where type == 'microsoft.resources/subscriptions' | project name, id | sort by name asc"
          $subscriptions = Search-AzGraph -Query $query -UseTenantScope
          $subscriptions

I'm looking forward for your help.
Thanks!

Add support for action input fromFile:

Is it possible to add support for running a script from a file location inside of the repo, rather than embedding the script "inline"?

Example:

inputs:
  inlineScript:
    description: 'Specify the Az PowerShell script here.'
    required: false

  fromFile:
    description: 'Path to script file relevant to repo root, default "." '
    required: false
    default: .

slow azure blob upload with the powershell action

Hi,

Uploading 3 small files (< 15 KB each) to an azure blob using the powershell action takes 3 minutes. For comparison, uploading the same files into a github release takes 1 second.

I am running something like this:

    - name: Publish to Azure blob
      uses: azure/powershell@v1
      with:
        inlineScript: |
          $context = New-AzStorageContext -StorageAccountName myaccount -SasToken "${{secrets.azureBlobQuerystring}}"
          Set-AzStorageBlobContent -File First.zip -Container mycontainer -Context $context.Context -Force
          Set-AzStorageBlobContent -File Second.zip -Container mycontainer -Context $context.Context -Force
          Set-AzStorageBlobContent -File Third.zip -Container mycontainer -Context $context.Context -Force
        azPSVersion: '3.1.0'

The above skips the login action since it uses a write only SaS token as we need to limit the access given in this repository. The length of the files as reported in the log by the powershell action are: 13278, 10807, 9747.

Is it expected? Is there any alternate way of running the action that avoids that? Should I use the cli action or even the rest API directly to upload the small files instead?

set-output On Git Action Fails

The output parameter for the task is always blank.

- name: Set Parameter
  id: task-set-parameter
  uses: azure/powershell@v1
  with:
    inlineScript: |
      Write-Output ::set-output name=my_param::"test"
    azPSVersion: "latest"

- name: Read Parameter
  uses: azure/powershell@v1
  with:
    inlineScript: |
      Write-Output '${{ steps.task-set-parameter.ouputs.my_param}}'
    azPSVersion: "latest"

Which docker image can I use to run the github action

I want to use this github action to run inlineScript. The github should be running in a docker container, but I can not find any official image for this purpose.

My workflow file looks similar to the one in README. I only added container:

on: [push]

name: AzurePowerShellSample

jobs:

  build:
    runs-on: ubuntu-latest
    container:
      image: ???
    steps:
    
    - name: Login via Az module
      uses: azure/login@v2
      with:
        creds: ${{secrets.AZURE_CREDENTIALS}}
        enable-AzPSSession: true 
        
    - name: Run Azure PowerShell inline script
      uses: azure/powershell@v2
      with:
        inlineScript: |
          Get-AzVM -ResourceGroupName "ResourceGroup11"
        azPSVersion: "latest"

With image: mcr.microsoft.com/azure-powershell:latest I get error Error: Login failed with Error: Unable to locate executable file: az. in the login step.
With image:mcr.microsoft.com/azure-cli:latest I get error Error: Unable to locate executable file: pwsh. in the running script step.

Can someone help me? Or I need a customer docker image for running this simple workflow?

> @Jakkapob8504 please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

          > @Jakkapob8504 please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.
@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"

Contributor License Agreement

Originally posted by @Jakkapob8504 in #95 (comment)

Initializing Az Module - Error

Hi,

I have a self-hosted runner on RHEL 9 with:

  • powershell 7.2.16 (also tried 7.3)
  • the AZ module

and I get the following error when executing the azure/powershell action:
Error: You cannot call a method on a null-valued expression.

Run azure/powershell@v1
[...]
Validating inputs
Module Az latest installed from hostedAgentFolder
Initializing Az Module
/usr/bin/pwsh -NoLogo -NoProfile -NonInteractive -Command Test-Path (Join-Path /usr/share az_*)
/usr/bin/pwsh -NoLogo -NoProfile -NonInteractive -Command try ***
            $ErrorActionPreference = "Stop"
            $WarningPreference = "SilentlyContinue"
            $output = @***
            $data = Get-Module -Name Az -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
            $output['AzVersion'] = $data.Version.ToString()
            $output['Success'] = "true"
        ***
        catch ***
            $output['Error'] = $_.exception.Message
        ***
        return ConvertTo-Json $output
False
***
  "Error": "You cannot call a method on a null-valued expression."
***
Error: Error: You cannot call a method on a null-valued expression.

I previously had the same configuration on Ubuntu and it was working fine.

Any ideas?

Azure powershell support on self-hosted runners

Hi Team,

The README.md states that Azure/PowerShell action is unsupported on self-hosted runners. Is it still the case?
We are trying to get this work on our Ubuntu self-hosted runners hosted on AWS and it fails.

Thanks
Mu.

Error parsing boolean value. Path '', line 1, position 1.

I'm attempting to deploy a Bicep file that I don't have issues deploying locally

I keep hitting Error parsing boolean value. Path '', line 1, position 1.

    - name: Bicep Hyperscale
      uses: azure/[email protected]
      with:
        azPSVersion: '3.5.0'
        inlineScript: |
          Set-Location ${{ github.workspace }}/script/
          New-AzResourceGroupDeployment -ResourceGroupName "test-rg" -TemplateFile my.bicep -Mode Incremental

Add script file execution support

Currently only way to run Powershell script is to add the script as inline inside the yaml file. This can be very messy in bigger scripts. Add support to execute Powershell script file from the current repository.

Example:

on: [push]

name: AzurePowerShellSample

jobs:

  build:
    runs-on: ubuntu-latest
    steps:
    
    - name: Login via Az module
      uses: azure/[email protected]
      with:
        creds: ${{secrets.AZURE_CREDENTIALS}}
        enable-AzPSSession: true 
        
    - name: Run Azure PowerShell script
      uses: azure/powershell@v1
      with:
        scriptFile: ./my-script.ps1

Private hosted runners

Hi

I would like to be able to run this action on my private azure windows deploy box like I could do with Azure pipelines. Is this an option? Or could be be added to the roadmap?

Thanks

Mark

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.