pulumi-django-azure


Namepulumi-django-azure JSON
Version 1.0.43 PyPI version JSON
download
home_pageNone
SummarySimply deployment of Django on Azure with Pulumi
upload_time2025-10-19 22:04:14
maintainerNone
docs_urlNone
authorMaarten Ureel
requires_python<3.14,>=3.11
licenseNone
keywords django pulumi azure
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Pulumi Django Deployment

This project aims to make a simple Django deployment on Azure easier.

To have a proper and secure environment, we need these components:
* Storage account for media and static files
* CDN endpoint in front with a domain name of our choosing
* PostgreSQL server
* Azure Communication Services to send e-mails
* Webapp with multiple custom host names and managed SSL for the website itself
* Azure Key Vault per application
* Webapp running pgAdmin

## Project requirements

## Installation
This package is published on PyPi, so you can just add pulumi-django-azure to your requirements file.

To use a specific branch in your project, add to pyproject.toml dependencies:
```
pulumi-django-azure = { git = "git@gitlab.com:MaartenUreel/pulumi-django-azure.git", branch = "dev" }
```

A simple project could look like this:
```python
import pulumi
import pulumi_azure_native as azure
from pulumi_django_azure import DjangoDeployment

stack = pulumi.get_stack()
config = pulumi.Config()


# Create resource group
rg = azure.resources.ResourceGroup(f"rg-{stack}")

# Create VNet
vnet = azure.network.VirtualNetwork(
    f"vnet-{stack}",
    resource_group_name=rg.name,
    address_space=azure.network.AddressSpaceArgs(
        address_prefixes=["10.0.0.0/16"],
    ),
)

# Deploy the website and all its components
django = DjangoDeployment(
    stack,
    tenant_id="abc123...",
    resource_group_name=rg.name,
    vnet=vnet,
    pgsql_ip_prefix="10.0.10.0/24",
    appservice_ip_prefix="10.0.20.0/24",
    app_service_sku=azure.web.SkuDescriptionArgs(
        name="B2",
        tier="Basic",
    ),
    storage_account_name="mystorageaccount",
    cdn_host="cdn.example.com",
)

django.add_django_website(
    name="web",
    db_name="mywebsite",
    repository_url="git@gitlab.com:project/website.git",
    repository_branch="main",
    website_hosts=["example.com", "www.example.com"],
    django_settings_module="mywebsite.settings.production",
    comms_data_location="europe",
    comms_domains=["mydomain.com"],
)

django.add_database_administrator(
    object_id="a1b2c3....",
    user_name="user@example.com",
    tenant_id="a1b2c3....",
)
```

## Changes to your Django project
1. Add `pulumi_django_azure` to your `INSTALLED_APPS`
2. Add to your settings file:
   ```python
   from pulumi_django_azure.settings import *  # noqa: F403

   # This will provide the management command to purge the CDN and cache
   INSTALLED_APPS += ["pulumi_django_azure"]

   # This will provide the health check middleware that will also take care of credential rotation.
   MIDDLEWARE += ["pulumi_django_azure.middleware.HealthCheckMiddleware"]
   ```
   This will pre-configure most settings to make your app work on Azure. You can check the source for details,
   and ofcourse override any value after importing them.


## Deployment steps
1. Deploy without custom hosts (for CDN and websites)
2. Configure the PostgreSQL server (create and grant permissions to role for your websites)
3. Retrieve the deployment SSH key and configure your remote GIT repository with it
4. Configure your CDN host (add the CNAME record)
5. Configure your custom website domains (add CNAME/A record and TXT validation records)
6. Re-deploy with custom hosts
7. Re-deploy once more to enable HTTPS on website domains
8. Manually activate HTTPS on the CDN host
9. Go to the e-mail communications service on Azure and configure DKIM, SPF,... for your custom domains.

## Custom domain name for CDN
When deploying the first time, you will get a `cdn_cname` output. You need to create a CNAME to this domain before the deployment of the custom domain will succeed.

You can safely deploy with the failing CustomDomain to get the CNAME, create the record and then deploy again.

