Azure Container Registry authorization for Azure Web App - azure

Is there a way to pull an image from an Azure Containter Registry without having to use the following app settings?
DOCKER_REGISTRY_SERVER_URL
DOCKER_REGISTRY_SERVER_PASSWORD
I tried giving the appropriate RBAC to my App Service and use the Azure Web App on Container Deploy DevOps task, but this doesn't work.
Currently, I have it set up for CD by using the admin user/password, but that is not an option I would like to put to production.
The error message I get (when I do not set DOCKER_REGISTRY_SERVER_URL and DOCKER_REGISTRY_SERVER_PASSWORD):
2020-06-18T11:01:51.313Z INFO - Pulling image from Docker hub: xx.azurecr.io/xx:xx
2020-06-18T11:01:51.545Z ERROR - DockerApiException: Docker API responded with status code=InternalServerError, response={"message":"Get https://xx.azurecr.io/v2/xx/manifests/xx: unauthorized: authentication required"}
2020-06-18T11:01:51.553Z ERROR - Image pull failed: Verify docker image configuration and credentials (if using private repository)

The environment variables in the app settings:
DOCKER_REGISTRY_SERVER_URL DOCKER_REGISTRY_SERVER_PASSWORD
are the necessary things when you need to pull the image from an Azure Container Registry. You need to know the right sequence between the credential of the ACR in the app settings and the Managed Identity of the Web App.
The Managed Identity of the Web App is used to access other resources inside the Web App when it is running. Watch out, the Web App is running. It means the image is already pulled from the ACR. So you see, the credential of the ACR will be used before the Managed Identity. If you do not set the credential, the image cannot be pulled so that the Web App won't run well. At this time, the Managed Identity does not make sense.

Related

Use DefaultAzureCredentials to authenticate Service bus in Docker Container

I'm trying to use DefaultAzureCredentials to authenticate my Azure function against Azure Service Bus. In my azure function azure-func-service-bus, I call to Azure Service Bus
servicebus_client = ServiceBusClient(
fully_qualified_namespace=MY_SERVICE_BUS_NAMESPACE_NAME+".servicebus.windows.net",
credential=DefaultAzureCredential(additionally_allowed_tenants=['*'])
)
I created and pushed Docker container to ACR. When I run the container locally for testing outside of Azure, it does not know what permissions to use.
az acr login --name acr01
docker push acr01.azurecr.io/azure-func-service-bus:v1
docker pull acr01.azurecr.io/azure-func-service-bus:v1
docker run -it --rm -p 8080:80 acr01.azurecr.io/azure-func-service-bus:v1
but got the following error.
DefaultAzureCredential failed to retrieve a token from the included credentials.
Attempted credentials:
EnvironmentCredential: EnvironmentCredential authentication unavailable. Environment variables are not fully configured.
Visit https://aka.ms/azsdk/python/identity/environmentcredential/troubleshoot to troubleshoot.this issue.
ManagedIdentityCredential: ManagedIdentityCredential authentication unavailable, no response from the IMDS endpoint.
SharedTokenCacheCredential: SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache.
VisualStudioCodeCredential: Failed to get Azure user details from Visual Studio Code.
AzureCliCredential: Azure CLI not found on path
AzurePowerShellCredential: PowerShell is not installed
To mitigate this issue, please refer to the troubleshooting guidelines here at https://aka.ms/azsdk/python/identity/defaultazurecredential/troubleshoot.
Unexpected error occurred (ClientAuthenticationError('DefaultAzureCredential failed to retrieve a token from the included credentials.\nAttempted credentials:\n\tEnvironmentCredential: EnvironmentCredential authentication unavailable. Environment variables are not fully configured.\nVisit https://aka.ms/azsdk/python/identity/environmentcredential/troubleshoot to troubleshoot.this issue.\n\tManagedIdentityCredential: ManagedIdentityCredential authentication unavailable, no response from the IMDS endpoint.\n\tSharedTokenCacheCredential: SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache.\n\tVisualStudioCodeCredential: Failed to get Azure user details from Visual Studio Code.\n\tAzureCliCredential: Azure CLI not found on path\n\tAzurePowerShellCredential: PowerShell is not installed\nTo mitigate this issue, please refer to the troubleshooting guidelines here at https://aka.ms/azsdk/python/identity/defaultazurecredential/troubleshoot.')). Handler shutting down.
I'm missing a key piece of the puzzle. How can I handle this?
When the Azure Function runs in Azure, it's configured to support ManagedIdentityCredential. For your case I'd recommend trying to configure EnvironmentCredential to test locally.
You can find the details in the link, but the short version is:
Create a service principle (Docs) and give it the needed access
Run the container with extra Environment Variables:
AZURE_TENANT_ID: service principal's Tenant ID
AZURE_CLIENT_ID: service principal's AppId
AZURE_CLIENT_SECRET: service principle's password
I'd recommend using a .env file to make this easier, but be sure it doesn't get checked in anywhere.
FYI If your account doesn't use MFA, you can instead use the variables AZURE_USERNAME and AZURE_PASSWORD. But then you've put your username and password in a file or your terminal history which is concerning. Admittedly the service principal has the same problem, but you can more easily mitigate that with minimizing it's access and regularly rolling the secret.
P.S. If you're using Visual Studio for making your Azure Function you should be able to use something like: EnvironmentCredentialExample to automate setting up and using the needed .env file.

