Django can't access Azure mounted storage - django

I am running my Djagno app (python 2.7, django 1.11) on an Azure server using AKS (kubernetes).
I have a persistent storage volume mounted at /data/media .
When I try to upload files through my app, I get the following error:
Exception Value: [Errno 13] Permission denied: '/data/media/uploads/<some_dir>'
Exception Location: /usr/local/lib/python2.7/os.py in makedirs, line 157
The problematic line in os.py is the one trying to create a directory mkdir(name, mode) .
When I use kubectl exec -it <my-pod> bash to access the pod (user is root), I can easily cd into the /data/media directory, create sub-folders and see them reflected in the Azure portal. So my mount is perfectly fine.
I tried chmoding /data/media but that does not work. It seems like I cannot change the permissions of the folders on the mounted persistent volume, nor can I add users or change groups. So, it seems there is no problem accessing the volume from my pod, but since Django is not running as root, it cannot access it.
Ho do I resolve this? Thanks.

It turns out that since the Azure file share mount is actually owned by the k8s cluster, the Docker containers running in the pods only mount it as an entry point but cannot modify its permissions since they do not own it.
The reason it started happening now is explained here:
... it turned out that the default directory mode and file mode differs between Kubernetes versions. So while the the access mode is 0777 for Kubernetes v1.6.x, v1.7.x, in case of v1.8.6 or above it is 0755
So for me the fix was adding the required access permissions for the mounted volume to k8s spec like so:
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: <volumeName>
annotations:
volume.beta.kubernetes.io/storage-class: <className>
spec:
mountOptions:
- dir_mode=0777
- file_mode=0777
accessModes:
- ReadWriteMany
...
** I wrote 0777 as an example. You should carefully set what's write for you.
Hope this helps anyone.

Related

Unable to write to AWS EFS from AWS ECS Fargate task

I followed this tutoiral to add persistent storage to my Grafana with a Fargate instance: https://aws.amazon.com/premiumsupport/knowledge-center/ecs-fargate-mount-efs-containers-tasks/
Before I followed the tutorial the task and deployment worked fine (just without persistent data). Now my task fails:
Essential container in task exited
When I check the log in my task I get the following:
Failed to start grafana. error: failed to connect to database: failed to create SQLite database file "/var/lib/grafana/grafana.db": open /var/lib/grafana/grafana.db: permission denied
...
GF_PATHS_DATA='/var/lib/grafana' is not writable.
My Dockerfile looks like this:
FROM grafana/grafana-oss:8.2.7
ENV GF_DEFAULT_APP_MODE "development"
ENV GF_LOG_LEVEL "debug"
ENV GF_PATHS_PLUGINS "/app/grafana/plugins"
COPY plugins /app/grafana/plugins
EXPOSE 3000
What can I do? Where could the issue be? I googled a lot and nothing worked / helped.

How to open permissions for Deployment volumeMount mapped to EFS

After creating the AWS EFS file system I went ahead and mapped it to one of the deployments/container's Volume as /data/files directory:
volumeMounts:
- name: efs-persistent-storage
mountPath: /data/files
readOnly: false
volumes:
- name: efs-persistent-storage
nfs:
server: fs-1234.efs.us-west-2.amazonaws.com
path: /files
I now am able to delete, create and modify the files stored on EFS drive. But running .sh script that tries to copy the files fails telling that the permissions of the /data/files directory don't allow it to create the files.
I double checked the directory permissions. And they are all open. How could I make it work?
May be the problem is that I am mapping directly to the efs server fs-1234.efs.us-west-2.amazonaws.com? Would it give me more options if I would use Persistant Volume Claim instead?

Problem with data transfer from Cloud Build container to Google Compute Engine instance

