Giter Club home page Giter Club logo

cli's Introduction

GitHub Action for Azure CLI

With Azure CLI GitHub Action, you can automate your workflow by executing Azure CLI commands to manage Azure resources inside of an Action.

The action executes the Azure CLI Bash script on a user defined Azure CLI version. If the user does not specify a version, the version of Azure CLI installed on the agent is used. If there is no version of Azure CLI found on the agent, the action falls back the version to latest. Read more about various Azure CLI versions here.

  • azcliversionOptional Example: 2.30.0, Default: set to az cli version of the agent.
  • inlineScriptRequired

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

The definition of this GitHub Action is in action.yml. The action status is determined by the exit code returned by the script rather than StandardError stream.

Note

Please note that the action executes Azure CLI script in a docker container. This means that the action is subjected to potential restrictions which arise from containerized execution. For example:

  1. If script sets up an environment variable, it will not take effect in host and hence subsequent actions shouldn't rely on such environment variable.
  2. There is some restriction on how cross action file read/write is done. GITHUB_WORKSPACE directory in host is mapped to working directory inside container. So, if the action wants to create a file, which will be read by subsequent actions, it should do so within current working directory tree.

Warning

By default, the output of Azure CLI commands is printed to the stdout stream. Without redirecting the stdout stream, contents in it will be stored in the build log of the action. Configure Azure CLI to not show output in the console screen or print in the log by setting the environment variable AZURE_CORE_OUTPUT to none. If you need the output of a specific command, override the default setting using the argument --output with your format of choice. For more information on output options with the Azure CLI, see Format output.

Sample workflow

Dependencies on other GitHub Actions

  • Azure LoginOptional Login with your Azure credentials, required only for authentication via Azure credentials. If you use this action, make sure to either use the default value of azcliversion or azcliversion >= 2.30.0 for all the workflows. Authentication via connection strings or keys do not require this step.
  • CheckoutOptional To execute the scripts present in your repository.

Workflow to execute an Azure CLI script of the latest Azure CLI version

# File: .github/workflows/workflow.yml

on: [push]

name: AzureCLISample

jobs:

  build-and-deploy:
    runs-on: ubuntu-latest
    steps:

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

    - name: Azure CLI script
      uses: azure/cli@v2
      with:
        azcliversion: latest
        inlineScript: |
          az account show
          az storage -h

Workflow to execute an Azure CLI script of a specific CLI version via file present in your repository.

# File: .github/workflows/workflowForFile.yml

on: [push]

name: AzureCLISampleForFile

jobs:

  build-and-deploy:
    runs-on: ubuntu-latest
    steps:

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

    - name: Checkout
      uses: actions/checkout@v1

    - name: Azure CLI script file
      uses: azure/cli@v2
      with:
        azcliversion: 2.30.0
        inlineScript: |
          chmod +x $GITHUB_WORKSPACE/sampleScript.sh
          $GITHUB_WORKSPACE/sampleScript.sh
  • GITHUB_WORKSPACE is the environment variable provided by GitHub which represents the root of your repository.

Getting Help for Azure CLI Issues

If you encounter an issue related to the Azure CLI commands executed in your script, you can file an issue directly on the Azure CLI 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.

cli's People

Contributors

actions-user avatar baysideengineer avatar bishal-pdmsft avatar dependabot[bot] avatar eikooc avatar isra-fel avatar jalajmsft avatar jamesc avatar johnlokerse avatar kanika1894 avatar microsoft-github-operations[bot] avatar mochilia avatar mrako avatar n-usha avatar oliwheeler avatar pankajgovindrao avatar roopeshnair avatar t-dedah avatar tjcorr 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  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  avatar  avatar  avatar  avatar  avatar  avatar

cli's Issues

Getting network connection error while deploying ARM templates using az deployment group.

Error: Please ensure you have network connection. Error detail: HTTPSConnectionPool(host='login.microsoftonline.com', port=443):
Max retries exceeded with url: /36685-1262-420b-a94b-********/oauth2/token
(Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f1f92433dd8>:
Failed to establish a new connection: [Errno -3] Try again',)).

Could someone please help us, how can we resolve this. As this impacting our Automation process.

Thanks
Sai

Action throws error: Unable to find image 'mcr.microsoft.com/azure-cli:2.19.1' locally

Hey all. Thanks everyone for the very good work on all the azure related github actions.
I am following this simple tutorial, in order to host a static react website using gihube actions.

I am getting an error, right after the inlineScript is executed. The error returns

Error: Error: Unable to find image 'mcr.microsoft.com/azure-cli:2.19.1' locally

see also image bellow
image

My workflow gh action looks like this

name: Deploy front webapp

on:
  push:
    branches:
      - develop
  pull_request:
    types: [opened, synchronize, reopened, closed]
    branches:
      - develop

jobs:
  install:
    runs-on: ubuntu-latest
    if: "!contains(github.event.head_commit.message, '[skip ci]')"
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v1
        with:
          node-version: 12.x

      - uses: actions/cache@v2
        id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
        with:
          path: '**/node_modules'
          key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}

      - name: Install
        if: steps.yarn-cache.outputs.cache-hit != 'true'
        run: cd ./redi-connect-front && yarn install --frozen-lockfile

  build:
    runs-on: ubuntu-latest
    needs: [install]
    if: "!contains(github.event.head_commit.message, '[skip ci]')"
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v1
        with:
          node-version: 12.x

      - uses: actions/cache@v2
        id: yarn-cache
        with:
          path: '**/node_modules'
          key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}

      - name: Build
        env:
          CI: "" # This needs to be true ideally however the app wont build because of some js errors
        run: cd ./redi-connect-front && yarn build:prod:berlin

      - uses: actions/upload-artifact@v2
        with:
          name: app-build
          path: |
            **/build
            !**/node_modules
          retention-days: 1

  deploy:
    runs-on: ubuntu-latest
    if: "!contains(github.event.head_commit.message, '[skip ci]')"
    needs: [build]
    steps:
      - uses: actions/checkout@v2
      - uses: azure/login@v1
        with:
          creds: ${{ secrets.AZURE_CREDENTIALS }}

      - name: Upload to blob storage
        uses: azure/CLI@v1
        with:
          azcliversion:  2.19.1
          inlineScript: |
            az storage blob upload-batch --account-name storagedevrediaduz -d '$web' -s ./redi-connect-front/build

      - name: Purge CDN endpoint
        uses: azure/CLI@v1
        with:
          azcliversion: 2.19.1
          inlineScript: |
          az cdn endpoint purge --content-paths  "/*" --profile-name "cdnprofiledevrediaduz" --name cdn-endpoint-dev-redi-aduz" --resource-group "rg-dev-redi-aduz"

      # Azure logout
      - name: logout
        run: |
          az logout