Azure Key Vault reference in Azure App Service

I'm currently deploying a docker container to an Azure App Service slot.
I'm using a Linux based app service (App Service Plan S1) and the container is hosted in an Azure Container Registry.
I've configured the required DOCKER_REGISTRY_SERVER_* settings for the app service.
For the server password I'm using a key vault reference (#Microsoft.KeyVault(VaultName=my-vault;SecretName=my-secret)). I've created a managed identity for the app service slot and assigned the GET secret permission in the key vault.
The app settings also show that it is a valid reference:
Successful key vault reference
However when I then try to browse to the website I get an error message in the logs stating that the pull request on ACR is unauthorized.
App Service log error
2022-01-24T09:21:33.589Z INFO - Pulling image: ******.azurecr.io/******:33819
2022-01-24T09:21:33.730Z ERROR - DockerApiException: Docker API responded with status code=InternalServerError, response={"message":"Get https://******.azurecr.io/v2/******/manifests/33819: unauthorized: authentication required, visit https://aka.ms/acr/authorization for more information."}
2022-01-24T09:21:33.740Z ERROR - Pull image threw Exception: Input string was not in a correct format.
2022-01-24T09:21:33.747Z INFO - Pulling image from Docker hub: ******.azurecr.io/******:33819
2022-01-24T09:21:33.870Z ERROR - DockerApiException: Docker API responded with status code=InternalServerError, response={"message":"Get https://******.azurecr.io/v2/******/manifests/33819: unauthorized: authentication required, visit https://aka.ms/acr/authorization for more information."}
2022-01-24T09:21:33.872Z WARN - Image pull failed. Defaulting to local copy if present.
When I replace the DOCKER_REGISTRY_SERVER_PASSWORD value with the actual password the app service is able to successfully pull the container and start the website.
Any reason why this wouldn't work?
When I replace the DOCKER_REGISTRY_SERVER_PASSWORD value with the
actual password the app service is able to successfully pull the
container and start the website.
As your Container Registry does not have the access to the Azure Key Vault secrets, you are getting pull request on ACR is unauthorized error
You can assign System-Assigned managed identity to your Azure Container Registry and assign the GET secret permission in the key vault
Then you would be able to pull the container and start the website using the key vault reference only

Cannot pull image in WebApp from ACR with private endpoint enabled