Currently I'm using Cloud Build to produce some artifacts that I need to deploy to GCE instance. I've tried to use gcloud builder for this purpose with the following args:
- name: 'gcr.io/cloud-builders/gcloud'
args: ['compute', 'scp', '--zone=<zone_id>', '<local_path>', '<google compute engine instance name>:<instance_path>']
and build fails with the following error:
ERROR: (gcloud.compute.scp) Could not SSH into the instance. It is
possible that your SSH key has not propagated to the instance yet. Try
running this command again. If you still cannot connect, verify that
the firewall and instance are set to accept ssh traffic.
I've already opened port 22 on my instance but that haven't helped me.
Could you guys help me to solve this problem?
What points I need to check/fix in my build definition?
May be you can give me an advice which builder instead of gcloud I can use to deliver my data from Cloud Build container to the GCE instance?
A few things to try:
1.Make sure you can ssh normally this way.
Troubleshooting SSH if step one fails.
2.Try to change the SSH target from 'instancename' to 'username#instance' in order to indicate the name of the user inside the VM, eg
username#InstanceName
You must find a way to generate and locace the SSH Key Files for the builder to connect to the GCE Instance:
google_compute
google_compute.pub
google_compute_known_hosts
They are identical to the ones you use to directly connect to the instance from your Cloud Shell or from your Local Computer, but this time the connection has to be done by the builder it self.
Make that files interactively like explained in SSH Key Generation to the identity path of builder (test it by cd ~ && pwd, usually: /builder/home/.ssh).
After a connection has been made then copy these files to Google Cloud Storage via gsutil. This step is need to be done one time only.
steps:
- name: 'gcr.io/cloud-builders/gsutil'
args: ['cp', '-rP', '${_BUIKDER_HOME}', 'gs://${_BUCKET_NAME}/builder/']
substitutions:
_BUCKET_NAME: <bucket_name>
_BUIKDER_HOME: <builder_home>
timeout: "60s"
You might take those key files to your workspace. If you prefer as it then they will need to be remain stay in the storage.
The purpose of this placement is that they will be used to reconnect to the instance because each time the builder is started it will be configured back to the default stage so the files will no more exist.
Once the key files are ready, then you can do the scp transfer like below:
steps:
- name: 'gcr.io/cloud-builders/gsutil'
args: ['cp', '-rP', 'gs://${_BUCKET_NAME}/builder/.ssh'], '_${_BUILDER_HOME}']
- name: 'gcr.io/cloud-builders/gcloud'
args: ['compute', 'scp', '--recurse', '--zone', '${_ZONE}', '${_LOCAL_PATH}', '${_USER_NAME}#${_INSTANCE_NAME}:${INSTANCE_PATH}']
substitutions:
_ZONE: <zone>
_USER_NAME: <user_name>
_LOCAL_PATH: <local_path>
_BUCKET_NAME: <bucket_name>
_BUILDER_HOME: : <builder_home>
_INSTANCE_NAME: <instance_name>
_INSTANCE_PATH: <instance_path>
timeout: "60s"
Note: Use the flag of '--recurse' to copy a directory or none to copy a file only.

Unable to pull docker image into Kubernetes Pod from Google Container Registry

I have read this question and this one, and created my Kubernetes secret for Google Container Registry using a service account JSON key with project: owner and viewer permissions. I have also verified that the image does in fact exist in Google Container Registry by going to the console.
I have also read this document.
When I run:
minikube dashboard
And then from the user interface, I click the "+" sybmol, specify the URL of my image like this:
project-123456/bot-image
then click on 'advanced options' and specify the Secret that was imported.
After a few seconds I see this error:
Error: Status 403 trying to pull repository project-123456/bot-image: "Unable to access the repository: project-123456/bot-image; please verify that it exists and you have permission to access it (no valid credential was supplied)."
If I look at what's inside the Secret file (.dockerconfigjson), it's like:
{"https://us.gcr.io": {"email": "admin#domain.com", "auth": "longtexthere"}}
What could be the issue?
The json needs to have a top level "{auths": json key from:
Creating image pull secret for google container registry that doesn't expire?
So the json should be structured like:
{"auths":{"https://us.gcr.io": {"email": "admin#domain.com", "auth": "longtexthere"}}}
If you are still having issues, you can alternatively download the latest version of minikube (0.17.1) and run
minikube addons configure registry-creds
following the prompts there to setup creds
then run minikube addons enable registry-creds
Now you should be able to pull down pods from GCR using a yaml structured like this:
apiVersion: v1
kind: Pod
metadata:
name: foo
namespace: default
spec:
containers:
- image: gcr.io/example-vm/helloworld:latest
name: foo
EDIT: 6/13/2018 updating the commands to reflect comment by #Rambatino

What is the best way to pass AWS credentials to a Docker container?