Any ideas why this error coems up?

Misleading docs: Azure Login is NOT required

The following section of the docs states that:

Dependencies on other GitHub Actions

Azure Login – Required Login with your Azure credentials
Checkout – Optional To execute the scripts present in your repository

As a new user to azure, this is simply false and confusing, you do not need azure login if your AZ command works using connections strings and keys. I strongly advise against making people add an extra 10 seconds to their github actions for no reason. It is also just a good idea in general to use anonymous keys in your CI/CD which can easily be reset if compromised. Misleasing users of this action into thinking they need to perform some sort of login (even if it is just with tightly scoped service principal) is needlessly risky. I suggest changing the docs to something like:

Dependencies on other GitHub Actions

Azure Login – [Optional] Login with your Azure credentials, required only for authentication via azure credentials. Authentication via connection strings or keys do not require this step.
Checkout – [Optional] To execute the scripts present in your repository

"Invalid reference format" error

Attempting to use Azure CLI in a GitHub action using the official GitHub actions CLI to whitelist an IP address through the ACR firewall, with the following code:

      - name: Whitelist Runner IP
        uses: azure/CLI@v1
        with:
          azcliversion: 2.30.0
          inlineScript: |
            az acr network-rule add --name retailde --ip-address <redacted>

results in: Error: Error: docker: invalid reference format.

This action was working flawlessly for months and then suddenly stopped working.

Not obtaining the latest AZ CLI version

I'm getting the error
Error: Please enter a valid azure cli version. See available versions: https://github.com/Azure/azure-cli/releases.

When specifying

      - name: What If
        uses: Azure/[email protected]
        with:
          azcliversion: 2.28.1

I get the error above.
When I remove azcliversion the action installs version 2.28.0 of the Azure CLI

v2.28.1 was released 3 days ago.
image

CLI requiring set account command

Each attempt to run any commands with the azure/cli ends with the same error:

Starting script execution via docker image mcr.microsoft.com/azure-cli:2.0.72
ERROR: Please run 'az account set' to select active account.
Error: Error: az cli script failed.

The same commands were working as of Nov 8, stopped working on Nov 9 with this error. I attempted to add the following line to each of my uses of the Azure/CLI action, but the same issue persists.

az account set -s "$SUBSCRIPTION"

Running on: ubuntu-latest
here is the full command

      - name: Set version info in staging slot
        uses: azure/CLI@v1
        with:
          azcliversion: 2.0.72
          inlineScript: |
            az account set -s "$SUBSCRIPTION"
            az functionapp config appsettings set --slot staging --output none --name ${{ env.AZURE_FUNCTIONAPP_NAME }} --resource-group my-resource-group --settings "VERSION=${{ needs.build_and_deploy.outputs.RELEASE_VERSION }}"

az deployment what-if gives different error then az deploy create

Today i did try to deploy a Private Link endpoint en was getting the following error when deploy with:

az deployment sub what-if --template-file .\Azure.bicep --location 'west europe' --parameters @Azure.parameters.json

error:

"error": {
"code": "InvalidRequestFormat",
"message": "Cannot parse the request.",
"details": []

And this is the error what az command gives:

DeploymentWhatIfResourceInvalidResponse - The request to predict template deployment changes to scope '/subscriptions/' has failed due to missing or unexpected response on request '/subscriptions//resourceGroups//providers/Microsoft.Network/privateEndpoints//privateDnsZoneGroups/dnsgroupname?api-version=2021-02-01'. Diagnostic information: timestamp '20210706T182248Z', tracking id '', request correlation id '', location 'westeurope'.

but when deploy with:

az deployment sub create --template-file .\Azure.bicep --location 'west europe' --parameters @Azure.parameters.json

getting this 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": "MoreThanOnePrivateDnsZoneGroupPerPrivateEndpointNotAllowed",
"message": "Cannot create more than one private dns zone groups in the private endpoint tm-aws-prod-pl01. Current private dns zone group count: 2."
}
]
}