I have a azure webapp Container , and azure container registry
The app is up and can pull image from acr when no security enabled (private endpoint)
If i enable private endpoint in the web app , the web app cannot pull the image from ACR
this is the logs from Azure DevOps
2021-06-28T07:37:06.7931299Z Single-container Deployment to the webapp 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' as only the image detail was specified.
2021-06-28T07:37:07.0710385Z Trying to update App Service Configuration settings. Data: {"appCommandLine":null,"linuxFxVersion":"DOCKER|XXXXXXXXXXXXXXX.azurecr.io/XXXXXXXXXXXXXX:976"}
2021-06-28T07:37:14.0740862Z Updated App Service Configuration settings.
2021-06-28T07:37:14.0742609Z Restarting App Service: XXXXXXXXXXXXXXXXXXX
2021-06-28T07:37:14.3232789Z App Service 'XXXXXXXXXXXXXXXXXXXX' restarted successfully.
2021-06-28T07:37:15.3657905Z ##[warning]Error: Failed to update deployment history. Error: Ip Forbidden (CODE: 403)
2021-06-28T07:37:15.7454935Z App Service Application URL: https://XXXXXXXXXXXXXXXXXXXXXXXXXXX
2021-06-28T07:37:15.7532798Z ##[section]Finishing: Azure Web App on Container Deploy: XXXXXXXXXXXXXXXXXXXXXXXXXXXX
In the log in Azure Portal, the web app looks consider the ACR registry as Docker hub:
2021-06-28T08:06:54.100Z INFO - Pulling image from Docker hub: XXXXXXXXXXXXXXXXXXXXX
2021-06-28T08:06:54.201Z ERROR - DockerApiException: Docker API responded with status code=InternalServerError, response={"message":"Get https://XXXXXXXXXXXXXXXXXXXXXXXXXXX/v2/XXXXXXXXXXXXX/manifests/976: unauthorized: authentication required, visit https://aka.ms/acr/authorization for more information."}
2021-06-28T08:06:54.203Z ERROR - Image pull failed: Verify docker image configuration and credentials (if using private repository)
2021-06-28T08:06:54.205Z INFO - Stopping site XXXXXXXXXXXXXXXXXXXXXX because it failed during startup.
this is my AzureDevops step :
Any idea to resolve that ?
The problem is that you don't have permission to pull the image from ACR. ACR is a private registry, so you need to set the credential of ACR for the Web App. And Azure Web App for container uses the environment variables to set the credential for the private registry. Here are the variables for the ACR:
DOCKER_REGISTRY_SERVER_USERNAME - The username for the ACR server.
DOCKER_REGISTRY_SERVER_URL - The full URL to the ACR server. (For
example, https://my-server.azurecr.io.)
DOCKER_REGISTRY_SERVER_PASSWORD - The password for the ACR server.
And in the DevOps, you set the variables like this:

Docker fails to pull the image from within Azure App Service

The Container Setting on the App Service it self look solid:
But the log pane shows errors:
2020-02-11 06:31:40.621 ERROR - Image pull failed: Verify docker image configuration and credentials (if using private repository)
2020-02-11 06:31:41.240 INFO - Stoping site app505-dfpg-qa2-web-eastus2-gateway-apsvc because it failed during startup.
2020-02-11 06:36:05.546 INFO - Starting container for site
2020-02-11 06:36:05.551 INFO - docker run -d -p 9621:8081 --name app505-dfpg-qa2-web-eastus2-gateway-apsvc_0_a9c8277e_msiProxy -e WEBSITE_SITE_NAME=app505-dfpg-qa2-web-eastus2-gateway-apsvc -e WEBSITE_AUTH_ENABLED=False -e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_HOSTNAME=app505-dfpg-qa2-web-eastus2-gateway-apsvc.azurewebsites.net -e WEBSITE_INSTANCE_ID=7d18d5957d129d3dc3a25d7a2c85147ef57f1a6b93910c50eb850417ab59dc56 appsvc/msitokenservice:1904260237
2020-02-11 06:36:05.552 INFO - Logging is not enabled for this container.
Please use https://aka.ms/linux-diagnostics to enable logging to see container logs here.
2020-02-11 06:36:17.766 INFO - Pulling image: a...cr/gateway:1.0.20042.2
2020-02-11 06:36:17.922 ERROR - DockerApiException: Docker API responded with status code=NotFound, response={"message":"pull access denied for a...cr/gateway, repository does not exist or may require 'docker login': denied: requested access to the resource is denied"}
2020-02-11 06:36:17.923 ERROR - Pulling docker image a...cr/gateway:1.0.20042.2 failed:
2020-02-11 06:36:17.923 INFO - Pulling image from Docker hub: a...cr/gateway:1.0.20042.2
2020-02-11 06:36:18.092 ERROR - DockerApiException: Docker API responded with status code=NotFound, response={"message":"pull access denied for a...cr/gateway, repository does not exist or may require 'docker login': denied: requested access to the resource is denied"}
2020-02-11 06:36:18.094 ERROR - Image pull failed: Verify docker image configuration and credentials (if using private repository)
2020-02-11 06:36:19.062 INFO - Stoping site app505-dfpg-qa2-web-eastus2-gateway-apsvc because it failed during startup.
The Service Principal used to deploy the App Service has AcrPush access to the parent resource group of the container registry:
The setting are present:
I did az login with that service principal and then tried az acr login to the registry. It works fine. So what am I missing here?
EDIT 1
I know the credentials are correct, because I tested them like this:
Where I just copied the values from the app service configuration and pasted on the console. docker has no problem logging in.
It must be something else.
EDIT 2
However, I also get this:
C:\Dayforce\fintech [shelve/terraform ≡]> docker pull a...r/gateway
Using default tag: latest
Error response from daemon: pull access denied for a...r/gateway, repository does not exist or may require 'docker login': denied: requested access to the resource is denied
So, I can login, but not pull. Very strange, because the account is configured to have AcrPush access to the container, which includes AcrPull:
EDIT 3
I was able to pull successfully when using the FQDN for the registry:
I updated the pipeline, but I still get the same errors:
2020-02-11 16:03:50.227 ERROR - Pulling docker image a...r.azurecr.io/gateway:1.0.20042.2 failed:
2020-02-11 16:03:50.228 INFO - Pulling image from Docker hub: a...r.azurecr.io/gateway:1.0.20042.2
2020-02-11 16:03:50.266 ERROR - DockerApiException: Docker API responded with status code=InternalServerError, response={"message":"Get https://a...r.azurecr.io/v2/gateway/manifests/1.0.20042.2: unauthorized: authentication required"}
2020-02-11 16:03:50.269 ERROR - Image pull failed: Verify docker image configuration and credentials (if using private repository)
2020-02-11 16:03:50.853 INFO - Stoping site app505-dfpg-qa2-web-eastus2-gateway-apsvc because it failed during startup.
EDIT 4
The only way that I found working was to enable the Admin User on the ACR and pass its credentials in the DOCKER_... variables instead of credentials of the Service Principal.
This is frustrating, I know the Service Principal can login and pull when ran locally, it is a mystery why it does not work for docker running on an App Service Host. We have another team here which faced the same issue and they have not found any solution, but enable the Admin User.
EDIT 5
The entire process runs as part of the Azure DevOps on-prem release pipeline using a dedicated Service Principal. Let me call it Pod Deploy Service Principal or just SP for short.
Let DOCKER_xyz denote the three app settings controlling the docker running on the App Service host:
DOCKER_REGISTRY_SERVER_URL
DOCKER_REGISTRY_SERVER_USERNAME
DOCKER_REGISTRY_SERVER_PASSWORD
I think we need to distinguish two parts here:
App Service needs to talk to the ACR in order to pull from it the details about the image and present them in this GUI - For that to work, the SP must have the AcrPull role in the ACR. Failure to do so results in the GUI presenting a spinning icon for the Image and Tag rows. I stumbled on it before - How to configure an Azure app service to pull images from an ACR with terraform? Now the answer to that question suggests that I have to assign the AcrPull role and set the DOCKER_xyz app settings. I think that the DOCKER_xyz app settings are not for that, but for the second part.
It seems to me that when an App Service is started, the host uses docker to actually pull the right image from the ACR. This part seems to be detached from (1). For it to work, the app settings must have the DOCKER_xyz app settings.
My problem is that part (1) works great, but part (2) does not even if DOCKER_xyz app settings specify the credentials of the SP from part (1). The only way I could make it work if I point DOCKER_xyz at the Admin User of the ACR.
But that why on Earth the DOCKER_xyz app settings cannot point to the pipeline SP, which was good enough for the part (1)?
EDIT 6
The current state of affairs is this. Azure App Service is unable to communicate with an ACR except using ACR admin user and password. So, even if the docker runtime running on the App Service host machine may know how to login using any service principal, the App Service would not use any identity or Service Principal to read metadata from the ACR - only admin user and password. The relevant references are:
https://feedback.azure.com/forums/169385-web-apps/suggestions/36145444-web-app-for-containers-acr-access-requires-admin#%7btoggle_previous_statuses%7d
https://github.com/MicrosoftDocs/azure-docs/issues/49186
On a personal note I find it amazing that Microsoft recommends not to use ACR admin user, yet a very core piece of their offering, namely Azure App Service, depends on it being enable. Makes me wonder whether different teams in Microsoft are aware of what others are doing or not doing...
App service started pulling after doing these steps for me. :D
Enable Admin Access in Azure Container Registry
In the App service configuration, provide container registry admin credentials
DOCKER_REGISTRY_SERVER_PASSWORD(admin enabled password),
DOCKER_REGISTRY_SERVER_USERNAME(crxxxxxx),
DOCKER_REGISTRY_SERVER_URL (https://crxxxxxx.azurecr.io)
Go to your app service and select identity section on the left, and click on system assigned - change status to On.
Now go to IAM Control container registry, add ACR pull role to App Service system assigned identity enabled on step 3.
Restart your App Service and wait .Changes will take few minutes to reflect so refresh your logs. (10 minutes or more)
Good luck :)
After a lot of research I figured out a way to resolve this without enabling Admin user
Create an app registration using Azure Active Directory and store the secret somewhere.
Go to the Azure container registry and add role assignment to this newly created app with permissions of AcrPush (which also contains AcrPull).
In the App service configuration, replace the variables .
DOCKER_REGISTRY_SERVER_PASSWORD with Client Secret of app registration which was saved in the first step
DOCKER_REGISTRY_SERVER_USERNAME with client Id of App registration
This should solve the Docker Api exception.
It's baffling that this is not mentioned in any Azure Container Registry documentation. Although I think it is mentioned somewhere in AAD documentation indirectly 😐.
From the message I got of the talk, let me solve your puzzle about the error.
I guess you deploy the image in ACR to the Web App through the Azure portal. When you use the Azure portal to deploy the Web App from the ACR, it only lets you select the ACR and image and tag, but do not let you set the credential. In this way, Azure will set it itself with the admin user and password if you enable the admin user. If you do not enable it, the error you got happens.
And if you want to use the service principal, I recommend you use the other tools, such as Azure CLI. Then you can set the docker registry credential yourself with the command az webapp config container set.
Here is the example and it works fine on my side:
With the Azure CLI, you can follow the steps here.
Update:
Here are the screenshots of the test on my side:
Found the answer by setting "acrUseManagedIdentityCreds" to True. The second command in this comment: https://stackoverflow.com/a/69120462/17430834
Edit 1: Adding the command
Here is the command that you will need to run to make this change.
az resource update --ids /subscriptions/<subscription-id>/resourceGroups/myResourceGroup/providers/Microsoft.Web/sites/<app-name>/config/web --set properties.acrUseManagedIdentityCreds=True
I was trying to do the same from Azure DevOps pipelines and got the same problem.
I didn't find out how to make it work using the ACR name, but it works if you use your_acr_name.azurecr.io instead.
If you go to the Access Keys page of your ACR you will find two values
Registry name: MyCoolRegistry (doesn't work if you use this one)
Login server: mycoolregistry.azurecr.io
The login server is working - just put it as the containerRegistry in your Pipeline without creating a service connection.
Just in case someone is struggling with that one.
Just to add to mark's amazing job of working it all through and for the fast readers: for everything to work, one of course also has to enable the admin user (who by default is disabled). For example by issuing:
az acr update -n <your-azureregistry-name> --admin-enabled true
on the console.
I experienced this same issue when trying to deploy an Docker application to Azure Web Apps for containers.
When I deployed the application I will get the error:
DockerApiException: Docker API responded with status code=NotFound, response={"message":"pull access denied for a..my-repo/image, repository does not exist or may require 'docker login': denied: requested access to the resource is denied"}.
Here's how I solved it:
The issue was that I was not specifying the full path to the image. I was supposed to include my-registry-url in the docker image-name. That is instead of just image-name I was supposed to use my-registry-url/image-name, since I am trying to pull from a private repository.
So say these are variables:
docker image name is promiseapp
docker-registry_url is promisecicdregistry.azurecr.io
resource-group is dockerprojects
app-service-plan is dockerlinuxprojects
azure-web-app name is promiseapptest
docker-registry-user is test-user
docker-registry-password is 12345678
Then my command will be:
az webapp create --resource-group dockerprojects --plan dockerlinuxprojects --name promiseapptest --deployment-container-image-name promisecicdregistry.azurecr.io/promiseapp
az webapp config container set --resource-group dockerprojects --name promiseapptest --docker-custom-image-name promisecicdregistry.azurecr.io/promiseapp --docker-registry-server-url https://promisecicdregistry.azurecr.io --docker-registry-server-user test-user --docker-registry-server-password 12345678
In my case, I fixed the error by using the fully qualified Azure Container Registery name like this:
xwezi.azurecr.io
The previous value was
xwezi
When I deploy manually to App Services, I wouldn't get that error.
But, when I used Azure App Service deploy task to deploy the container to the App Service, the service won't work correctly.
And, the log stream will show the above errors.
Unfortunately, the error messages weren't helpful for me to find this out. But I hope this will save your time :)

Azure Container Registry in Azure Web App for Containers across subscriptions

I'm currently trying to set up an Azure Web App for Containers, linking it to a Azure Container Registry that lives inside a different subscription. That's why my initial thought was to use the Private Registrytab inside the Web apps Container Settings to enter the credentials of said Registry.
However when I save and reload the page the settings of the Azure Container Registry tab are now populated and the Private Registry tab is empty. The issue is, that I get now get following error:
2020-01-21 21:51:12.951 ERROR - DockerApiException: Docker API responded with status code=NotFound, response={"message":"pull access denied for cliswebapi, repository does not exist or may require 'docker login': denied: requested access to the resource is denied"}
I assume because no password was stored. How do I configure this properly?
While you use the private registry, the Azure Container Registry is also a private registry, and deploy to Web App for Containers, you need to set the environment variables here:
DOCKER_REGISTRY_SERVER_USERNAME - The username for the ACR server.
DOCKER_REGISTRY_SERVER_URL - The full URL to the ACR server. (For example, https://my-server.azurecr.io.)
DOCKER_REGISTRY_SERVER_PASSWORD - The password for the ACR server.
See more details in If you're using Azure Container Registry, you need to set some app settings.
And if you create multiple containers, all the images must be in the same registry. All in Docker Hub or Azure Container Registry. See more details in All images must use the same registry.
Update:
With the message that you deploy the Web App using the image in the ACR in a different subscription. It seems it's a bug in Web App and you can see the issue in the Github. And the suggestion is that maybe you can use the service principal for the ACR to authenticate and the steps here.
I have spend some time on this issue and figured it out. Here is my solution:
Assuming we are having two subscriptions, let's call them SUB-A and SUB-B, where we are having an Azure Container Registry in SUB-A (called azurebluedev in my example).
Now we'd like to create an App Service in SUB-B that pulls its image of our container registry by using the admin username.
It's critical that you use the correct format under Image and tag in the docker blade when creating the app service. It must follow the format url/image:tag (without https) otherwise you will run into the described problem. I was using image:tag format beforehand which didn't work.
This worked for me!

Resources