I am running docker-container on Amazon EC2. Currently I have added AWS Credentials to Dockerfile. Could you please let me know the best way to do this?
A lot has changed in Docker since this question was asked, so here's an attempt at an updated answer.
First, specifically with AWS credentials on containers already running inside of the cloud, using IAM roles as Vor suggests is a really good option. If you can do that, then add one more plus one to his answer and skip the rest of this.
Once you start running things outside of the cloud, or have a different type of secret, there are two key places that I recommend against storing secrets:
Environment variables: when these are defined on a container, every process inside the container has access to them, they are visible via /proc, apps may dump their environment to stdout where it gets stored in the logs, and most importantly, they appear in clear text when you inspect the container.
In the image itself: images often get pushed to registries where many users have pull access, sometimes without any credentials required to pull the image. Even if you delete the secret from one layer, the image can be disassembled with common Linux utilities like tar and the secret can be found from the step where it was first added to the image.
So what other options are there for secrets in Docker containers?
Option A: If you need this secret only during the build of your image, cannot use the secret before the build starts, and do not have access to BuildKit yet, then a multi-stage build is a best of the bad options. You would add the secret to the initial stages of the build, use it there, and then copy the output of that stage without the secret to your release stage, and only push that release stage to the registry servers. This secret is still in the image cache on the build server, so I tend to use this only as a last resort.
Option B: Also during build time, if you can use BuildKit which was released in 18.09, there are currently experimental features to allow the injection of secrets as a volume mount for a single RUN line. That mount does not get written to the image layers, so you can access the secret during build without worrying it will be pushed to a public registry server. The resulting Dockerfile looks like:
# syntax = docker/dockerfile:experimental
FROM python:3
RUN pip install awscli
RUN --mount=type=secret,id=aws,target=/root/.aws/credentials aws s3 cp s3://... ...
And you build it with a command in 18.09 or newer like:
DOCKER_BUILDKIT=1 docker build -t your_image --secret id=aws,src=$HOME/.aws/credentials .
Option C: At runtime on a single node, without Swarm Mode or other orchestration, you can mount the credentials as a read only volume. Access to this credential requires the same access that you would have outside of docker to the same credentials file, so it's no better or worse than the scenario without docker. Most importantly, the contents of this file should not be visible when you inspect the container, view the logs, or push the image to a registry server, since the volume is outside of that in every scenario. This does require that you copy your credentials on the docker host, separate from the deploy of the container. (Note, anyone with the ability to run containers on that host can view your credential since access to the docker API is root on the host and root can view the files of any user. If you don't trust users with root on the host, then don't give them docker API access.)
For a docker run, this looks like:
docker run -v $HOME/.aws/credentials:/home/app/.aws/credentials:ro your_image
Or for a compose file, you'd have:
version: '3'
services:
app:
image: your_image
volumes:
- $HOME/.aws/credentials:/home/app/.aws/credentials:ro
Option D: With orchestration tools like Swarm Mode and Kubernetes, we now have secrets support that's better than a volume. With Swarm Mode, the file is encrypted on the manager filesystem (though the decryption key is often there too, allowing the manager to be restarted without an admin entering a decrypt key). More importantly, the secret is only sent to the workers that need the secret (running a container with that secret), it is only stored in memory on the worker, never disk, and it is injected as a file into the container with a tmpfs mount. Users on the host outside of swarm cannot mount that secret directly into their own container, however, with open access to the docker API, they could extract the secret from a running container on the node, so again, limit who has this access to the API. From compose, this secret injection looks like:
version: '3.7'
secrets:
aws_creds:
external: true
services:
app:
image: your_image
secrets:
- source: aws_creds
target: /home/user/.aws/credentials
uid: '1000'
gid: '1000'
mode: 0700
You turn on swarm mode with docker swarm init for a single node, then follow the directions for adding additional nodes. You can create the secret externally with docker secret create aws_creds $HOME/.aws/credentials. And you deploy the compose file with docker stack deploy -c docker-compose.yml stack_name.
I often version my secrets using a script from: https://github.com/sudo-bmitch/docker-config-update
Option E: Other tools exist to manage secrets, and my favorite is Vault because it gives the ability to create time limited secrets that automatically expire. Every application then gets its own set of tokens to request secrets, and those tokens give them the ability to request those time limited secrets for as long as they can reach the vault server. That reduces the risk if a secret is ever taken out of your network since it will either not work or be quick to expire. The functionality specific to AWS for Vault is documented at https://www.vaultproject.io/docs/secrets/aws/index.html
The best way is to use IAM Role and do not deal with credentials at all. (see http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html )
Credentials could be retrieved from http://169.254.169.254..... Since this is a private ip address, it could be accessible only from EC2 instances.
All modern AWS client libraries "know" how to fetch, refresh and use credentials from there. So in most cases you don't even need to know about it. Just run ec2 with correct IAM role and you good to go.
As an option you can pass them at the runtime as environment variables ( i.e docker run -e AWS_ACCESS_KEY_ID=xyz -e AWS_SECRET_ACCESS_KEY=aaa myimage)
You can access these environment variables by running printenv at the terminal.
Yet another approach is to create temporary read-only volume in docker-compose.yaml. AWS CLI and SDK (like boto3 or AWS SDK for Java etc.) are looking for default profile in ~/.aws/credentials file.
If you want to use other profiles, you just need also to export AWS_PROFILE variable before running docker-compose command.
export AWS_PROFILE=some_other_profile_name
version: '3'
services:
service-name:
image: docker-image-name:latest
environment:
- AWS_PROFILE=${AWS_PROFILE}
volumes:
- ~/.aws/:/root/.aws:ro
In this example, I used root user on docker. If you are using other user, just change /root/.aws to user home directory.
:ro - stands for read-only docker volume
It is very helpful when you have multiple profiles in ~/.aws/credentials file and you are also using MFA. Also helpful when you want to locally test docker-container before deploying it on ECS on which you have IAM Roles, but locally you don't.
Another approach is to pass the keys from the host machine to the docker container. You may add the following lines to the docker-compose file.
services:
web:
build: .
environment:
- AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID}
- AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY}
- AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION}
The following one-liner works for me even when my credentials are set up by aws-okta or saml2aws:
$ docker run -v$HOME/.aws:/root/.aws:ro \
-e AWS_ACCESS_KEY_ID \
-e AWS_CA_BUNDLE \
-e AWS_CLI_FILE_ENCODING \
-e AWS_CONFIG_FILE \
-e AWS_DEFAULT_OUTPUT \
-e AWS_DEFAULT_REGION \
-e AWS_PAGER \
-e AWS_PROFILE \
-e AWS_ROLE_SESSION_NAME \
-e AWS_SECRET_ACCESS_KEY \
-e AWS_SESSION_TOKEN \
-e AWS_SHARED_CREDENTIALS_FILE \
-e AWS_STS_REGIONAL_ENDPOINTS \
amazon/aws-cli s3 ls
Please note that for advanced use cases you might need to allow rw (read-write) permissions, so omit the ro (read-only) limitation when mounting the .aws volume in -v$HOME/.aws:/root/.aws:ro
Volume mounting is noted in this thread but as of docker-compose v3.2 + you can Bind Mount.
For example, if you have a file named .aws_creds in the root of your project:
In your service for the compose file do this for volumes:
volumes:
# normal volume mount, already shown in thread
- ./.aws_creds:/root/.aws/credentials
# way 2, note this requires docker-compose v 3.2+
- type: bind
source: .aws_creds # from local
target: /root/.aws/credentials # to the container location
Using this idea, you can publicly store your docker images on docker-hub because your aws credentials will not physically be in the image...to have them associated, you must have the correct directory structure locally where the container is started (i.e. pulling from Git)
You could create ~/aws_env_creds containing:
touch ~/aws_env_creds
chmod 777 ~/aws_env_creds
vi ~/aws_env_creds
Add these value (replace the key of yours):
AWS_ACCESS_KEY_ID=AK_FAKE_KEY_88RD3PNY
AWS_SECRET_ACCESS_KEY=BividQsWW_FAKE_KEY_MuB5VAAsQNJtSxQQyDY2C
Press "esc" to save the file.
Run and test the container:
my_service:
build: .
image: my_image
env_file:
- ~/aws_env_creds
If someone still face the same issue after following the instructions mentioned in accepted answer then make sure that you are not passing environment variables from two different sources. In my case I was passing environment variables to docker run via a file and as parameters which was causing the variables passed as parameters show no effect.
So the following command did not work for me:
docker run --env-file ./env.list -e AWS_ACCESS_KEY_ID=ABCD -e AWS_SECRET_ACCESS_KEY=PQRST IMAGE_NAME:v1.0.1
Moving the aws credentials into the mentioned env.list file helped.
for php apache docker the following command works
docker run --rm -d -p 80:80 --name my-apache-php-app -v "$PWD":/var/www/html -v ~/.aws:/.aws --env AWS_PROFILE=mfa php:7.2-apache
Based on some of previous answers, I built my own as follows.
My project structure:
├── Dockerfile
├── code
│   └── main.py
├── credentials
├── docker-compose.yml
└── requirements.txt
My docker-compose.yml file:
version: "3"
services:
app:
build:
context: .
volumes:
- ./credentials:/root/.aws/credentials
- ./code:/home/app
My Docker file:
FROM python:3.8-alpine
RUN pip3 --no-cache-dir install --upgrade awscli
RUN mkdir /app
WORKDIR /home/app
CMD python main.py