Bicep support

When I try to deploy or validate a bicep template, I'm getting the following error:

Run azure/cli@v1
  with:
    inlineScript: az deployment group validate -g contoso -f ./main.bicep
    azcliversion: latest

Starting script execution via docker image mcr.microsoft.com/azure-cli:latest
ERROR: Error loading shared library ld-linux-x86-64.so.2: No such file or directory (needed by /root/.azure/bin/bicep)
Error relocating /root/.azure/bin/bicep: __isnanf: symbol not found
Error relocating /root/.azure/bin/bicep: sysctl: symbol not found
Error relocating /root/.azure/bin/bicep: __isnan: symbol not found
Error relocating /root/.azure/bin/bicep: __strdup: symbol not found

Installing Bicep CLI v0.3.1...
Successfully installed Bicep CLI to "/root/.azure/bin/bicep".

Error: Error: az cli script failed.

Apparently, Bicep CLI installation succeeds, but nevertheless the build fails.

The same error occurs with az bicep install and az bicep build commands.

Add service principal id, key and tenant id as environment variables

Similarly to the addSpnToEnvironment: true option in the Azure CLI task for a Azure DevOps pipeline, can we add the service principal id, key and tenant id as environment variables by setting a flag to true?

From the Azure DevOps pipeline Azure CLI Task:

  "loc.input.help.addSpnToEnvironment": "Adds service principal id, service principal key and tenant id of the Azure endpoint you chose to the script's execution environment. You can use variables: `servicePrincipalId`, `servicePrincipalKey` and `tenantId` in your script.\n\nThis is honored only when the Azure endpoint has Service Principal authentication scheme.\n\nSyntax to access environment variables based on script type.\n\nPowershell script: $env:servicePrincipalId\n\nBatch script: %servicePrincipalId% \n\nShell script: $servicePrincipalId",

latest v1.0.7 does not seem to run anything

Hello

I just noticed there was a new release which seems to have broken our workflow.
It looks like the action isn't actually executing anything. The task doesn't report a failure and the workflow continues, yet there is no output in the logs and it did not do what it is supposed to do.

When reverting back to v1.0.6 everything works as expected.

I am running selfhosted agents with node 16.

Does Azure CLI Action has access to GITHUB_WORKSPACE folder?

Hi!

I'm using your Action to push my Helm package to ACR and have a problem which I cannot solve (and understand why it's happening in the first place).

My workflow:

  1. Create a Helm Package
  2. Login into Azure
  3. Push it into ACR with Azure CLI command az acr helm push

My workflow yaml:

   - name: Helm package
      run: 'helm package ${{ github.workspace }}/chart/${{ secrets.APP_NAME }}--version v${{ github.run_number }} --destination ${{ github.workspace }}/helm --app-version v${{ github.run_number }}'
 
   - name: Azure Login
      uses: Azure/login@v1
      with:
        creds: ${{ secrets.AZURE_CREDENTIALS }} 

    - name: Push TO ACR
      uses: Azure/[email protected]
      with:
        inlineScript: |
          az acr helm push ${{ github.workspace }}/helm/${{ secrets.APP_NAME }}-v${{ github.run_number }}.tgz --name ${{ secrets.ACR_NAME }} --force;

the result:
image
image

Paths are exactly the same, the package seems to exists.

Can you tell me what I am doing wrong?

Cannot connect to the Docker daemon at unix:///var/run/docker.sock

I am trying to run Azure Cli in GitHub Selfhosted agent which is provisioned in AKS Cluster.

As AKS has restriction to mount docker.sock, containerd.sock mounted already in self-hosted pod.

But Azure Cli expecting docker.sock mounted in pod.

Starting script execution via docker image mcr.microsoft.com/azure-cli:2.31.0
Error: Error: docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
See 'docker run --help'.

cleaning up container...
Warning: Error: The process '/usr/bin/docker' failed with exit code 1
Warning: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

(node:13057) UnhandledPromiseRejectionWarning: Error: docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?.
See 'docker run --help'.

Error: /bin/sh: 1: az: not found in v1.0.5

We're getting the following output in the pipeline run logs since v1.0.5 is released:

Run azure/CLI@v1
  with:
    inlineScript: az login --identity --only-show-errors
  echo "TOKEN=$(az acr login --name <redacted>.azurecr.io \
      --expose-token \
      --output tsv \
      --query accessToken \
      --only-show-errors)" >> $GITHUB_ENV

    azcliversion: agentazcliversion
  env:
    EXPOSE_DOMAIN_NAME: <redacted>
    ACR_RELEASE: <redacted>.azurecr.io
    ENVIRONMENT_REPOSITORY_STAGING: <redacted>
    VERSION: 2.0.259
    POI_REGISTRY: <redacted>.azurecr.io
    JAVA_HOME: /opt/hostedtoolcache/Java_Adopt_jdk/11.0.13-8/x64
Error: Error: Command failed: az version
/bin/sh: 1: az: not found

Error: /bin/sh: 1: az: not found

Warning: Error: EISDIR: illegal operation on a directory, unlink '/runner/_work/_temp'
cleaning up container...
Warning: Error: No such container: MICROSOFT_AZURE_CLI_1636963334349_CONTAINER

