Create Django Super User In A Docker Container Without Inputting Password
Answer :
Get the container ID and run the command.
docker exec -it container_id python manage.py createsuperuser
I recommend adding a new management command that will automatically create a superuser if no Users exist.
See small example I created at https://github.com/dkarchmer/aws-eb-docker-django. In particular, see how I have a python manage.py initadmin
which runs:
class Command(BaseCommand):
def handle(self, *args, **options):
if Account.objects.count() == 0:
for user in settings.ADMINS:
username = user[0].replace(' ', '')
email = user[1]
password = 'admin'
print('Creating account for %s (%s)' % (username, email))
admin = Account.objects.create_superuser(email=email, username=username, password=password)
admin.is_active = True
admin.is_admin = True
admin.save()
else:
print('Admin accounts can only be initialized if no Accounts exist')
(See Authentication/management/commands).
You can see how the Dockerfile then just runs CMD to runserver.sh which basically runs
python manage.py migrate --noinput
python manage.py initadmin
python manage.py runserver 0.0.0.0:8080
Obviously, this assumes the Admins immediately go change their passwords after the server is up. That may or may not be good enough for you.
Disclaimer:
Storing the passwords plaintext in the Dockerfile is insecure as the passwords can be extracted from the image at any time and the Dockerfiles are usually committed to version control. However, this answer is not about password security, rather about automating the createsuperuser
command; if you are looking for a proper way to store the superuser password, take a look at this SO question: Docker and securing passwords
.
I handle this by evaluating the python code line in Dockerfile.
ENV DJANGO_DB_NAME=default
ENV DJANGO_SU_NAME=admin
ENV DJANGO_SU_EMAIL=admin@my.company
ENV DJANGO_SU_PASSWORD=mypass
RUN python -c "import django; django.setup(); \
from django.contrib.auth.management.commands.createsuperuser import get_user_model; \
get_user_model()._default_manager.db_manager('$DJANGO_DB_NAME').create_superuser( \
username='$DJANGO_SU_NAME', \
email='$DJANGO_SU_EMAIL', \
password='$DJANGO_SU_PASSWORD')"
Note that this is different from calling
User.objects.create_superuser('admin', 'admin@example.com', 'pass')
as django.contrib.auth.get_user_model
will work fine with custom user model if you should have any (which is quite common), while with User.objects.create
you only create a standard user entity, ignoring any custom user model.
Also, it's the same call that django's createsuperuser
command does under the hood, so it should be pretty safe to do.
Comments
Post a Comment