To enable HTTPS, you need to do this manually in the console. This is because of a limitation in the Azure API:
https://github.com/Azure/azure-rest-api-specs/issues/17498

## Custom domain names for web application
Because of a circular dependency in custom domain name bindings and certificates that is out of our control, you need to deploy the stack twice.

The first time will create the bindings without a certificate.
The second deployment will then create the certificate for the domain (which is only possible if the binding exists), but also set the fingerprint of that certificate on the binding.

To make the certificate work, you need to create a TXT record named `asuid` point to the output of `{your_app}_site_domain_verification_id`. For example:

```
asuid.mywebsite.com.      TXT  "A1B2C3D4E5..."
asuid.www.mywebsite.com.  TXT  "A1B2C3D4E5..."
```

## Database authentication
The PostgreSQL uses Entra ID authentication only, no passwords.

### Administrator login
If you want to log in to the database yourself, you can add yourself as an administrator with the `add_database_administrator` function.
Your username is your e-mailaddress, a temporary password can be obtained using `az account get-access-token`.

You can use this method to log in to pgAdmin.

### Application
Refer to this documentation:
https://learn.microsoft.com/en-us/azure/postgresql/flexible-server/how-to-manage-azure-ad-users#create-a-role-using-microsoft-entra-object-identifier

In short, run something like this in the `postgres` database:
```
SELECT * FROM pgaadauth_create_principal_with_oid('web_managed_identity', 'c8b25b85-d060-4cfc-bad4-b8581cfdf946', 'service', false, false);
```
Replace the GUID of course with the managed identity our web app gets.

The name of the role is outputted by `{your_app}_site_db_user`

Be sure to grant this role the correct permissions too.

## pgAdmin specifics
pgAdmin will be created with a default login:
* Login: dbadmin@dbadmin.net
* Password: dbadmin

Best practice is to log in right away, create a user for yourself and delete this default user.

## Azure OAuth2 / Django Social Auth
If you want to set up login with Azure, which would make sense since you are in the ecosystem, you need to create an App Registration in Entra ID, create a secret and then register these settings in your stack:
```
pulumi config set --secret --path 'mywebsite_social_auth_azure.key' secret_ID
pulumi config set --secret --path 'mywebsite_social_auth_azure.secret' secret_value
pulumi config set --secret --path 'mywebsite_social_auth_azure.tenant_id' directory_tenant_id
pulumi config set --secret --path 'mywebsite_social_auth_azure.client_id' application_id
```

Then in your Django deployment, pass to the `add_django_website` command:
```
secrets={
    "mywebsite_social_auth_azure": "AZURE_OAUTH",
},
```

The value will be automatically stored in the vault where the application has access to.
The environment variable will be suffixed with `_SECRET_NAME`.

Then, in your application, retrieve this data from the vault, e.g.:
```python
# Social Auth settings
oauth_secret = AZURE_KEY_VAULT_CLIENT.get_secret(env("AZURE_OAUTH_SECRET_NAME"))
oauth_secret = json.loads(oauth_secret.value)
SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_KEY = oauth_secret["client_id"]
SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_SECRET = oauth_secret["secret"]
SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_TENANT_ID = oauth_secret["tenant_id"]
SOCIAL_AUTH_ADMIN_USER_SEARCH_FIELDS = ["username", "first_name", "last_name", "email"]
SOCIAL_AUTH_POSTGRES_JSONFIELD = True

AUTHENTICATION_BACKENDS = (
    "social_core.backends.azuread_tenant.AzureADTenantOAuth2",
    "django.contrib.auth.backends.ModelBackend",
)
```

And of course add the login button somewhere, following Django Social Auth instructions.

## Automate deployments
When using a service like GitLab, you can configure a Webhook to fire upon a push to your branch.

You need to download the deployment profile to obtain the deployment username and password, and then you can construct a URL like this:

```
https://{user}:{pass}@{appname}.scm.azurewebsites.net/deploy

```

```
https://{appname}.scm.azurewebsites.net/api/sshkey?ensurePublicKey=1
```

Be sure to configure the SSH key that Azure will use on GitLab side. You can obtain it using:

This would then trigger a redeploy everytime you make a commit to your live branch.


## Change requests
I created this for internal use but since it took me a while to puzzle all the things together I decided to share it.
Therefore this project is not super generic, but tailored to my needs. I am however open to pull or change requests to improve this project or to make it more usable for others.


            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "pulumi-django-azure",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<3.14,>=3.11",
    "maintainer_email": null,
    "keywords": "django, pulumi, azure",
    "author": "Maarten Ureel",
    "author_email": "maarten@youreal.eu",
    "download_url": "https://files.pythonhosted.org/packages/f3/99/df68b433d96e460b36e854ba7e48e8e0bed34431ed3c367c6dc3633b6905/pulumi_django_azure-1.0.43.tar.gz",
    "platform": null,
    "description": "# Pulumi Django Deployment\n\nThis project aims to make a simple Django deployment on Azure easier.\n\nTo have a proper and secure environment, we need these components:\n* Storage account for media and static files\n* CDN endpoint in front with a domain name of our choosing\n* PostgreSQL server\n* Azure Communication Services to send e-mails\n* Webapp with multiple custom host names and managed SSL for the website itself\n* Azure Key Vault per application\n* Webapp running pgAdmin\n\n## Project requirements\n\n## Installation\nThis package is published on PyPi, so you can just add pulumi-django-azure to your requirements file.\n\nTo use a specific branch in your project, add to pyproject.toml dependencies:\n```\npulumi-django-azure = { git = \"git@gitlab.com:MaartenUreel/pulumi-django-azure.git\", branch = \"dev\" }\n```\n\nA simple project could look like this:\n```python\nimport pulumi\nimport pulumi_azure_native as azure\nfrom pulumi_django_azure import DjangoDeployment\n\nstack = pulumi.get_stack()\nconfig = pulumi.Config()\n\n\n# Create resource group\nrg = azure.resources.ResourceGroup(f\"rg-{stack}\")\n\n# Create VNet\nvnet = azure.network.VirtualNetwork(\n    f\"vnet-{stack}\",\n    resource_group_name=rg.name,\n    address_space=azure.network.AddressSpaceArgs(\n        address_prefixes=[\"10.0.0.0/16\"],\n    ),\n)\n\n# Deploy the website and all its components\ndjango = DjangoDeployment(\n    stack,\n    tenant_id=\"abc123...\",\n    resource_group_name=rg.name,\n    vnet=vnet,\n    pgsql_ip_prefix=\"10.0.10.0/24\",\n    appservice_ip_prefix=\"10.0.20.0/24\",\n    app_service_sku=azure.web.SkuDescriptionArgs(\n        name=\"B2\",\n        tier=\"Basic\",\n    ),\n    storage_account_name=\"mystorageaccount\",\n    cdn_host=\"cdn.example.com\",\n)\n\ndjango.add_django_website(\n    name=\"web\",\n    db_name=\"mywebsite\",\n    repository_url=\"git@gitlab.com:project/website.git\",\n    repository_branch=\"main\",\n    website_hosts=[\"example.com\", \"www.example.com\"],\n    django_settings_module=\"mywebsite.settings.production\",\n    comms_data_location=\"europe\",\n    comms_domains=[\"mydomain.com\"],\n)\n\ndjango.add_database_administrator(\n    object_id=\"a1b2c3....\",\n    user_name=\"user@example.com\",\n    tenant_id=\"a1b2c3....\",\n)\n```\n\n## Changes to your Django project\n1. Add `pulumi_django_azure` to your `INSTALLED_APPS`\n2. Add to your settings file:\n   ```python\n   from pulumi_django_azure.settings import *  # noqa: F403\n\n   # This will provide the management command to purge the CDN and cache\n   INSTALLED_APPS += [\"pulumi_django_azure\"]\n\n   # This will provide the health check middleware that will also take care of credential rotation.\n   MIDDLEWARE += [\"pulumi_django_azure.middleware.HealthCheckMiddleware\"]\n   ```\n   This will pre-configure most settings to make your app work on Azure. You can check the source for details,\n   and ofcourse override any value after importing them.\n\n\n## Deployment steps\n1. Deploy without custom hosts (for CDN and websites)\n2. Configure the PostgreSQL server (create and grant permissions to role for your websites)\n3. Retrieve the deployment SSH key and configure your remote GIT repository with it\n4. Configure your CDN host (add the CNAME record)\n5. Configure your custom website domains (add CNAME/A record and TXT validation records)\n6. Re-deploy with custom hosts\n7. Re-deploy once more to enable HTTPS on website domains\n8. Manually activate HTTPS on the CDN host\n9. Go to the e-mail communications service on Azure and configure DKIM, SPF,... for your custom domains.\n\n## Custom domain name for CDN\nWhen deploying the first time, you will get a `cdn_cname` output. You need to create a CNAME to this domain before the deployment of the custom domain will succeed.\n\nYou can safely deploy with the failing CustomDomain to get the CNAME, create the record and then deploy again.\n\nTo enable HTTPS, you need to do this manually in the console. This is because of a limitation in the Azure API:\nhttps://github.com/Azure/azure-rest-api-specs/issues/17498\n\n## Custom domain names for web application\nBecause of a circular dependency in custom domain name bindings and certificates that is out of our control, you need to deploy the stack twice.\n\nThe first time will create the bindings without a certificate.\nThe second deployment will then create the certificate for the domain (which is only possible if the binding exists), but also set the fingerprint of that certificate on the binding.\n\nTo make the certificate work, you need to create a TXT record named `asuid` point to the output of `{your_app}_site_domain_verification_id`. For example:\n\n```\nasuid.mywebsite.com.      TXT  \"A1B2C3D4E5...\"\nasuid.www.mywebsite.com.  TXT  \"A1B2C3D4E5...\"\n```\n\n## Database authentication\nThe PostgreSQL uses Entra ID authentication only, no passwords.\n\n### Administrator login\nIf you want to log in to the database yourself, you can add yourself as an administrator with the `add_database_administrator` function.\nYour username is your e-mailaddress, a temporary password can be obtained using `az account get-access-token`.\n\nYou can use this method to log in to pgAdmin.\n\n### Application\nRefer to this documentation:\nhttps://learn.microsoft.com/en-us/azure/postgresql/flexible-server/how-to-manage-azure-ad-users#create-a-role-using-microsoft-entra-object-identifier\n\nIn short, run something like this in the `postgres` database:\n```\nSELECT * FROM pgaadauth_create_principal_with_oid('web_managed_identity', 'c8b25b85-d060-4cfc-bad4-b8581cfdf946', 'service', false, false);\n```\nReplace the GUID of course with the managed identity our web app gets.\n\nThe name of the role is outputted by `{your_app}_site_db_user`\n\nBe sure to grant this role the correct permissions too.\n\n## pgAdmin specifics\npgAdmin will be created with a default login:\n* Login: dbadmin@dbadmin.net\n* Password: dbadmin\n\nBest practice is to log in right away, create a user for yourself and delete this default user.\n\n## Azure OAuth2 / Django Social Auth\nIf you want to set up login with Azure, which would make sense since you are in the ecosystem, you need to create an App Registration in Entra ID, create a secret and then register these settings in your stack:\n```\npulumi config set --secret --path 'mywebsite_social_auth_azure.key' secret_ID\npulumi config set --secret --path 'mywebsite_social_auth_azure.secret' secret_value\npulumi config set --secret --path 'mywebsite_social_auth_azure.tenant_id' directory_tenant_id\npulumi config set --secret --path 'mywebsite_social_auth_azure.client_id' application_id\n```\n\nThen in your Django deployment, pass to the `add_django_website` command:\n```\nsecrets={\n    \"mywebsite_social_auth_azure\": \"AZURE_OAUTH\",\n},\n```\n\nThe value will be automatically stored in the vault where the application has access to.\nThe environment variable will be suffixed with `_SECRET_NAME`.\n\nThen, in your application, retrieve this data from the vault, e.g.:\n```python\n# Social Auth settings\noauth_secret = AZURE_KEY_VAULT_CLIENT.get_secret(env(\"AZURE_OAUTH_SECRET_NAME\"))\noauth_secret = json.loads(oauth_secret.value)\nSOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_KEY = oauth_secret[\"client_id\"]\nSOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_SECRET = oauth_secret[\"secret\"]\nSOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_TENANT_ID = oauth_secret[\"tenant_id\"]\nSOCIAL_AUTH_ADMIN_USER_SEARCH_FIELDS = [\"username\", \"first_name\", \"last_name\", \"email\"]\nSOCIAL_AUTH_POSTGRES_JSONFIELD = True\n\nAUTHENTICATION_BACKENDS = (\n    \"social_core.backends.azuread_tenant.AzureADTenantOAuth2\",\n    \"django.contrib.auth.backends.ModelBackend\",\n)\n```\n\nAnd of course add the login button somewhere, following Django Social Auth instructions.\n\n## Automate deployments\nWhen using a service like GitLab, you can configure a Webhook to fire upon a push to your branch.\n\nYou need to download the deployment profile to obtain the deployment username and password, and then you can construct a URL like this:\n\n```\nhttps://{user}:{pass}@{appname}.scm.azurewebsites.net/deploy\n\n```\n\n```\nhttps://{appname}.scm.azurewebsites.net/api/sshkey?ensurePublicKey=1\n```\n\nBe sure to configure the SSH key that Azure will use on GitLab side. You can obtain it using:\n\nThis would then trigger a redeploy everytime you make a commit to your live branch.\n\n\n## Change requests\nI created this for internal use but since it took me a while to puzzle all the things together I decided to share it.\nTherefore this project is not super generic, but tailored to my needs. I am however open to pull or change requests to improve this project or to make it more usable for others.\n\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Simply deployment of Django on Azure with Pulumi",
    "version": "1.0.43",
    "project_urls": {
        "Homepage": "https://gitlab.com/MaartenUreel/pulumi-django-azure"
    },
    "split_keywords": [
        "django",
        " pulumi",
        " azure"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "e342dd0641fc040c43845befc4443991a8d90b0423b29a593c53010081a1fda7",
                "md5": "e0664e7a18229735d67d61fbb21103dd",
                "sha256": "c015cc6230761beb9853ba399c0a3c1231fc5ec7af7f6a8857d12eedf45f0b76"
            },
            "downloads": -1,
            "filename": "pulumi_django_azure-1.0.43-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "e0664e7a18229735d67d61fbb21103dd",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<3.14,>=3.11",
            "size": 25003,
            "upload_time": "2025-10-19T22:04:13",
            "upload_time_iso_8601": "2025-10-19T22:04:13.499613Z",
            "url": "https://files.pythonhosted.org/packages/e3/42/dd0641fc040c43845befc4443991a8d90b0423b29a593c53010081a1fda7/pulumi_django_azure-1.0.43-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "f399df68b433d96e460b36e854ba7e48e8e0bed34431ed3c367c6dc3633b6905",
                "md5": "1213829a06fb9ac2f5f93ee25209bcce",
                "sha256": "3256fc72d698ae4eae73ad905a31c29173cd8b5663fbfacf48d3e2d336eaab58"
            },
            "downloads": -1,
            "filename": "pulumi_django_azure-1.0.43.tar.gz",
            "has_sig": false,
            "md5_digest": "1213829a06fb9ac2f5f93ee25209bcce",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<3.14,>=3.11",
            "size": 24681,
            "upload_time": "2025-10-19T22:04:14",
            "upload_time_iso_8601": "2025-10-19T22:04:14.737382Z",
            "url": "https://files.pythonhosted.org/packages/f3/99/df68b433d96e460b36e854ba7e48e8e0bed34431ed3c367c6dc3633b6905/pulumi_django_azure-1.0.43.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-10-19 22:04:14",
    "github": false,
    "gitlab": true,
    "bitbucket": false,
    "codeberg": false,
    "gitlab_user": "MaartenUreel",
    "gitlab_project": "pulumi-django-azure",
    "lcname": "pulumi-django-azure"
}
        
Elapsed time: 3.41086s