(node:12389) UnhandledPromiseRejectionWarning: Error: Command failed: az version
/bin/sh: 1: az: not found

    at ChildProcess.exithandler (child_process.js:295:12)
    at ChildProcess.emit (events.js:210:5)
    at maybeClose (internal/child_process.js:1021:16)
    at Socket.<anonymous> (internal/child_process.js:430:11)
    at Socket.emit (events.js:210:5)
    at Pipe.<anonymous> (net.js:659:12)
(node:12389) 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:12389) [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.

When using previous version 1.0.4 (by configuring uses: azure/[email protected]) no such errors are observed and the build is completing successfully.

Azure CLI use_dynamic_install throws Unhandled promise rejection

I'm trying to run code that requires the az automation extension.

I'm calling az config set extension.use_dynamic_install=yes_without_prompt

Related Issue here Azure/azure-cli#21505

- name: Clean Up Resources
        uses: azure/CLI@v1
        with:
          azcliversion: 2.30.0
          inlineScript: |
            
            # Allow Dynamic installation of extensions
            az config set extension.use_dynamic_install=yes_without_prompt

However it throws the following error:

UnhandledPromiseRejectionWarning: Error: az cli script failed.
    at /home/runner/work/_actions/azure/CLI/v1/dist/index.js:1:2[39](https://github.com/xxx/xxx/runs/5400826457?check_suite_focus=true#step:8:39)64
    at Generator.throw (<anonymous>)
    at rejected (/home/runner/work/_actions/azure/CLI/v1/dist/index.js:1:20436)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:1861) 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:1861) [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.

[Errno 2] No such file or directory

This used to work as recently as yesterday. It's no longer working. Would you have any advice?

name: Publish styles
uses: Azure/[email protected]
with:
azcliversion: latest
inlineScript:

az storage blob upload-batch -s $GITHUB_WORKSPACE/.out-styles -d ui-component-library/styles/${{ steps.publishVersion.outputs.version }} --account-name ${{ secrets.STORAGE_ACCOUNT_NAME }} --account-key ${{ secrets.STORAGE_ACCOUNT_KEY }}

Starting script execution via docker image mcr.microsoft.com/azure-cli:latest
The command failed with an unexpected error. Here is the traceback:

[Errno 2] No such file or directory: 'ui-component-library/styles/2-2-3'
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/knack/cli.py", line 215, in invoke
cmd_result = self.invocation.execute(args)

Breaking change latest CLI version

When running the Azure/[email protected] action with the latest CLI version (2.30.0 since today) in a workflow I get the following error despite having run the Azure/login@v1 action in a previous step in the same job:

ERROR: Could not retrieve credential from local cache for service principal *****. Run 'az login' for this service principal.

Reverting to the previous CLI version by passing the argument azcliversion: 2.29.2 to the Azure/[email protected] action solved the issue for me.

IPV4 or CIDR for Storage, event hub etc

hi,
I am trying to add 2 IP or CIDR ranges to my storage account or event hub namespsace in this case using az cli but it won't let me add more than one at a time. I am using this following command:
az eventhubs namespace network-rule add
--namespace-name ns-name
--resource-group rg-name
--ip-address 10.1.0.0/16,162.168.0.0/24 (allows me add one IP, how can I add more IPs here?)
I keep getting this error when I add more than one IP:
ERROR: BadRequest: The provided ip address mask does not follow the CIDR notation.

When I run the command twice with separate IPs then it works fine but I don't want that. I want to be able to add more IPs to one single command such as above az cli script. Any ideas? Thanks!

'az batch application package create' file upload failing

Failing action: https://github.com/christophwille/azurebatch-playground/runs/2465121361?check_suite_focus=true
Source script: https://github.com/christophwille/azurebatch-playground/blob/main/.github/workflows/simple-cicd.yml

Using

    - name: Upload artifact
      uses: actions/upload-artifact@v2
      with:
        name: Batch Task App Package
        path: ${{ env.BATCH_APP_PACKAGE_PATH }}/batchtaskapp.zip

I can collect the file no problems, but the az/cli action fails me with

Starting script execution via docker image mcr.microsoft.com/azure-cli:latest
ERROR: The command failed with an unexpected error. Here is the traceback:
ERROR: [Errno 2] No such file or directory: '/home/runner/work/azurebatch-playground/azurebatch-playground/.app/batchtaskapp.zip'
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/knack/cli.py", line 231, in invoke
    cmd_result = self.invocation.execute(args)
  File "/usr/local/lib/python3.6/site-packages/azure/cli/core/commands/__init__.py", line 657, in execute
    raise ex
  File "/usr/local/lib/python3.6/site-packages/azure/cli/core/commands/__init__.py", line 720, in _run_jobs_serially
    results.append(self._run_job(expanded_arg, cmd_copy))
  File "/usr/local/lib/python3.6/site-packages/azure/cli/core/commands/__init__.py", line 712, in _run_job
    return cmd_copy.exception_handler(ex)
  File "/usr/local/lib/python3.6/site-packages/azure/cli/command_modules/batch/_exception_handler.py", line 30, in batch_exception_handler
    reraise(*sys.exc_info())
  File "/usr/local/lib/python3.6/site-packages/six.py", line 703, in reraise
    raise value
  File "/usr/local/lib/python3.6/site-packages/azure/cli/core/commands/__init__.py", line 691, in _run_job
    result = cmd_copy(params)
  File "/usr/local/lib/python3.6/site-packages/azure/cli/core/commands/__init__.py", line 328, in __call__
    return self.handler(*args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/azure/cli/core/__init__.py", line 807, in default_command_handler
    return op(**command_args)
  File "/usr/local/lib/python3.6/site-packages/azure/cli/command_modules/batch/custom.py", line 228, in create_application_package
    _upload_package_blob(cmd.cli_ctx, package_file, result.storage_url)
  File "/usr/local/lib/python3.6/site-packages/azure/cli/command_modules/batch/custom.py", line 209, in _upload_package_blob
    file_path=package_file,
  File "/usr/local/lib/python3.6/site-packages/azure/multiapi/storage/v2018_11_09/blob/blockblobservice.py", line 453, in create_blob_from_path
    count = path.getsize(file_path)
  File "/usr/local/lib/python3.6/genericpath.py", line 50, in getsize
    return os.stat(filename).st_size
FileNotFoundError: [Errno 2] No such file or directory: '/home/runner/work/azurebatch-playground/azurebatch-playground/.app/batchtaskapp.zip'
To open an issue, please run: 'az feedback'

So the file is there, but the az/cli action doesn't see it - or I am doing something wrong compared to upload?

Environment variables unavailable in inlineScript

Currently, only the GITHUB_WORKSPACE environment variable is set.
The other default environment variables are not available.

Environment variables set by the user in the workflow YAML are also not available.

The documentation regarding create a Docker container action shows that the environment variables are passed to the container here

Expected behaviour:

  • All default environment variables are available in inlineScript
  • All user set environment variables are available in inlineScript

Update to Node16 and new @actions/core

GitHub Actions is now giving deprecation warnings around this Action:

Support `echo "{name}={value}" >> $GITHUB_ENV` pattern instead of deprecated `echo ::set-env name={name}::{value}` pattern

Currently, to pass a value from Azure CLI Action step to a following step, the following pattern have to be used:
echo ::set-env name={name}::{value}
However, set-env is deprecated as explained here
https://github.blog/changelog/2020-10-01-github-actions-deprecating-set-env-and-add-path-commands/
Could you please support the following pattern for exporting environment variables
echo "{name}={value}" >> $GITHUB_ENV
explained in
https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-commands-for-github-actions#setting-an-environment-variable
thank you!

"Unhandled promise rejection" error

I have a pretty simple Azure/cli step in my pipeline that's giving me the error:

(node:3210) UnhandledPromiseRejectionWarning: Error: az cli script failed.
    at /home/runner/work/_actions/azure/CLI/v1/dist/index.js:1:23964
    at Generator.throw (<anonymous>)
    at rejected (/home/runner/work/_actions/azure/CLI/v1/dist/index.js:1:20436)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:3210) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:3210) [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.

This is the task code:

      - name: Dewhitelist IP
        if: always()
        uses: azure/CLI@v1
        with:
          azcliversion: 2.30.0
          inlineScript: |
            az acr network-rule remove --name retailde --ip-address ${{steps.runner_ip.outputs.runnerip}}

Easier to identify container based action

Hi,

I know that there is a NOTE in the docs about this action mentioning that it is docker based, but this should be towards the top. Or provided via a tag or something that easily allows to identify container based actions.

Thanks

Performance

I tried using azure/cli to upload a batch of files to Azure Storage. Unfortunately it takes 33 seconds to upload a single mid-size file. That's down from 55 seconds when I follow the instructions in the repo that suggest azure/login is mandatory first. It's 29 second longer than it takes me to upload the files to s3 with https://github.com/shallwefootball/upload-s3-action.

I may be using azure/cli when a node script would be more appropriate. If so that guidance would be useful both here in this issue, and on the azure/cli README.

azure/cli@v1 not working with azure/login@v1 on self-hosted runner

Hi,

I'm running self hosted runners on k8s using https://github.com/actions-runner-controller/actions-runner-controller, which doesn't have az cli installed by default.

So in my workflow, I'm installing it using curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash as per MS's documentation and signing in using azure/login@v1 and a service account which works fine, but when I'm running azure/cli@v1 right after, it gives the following errors:

ERROR: Please run 'az login' to setup account.
Error: Error: az cli script failed.

image

here is how the github job looks:

  preview:
    runs-on: self-hosted
    steps:
      - uses: actions/checkout@v2

      - name: Install az cli
        run: curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash

      - uses: azure/login@v1
        name: Sign in to Azure
        with:
          creds: ${{ secrets.AZURE_CREDENTIALS }}
          environment: azurecloud

      - uses: azure/cli@v1
        name: Run what-if
        with:
          inlineScript: |
            az deployment sub what-if --location ${{ env.RESOURCEGROUP_LOCATION }} \
              --template-file deploy/main.bicep

Any idea how to fix this?

Confused on when to use this Action

Since you can directly run az command with run, like:

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
    ...
    - name: AZ CLI commands
          run: |
            az account show

I'm confused when should I use this Action for Azure CLI? to use a specific CLI version? or for platforms without az installed?

Issue Running az cli inline command on windows agent

I have task working fine on an Ubuntu agent as per:

some-task:
    runs-on: ubuntu-latest
    steps:
     - name: Do something
        uses: azure/CLI@v1
        with:
          azcliversion: 2.40.0
          inlineScript: az apim api ....etc

When trying the following however:

build:
    runs-on: windows-latest
    environment: Development
    steps:

      - name: Do something
        uses: azure/CLI@v1
        with:
           azcliversion: 2.40.0
           inlineScript: call az somecall....

I am receiving the error:
Error: Please use Linux based OS as a runner.

The documentation isn't quite clear for me:
https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/reference/azure-cli-v1?view=azure-pipelines

Suggests just adding "call" as I have done.

How do I set output for the action?

If I run the cli action and get a response that I want to pass on to the next action, is it possible to set the output for this action?
Looking in the action.yml I can't see any output property defined.

az synapse workspace activate fails for --ids option

zz --version
azure-cli 2.31.0

core 2.31.0
telemetry 1.0.6

Describe the bug
I am trying to activate Synapse workspace via AZ CLI command using --ids option. What exactly is needed for --ids to work? The command is unable to get the --name option. Its ignores if I provide the option.

--W/O --name option
az synapse workspace activate --ids /subscriptions/xxxxxxxxxxxxxxxxx/resourceGroups/rg-mddsha1prodeastus-synapse-ws/providers/Microsoft.Synapse/workspaces/synmddsha1prodeastus --key-identifier https://xxxxxxxxx.vault.azure.net/keys/key-cmk-mddsha1prodeastus

Argument --name cannot be derived from ID /subscriptions/a0b62ca5-4dbf-4ddb-8d97-9d36cea4875c/resourceGroups/rg-mddsha1prodeastus-synapse-ws/providers/Microsoft.Synapse/workspaces/synmddsha1prodeastus,. Please provide a complete resource ID containing all information of 'Resource Id' arguments.

---With --name option

az synapse workspace activate --ids /subscriptions/xxxxxxxxxxxxxxxxx/resourceGroups/rg-mddsha1prodeastus-synapse-ws/providers/Microsoft.Synapse/workspaces/synmddsha1prodeastus --key-identifier https://xxxxxxxxx.vault.azure.net/keys/key-cmk-mddsha1prodeastus --name key-cmk-xxxxxxxx

option '--name' will be ignored due to use of '--ids'.

To Reproduce
Create synapse workspace with double encryption/system managed identity and run above command
Additional context
Add any other context about the problem here.

Consider using an improved JMESPath library

More than a feature request, this issue is my formal way to introduce JMESPath Community.

For many months we at JMESPath Community worked on brainstorming ideas for new features and curated a reasonably scoped set of new features as our first milestone.

The goal is to pick the JMESPath language were it left off and steward improvements to the specification at a quicker pace with a clear governance.

Amongst the new features being proposed one can find:

  • Arithmetic expressions : allowing simple numeric operations.
  • String manipulation functions.
  • Ability to refer to arbitrary lexical scopes.
  • and more.

As we are wrapping up and nearing completion of this first batch of improvements, we are publishing release candidates of the Python implementation of the spec.

If those sound like useful features for az CLI, I would like to enquire about the required steps and process to have this library included as a dependency to this repository.

I would be happy to submit a pull request in due course obviously. Please let me know if that is something you would consider.

invalid reference format: repository name must be lowercase

running azure/CLI fails with "invalid reference format: repository name must be lowercase"

https://github.com/ezYakaEagle442/aca-java-petclinic-mic-srv/blob/main/.github/workflows/deploy-iac.yml#L77

env:
  AZ_CLI_VERSION: 2.40.0

    - name: Deploy Azure Key Vault
      uses: azure/[email protected] # https://github.com/marketplace/actions/azure-cli-action
      with:
        azcliversion: ${{ env.AZ_CLI_VERSION }}
        inlineScript: |

          # leave this fake dummy accessPoliciesObject as anyway SET_KV_ACCESS_POLICIES is set to FALSE at this stage
          accessPoliciesObject='{}'

          az deployment group create --name aca-petclinic-kv -f ../../iac/bicep/modules/kv/kv.bicep -g ${{ env.RG_KV }} \
            -p appName=${{ env.APP_NAME }} \
            -p kvName=${{ env.KV_NAME }} \
            -p location=${{ env.LOCATION }} \
            -p setKVAccessPolicies=${{ env.SET_KV_ACCESS_POLICIES }} \
            -p accessPoliciesObject=$accessPoliciesObject \
            -p secretsObject=${{ secrets.SECRET_OBJECT }} \
            -p secretExpiryDate=${{ env.SECRET_EXPIRY_DATE }}

see https://github.com/ezYakaEagle442/aca-java-petclinic-mic-srv/actions/runs/3141520108/jobs/5104050174

##[group***Run azure/[email protected]
with:
  azcliversion: [2](https://github.com/ezYakaEagle442/aca-java-petclinic-mic-srv/actions/runs/3141520108/jobs/5104050174#step:4:2).40.0
  inlineScript: 
# leave this fake dummy accessPoliciesObject as anyway SET_KV_ACCESS_POLICIES is set to FALSE at this stage
accessPoliciesObject='***'

az deployment group create --name aca-petclinic-kv -f ../../iac/bicep/modules/kv/kv.bicep -g rg-iac-kv777 \
  -p appName=petcliaca \
  -p kvName=kv-petcliaca442 \
  -p location=westeurope \
  -p setKVAccessPolicies=false \
  -p accessPoliciesObject=$accessPoliciesObject \
  -p secretsObject=*** \
  -p secretExpiryDate=1672444800

env:
  APP_NAME: petcliaca
  LOCATION: westeurope
  RG_KV: rg-iac-kv777
  RG_APP: rg-iac-aca-petclinic-mic-srv
  ACA_ENV_NAME: aca-env-pub
  DEPLOY_TO_VNET: false
  KV_NAME: kv-petcliaca442
  SET_KV_ACCESS_POLICIES: false
  AZURE_CONTAINER_REGISTRY: acrpetcliaca
  REPOSITORY: petclinic
  GHA_SETTINGS_CFG_REGISTRY_URL: acrpetcliaca.azurecr.io
  GHA_SETTINGS_CFG_REPO_URL: https://github.com/ezYakaEagle442/aca-java-petclinic-mic-srv
  GHA_SETTINGS_CFG_CRD_CLIENT_ID: 
  GHA_SETTINGS_CFG_CRD_CLIENT_SECRET: 
  GHA_REVISION_NAME: poc-aca-101
  SECRET_OBJECT: ***
  SECRET_EXPIRY_DATE: 1672444800
  credentials: ***
  AZURE_TENANT_ID: ***
  AZURE_SUBSCRIPTION_ID: ***
  DEPLOYMENT_VERSION: 2.6.6
  AZ_CLI_VERSION: 2.40.0
  JAVA_VERSION: 11
  LOCAL_IP: 104.210.40.215
  AZURE_HTTP_USER_AGENT: 
  AZUREPS_HOST_ENVIRONMENT: 
##[endgroup***
Starting script execution via docker image mcr.microsoft.com/azure-cli:2.40.0
##[error***Error: docker: invalid reference format: repository name must be lowercase.
See 'docker run --help'.

cleaning up container...
##[warning***Error: No such container: MICROSOFT_AZURE_CLI_1664[3](https://github.com/ezYakaEagle442/aca-java-petclinic-mic-srv/actions/runs/3141520108/jobs/5104050174#step:4:3)[4](https://github.com/ezYakaEagle442/aca-java-petclinic-mic-srv/actions/runs/3141520108/jobs/5104050174#step:4:4)9199491_CONTAINER

(node:1[5](https://github.com/ezYakaEagle442/aca-java-petclinic-mic-srv/actions/runs/3141520108/jobs/5104050174#step:4:5)[6](https://github.com/ezYakaEagle442/aca-java-petclinic-mic-srv/actions/runs/3141520108/jobs/5104050174#step:4:6)5) UnhandledPromiseRejectionWarning: Error: docker: invalid reference format: repository name must be lowercase.
See 'docker run --help'.

    at /home/runner/work/_actions/azure/CLI/v1.0.6/dist/index.js:1:23964
    at Generator.throw (<anonymous>)
    at rejected (/home/runner/work/_actions/azure/CLI/v1.0.6/dist/index.js:1:20436)
    at processTicksAndRejections (internal/process/task_queues.js:9[7](https://github.com/ezYakaEagle442/aca-java-petclinic-mic-srv/actions/runs/3141520108/jobs/5104050174#step:4:7):5)
(node:1565) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1565) [DEP001[8](https://github.com/ezYakaEagle442/aca-java-petclinic-mic-srv/actions/runs/3141520108/jobs/5104050174#step:4:8)*** 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.

Azure Maps - Global in CLI vs location selection in Portal

When creating Azure Maps v2 in Portal we get presented with Region selection like this

image

When creating the same resource via CLI, Region selection is not available and it is created as global.

Here's how both resources look side by side

image

Unable to use GITHUB_OUTPUT or GITHUB_STEP_SUMMARY

Previously if you wanted to output data from this task you might use:

echo '::set-output name=key::value'

This functionality was recently deprecated per link. The new mechanism is to use environment files. However if you use this functionality currently you will get an error that it can't find the file:

/_temp/AZ_CLI_GITHUB_ACTION_1665589813118.sh: line 10: /home/runner/work/_temp/_runner_file_commands/set_output_93294b01-dcab-4b3d-979e-1411fcc565cf: No such file or directory

It looks like this is a result of how we are mapping in the temporary directory. Not all of the GITHUB environment variables are getting re-mapped to the different path.

Error: Error: docker: invalid reference format.

Hello,

I am attempting to use Azure CLI to upload to a blob storage. I have followed the documentation and am receiving the error message displayed in the title of this bug request. "Error: Error: docker: invalid reference format."

Here is the github action yaml that I am using.

- name: Upload To Blob Storage
   uses: azure/CLI@v1
   with:
     azcliversion: 2.34.1
     inlineScript: |
       az storage blob upload-batch -d $web -s ./dist/portal --account-name documentuploadstaticsite --overwrite

I have attempted several things to try to resolve this.

  1. I have verified the source directory has files in it.
  2. I have tested the az cli command locally and verified it works properly with no exceptions.
  3. I have tested using different versions of Azure CLI.

I am all out of options, and any assistance would be greatly appreciated.

Thank you.

Can you add a property to turn off console.log for the cli command output

Looking at the code, you are using console.log

We are currently using an azure cli to push some appsetting for Azure function (java) such as JDBC settings and etc. We stored the value in github secret but when we use the cli action to push it to azure, the cli action outputs all the value in clear text in the build log. It won't pass our security audit.

console.log(${START_SCRIPT_EXECUTION_MARKER}${azcliversion});
await executeDockerCommand(command);
console.log("az script ran successfully.");

Thanks

az & azure-cli-ml extension for deploying model

Hi,

I'm roughly following this setup here - https://github.com/marketplace/actions/azure-cli-action

Here's my Github action setup --

name: deploy

on: [push]

jobs:

  build-and-deploy:
    runs-on: ubuntu-latest
    steps:

    - name: Checkout
      uses: actions/checkout@v2
      with:
        ref: ${{ github.ref }}

    - name: Azure Login
      uses: azure/login@v1
      with:
        creds: ${{ secrets.AZURE_CREDENTIALS }}

    - name: Azure CLI script file
      uses: azure/CLI@v1
      env:
        TENANT_ID: ${{ fromJSON(secrets.AZURE_CREDENTIALS).tenantId }}
        CLIENT_ID: ${{ fromJSON(secrets.AZURE_CREDENTIALS).clientId }}
        CLIENT_SECRET: ${{ fromJSON(secrets.AZURE_CREDENTIALS).clientSecret }}
      with:
        azcliversion: 2.30.0
        inlineScript: |
          az extension add --name azure-cli-ml
          az login --service-principal --username="${CLIENT_ID}" --password="${CLIENT_SECRET}" --tenant="${TENANT_ID}"
          az acr login --name <>.azurecr.io

          cd $GITHUB_WORKSPACE/deployment

          az ml model deploy --ct <>  --model <>

Error messages gets triggered in the last line around az ml model deploy , and here's the core feedback:

ERROR: An error occurred: DOCKER_COMMAND_ERROR
Please verify if Docker client is installed and running.
Error: Error: az cli script failed.
cleaning up container...
MICROSOFT_AZURE_CLI_1662163098469_CONTAINER

Would anything be suggested to easily start-up and run a Docker client (daemon). Seems like I need to have Docker running, but also I will need to have uses: azure/CLI@v1

('Cannot connect to proxy.', NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f8e632dfdd8>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',))

Having issues logging into Azure via the Azure CLI on a linux machine. No issues from my Windows Machine on the same network.

I am behind a Corp Proxy and same Env settings work for windows machine but not Linux.

****Error ****
('Cannot connect to proxy.', NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f8e632dfdd8

When I use: az login --use-device-code I get the device code back from the terminal but once I enter it into the web page I get the error above

When I login by Service Principal I get the error straight away.

Steps Taken Already

  1. We have set the http_proxy and https_proxy environment variables as shown in the Working behind a proxy section of the Azure CLI documentation: Use Azure CLI effectively | Microsoft Docs.

Proxy Settings:
http_proxy=http://HKG\username:@ourproxy:8080>
https_proxy=https://HKG\username:@ourproxy:8080>
no_proxy=.microsoftonline.com,.microsoft.com,.windows.net,.azmk8s.io,.azurecr.io

  1. I also appended our MHSA CA and Proxy Cert to the cacert file used by the Azure CLI as instructed in the docs if we encounter any issues with connectivity.

/usr/lib/python3.6/site-packages/pip/_vendor/certifi/cacert.pem
/usr/lib/python3.6/site-packages/pip/_vendor/requests/cacert.pem
/usr/lib64/az/lib/python3.6/site-packages/certifi/cacert.pem
/usr/lib64/az/lib/python3.6/site-packages/pip/_vendor/certifi/cacert.pem
/usr/lib64/az/lib/python3.6/site-packages/websocket/cacert.pem
/usr/local/lib/python3.6/site-packages/certifi/cacert.pem
/usr/local/lib/python3.6/site-packages/websocket/cacert.pem

  1. Confirmed curl to webpages is okay and also confirmed no issue with nslookups to proxy server or internet destinations

System Versions

az version:
{
"azure-cli": "2.23.0",
"azure-cli-core": "2.23.0",
"azure-cli-telemetry": "1.0.6",
"extensions": {}
}

OS Version: Red Hat Enterprise Linux Server release 7.9 (Maipo)

Suspected Root Cause
It appears that the Python under the hood of Azure CLI is not picking up the proxy env variables when it needs to. The no_proxy variables do not seem to have an issue as when they included added I am able to launch the device login page. Without these settings I am not able to launch the device login instead I get slightly different error:

Please ensure you have network connection. Error detail: HTTPSConnectionPool(host='login.microsoftonline.com', port=443): Max retries exceeded with url: /common/oauth2/devicecode?api-version=1.0 (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f452ae3ff60>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)))

But the no_proxy settings are standard for my environment as this is what I use on my windows machine and I connect via device login or service principal without issue.

Azure CLI Install Method

https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-linux?pivots=dnf

Followed the instructions to build from source as I do not have the dnf package manager i.e.:
curl -sL https://azurecliprod.blob.core.windows.net/rhel7_6_install.sh | sudo bash

Why is the Azure CLI action only available on Linux based runners?

I tried running the AZ command using the AZ CLI action and I got the following error:

Please use Linux based OS as a runner.

I'm wondering why enforcing Linux based runners and not allowing windows runner. I ran the same az command with the run command and it worked fine on Windows

Add an example for Azune Key Vault in GA

Hi there

The official https://github.com/Azure/get-keyvault-secrets Action was recently deprecated (without cause given), pointing to this Action with the vague instruction "pass a custom script".

This has left a bit of confusion about how best do something like grab a code signing certificate from Azure KSM in GitHub Actions.

An example would be really helpful, if indeed this is the recommended Action to use to interact with Azure Key Vault.

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.