<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yevhen Bondar on Medium]]></title>
        <description><![CDATA[Stories by Yevhen Bondar on Medium]]></description>
        <link>https://medium.com/@eugen1j.bondar?source=rss-aa0a9baa9910------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HAvCVWmej1PDP7dnKGddJw.jpeg</url>
            <title>Stories by Yevhen Bondar on Medium</title>
            <link>https://medium.com/@eugen1j.bondar?source=rss-aa0a9baa9910------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 19:27:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eugen1j.bondar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to build the SSR web application and mobile apps from the same code base]]></title>
            <link>https://blog.devgenius.io/how-to-build-the-ssr-web-application-and-mobile-apps-from-the-same-code-base-e6480640e8cf?source=rss-aa0a9baa9910------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6480640e8cf</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[nuxtjs]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[capacitor]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <dc:creator><![CDATA[Yevhen Bondar]]></dc:creator>
            <pubDate>Sun, 25 Sep 2022 11:42:57 GMT</pubDate>
            <atom:updated>2022-09-25T11:42:57.884Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*_SdvhOHsw1Pm4q0M.png" /></figure><p>Server-side rendering improves initial page load speed. The browser receives pre-rendered HTML from the server, so it takes less time to build the page.</p><p>Also, SSR sites play better with SEO. Search engine crawlers grab the site’s HTML content without executing JS code. Without SSR, search engines will not index page content and will not find internal links.</p><p>NuxtJS has a <a href="https://nuxtjs.org/docs/concepts/server-side-rendering/">Server-side rendering</a> feature:</p><blockquote><em>Server-side rendering (SSR), is the ability of an application to contribute by displaying the web-page on the server instead of rendering it in the browser. Server-side sends a fully rendered page to the client.</em></blockquote><p>But you cannot use SSR when you build a static site for the mobile application. Here I’ll show how to create an SSR web and cross-platform mobile application from the same code base using CapacitorJS and NuxtJS.</p><h3>Building the app</h3><p>As an example, we will build a simple app to show local time in <a href="https://en.wikipedia.org/wiki/Kyiv">Kyiv</a>.</p><p>To test SSR, we need to get data from the API server. We will receive data from <a href="http://worldtimeapi.org/">worldtimeapi.org</a> API using the <a href="https://v3.nuxtjs.org/getting-started/data-fetching/#usefetch">useFetch</a> method.</p><p>Let’s start with the application from the <a href="https://dev.to/daiquiri_team/how-to-create-android-and-ios-apps-from-the-nuxtjs-application-using-capacitorjs-134h">previous guide</a>.</p><p>Remove app.vue file and add pages/index.vue with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01a3ac04a73d9c5b99782dec9c91b344/href">https://medium.com/media/01a3ac04a73d9c5b99782dec9c91b344/href</a></iframe><p>Here we have:</p><ul><li>Retrieving current time in const timeData variable.</li><li>🕥 displaying time on the page.</li><li>🔄 refresh button.</li></ul><p>Run yarn dev and check <a href="http://localhost:3000/">http://localhost:3000/</a> what we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/0*G3XYx0iwU_lVTdnz.png" /></figure><p>Let’s look at the page source code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7SZRKQBwqJBFSane.png" /></figure><p>In NuxtJS, Server-side rendering is enabled by default. But what will we get if we create a static site for the mobile build? Run yarn generate &amp;&amp; yarn preview and recheck <a href="http://localhost:3000/">http://localhost:3000/</a>.</p><p>If you try to refresh the page, you will see that time doesn’t change. NuxtJS retrieved time from the server during static site generation and saved it in the pre-rendered HTML page.</p><p>Let’s add ssr: false to the nuxt.config.ts</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e39678d985dc425acbc484eecf0c37f0/href">https://medium.com/media/e39678d985dc425acbc484eecf0c37f0/href</a></iframe><p>and rebuild the site with yarn generate &amp;&amp; yarn preview.</p><p>Now NuxtJS runs HTTP requests on the client side. There is no datetime in the page sources, and datetime changes every time you refresh a page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h19eCdge_0atzxgK.png" /></figure><p>So, we must build a web application with SSR and a mobile application in client-only mode. Let’s use an environment flag MOBILE_BUILD: we will build a web application with MOBILE_BUILD=0 and a mobile application with MOBILE_BUILD=1.</p><p>You can use a .env file to store environment variables, and I&#39;ll go with export MOBILE_BUILD=1.</p><p>Change nuxt.config.ts:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/773fb83b47f5c2c9cb684d3d67c630b4/href">https://medium.com/media/773fb83b47f5c2c9cb684d3d67c630b4/href</a></iframe><p>Run yarn generate &amp;&amp; yarn preview and verify that the application works in client-only mode.</p><p>Finally, let’s build and check the Android application:</p><pre>yarn cap sync<br>yarn cap open android</pre><p>Run the application on an emulator and check that the refresh button works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/0*vXSUf4-uKCbhQB6k.png" /></figure><p>🎉 Congratulations, it works (on my laptop, at least 🙂).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6480640e8cf" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/how-to-build-the-ssr-web-application-and-mobile-apps-from-the-same-code-base-e6480640e8cf">How to build the SSR web application and mobile apps from the same code base</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Makefile for Your Django Project]]></title>
            <link>https://python.plainenglish.io/makefile-for-your-django-project-abd76d4f6444?source=rss-aa0a9baa9910------2</link>
            <guid isPermaLink="false">https://medium.com/p/abd76d4f6444</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[makefile]]></category>
            <dc:creator><![CDATA[Yevhen Bondar]]></dc:creator>
            <pubDate>Mon, 19 Sep 2022 15:16:47 GMT</pubDate>
            <atom:updated>2022-09-19T15:16:47.191Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vClopmtx1D8B41tycp1yhw.jpeg" /></figure><p>During the development process, you often need to run some commands in your terminal: create migrations, run tests, linters, etc. Usually, you execute these commands regularly.</p><p>It’s helpful to have shortcuts for such commands. And even better to share them among other developers on the project. For this goal, I use <a href="https://en.wikipedia.org/wiki/Make_(software)#Makefile">Makefile</a>. Here is the list of useful commands for a Django project.</p><h4>Installing dependencies</h4><p>I’m not a big fan of <a href="https://python-poetry.org/">Poetry</a>. It has <a href="https://github.com/dependabot/dependabot-core/issues?q=is%3Aissue+is%3Aopen+poetry+label%3A%22L%3A+python%3Apoetry%22">some problems</a> with Dependabot and doesn’t play with <a href="https://docs.renovatebot.com/python/">Renovate</a> at all. I use <a href="https://github.com/jazzband/pip-tools">pip-tools</a> with separate requirements.in and requirements-dev.in for local and prod environments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fca58e5df7e22ca546d0cf7e2ed2025f/href">https://medium.com/media/fca58e5df7e22ca546d0cf7e2ed2025f/href</a></iframe><p>Commands:</p><ul><li>pip-install-dev: Installs all requirements, including local. It is the main command for installing the project&#39;s dependencies, so I put this command at the top.</li><li>pip-install - I don&#39;t use this command often, but it could be helpful to run your code with production dependencies only.</li><li>pip-update Updates your requirements.txt and requirements-dev.txt after you add a new package to the requirements.in or requirements-dev.in.</li></ul><h4>Running the project</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc1461063a809bba36c7e02d8f19ae32/href">https://medium.com/media/cc1461063a809bba36c7e02d8f19ae32/href</a></iframe><p>That is an obvious one. The commands to run local web server and <a href="https://docs.celeryq.dev/en/stable/">Celery</a>. Also, I like to apply new migrations automatically when I run the server.</p><h4>Running linters</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38c8491206a421f4a472e7df90aaf3e1/href">https://medium.com/media/38c8491206a421f4a472e7df90aaf3e1/href</a></iframe><p>Commands:</p><ul><li>lint: Runs <a href="https://github.com/PyCQA/flake8">flake8</a> linter and <a href="https://github.com/python/mypy">mypy</a> type checker.</li><li>black: Automatic code formatting with <a href="https://github.com/psf/black">Black</a>.</li><li>cleanimports: runs <a href="https://github.com/PyCQA/isort">isort</a> and removes unused imports with <a href="https://github.com/PyCQA/autoflake">Autoflake</a>. Be sure to set up profile=black in isort settings to avoid conflicts with Black.</li><li>clean-lint: run all the stuff above. You can run this command before committing to formatting your code properly.</li><li>checkmigrations: prevents you from committing model changes without migrations. Really cool stuff!</li></ul><p>Also, I use make lint &amp;&amp; make checkmigrations in the CI pipeline and in the git pre-commit hook. You can also create a command for setting up such a hook:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bafdd8a089dd2f452a3110c3865dc64/href">https://medium.com/media/4bafdd8a089dd2f452a3110c3865dc64/href</a></iframe><h4>Running tests</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf335265d344cb9065b5c57232e189c1/href">https://medium.com/media/cf335265d344cb9065b5c57232e189c1/href</a></iframe><p>Runs <a href="https://docs.pytest.org/en/7.1.x/">pytest</a> in multiprocess mode using <a href="https://github.com/pytest-dev/pytest-xdist">pytest-xdist</a>.</p><h4>Compiling messages</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bae3a049717c3cac4a1da11013abe9f4/href">https://medium.com/media/bae3a049717c3cac4a1da11013abe9f4/href</a></iframe><p>Collects all string literals for <a href="https://docs.djangoproject.com/en/4.1/topics/i18n/translation/">translation</a>. Also, I use <a href="https://github.com/ankitpopli1891/django-autotranslate">Django Autotranslate</a> to translate phrases using Google Translate automatically.</p><h3>The end</h3><p>As long as the project goes on, new local commands appear. Maybe, you need to shell into the dev server to run some python code. Or download a fresh database dump (without sensitive data) for local bug reproducing. It’s better to keep this knowledge in the codebase, not in your head. Also, you won’t need to explain how to do exactly the same operation to your colleagues.</p><p>For more complex tasks, you can even create a shell script and call it from Makefile. So, it would be easier to find this new command for other devs.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em>. Interested in Growth Hacking? Check out </em><a href="https://circuit.ooo/"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abd76d4f6444" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/makefile-for-your-django-project-abd76d4f6444">Makefile for Your Django Project</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create A Custom Page in Django Admin]]></title>
            <link>https://python.plainenglish.io/create-a-custom-page-in-django-admin-f3b07590e109?source=rss-aa0a9baa9910------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3b07590e109</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-admin]]></category>
            <dc:creator><![CDATA[Yevhen Bondar]]></dc:creator>
            <pubDate>Tue, 13 Sep 2022 06:17:45 GMT</pubDate>
            <atom:updated>2022-09-13T06:17:45.129Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*3ENMhjJwSMpkvBsN.png" /></figure><p><a href="https://www.djangoproject.com/">Django</a> is a great web framework for fast development. <a href="https://docs.djangoproject.com/en/4.1/ref/contrib/admin/">Django Admin</a> allows you to manage your data without creating your own views.</p><p>The primary use case of the Admin is <a href="https://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a> operations. You can populate your local database with test data or change some real data in the production environment.</p><p>Sometimes, you need some custom interfaces to perform your routines on the project. Fortunately, Django Admin has a lot of room for customization. In this guide, I’ll show how to create a custom detail page in Django Admin.</p><h3>Basic setup</h3><p>Let’s start from scratch. I’ll use python3.9 in this guide. If you are not interested in the basic details, you can jump to the <a href="https://dev.to/daiquiri_team/creating-a-custom-page-in-django-admin-2al2-temp-slug-9545398/edit#custom-order-page">custom Order page</a> part.</p><p>First, create a virtual environment and install <a href="https://pypi.org/project/Django/">Django</a>. Also, we need <a href="https://pypi.org/project/Pillow/">Pillow</a> for Django’s ImageField:</p><pre>python3.9 -m venv venv <br>. ./venv/bin/activate<br>pip install django==4.1.1 Pillow==9.2.0</pre><p>Then, create a new Django project and product app inside.</p><pre>python -m django startproject django_admin_example .<br>python -m django startapp products</pre><p>It will be a simple shop application with Product, Order, and OrderItem models. Order can have several OrderItem and belongs to some User. Each OrderItem contains the Product and count—quantity of the Product in the Order.</p><p>Add these models in products/models.py:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3d11bcedc2ff719994559b62264d070/href">https://medium.com/media/e3d11bcedc2ff719994559b62264d070/href</a></iframe><p>Let’s include the product app in django_admin_example/settings.py. Also, we need to set MEDIA_URL and MEDIA_ROOT for file uploading:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9635c416ba467111455059c3de81cdc0/href">https://medium.com/media/9635c416ba467111455059c3de81cdc0/href</a></iframe><p>Now we can create and run migrations:</p><pre>python manage.py makemigrations<br>python manage.py migrate</pre><p>We are done with the models. Moving to the Admin part. Create a products/admin.py with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf5624abeba4037c782d49869779246d/href">https://medium.com/media/cf5624abeba4037c782d49869779246d/href</a></iframe><p>We created <a href="https://docs.djangoproject.com/en/4.1/ref/contrib/admin/#inlinemodeladmin-objects">OrderItemInline</a> to change order items on the Order form.</p><p>Next, we need to add a URL configuration for the admin site in urls.py. Also, we want to add media file URLs to serve images:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3bbbed0093896a1ecd9967521cd4118/href">https://medium.com/media/a3bbbed0093896a1ecd9967521cd4118/href</a></iframe><p>Finally, we need a superuser to login into the admin:</p><pre>$ python manage.py createsuperuser<br>Username (leave blank to use &#39;user&#39;): admin<br>Email address: admin@test.com<br>Password: <br>Password (again): <br>Superuser created successfully.</pre><p>Run python manage.py runserver, go to the <a href="http://127.0.0.1:8000/admin/">http://127.0.0.1:8000/admin/</a>, and log in with the admin user.</p><p>Now, it’s time to fill our database with some dummy data!</p><p>Let’s add a customer user;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*7_K5u0CngRsyT3Fu.png" /></figure><p>Some product to our shop;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*qq9QGtWtq6twgZdH.png" /></figure><p>And create an order for the customer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*m8GPrlpwT2Bw05Kx.png" /></figure><h3>Custom Order Page</h3><p>Now we are ready to create a page for order summary. We want customer information, a list of ordered products, and a total order sum on this page.</p><p>Let’s start with an empty template in products/templates/admin/products/order/detail.html. Django Admin enforces this structure for the templates: admin/APP_NAME/MODEL_NAME/some_template.html. So, all custom templates for the Order model will be in this folder.</p><p>Then, let’s create an OrderDetailView in admin.py:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/561fb7846c1ca570388c352632494346/href">https://medium.com/media/561fb7846c1ca570388c352632494346/href</a></iframe><p>Add this view to the OrderAdmin.get_urls, create the detail column and add it to the list_display:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed822f2eb420ab09345b633df178ea7e/href">https://medium.com/media/ed822f2eb420ab09345b633df178ea7e/href</a></iframe><p>OrderDetailView will accept pk as an argument. Also, we wrap the view into admin_site.admin_view. This wrapper checks that user is logged in, user.is_staff=True, and enforces CSRF validation.</p><p>Let’s check how it looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*iq4y6kBgzWAfw6PY.png" /></figure><h3>Creating a template</h3><p>Now the detail link leads to an empty page. Let’s create a real one.</p><p>As docs says:</p><blockquote><em>If you want to use the admin layout, extend from admin/base_site.html:</em></blockquote><p>Add this code to the detail.html and check the page in your browser:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2bae27481f7a941f6983917c97b016c/href">https://medium.com/media/d2bae27481f7a941f6983917c97b016c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*zknLCIEsoUuATQqA.png" /></figure><p>The page looks like a Django Page, but we are missing some components on the page: breadcrumbs, sidebar, and change password/logout buttons. You can check <a href="https://github.com/django/django/blob/main/django/contrib/admin/templates/admin/base.html">admin/base.html</a> and <a href="https://github.com/django/django/blob/main/django/contrib/admin/templates/admin/change_form.html">admin/change_form.html</a> to see how they are implemented.</p><p>First, we need a context for the template. Let’s override a OrderDetailView.get_context method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8260bd0f5c1c772603dae0927984597/href">https://medium.com/media/f8260bd0f5c1c772603dae0927984597/href</a></iframe><p>This will be enough for the sidebar and change password/logout buttons. Now, let’s add the breadcrumbs block to the detail.html. We can take the breadcrumbs block from the admin/change_form.html and modify it like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/319b40e4e67aa2b6bcb38340e0578338/href">https://medium.com/media/319b40e4e67aa2b6bcb38340e0578338/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*sDV7AaKEHmDbIDet.png" /></figure><p>Finally, let’s add a product table. We need a total amount of Order, so create a total_amount method for OrderItem and Order:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e7dbd412920e2e20ccca58152956753/href">https://medium.com/media/8e7dbd412920e2e20ccca58152956753/href</a></iframe><p>Add the table and the total to the detail.html:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09244fc033bc7d39d7a14158b20afbaa/href">https://medium.com/media/09244fc033bc7d39d7a14158b20afbaa/href</a></iframe><p>Check the final result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*3ENMhjJwSMpkvBsN.png" /></figure><h3>The end</h3><p>Congratulations! We added a custom page to the Django Admin. This is a way you can customize the Admin Django according to your project needs.</p><p>You can find the source code <a href="https://github.com/eugen1j/django-admin-example">here</a>.</p><p>If you need to build a custom web application, check out our <a href="https://daiquiri.team/services/agile-development?utm_medium=referral&amp;utm_source=medium_blog&amp;utm_campaign=django_admin_1">website</a> or connect with me directly on <a href="https://www.linkedin.com/in/yevhen-bondar/">LinkedIn</a>.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em>. Interested in Growth Hacking? Check out </em><a href="https://circuit.ooo/"><strong><em>Circuit</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3b07590e109" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/create-a-custom-page-in-django-admin-f3b07590e109">Create A Custom Page in Django Admin</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create Android and iOS apps from the NuxtJS application using CapacitorJS]]></title>
            <link>https://blog.devgenius.io/how-to-create-android-and-ios-apps-from-the-nuxtjs-application-using-capacitorjs-8663e5037493?source=rss-aa0a9baa9910------2</link>
            <guid isPermaLink="false">https://medium.com/p/8663e5037493</guid>
            <category><![CDATA[capacitorjs]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[nuxtjs]]></category>
            <dc:creator><![CDATA[Yevhen Bondar]]></dc:creator>
            <pubDate>Wed, 31 Aug 2022 07:58:39 GMT</pubDate>
            <atom:updated>2022-08-31T07:58:39.398Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D90cWhQX73koIk97zMbhJQ.png" /></figure><p>In this guide, I will show how to wrap an existing <a href="https://v3.nuxtjs.org/">NuxtJS</a> web application into Android and iOS mobile apps using <a href="https://capacitorjs.com/">CapacitorJS</a></p><blockquote><em>Capacitor is an open-source native runtime for building Web Native apps. Create cross-platform iOS, Android, and Progressive Web Apps with JavaScript, HTML, and CSS.</em></blockquote><p>CapacitorJS runs your static site on a local browser and shows it to the user. Also, it has some interface between native and web contexts for accessing native features.</p><p>But why do you need this if users can access your website from mobile browsers?</p><ol><li>It’s more useful for users. If a user uses your web app frequently, it’s easier for them just to click on your app icon than go to the browser and search for your app bookmark or type your app domain name. Both Android and iOS have the feature “Add website to home screen”. But a separate native app provides better UX.</li><li>Distribution channel. Users can search for your app in AppStore and PlayMarket. So, it’s better to be present on all popular platforms to reach more users.</li><li>Native features. Maybe, your web app doesn’t need them. But after you create a mobile version of your app, you can change your mind. At least you can add notifications by <a href="https://firebase.google.com/docs/cloud-messaging">FCM</a>.</li></ol><p>I think we are done with the “why?” part. Let’s go to the “how?” part.</p><h3>Creating dummy NuxtJS application</h3><p>To simplify this guide, I’ll create a new Nuxt application. Feel free to jump to the Installing CapacitorJS section if you already have one.</p><p>So, let’s create a nuxt3 application using the <a href="https://v3.nuxtjs.org/getting-started/quick-start/">official guide</a>. I’ll use <a href="https://nodejs.org/">NodeJS v16</a> and <a href="https://yarnpkg.com/">Yarn v1.22</a> for installation.</p><p>Open a terminal and run:</p><pre>$ yarn add global nuxi<br>$ yarn nuxi init nuxt-mobile<br>$ cd nuxt-mobile<br>$ yarn install</pre><p>Here we installed <a href="https://www.npmjs.com/package/nuxi">nuxi</a> Nuxt Command Line Interface, created a new project nuxt-mobile, and installed dependencies from package.json. You can replace nuxt-mobile with any name.</p><p>Next, let’s change app.vue. Replace the existing file with the following one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b97005c1cd8d1bec1432c8b187f1bd6/href">https://medium.com/media/8b97005c1cd8d1bec1432c8b187f1bd6/href</a></iframe><p>Now, let’s see what we got. Run the development server:</p><pre>$ yarn dev -o</pre><p>You will be navigated to the browser. Here you will see your web application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/0*AXw4n4lgXw7_-yVY.png" /></figure><p>It’s pretty empty, but it will be enough to show how to wrap a web application into mobile apps.</p><h3>Installing CapacitorJS</h3><p>Now, let’s add CapacitorJS to the application. I’ll follow instructions from the <a href="https://capacitorjs.com/docs/getting-started">official guide</a>:</p><blockquote><em>In the root of your app, install Capacitor’s main npm depdencies: the core JavaScript runtime and the command line interface (CLI).</em></blockquote><pre>$ yarn add @capacitor/core<br>$ yarn add --dev @capacitor/cli</pre><blockquote><em>Then, initialize Capacitor using the CLI questionnaire:</em></blockquote><pre>$ yarn cap init</pre><p>The CLI will ask you questions about your package. You can pick any Name and Package (I used NuxtMobile and com.mycompany.nuxtmobile values). Then you need to set the Web asset directory as dist. This is a destination on <a href="https://nuxtjs.org/docs/concepts/static-site-generation/">NuxtJS static site</a>. The CLI will save these answers into capacitor.config.json and check the file content.</p><blockquote><em>After the Capacitor core runtime is installed, you can install the Android and iOS platforms.</em></blockquote><pre>$ yarn add @capacitor/android @capacitor/ios</pre><p>CapacitorJS uses a static version of the site. So, we need to generate it:</p><pre>$ yarn generate</pre><p>Now we have a static site so that we can initialize iOS and Android applications:</p><pre>$ yarn cap add android<br>$ yarn cap add ios</pre><p>These commands create native applications in android and ios folders. They clone web content from the dist directory to ios/App/App/public and android/app/src/main/assets/public directories.</p><p>Every time you change your site, you need to run yarn generate to generate a new static site and npx cap sync to update the native apps.</p><h3>Running Android app</h3><p>Let’s run the Android application. First, download and install <a href="https://developer.android.com/studio">AndroidStudio</a>.</p><p>After you finish, return to the console and run yarn cap open android. This will open android folder in AndroidStudio. Here you can change your Android files and run the application.</p><p>Let’s add an emulator to run. Go to the “Tools” -&gt; “Device Manager” and click “Create Device.”</p><p>First, you need to pick “Hardware device.” The main difference between different devices is a screen size and availability of PlayMarket. I’ll pick the Pixel 2 because it has PlayMarket and a 5.0&quot; screen size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/0*gYRogCCwsrzVmA9B.png" /></figure><p>Then, you need to choose the Android OS image. I will use Android API 33.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*25D9mtz_G5RQ9Iie.png" /></figure><p>Finally, click ‘Next’ and ‘Finish’. After this, you will see a new device on the ‘Devices’ dropdown.</p><p>Now, you can choose your device and click ‘Run’ to build and start the application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/0*CgUM9vdiJnhmljUT.png" /></figure><p>Android Studio will start the emulator, build, install and run your application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/0*ckd5-9gR3bsNd9mz.png" /></figure><p>We are done with Android; let’s move to the iOS part.</p><h3>Running iOS app</h3><p>To build the application for iOS, you need a MacBook. If you have Linux or Windows, you can skip this part.</p><p>First, you need XCode to build and run the iOS application. You can get it on <a href="https://apps.apple.com/us/app/xcode/id497799835">AppStore</a>.</p><p>After installation, return to the console and run yarn cap open ios. This command will open the ios folder as an XCode project. Here you can change iOS application files and settings; build and run the application.</p><p>Now, we need to pick an emulator device to run the application. I’ll use the iPod touch.</p><p>Then click ‘Run’. XCode will build the app and run it on the device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*uLToq0s2lYS6uhUz.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/0*oCt5PJ-m4M-DuH0V.png" /></figure><p>We are done with the iOS part.</p><h3>The end</h3><p>Congratulations! In this guide, we turn a new NuxtJS web application into iOS and Android mobile applications. It’s a very basic web app so we wouldn’t upload it to stores :) But if you already have a full-featured web application, you can turn it into mobile apps and upload them to PlayMarket and AppStore!</p><p>You can find the source code of the project <a href="https://github.com/eugen1j/nuxt-mobile">here</a>.</p><p>If you need to build a web or mobile app prototype, check out our <a href="https://daiquiri.team/services/prototyping?utm_medium=referral&amp;utm_source=medium_blog&amp;utm_campaign=nuxt_mobile_1">website</a> or connect with me directly on <a href="https://www.linkedin.com/in/yevhen-bondar/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8663e5037493" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/how-to-create-android-and-ios-apps-from-the-nuxtjs-application-using-capacitorjs-8663e5037493">How to create Android and iOS apps from the NuxtJS application using CapacitorJS</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Django Application on AWS with Terraform. ECS Autoscaling]]></title>
            <link>https://aws.plainenglish.io/deploying-django-application-on-aws-with-terraform-ecs-autoscaling-f4ebd78dcec1?source=rss-aa0a9baa9910------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4ebd78dcec1</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[autoscaling]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Yevhen Bondar]]></dc:creator>
            <pubDate>Tue, 23 Aug 2022 11:35:54 GMT</pubDate>
            <atom:updated>2022-08-23T11:35:54.357Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P81_GPxMPRTBou7Q6wPZ8A.png" /></figure><p>This is the 7th part of the “Deploying Django Application on AWS with Terraform” guide. You can check out the previous steps here:</p><ul><li><a href="https://medium.com/@eugen1j.bondar/deploying-django-application-on-aws-with-terraform-minimal-working-setup-d6075b3b8299">Part 1: Minimal Working Setup</a></li><li><a href="https://medium.com/@eugen1j.bondar/deploying-django-application-on-aws-with-terraform-connecting-postgresql-rds-bcd9c29d6276">Part 2: Connecting PostgreSQL RDS</a></li><li><a href="https://blog.devgenius.io/deploying-django-application-on-aws-with-terraform-gitlab-ci-cd-fbc2bbc0d286">Part 3: GitLab CI/CD</a></li><li><a href="https://blog.devgenius.io/deploying-django-application-on-aws-with-terraform-namecheap-domain-ssl-457779e3a20">Part 4: Namecheap Domain + SSL</a></li><li><a href="https://medium.com/python-in-plain-english/deploying-django-on-aws-setting-up-celery-and-sqs-95632a6e79cb">Part 5: Celery and SQS</a></li><li><a href="https://python.plainenglish.io/deploy-django-application-on-aws-with-terraform-connect-to-amazon-s3-307b1e60d188">Part 6: Connecting to Amazon S3</a></li></ul><p>In this part, we’ll make our Django web application scalable using <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-auto-scaling.html">ECS Autoscaling</a>.</p><p>Autoscaling is the ability to increase or decrease the number of running instances. It allows you to handle traffic spikes and save money for low intensive periods of time.</p><p>When you enable autoscaling for ECS service, AWS creates <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html">Cloudwatch alarms</a> to determine whether we need to add a new instance or remove a redundant one.</p><p>Let’s see how it works in practice.</p><h3>ECS Autoscaling configuration</h3><p>First, create a new autoscale.tf with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6850b514ad85022e3e5c7c52e342c3b/href">https://medium.com/media/e6850b514ad85022e3e5c7c52e342c3b/href</a></iframe><p>Here we defined:</p><ul><li><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/appautoscaling_target">AWS AppAutoscaling Target</a>. We want to scale the prod_backend_web service by instance count dimension from 1 to 5.</li><li><a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/appautoscaling_policy">AWS AppAutoscaling Policy</a>. We want to scale prod_backend_web up when the ECSServiceAverageCPUUtilization metric exceeds 80%.</li></ul><p>We are ready to apply changes, but first, let’s think about load balancer health checks.</p><h3>Load Balancer Health Checks</h3><p>Now we have a quire aggressive health checks. If the container fails to respond twice with a timeout of 2 seconds, Load Balancer considers this container unhealthy and removes them.</p><p>It could be an okay solution for the little amount of traffic. But if many requests reach the container and CPU usage goes up to 100%, the container will fail to respond to Health Checks. So, Load Balancer kills them, and we will face an even worse situation: there will be no containers to handle the traffic at all</p><p>The possible solution is to increase health checks timeout and unhealthy_threshold. Thus, there will be more possibility for overloaded containers to survive.</p><p>I think it’s not a perfect solution, but it will work for this test. If you know a more elegant way to keep overloaded containers running, feel free to leave a comment.</p><p>Go to the load_balancer.tf and increase unhealthy_threshold, timeout, and interval parameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c9ab5f558d47e24a7c8559d9a23580a/href">https://medium.com/media/3c9ab5f558d47e24a7c8559d9a23580a/href</a></iframe><p>Let’s apply our changes and check them at the AWS console.</p><h3>CloudWatch Alarms</h3><p>First, go to the <a href="https://console.aws.amazon.com/ecs/home">ECS console</a> and check the autoscaling policy for the prod_backend_web ECS Service. Select prod ECS cluster, select prod-backend-web service and click &quot;Update&quot;. Pass to the step &quot;Set Auto Scaling&quot; and click on the prod-backend-web-cpu autoscaling policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X4UqNGFMG2iLhDDV.png" /></figure><p>Here we see that autoscaling becomes effective when average CPU utilization reaches 80%. But what is the condition for scaling down? Let’s check CloudWatch alarms associated with this autoscaling policy.</p><p>Go to the <a href="https://console.aws.amazon.com/cloudwatch/home">CloudWatch console</a> and look at the alarms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uo4E8MCxOcm4LteW.png" /></figure><p>Here we see that we scale up when the average CPU load exceeds 80% during 3+ minutes. And, we scale down when the average CPU load goes less than 72% for 15 minutes.</p><p>Such specific numbers, but how can we adjust them to our case? For this, you need to create and use custom metrics for alarms with <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/appautoscaling_policy#customized_metric_specification">customized_metric_specification</a> param in aws_appautoscaling_policy.</p><p>Also, you can change AlarmHigh and AlarmLow metrics manually in the console. It&#39;s not a preferable way to create a repeatable setup, but it&#39;s okay for our test. So, I&#39;ll change the AlarmLow metric to 50% and 10 minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/0*JSX3y2Dj82xUiJx4.png" /></figure><h3>Stress Testing</h3><p>Let’s move to the tests. I’ll use <a href="https://httpd.apache.org/docs/2.4/programs/ab.html">ApacheBenchmark</a> for stress testing. This tool can send a lot of requests to our service, so the CPU load goes up.</p><p>First, ensure that now the web service has only one container running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LmZWN1RiRR0iLyYC.png" /></figure><p>Also, you need to increase the limit of open files with ulimit -n 10000.</p><p>Now we are ready to run the benchmark. We’ll use the health-check URL for this test:</p><pre>$ ab -n 100000 -c 1000 &lt;https://api.example53.xyz/health/&gt;</pre><p>Where -c 1000 concurrent number of requests, -n 100000 is the total number of requests.</p><p>Check the CloudWatch metrics and ECS Service for the next 10–15 minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AvVUz5U6yJAtql9Z.png" /></figure><p>First, you should see the CPU spike in the charts. After 3 minutes, ECS autoscale starts to spawn new instances.</p><p>Then, the average CPU drops below 80%. There were 3 ECS tasks at this moment of time.</p><p>After some time, CPU load exceeds 80% again, and ECS autoscale creates the 4th instance. You can see them on the ECS console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9KEEmFceSym2GXRi.png" /></figure><p>So, scale up works; let’s check scale down. Stop ApacheBenchmark and wait for 10–15 minutes to wait for scale down.</p><p>You’ll see how CPU load drops to zero and ECS scales down the web service to 1 instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iC5L0_6tw2f10jbv.png" /></figure><p>Recheck the ECS console to ensure that we have only one web task running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sh2Ri6cmbgfEYZDk.png" /></figure><p>So, scale down works too. Let’s commit and push our changes to the infrastructure repository.</p><h3>The end</h3><p>Congratulations! In this part, we added ECS autoscaling for the web service. We increase Health Check timeout and period to prevent killing overloaded containers. Then, we run a stress test and verify that number of instances increases when CPU load goes up and decreases when CPU load goes down.</p><p>You can find the source code of backend and infrastructure projects <a href="https://gitlab.com/django-aws/django-aws-backend">here</a> and <a href="https://gitlab.com/django-aws/django-aws-infrastructure">here</a>.</p><p>If you need technical consulting on your project, check out our <a href="https://daiquiri.team/services/technical-consulting?utm_medium=referral&amp;utm_source=medium_blog&amp;utm_campaign=django_aws_7">website</a> or connect with me directly on <a href="https://www.linkedin.com/in/yevhen-bondar/">LinkedIn</a>.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><strong><em>, </em></strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><strong><em>, and</em></strong><em> </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4ebd78dcec1" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/deploying-django-application-on-aws-with-terraform-ecs-autoscaling-f4ebd78dcec1">Deploying Django Application on AWS with Terraform. ECS Autoscaling</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Django Application on AWS with Terraform & Connect to Amazon S3]]></title>
            <link>https://python.plainenglish.io/deploy-django-application-on-aws-with-terraform-connect-to-amazon-s3-307b1e60d188?source=rss-aa0a9baa9910------2</link>
            <guid isPermaLink="false">https://medium.com/p/307b1e60d188</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Yevhen Bondar]]></dc:creator>
            <pubDate>Wed, 17 Aug 2022 09:17:54 GMT</pubDate>
            <atom:updated>2022-08-17T09:17:54.142Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RouY4c2JZDYRYszhvltIEw.png" /></figure><p>This is the sixth part of the “Deploying Django Application on AWS with Terraform” guide. You can check out the previous steps here:</p><ul><li><a href="https://medium.com/@eugen1j.bondar/deploying-django-application-on-aws-with-terraform-minimal-working-setup-d6075b3b8299">Part 1: Minimal Working Setup</a></li><li><a href="https://medium.com/@eugen1j.bondar/deploying-django-application-on-aws-with-terraform-connecting-postgresql-rds-bcd9c29d6276">Part 2: Connecting PostgreSQL RDS</a></li><li><a href="https://blog.devgenius.io/deploying-django-application-on-aws-with-terraform-gitlab-ci-cd-fbc2bbc0d286">Part 3: GitLab CI/CD</a></li><li><a href="https://blog.devgenius.io/deploying-django-application-on-aws-with-terraform-namecheap-domain-ssl-457779e3a20">Part 4: Namecheap Domain + SSL</a></li><li>Part 5: Celery and SQS</li></ul><p>In this step, we are going to:</p><ul><li>Create an <a href="https://aws.amazon.com/s3/">S3 bucket</a> for storing media files.</li><li>Add <a href="https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html">S3 storage</a> in the Django project.</li><li>Add image upload in the Django admin.</li><li>Add a <a href="https://www.terraform.io/language/settings/backends/s3">S3 Terraform backend</a>.</li></ul><h3>About S3</h3><p>Why do we actually need S3 storage?</p><p>Why do we need S3 storage? When a user uploads some file to the web server, Django, by default, saves this file in the filesystem. As far as we can have multiple containers for web ECS service, we can run into the situation when container web_1 creates the user file, and container web_2 tries to read them. Moreover, when ECS recreated container web_1, we will lose the user file.</p><p>So, now we have stateful behavior. To achieve a stateless behavior, we need to store user files in common global storage. S3 is the storage we are looking for.</p><p>In this case, container web_1 creates a new file in an S3 bucket, and container web_2 can read this file.</p><p>Here is an S3 description from AWS:</p><blockquote><em>Amazon Simple Storage Service (Amazon S3) is an object storage service offering industry-leading scalability, data availability, security, and performance. Customers of all sizes and industries can store and protect any amount of data for virtually any use case, such as data lakes, cloud-native applications, and mobile apps. With cost-effective storage classes and easy-to-use management features, you can optimize costs, organize data, and configure fine-tuned access controls to meet specific business, organizational, and compliance requirements.</em></blockquote><h3>File upload to local storage</h3><p>But first, let’s add a file upload in our Django application.</p><p>To work with S3, we need to install <a href="https://django-storages.readthedocs.io/en/latest/">django-storages</a> and <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/index.html">boto3</a> packages. And for handling images in Django, we need the <a href="https://pillow.readthedocs.io/en/stable/">Pillow</a> library. Add them to requirements.txt and run pip install -r requirements.txt.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c750c76c691ef72d302dfdaf08588c0a/href">https://medium.com/media/c750c76c691ef72d302dfdaf08588c0a/href</a></iframe><p>But for now, we’ll work with Django default <a href="https://docs.djangoproject.com/en/4.1/ref/files/storage/#the-filesystemstorage-class">FileSystemStorage</a>.</p><p>Let’s create a new Django application photos with a Photo model with image <a href="https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.ImageField">ImageField</a>.</p><p>Navigate to the django-aws-backend project and create a new Django application with python manage.py startapp photos.</p><p>Then add the photos application in settings.py at the bottom of INSTALLED_APPS and specify <a href="https://docs.djangoproject.com/en/4.0/ref/settings/#media-url">MEDIA_URL</a> and <a href="https://docs.djangoproject.com/en/4.0/ref/settings/#media-root">MEDIA_ROOT</a> settings:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33f1e06468864bb23d16fcb26a7c7f2b/href">https://medium.com/media/33f1e06468864bb23d16fcb26a7c7f2b/href</a></iframe><p>Now, we are ready to create a Photo model in photos/models.py:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0f89d10841a5d844e0ceb401c8f7979/href">https://medium.com/media/b0f89d10841a5d844e0ceb401c8f7979/href</a></iframe><p>To allow management of Photo objects in the admin panel, add PhotoAdmin class in photos/admin.py</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5868b6ff7af3819ee5a49f0546e69dcc/href">https://medium.com/media/5868b6ff7af3819ee5a49f0546e69dcc/href</a></iframe><p>Finally, to serve media files by the Django development server, add this code to the django_aws/urls.py:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e13e156114cb643696d3d186bf73a7a/href">https://medium.com/media/4e13e156114cb643696d3d186bf73a7a/href</a></iframe><p>All the necessary code is in place. So we can make and apply migrations.</p><pre>$ python manage.py makemigrations photos<br>Migrations for &#39;photos&#39;:<br>  photos/migrations/0001_initial.py<br>    - Create model Photo<br>$ python manage.py migrate<br>Operations to perform:<br>  Apply all migrations: admin, auth, contenttypes, photos, sessions<br>Running migrations:<br>  Applying photos.0001_initial... OK</pre><p>Now, let’s try to create a new Photo in Django admin. Run python manage.py runserver and go to the admin panel <a href="http://127.0.0.1:8000/admin/photos/photo/">http://127.0.0.1:8000/admin/photos/photo/</a>. Click &quot;Add Photo&quot;, enter a title, and pick any image from your filesystem. Then, click &quot;Save and continue editing&quot;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r1Sy0YRa_kndVCaD.png" /></figure><p>Django will save an image to the local filesystem. Verify that you can click on the “current image” and see it in the browser. You can also check it in the django-aws-backend/media/photos folder.</p><h3>Django S3 settings</h3><p>We’ve successfully uploaded an image to the local filesystem. I prefer to use FileSystemStorage for local development. It allows me to work and run tests without the internet connection.</p><p>But for the production environment, we need to provide S3 settings. So let’s add to settings.py the following settings:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/260391f18ea3ed86dbae4145a5e9b618/href">https://medium.com/media/260391f18ea3ed86dbae4145a5e9b618/href</a></iframe><p>We defined:</p><ul><li><a href="https://docs.djangoproject.com/en/4.0/ref/settings/#default-file-storage">DEFAULT_FILE_STORAGE</a>. We keep FileSystemStorage for local development and set <a href="https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings">S3Boto3Storage</a> for production.</li><li>AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY - AWS access key, as a string. We&#39;ll create a separate user and access key for accessing s3 storage.</li><li>AWS_STORAGE_BUCKET_NAME - the name of S3 bucket.</li><li>AWS_S3_REGION_NAME - AWS region. I&#39;ll use the same us-east-2 region; you can specify yours.</li><li>AWS_S3_ENDPOINT_URL - URL for connecting to S3.</li><li>AWS_S3_FILE_OVERWRITE - If the file with the specified name already exists, django-storages will append extra characters.</li></ul><p>We are done with the Django part. The application is ready to work with S3. Commit and push the changes, and ensure that CI/CD is passed successfully.</p><h3>Creating S3 bucket</h3><p>Move to the Terraform project. Let’s create an S3 bucket. First, we need to specify the bucket name in variables.tf. The name should be unique in your AWS region.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75b9e17fc0928ebb64ae94407ac3141e/href">https://medium.com/media/75b9e17fc0928ebb64ae94407ac3141e/href</a></iframe><p>Then, create a new s3.tf file in the django-aws-infrastructure project with the following content and run terraform apply:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b957936e58085ab771a1c305e319e23b/href">https://medium.com/media/b957936e58085ab771a1c305e319e23b/href</a></iframe><p>Here we created:</p><ul><li>A new S3 bucket. We allowed public access to all files in this bucket and specified <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">CORS</a> rules to allow the browser to load files for any origin (and for our domain as well).</li><li>A new <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html">IAM user</a> with the <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html">IAM policy</a> to connect to the S3 bucket.</li><li>An <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html">IAM Access Key</a> for the user to use in the Django application.</li></ul><p>Let’s check our bucket in <a href="https://s3.console.aws.amazon.com/s3/home">AWS S3 Console</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0lz0wxH47d2PGAeU.png" /></figure><p>Now, we are ready to pass S3 credentials to the ECS services. Add variables in ecs.tf:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c2dc9c1ab9f6046323e12116b886ce8/href">https://medium.com/media/2c2dc9c1ab9f6046323e12116b886ce8/href</a></iframe><p>Use these variables for defining environment variables in templates/backend_container.json.tpl and apply changes with terraform apply:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da9c3db54194d2442a085aa34037193f/href">https://medium.com/media/da9c3db54194d2442a085aa34037193f/href</a></iframe><p>Wait for the deployment new version of ECS services. Then, go to the admin panel of the deployed application and try to add a new photo. Fill the fields and click “Save and continue editing.” Then click the current image URL to ensure your photo is uploaded to S3 correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UkeQEUR_TF7SWW8Y.png" /></figure><p>Also, check your file in the S3 console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iJWe2G2gl9mU7DSq.png" /></figure><p>So, we successfully added file uploading to S3 for our Django application. Now the application is stateless so that we can scale without problems.</p><p>The last feature I want to add to our Terraform project is an <a href="https://www.terraform.io/language/settings/backends/s3">S3 backend</a>.</p><h3>Terraform S3 backend</h3><p>Why do we actually need an S3 backend for Terraform?</p><p>Now Terraform stores the state of our infrastructure locally in the terraform.tfstate file. So, you can apply changes from your local machine only and cannot collaborate with other developers. Also, if you decide to add CI/CD to the Terraform project, your CD runner will have no information about the current infrastructure state.</p><p>The solution to these problems is a remote backend. Terraform will store terraform.tfstate file in S3 bucket. So, you can apply changes from different environments, including CD runners.</p><p>So, let’s go to the AWS S3 Console and <a href="https://s3.console.aws.amazon.com/s3/bucket/create">create an S3 bucket</a> in your region. You can choose any name for your bucket, and I’ll go with terraform-427861343. Be sure to disable public access so that nobody can know your infrastructure state. Also, it&#39;s better to enable versioning on this bucket. It allows you to roll back to the previous version in case of some problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/0*AZpy5WB00R6zoXlV.png" /></figure><p>Now, we can specify the S3 backend in providers.tf:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcb1c3a88b05b7c661acc3f767f40986/href">https://medium.com/media/dcb1c3a88b05b7c661acc3f767f40986/href</a></iframe><p>and initialize the provider with terraform init.</p><p>Terraform will ask if you want to copy the existing state to the new backend. If you say no, Terraform will create an empty state in the S3 backend. We want to preserve the state of the infrastructure, so you need to respond yes.</p><pre>$ terraform init</pre><pre>Initializing the backend...<br>Do you want to copy existing state to the new backend?<br>  Pre-existing state was found while migrating the previous &quot;local&quot; backend to the<br>  newly configured &quot;s3&quot; backend. No existing state was found in the newly<br>  configured &quot;s3&quot; backend. Do you want to copy this state to the new &quot;s3&quot;<br>  backend? Enter &quot;yes&quot; to copy and &quot;no&quot; to start with an empty state.</pre><pre>  Enter a value: yes</pre><pre>Successfully configured the backend &quot;s3&quot;! Terraform will automatically<br>use this backend unless the backend configuration changes.<br>...</pre><p>So, let’s check that we’ve migrated successfully. Run terraform apply to verify that our infrastructure matches the configuration. You should see the message:</p><blockquote><em>Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.</em></blockquote><p>Also, check your S3 bucket. You should see a new terraform file here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GwKhF3ovN6CexO3d.png" /></figure><p>So, we successfully move our Terraform state to S3. Commit and push the changes in the Terraform project.</p><h3>The end</h3><p>Congratulations! In this part, we added image uploading to S3 for our Django application. Also, we moved Terraform backend to S3. If you want more insight into application state, resource usage, and changes, you can use <a href="https://registry.terraform.io/providers/spacelift-io/spacelift/latest/docs">Spacelift Terraform provider</a>. Check how Spacelift can improve your workflow <a href="https://spacelift.io/blog/how-specialized-solution-can-improve-your-iac">here</a>.</p><p>You can find the source code of backend and infrastructure projects <a href="https://gitlab.com/django-aws/django-aws-backend">here</a> and <a href="https://gitlab.com/django-aws/django-aws-infrastructure">here</a>.</p><p>If you need technical consulting on your project, check out our <a href="https://daiquiri.team/services/technical-consulting?utm_medium=referral&amp;utm_source=medium_blog&amp;utm_campaign=django_aws_6">website</a> or connect with me directly on <a href="https://www.linkedin.com/in/yevhen-bondar/">LinkedIn</a>.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=307b1e60d188" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/deploy-django-application-on-aws-with-terraform-connect-to-amazon-s3-307b1e60d188">Deploy Django Application on AWS with Terraform &amp; Connect to Amazon S3</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Django on AWS: Setting up Celery and SQS]]></title>
            <link>https://python.plainenglish.io/deploying-django-on-aws-setting-up-celery-and-sqs-95632a6e79cb?source=rss-aa0a9baa9910------2</link>
            <guid isPermaLink="false">https://medium.com/p/95632a6e79cb</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[sqs]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[celery]]></category>
            <dc:creator><![CDATA[Yevhen Bondar]]></dc:creator>
            <pubDate>Fri, 12 Aug 2022 12:17:37 GMT</pubDate>
            <atom:updated>2022-08-12T12:17:37.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UcioAz7eICsFwcYucaDv7g.png" /></figure><p>This is the fifth part of the “Deploying Django Application on AWS with Terraform” guide. You can check out the previous steps here:</p><ul><li><a href="https://medium.com/@eugen1j.bondar/deploying-django-application-on-aws-with-terraform-minimal-working-setup-d6075b3b8299">Part 1: Minimal Working Setup</a></li><li><a href="https://medium.com/@eugen1j.bondar/deploying-django-application-on-aws-with-terraform-connecting-postgresql-rds-bcd9c29d6276">Part 2: Connecting PostgreSQL RDS</a></li><li><a href="https://blog.devgenius.io/deploying-django-application-on-aws-with-terraform-gitlab-ci-cd-fbc2bbc0d286">Part 3: GitLab CI/CD</a></li><li><a href="https://blog.devgenius.io/deploying-django-application-on-aws-with-terraform-namecheap-domain-ssl-457779e3a20">Part 4: Namecheap Domain + SSL</a></li></ul><p>In this step, we are going to:</p><ul><li>Add a <a href="https://github.com/celery/celery">Celery</a> + SQS setup for local development.</li><li>Create a periodic task using <a href="https://docs.celeryq.dev/en/stable/userguide/periodic-tasks.html">Celery Beat</a>.</li><li>Add create an <a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html">SQS</a> instance on AWS.</li><li>Deploy <a href="https://docs.celeryq.dev/en/stable/userguide/workers.html">worker</a> and <a href="https://docs.celeryq.dev/en/stable/userguide/periodic-tasks.html">beat</a> <a href="https://aws.amazon.com/ecs/">ECS</a> services on AWS.</li></ul><h3>About Celery and SQS</h3><p>As docs says:</p><blockquote><em>Celery is a simple, flexible, and reliable distributed system to process vast amounts of messages, while providing operations with the tools required to maintain such a system. It’s a task queue with focus on real-time processing, while also supporting task scheduling.</em></blockquote><p>So, you can run your long-running, CPU-bound, IO-bound tasks in separate docker containers. Your web server can schedule some tasks, and Celery will pick and execute them.</p><p>Web server and Celery communicate via some backend. It could be <a href="https://redis.io/">Redis</a> or <a href="https://www.rabbitmq.com/">RabbitMQ</a>. But we use AWS as a cloud provider. So, we can use the <a href="https://docs.celeryq.dev/en/stable/getting-started/backends-and-brokers/index.html#sqs">SQS backend</a>. Celery docs says:</p><blockquote><em>If you already integrate tightly with AWS, and are familiar with SQS, it presents a great option as a broker. It is extremely scalable and completely managed, and manages task delegation similarly to RabbitMQ.</em></blockquote><p>You can check more info about SQS <a href="https://aws.amazon.com/sqs/">here</a>.</p><h3>Local development setup</h3><h4>Running SQS locally</h4><p>SQS is a managed solution by AWS. And we could create a separate SQS instance for development purposes. But I want to run all things locally to be able to work without the Internet connection. Also, it’s a good practice to run unit and integration tests without Internet access.</p><p>To run SQS locally, we will use <a href="https://hub.docker.com/r/softwaremill/elasticmq-native/">softwaremill/elasticmq-native</a> Docker image.</p><p>Go to the django-aws-backend folder and add a new service to docker-compose.yml in your Django project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b18fe10217a1c9a0159392645b07ec6/href">https://medium.com/media/8b18fe10217a1c9a0159392645b07ec6/href</a></iframe><p>Run docker-compose up -d to run the SQS container. Then check <a href="http://127.0.0.1:9325/">http://127.0.0.1:9325/</a> in your browser to see the SQS management panel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BHIi4vT5rn5ZjPgJ.png" /></figure><p>Also, check <a href="http://127.0.0.1:9324/">http://127.0.0.1:9324/</a> URL to ensure that SQS API is working. You will see an error XML output like this:</p><pre>&lt;ErrorResponse xmlns=&quot;&lt;http://queue.amazonaws.com/doc/2012-11-05/&gt;&quot;&gt;<br>      &lt;Error&gt;<br>        &lt;Type&gt;Sender&lt;/Type&gt;<br>        &lt;Code&gt;MissingAction&lt;/Code&gt;<br>        &lt;Message&gt;MissingAction; see the SQS docs.&lt;/Message&gt;<br>        &lt;Detail/&gt;<br>      &lt;/Error&gt;<br>      &lt;RequestId&gt;00000000-0000-0000-0000-000000000000&lt;/RequestId&gt;<br>    &lt;/ErrorResponse&gt;</pre><p>Now, we are ready to add Celery to our Django project.</p><h4>Adding Celery to Django project</h4><p>Let’s add the Celery package to requirements.txt and run pip install -r requirements.txt. Be sure you activated venv before.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cb2854bf4a292447114bb96b381f25d/href">https://medium.com/media/3cb2854bf4a292447114bb96b381f25d/href</a></iframe><p>Then, create a new file django_aws/celery.py with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6929696d98bfbdeb4e112e9b2098c003/href">https://medium.com/media/6929696d98bfbdeb4e112e9b2098c003/href</a></iframe><p>and add to the django_aws/settings.py these lines:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/545604e4a9665814e0597b2113712661/href">https://medium.com/media/545604e4a9665814e0597b2113712661/href</a></iframe><p>Here we initialized the Celery app in django_aws/celery.py. We will use this app to specify and schedule tasks for Celery. Also, we provided connection parameters in django_aws/settings.py. As default values, we set our local setup. For production, we can pass parameters via environment variables.</p><p>Now, we are ready to create and run our first task. Let’s create django_aws/tasks.py with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6cfe008fed7c1691e9552b30250b2ba/href">https://medium.com/media/c6cfe008fed7c1691e9552b30250b2ba/href</a></iframe><p>The web_task will run for 10 seconds and put messages in the log stream at the start and the end of execution.</p><p>Now, we need to add a way to add this task to the queue. Let’s create a django_aws/views.py with the following view:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9520b5399f470aa4bf3746613036d0d3/href">https://medium.com/media/9520b5399f470aa4bf3746613036d0d3/href</a></iframe><p>Add this view to urls.py:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae1eb11af2f812236070bb2a7ff32c52/href">https://medium.com/media/ae1eb11af2f812236070bb2a7ff32c52/href</a></iframe><p>Now, if we hit URL <a href="http://127.0.0.1:8000/create-task">http://127.0.0.1:8000/create-task</a>, the create_web_task view will add a new task to the local SQS. Start the local web server with python manage.py runserver, hit this URL several times, and look at the SQS admin page <a href="http://127.0.0.1:9325/">http://127.0.0.1:9325/</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C8fZSYV-t_wXlpzX.png" /></figure><p>So, we successfully add tasks to the queue. Now, let’s execute them with celery. Run celery -A django_aws worker --loglevel info to start the worker process. The worker will immediately pick tasks from the queue and execute them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kpvs582KCNVSqJ63.png" /></figure><p>Stop the celery process.</p><blockquote><em>If you run into the problem ImportError: The curl client requires the pycurl library, check out my post on StackOverflow</em></blockquote><p>Also, we need to add some libraries to Dockerfile for compiling the pycurl in the docker image. Replace Dockerfile with the next one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74a0e5a849647d488f9402cf24f0993a/href">https://medium.com/media/74a0e5a849647d488f9402cf24f0993a/href</a></iframe><h4>Adding Celery beat</h4><p>Now, let’s create a periodic task using <a href="https://docs.celeryq.dev/en/stable/userguide/periodic-tasks.html">Celery Beat</a>. We will add a simple task like create_web_task and schedule it for execution once a minute. For this, let&#39;s add beat_task to tasks.py:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df8e5e7663550685ecce0f35321fb032/href">https://medium.com/media/df8e5e7663550685ecce0f35321fb032/href</a></iframe><p>Then, add the <a href="https://docs.celeryq.dev/en/stable/userguide/configuration.html#beat-schedule">CELERY_BEAT_SCHEDULE</a> setting in settings.py:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/742a13bae13da2469ffbe799a0808aae/href">https://medium.com/media/742a13bae13da2469ffbe799a0808aae/href</a></iframe><p>and run the beat process celery -A django_aws beat --loglevel info. Every minute beat process adds a new task to SQS. Check <a href="http://127.0.0.1:9325/">http://127.0.0.1:9325/</a> to see them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*tNxkIpzRSMKY0I6X.png" /></figure><p>Wait for several tasks in queue, stop the beat process and run the worker again celery -A django_aws worker --loglevel info. The worker will process beat_task tasks, and you will see the logs:</p><pre>[2022-08-04 11:13:59,088: INFO/MainProcess] Task django_aws.tasks.beat_task[4189aa07-b75e-4743-94e0-2a0c3b84443a] received<br>[2022-08-04 11:13:59,089: INFO/MainProcess] Task django_aws.tasks.beat_task[0de67363-2e2a-421c-9630-1c6c7c685382] received<br>[2022-08-04 11:13:59,095: INFO/ForkPoolWorker-1] Starting beat task...<br>[2022-08-04 11:13:59,095: INFO/ForkPoolWorker-8] Starting beat task...<br>[2022-08-04 11:14:09,096: INFO/ForkPoolWorker-1] Done beat task.<br>[2022-08-04 11:14:09,096: INFO/ForkPoolWorker-8] Done beat task.<br>[2022-08-04 11:14:09,097: INFO/ForkPoolWorker-1] Task django_aws.tasks.beat_task[0de67363-2e2a-421c-9630-1c6c7c685382] succeeded in 10.002475121000316s: None<br>[2022-08-04 11:14:09,097: INFO/ForkPoolWorker-8] Task django_aws.tasks.beat_task[4189aa07-b75e-4743-94e0-2a0c3b84443a] succeeded in 10.002584206999018s: None</pre><p>So, we successfully run Celery worker and beat processes using local SQS. Let’s add the celerybeat-schedule file to .gitignore, commit and push our changes. Ensure that CI/CD passed successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-SeLL3hW2eatenJ_.png" /></figure><p>We are done with Django part, let’s move to the AWS.</p><h3>Deploying to AWS</h3><h4>Creating AWS SQS instance and user</h4><p>Move to the django-aws-infrastructure folder, create a sqs.tf file with the following content, and run terraform apply.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1cc55e0b4e446b633d15a4333b89baf/href">https://medium.com/media/f1cc55e0b4e446b633d15a4333b89baf/href</a></iframe><p>Here we’ve created a new <a href="https://aws.amazon.com/sqs/">SQS</a> instance, a new <a href="https://aws.amazon.com/iam/">IAM</a> user, granted access to this SQS instance to this user, and created an <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html">IAM Access Key</a> to give access to SQS from the Django application. Let’s look at the new instance in the AWS console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tcJ73v9UNjtZgXAl.png" /></figure><h4>Activating a region</h4><p>Now, let’s create an ECS for the Celery worker and beat.</p><p>First, let’s “activate” our region on AWS. For some reason, AWS doesn’t allow you to create more than 2 ECS containers in the region. You need to create an EC2 instance in this region to remove this limit. Let’s do it manually in <a href="https://us-east-2.console.aws.amazon.com/ec2/v2/home">EC2 Console</a>. Be sure that you use your AWS region.</p><ol><li>Click “Launch Instance”</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*olSeWLL7sOa1PSLP.png" /></figure><ol><li>Pick any name for your instance. I’ll go with Test Server</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CcACFUIs4JUp7NLP.png" /></figure><ol><li>Scroll down to the “Key pair” card and pick “Proceed without a key pair”. We won’t connect to this server, so we don’t need one. Then click “Launch Instance” to create a new instance in your region.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KjXWZogxjmZ0blrO.png" /></figure><p>AWS will soon create an instance. Go to the <a href="https://us-east-2.console.aws.amazon.com/ec2/v2/home?region=us-east-2#Instances:">Instances</a> tab in EC2 Console and verify that you have 1 “Running” instance.</p><p>After that, you can terminate the instance because we don’t need it. Pick the instance, click the “Instance state”, then “Terminate instance”, and confirm termination. AWS will permanently remove your EC2 instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xvsC4JWknZht8PCR.png" /></figure><p>So, now we can create more than two ECS containers. Let’s continue creating Celery ECS.</p><h4>Running a Celery via ECS</h4><p>Now, let’s define our Celery ECS service. First, add new variables in ecs.tf:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18d560481d93491d2a9eaa124a3b2285/href">https://medium.com/media/18d560481d93491d2a9eaa124a3b2285/href</a></iframe><p>and pass it to containers in backend_container.json.tpl:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13f3383a2a876f5846addfd933b93f6d/href">https://medium.com/media/13f3383a2a876f5846addfd933b93f6d/href</a></iframe><p>So, we passed SQS credentials to ECS services. Then, add the following content in ecs.tf and run terraform apply:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddcb880416ef2be2dcca27455a606d15/href">https://medium.com/media/ddcb880416ef2be2dcca27455a606d15/href</a></iframe><p>Here we created:</p><ul><li><a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html">Cloudwatch Logs streams</a> for worker and beat.</li><li>Worker <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html">ECS task definition</a> and <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html">ECS service</a>. We specified desired_count=2 to show how multiple workers can run for the same queue. In the future we will scale worker ECS depending on CPU load.</li><li>Beat ECS task definition and ECS service. Here we specified desired_count=1 because we don&#39;t want to schedule duplicates for periodic tasks.</li></ul><p>Let’s check our services in the <a href="https://us-east-2.console.aws.amazon.com/ecs/home">ECS console</a>.</p><p>Here are our worker and beat service:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xcfiws0xIKl53e1K.png" /></figure><p>Here are worker and beat tasks. You can see that ECS creates two tasks for the worker service and only one task for the beat service:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*627HzAqpEsfxLfga.png" /></figure><p>Here are worker logs. For now, we see only beat tasks in logs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dBsPbwD19x41jyOK.png" /></figure><p>Let’s add a new task from the web. Hit <a href="https://api.example53.xyz/create-task">https://api.example53.xyz/create-task</a> URL (replace a domain with your one). You should see a ‘Task added’ message in response. Then, return to ECS worker logs, and pick the ‘30s’ interval to see the most recent log events. You should see ‘Starting web task’ and ‘Done web task’ messages in the logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sL7YMoHhNl6mCpc9.png" /></figure><p>So, we successfully run ECS for worker and beat processes and ensure that both web and beat Celery tasks are executed successfully.</p><p>We are done with the infrastructure repo so that you can commit and push the changes.</p><h3>Updating deploy</h3><p>There is still one more task. To ensure that we will update our ECS services with every deployment, we need to modify our ./scripts/deploy.sh. Let&#39;s add the same instruction as for the web service:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b00e2ef5d24316c2f7eaa8d59f9118b0/href">https://medium.com/media/b00e2ef5d24316c2f7eaa8d59f9118b0/href</a></iframe><p>So, we will force a new deployment for the worker and beat services on ECS with every push.</p><p>Commit and push changes. Wait for CI/CD and check your services in ECS Console. After some time, new tasks will arise:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LJMtKTEQ9evvHjrU.png" /></figure><p>You can schedule more web tasks and see them in logs to ensure that things work as expected.</p><h3>The end</h3><p>Congratulations! We’ve successfully created an AWS SQS instance and added Celery worker + beat services to ECS. Our Django application can run long-living tasks in the background worker process.</p><p>You can find the source code of backend and infrastructure projects <a href="https://gitlab.com/django-aws/django-aws-backend">here</a> and <a href="https://gitlab.com/django-aws/django-aws-infrastructure">here</a>.</p><p>If you need technical consulting on your project, check out our <a href="https://daiquiri.team/services/technical-consulting?utm_medium=referral&amp;utm_source=medium_blog&amp;utm_campaign=django_aws_5">website</a> or connect with me directly on <a href="https://www.linkedin.com/in/yevhen-bondar/">LinkedIn</a>.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95632a6e79cb" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/deploying-django-on-aws-setting-up-celery-and-sqs-95632a6e79cb">Deploying Django on AWS: Setting up Celery and SQS</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Django Application on AWS with Terraform. Namecheap Domain + SSL]]></title>
            <link>https://blog.devgenius.io/deploying-django-application-on-aws-with-terraform-namecheap-domain-ssl-457779e3a20?source=rss-aa0a9baa9910------2</link>
            <guid isPermaLink="false">https://medium.com/p/457779e3a20</guid>
            <category><![CDATA[ssl]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[namecheap]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Yevhen Bondar]]></dc:creator>
            <pubDate>Tue, 09 Aug 2022 10:01:28 GMT</pubDate>
            <atom:updated>2022-08-09T10:01:28.738Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7QAh-dyg7CB_qlw5adR3XA.png" /></figure><p>In previous steps, we’ve <a href="https://www.notion.so/Deploying-Django-Application-on-AWS-with-Terraform-Minimal-Working-Setup-a48cfb630cf344a7a4f9b0f20f57a385">deployed Django with AWS ECS</a>, <a href="https://www.notion.so/Deploying-Django-Application-on-AWS-with-Terraform-Connecting-PostgreSQL-RDS-b8349e46f19548bb8ec41d8e8d28a5b9">connected it to the PostgreSQL RDS</a>, and <a href="https://www.notion.so/Deploying-Django-Application-on-AWS-with-Terraform-GitLab-CI-CD-900e9fadec1945c099f88504343d4e3f">set up GitLab CI/CD</a></p><p>In this step, we are going to:</p><ul><li>Connect <a href="https://www.namecheap.com/">Namecheap</a> domain to <a href="https://aws.amazon.com/route53/">Route53 DNS</a> zone.</li><li>Create an SSL certificate with <a href="https://aws.amazon.com/certificate-manager/">Certificate Manager</a>.</li><li>Reroute HTTP traffic to HTTPS and disable ALB host for Django application.</li><li>Add /health/ route for Health Checks.</li></ul><h3>Setting up Namecheap API</h3><p>I already have a domain name on <a href="https://www.namecheap.com/">Namecheap</a>. So I choose to connect the Namecheap domain to an AWS Route53 zone. But you can <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-register.html">register domain</a> with AWS Route53.</p><p>First, let’s enable API access for Namecheap. Look through <a href="https://www.namecheap.com/support/api/intro/">this</a> guide to receive APIKey and add your IP to the whitelist.</p><p>Second, add the <a href="https://registry.terraform.io/providers/namecheap/namecheap/latest/docs">Namecheap provider</a> to Terraform project. Add to the provider.tf file following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75e8899bf63edabbcf632d57868f930c/href">https://medium.com/media/75e8899bf63edabbcf632d57868f930c/href</a></iframe><p>In variables.tf add:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d13ff496fec0467d2a47abf3d4af6a2d/href">https://medium.com/media/d13ff496fec0467d2a47abf3d4af6a2d/href</a></iframe><p>Also add TF_VAR_namecheap_api_username and TF_VAR_namecheap_api_key variables to .env to provide values to the corresponding Terraform variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ca70e6cdc0e39ca24575a12f2132998/href">https://medium.com/media/4ca70e6cdc0e39ca24575a12f2132998/href</a></iframe><p>Import .env variables with export $(cat .env | xargs) and run terraform init to add a Namecheap provider to the project.</p><h3>Connecting Domain to AWS</h3><p>Now, let’s create a Route53 zone for the Namecheap domain and set up AWS nameservers. Thus, all DNS queries will be routed to the AWS Route53 nameservers, and we can manage DNS records from the AWS Route53 zone.</p><p>Add to the variables.tf following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8ae9b9375c4ac938c7aea328b90466b/href">https://medium.com/media/e8ae9b9375c4ac938c7aea328b90466b/href</a></iframe><p>Add a route53.tf file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b698a57daff235bbc39786209e97121/href">https://medium.com/media/3b698a57daff235bbc39786209e97121/href</a></iframe><p>Run terraform apply. Check nameservers on Namecheap:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/0*FsYwYqOUe5ysizKl.png" /><figcaption>NameCheap Name Servers for domain</figcaption></figure><h3>Creating SSL Certificate</h3><p>Now, let’s create an SSL certificate and set up DNS A record for api.example53.xyz domain.</p><p>Add to the route53.tf following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b741837a12db970aaf8a3ec6077b6cc/href">https://medium.com/media/7b741837a12db970aaf8a3ec6077b6cc/href</a></iframe><p>Here we are going to create a new <a href="https://aws.amazon.com/certificate-manager/">SSL certificate</a> for api.example53.xyz, validate the SSL certificate via <a href="https://docs.aws.amazon.com/acm/latest/userguide/dns-validation.html">DNS CNAME</a> record, and <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-to-elb-load-balancer.html">add DNS A record to Load Balancer</a>.</p><p>Apply changes with terraform apply and wait for certificate validation. Usually, it takes up to several minutes. But in some cases, it can take several hours. You can check more info <a href="https://aws.amazon.com/blogs/security/easier-certificate-validation-using-dns-with-aws-certificate-manager/">here</a>.</p><h3>Redirecting HTTP to HTTPS</h3><p>Now let’s use the issued SSL certificate to enable HTTPS. Replace the resource &quot;aws_lb_listener&quot; &quot;prod_http&quot; block in the load_balancer.tf with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73a952a03b9d1ad00779fe1bc4ad8b65/href">https://medium.com/media/73a952a03b9d1ad00779fe1bc4ad8b65/href</a></iframe><p>Here we redirect unsecured HTTP traffic to HTTPS and add a listener for the HTTPS port. Apply changes and check <a href="https://api.example53.xyz/">https://api.example53.xyz</a> URL. You should see Django starting page.</p><h3>Setting up the ALLOWED_HOSTS variable</h3><p>Now, let’s provide the <a href="https://docs.djangoproject.com/en/3.2/ref/settings/#std-setting-ALLOWED_HOSTS">ALLOWED_HOSTS</a> setting to the Django app. It&#39;s important to prevent <a href="https://docs.djangoproject.com/en/3.2/topics/security/#host-headers-virtual-hosting">HTTP Host header attacks</a>. So, Django Application should only accept our domain api.example53.xyz in the host header.</p><p>Now Django accepts any domain, for example, Load Balancer’s domain. Visit https://prod-1222631842.us-east-2.elb.amazonaws.com to check this fact. You can ignore the warning about an invalid SSL Certificate and see that Django responds to this host.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7NJDnuQeSM1b1Ln3.png" /></figure><p>Also, let’s disable a Debug mode and remove the SECRET_KEY value from the code to improve security. Add the TF_VAR_prod_backend_secret_key variable with a random generated value to the .env, run export $(cat .env | xargs), and specify this var in variables.tf:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb79f94ba4a13b8f5d5e0870f94f6bac/href">https://medium.com/media/bb79f94ba4a13b8f5d5e0870f94f6bac/href</a></iframe><p>Next, pass the domain name and SECRET_KEY in ecs.tf, set up SECRET_KEY, DEBUG, and ALLOWED_HOSTS variables in backend_container.json.tpl and apply changes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edf99d273ad2b1209e0321c79abbc1d1/href">https://medium.com/media/edf99d273ad2b1209e0321c79abbc1d1/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/134681d721bbac92b4e4ccb9511a1501/href">https://medium.com/media/134681d721bbac92b4e4ccb9511a1501/href</a></iframe><p>Now we have all necessary environment variables on ECS. Move to the Django app and change settings.py:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffafbeec446346318115ba4b5e7d04fb/href">https://medium.com/media/ffafbeec446346318115ba4b5e7d04fb/href</a></iframe><p>Here we receive SECRET_KEY, DEBUG, and ALLOWED_HOSTS variables from env variables. We provide default SECRET_KEY to allow running the application locally without specifying SECRET_KEY in the .env file.</p><h3>Health Check</h3><p>All user’s requests would have Host header api.example53.xyz. But, we also have <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/network/target-group-health-checks.html">health check requests</a> from a load balancer.</p><p>AWS load balancers can automatically check our container’s health. If the container responds correctly, the load balancer considers that target is <em>healthy</em>. Otherwise, the target will be marked as <em>unhealthy</em>. Load balancer routes traffic to <em>healthy</em> targets only. Thus, user requests wouldn’t hit <em>unhealthy</em> containers.</p><blockquote><em>For HTTP or HTTPS health check requests, the host header contains the IP address of the load balancer node and the listener port, not the IP address of the target and the health check port.</em></blockquote><p>We don’t know the Load Balancer IP address. Also, this IP can be changed after some time. Therefore, we cannot add the Load Balancer host to the ALLOWED_HOSTS.</p><p>The solution is to write a custom <a href="https://docs.djangoproject.com/en/3.2/topics/http/middleware/">middleware</a> that returns a successful response before the host checking in the SecurityMiddleware.</p><p>First, go to the infrastructure, change the health check URL in load_balancer.tf to /health/, and apply changes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93ae6d6c514ad0be73af6dc70ad64ec1/href">https://medium.com/media/93ae6d6c514ad0be73af6dc70ad64ec1/href</a></iframe><p>Return to the Django project and create django_aws/middleware.py:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/833cf11cbaead3ed16cd370ceb7389d6/href">https://medium.com/media/833cf11cbaead3ed16cd370ceb7389d6/href</a></iframe><p>Add this middleware to the settings.py before the SecurityMiddleware:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f61d321ea0a27b3e7d8221430b73ee3e/href">https://medium.com/media/f61d321ea0a27b3e7d8221430b73ee3e/href</a></iframe><p>Run python manage.py runserver and check 127.0.0.1:8000/health/ URL in your browser. You should see the text response Healthy!.</p><p>Commit and push changes, wait for the pipeline and check the Load Balancer domain again https://prod-57218461274.us-east-2.elb.amazonaws.com/. Now, we get a Bad Request error. Also, we didn&#39;t see a traceback or other debug information, so we can be sure that the debug mode is disabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/0*D06vKRYyhFSKi2BM.png" /></figure><p>Also, navigate to https://prod-57218461274.us-east-2.elb.amazonaws.com/health/ in your browser to check health_check_middleware. We get the Healthy! response. So, the Load Balancer will be able to check containers&#39; health without providing the correct Host header.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*6i12Y2anL-kkBSWx.png" /></figure><p>Congratulations! We’ve successfully set up a domain name, created health checks, disabled the debug mode, and removed SECRET_KEY value from the source code. Do not forget to push infrastructure code to GitLab.</p><p>You can find the source code of backend and infrastructure projects <a href="https://gitlab.com/daiquiri-team/templates/django-aws/djaws-infrastructure">here</a> and <a href="https://gitlab.com/daiquiri-team/templates/django-aws/djaws-backend">here</a>.</p><p>If you need technical consulting on your project, check out our <a href="https://daiquiri.team/services/technical-consulting?utm_medium=referral&amp;utm_source=medium_blog&amp;utm_campaign=django_aws_4">website</a> or connect with me directly on <a href="https://www.linkedin.com/in/yevhen-bondar/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=457779e3a20" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/deploying-django-application-on-aws-with-terraform-namecheap-domain-ssl-457779e3a20">Deploying Django Application on AWS with Terraform. Namecheap Domain + SSL</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Django Application on AWS with Terraform. GitLab CI/CD]]></title>
            <link>https://blog.devgenius.io/deploying-django-application-on-aws-with-terraform-gitlab-ci-cd-fbc2bbc0d286?source=rss-aa0a9baa9910------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbc2bbc0d286</guid>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Yevhen Bondar]]></dc:creator>
            <pubDate>Tue, 02 Aug 2022 16:25:04 GMT</pubDate>
            <atom:updated>2022-08-11T12:38:49.426Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eg5m3XHCMRhJwuKCdHjNbA.png" /></figure><p>In previous parts, we’ve <a href="https://medium.com/@eugen1j.bondar/deploying-django-application-on-aws-with-terraform-minimal-working-setup-d6075b3b8299">deployed the Django web application to ECS</a> and <a href="https://medium.com/@eugen1j.bondar/bcd9c29d6276">connected PostgreSQL</a> to it. But now, we have to deploy application changes manually. In this part, we are going to automate this process with the following steps:</p><ul><li>Create a GitLab group and projects for the <a href="https://gitlab.com/django-aws/django-aws-backend">backend</a> and the <a href="https://gitlab.com/django-aws/django-aws-infrastructure">infrastructure</a> repositories.</li><li>Add the test CI/CD stage to run tests.</li><li>Add the build CI/CD stage to build a docker image and push it to the ECR.</li><li>Add the deploy CI/CD stage to update the application on AWS.</li></ul><h3>Creating Projects</h3><p>Let’s start with creating a GitLab group and projects. Go to <a href="https://gitlab.com/">gitlab.com</a> and register an account.</p><p>Then <a href="https://gitlab.com/groups/new#create-group-pane">create</a> a <a href="https://docs.gitlab.com/ee/user/group/">GitLab group</a>. A group is like a folder for projects. You can configure shared settings like access policy and CI variables for them.</p><p>Create projects for <a href="https://gitlab.com/django-aws/django-aws-backend">Django</a> and <a href="https://gitlab.com/django-aws/django-aws-infrastructure">Terraform</a> in this group. Be sure to remove the “Initialize repository with a README” option to create a clean repository.</p><p>Also, add your ssh key to <a href="https://gitlab.com/-/profile/keys">SSH Keys</a> section. It allows you to access your projects via Git.</p><p>Now, let’s push both of our repositories to GitLab.</p><pre># Push backend<br>cd ../django-aws-backend<br>git remote add origin git@gitlab.com:django-aws/django-aws-backend<br>git push --set-upstream origin main</pre><pre># Push infrastructure<br>cd ../django-aws-infrastructure<br>git remote add origin git@gitlab.com:django-aws/django-aws-infrastructure<br>git push --set-upstream origin main</pre><p>Check your GitLab projects in a browser and verify that the push is successful.</p><h3>Stage: Test</h3><p>Now let’s add unit tests check to the Django project. Django’s unit tests use a Python standard library module <a href="https://docs.python.org/3/library/unittest.html#module-unittest">unittest</a>. See more info about testing a Django application <a href="https://docs.djangoproject.com/en/3.2/topics/testing/overview/">here</a>.</p><p>Go to the Django project, activate venv and start a PostgreSQL Docker container:</p><pre>$ cd ../django-aws-backend<br>$ . ./venv/bin/activate<br>$ docker-compose up -d</pre><p>Let’s create django_aws/tests.py and add a simple test to check DB connection:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c25ccd3424c717e515b98990b4d90d1b/href">https://medium.com/media/c25ccd3424c717e515b98990b4d90d1b/href</a></iframe><p>Run python manage.py test locally:</p><pre>$ python manage.py test<br>Creating test database for alias &#39;default&#39;...<br>System check identified no issues (0 silenced).<br>.<br>----------------------------------------------------------------------<br>Ran 1 test in 0.010s</pre><pre>OK<br>Destroying test database for alias &#39;default&#39;...</pre><p>Now, let’s add this check on GitLab’s side. Take a look <a href="https://docs.gitlab.com/ee/ci/quick_start/">here</a> if you have no idea what GitLab CI is. Generally, GitLab will run code specified in <a href="https://docs.gitlab.com/ee/ci/yaml/">.gitlab-ci.yml</a> on every push in the repository.</p><p>Create .gitlab-ci.yml file with following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb1791abbc9046ac634b0036a58de1d6/href">https://medium.com/media/fb1791abbc9046ac634b0036a58de1d6/href</a></iframe><p>Explanation:</p><ul><li>image: python:3.10. By default, GitLab runs CI/CD pipeline on shared runners hosted by GitLab using the <a href="https://docs.gitlab.com/runner/executors/docker.html">docker executor</a>. Here we specify docker image for the executor.</li><li>stages:. A pipeline can have several stages. Now we have only the test stage. In the future, we will have three stages: test, build, and deploy. GitLab will execute stages in the specified order.</li><li>services: postgres:14.2. GitLab will run PostgreSQL in a separate container during the test stage. So, our Django application will be able to run DB-related tests.</li><li>variables: POSTGRES_PASSWORD, POSTGRES_DB DATABASE_URL - environment variables for both Django and PostgreSQL docker containers.</li><li>cache: key:. Here we cache the result of the pip install command to speed up pipeline executions. If the key files: requirements.txt hasn&#39;t changed since the last run GitLab will download the cache for venv and .cache/pip directories.</li><li>script: ... is commands to execute. GitLab executes commands one by one. If some command returns a non-zero exit code, GitLab will interrupt pipeline execution and mark it <em>Failed</em>. If all commands have been executed successfully, GitLab marks the current stage as <em>Successful</em> and goes to the next stage.</li></ul><p>Now, push the changes and take a look at <a href="https://gitlab.com/django-aws/django-aws-backend/-/pipelines">CI/CD</a> tab of your GitLab Django project.</p><pre>$ git add .<br>$ git commit -m &quot;add gitlab-ci; add test&quot;<br>$ git push</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KsCUODONBAIn4_DF.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e2d27rVUJE8FoKUz.png" /></figure><h3>Stage: Build</h3><p>Tests are passed, so we move on to the build stage. At this stage, we need to connect our GitLab account with our AWS account to grant GitLab access to the ECR repository. For this, we&#39;ll create a separate AWS user gitlab with limited permissions. Let&#39;s go to the AWS IAM console and create a <a href="https://us-east-1.console.aws.amazon.com/iam/home#/users$new?step=details">new user</a>.</p><blockquote><em>You can find instructions on how to create an AWS user </em><a href="https://medium.com/@eugen1j.bondar/deploying-django-application-on-aws-with-terraform-minimal-working-setup-d6075b3b8299#0f15"><em>here</em></a></blockquote><p>Add to this user AmazonEC2ContainerRegistryPowerUser policy to enable read and write permission to any ECR repository on this account. Proceed to the final step of user creation and save ACCESS_KEY_ID and SECRET_ACCESS_KEY.</p><p>Now go to the GitLab group settings and add AWS_ACCOUNT_ID, AWS_SECRET_ACCESS_KEY, AWS_ACCESS_KEY_ID, and AWS_DEFAULT_REGION variables. GitLab runner will use these credentials for AWS CLI calls.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FrUv3P8NRAx4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DrUv3P8NRAx4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FrUv3P8NRAx4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7b04fe4fca1613cd47a7682ca3c424e/href">https://medium.com/media/a7b04fe4fca1613cd47a7682ca3c424e/href</a></iframe><p>Make sure to mask sensitive variables AWS_ACCOUNT_ID, AWS_SECRET_ACCESS_KEY, and AWS_ACCESS_KEY_ID to hide their values in GitLab logs. Take a look at the <a href="https://docs.gitlab.com/ee/ci/cloud_deployment/index.html#aws">AWS deployment</a> documentation page for more information.</p><p>Then add to the .gitlab-ci.yml build block:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e0aeca925f9d472cf812fd09531f9d8/href">https://medium.com/media/2e0aeca925f9d472cf812fd09531f9d8/href</a></iframe><p>Explanation:</p><ul><li>image: registry.gitlab.com/gitlab-org/cloud-deploy/aws-base:latest. This image allows using AWS CLI commands during CI/CD.</li><li>services: docker:20.10-dind. We use <a href="https://docs.gitlab.com/ee/ci/docker/using_docker_build.html#use-docker-in-docker">docker-in-docker</a> to build the docker image inside the <a href="https://docs.gitlab.com/runner/executors/docker.html">docker executor</a>. Docker starts as a separate service, so we can access the docker daemon from the GitLab job.</li><li>variables: DOCKER_HOST, DOCKER_TLS_CERTDIR. Specify the path to the docker-in-docker daemon and disable TLS connection.</li><li>AWS_REGISTRY_URL. Construct the ECR URL from the project name. Ensure that the names of the ECR repo and Gitlab project are the same.</li><li>before_script: aws ecr get-login-password. Log in to ECR.</li><li>docker pull $AWS_REGISTRY_URL || true. Pull actual image to use it as cache</li><li>docker push $AWS_REGISTRY_URL. Upload image to ECR.</li><li>only: main. We&#39;ll build a docker image for main branch only.</li></ul><p>Commit your changes and check a CI/CD pipeline:</p><pre>$ git add .<br>$ git commit -m &quot;add build stage&quot;<br>$ git push</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*npezz-RBXZI5VOLd.png" /></figure><h3>Stage: Deploy</h3><p>Build stage passed, now we’ll deploy container from ECR to ECS.</p><p>But let’s start with running migrations. We want to run migrations as separate ECS task to avoid any side effects on web application. Go to the infrastructure project and make following changes in ecs.tf and apply changes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/128aae6236226ba0135faee73c722415/href">https://medium.com/media/128aae6236226ba0135faee73c722415/href</a></iframe><p>Here we’ve moved the same variables for migration and web containers in container_vars. Then we&#39;ve created a separate task definition and log stream for the migration container. Now we can the start task with a specified task definition to apply migrations for every release.</p><p>Now let’s create a deployment script. Return the Django project and create scripts/deploy.sh file</p><pre>cd ../django-aws-backend<br>mkdir scripts<br>touch scripts/deploy.sh<br>chmod 777 scripts/deploy.sh</pre><p>with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89bfc54932881bfbfa49a668de73dfd4/href">https://medium.com/media/89bfc54932881bfbfa49a668de73dfd4/href</a></iframe><p>You can check the docs for <a href="https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/run-task.html">run-task</a>, <a href="https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/wait/tasks-stopped.html">wait tasks-stopped</a>, and <a href="https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/update-service.html">update-service</a> commands.</p><p>Run this script locally to check it:</p><pre>$ ./scripts/deploy.sh<br>Collecting data...<br>Running migration task...<br>Task arn:aws:ecs:us-east-2:947134793474:task/prod/dcc06d7ec1ac4bb69bba445565eddf8b running...<br>Updating web...<br>&quot;prod-backend-web&quot;<br>Done!</pre><p>We’ve successfully run this script by the admin user. GitLab CI/CD will use the gitlab user, so we need to grant all required permissions.</p><p>Let’s create a new policy gitlab-deploy-ecs, and add it to the gitlab user. Go to the <a href="https://us-east-1.console.aws.amazon.com/iam/home">IAM Console</a>, select the &quot;Users&quot; tab and click on the gitlab user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3j8hkIFSjWK_PWGL.png" /></figure><p>Next, click on “Add inline policy” and add the JSON policy definition. You need to use your AWS_ACCOUNT_ID instead of 947134793474 number.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa6f4a5ef0be4f5a8bae63cd60636f9f/href">https://medium.com/media/fa6f4a5ef0be4f5a8bae63cd60636f9f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/0*8zJloHL_CC_MWj48.png" /></figure><p>Explaining policies:</p><ul><li>ec2:DescribeSubnets, ec2:DescribeSecurityGroups — for &quot;Collecting data...&quot; stage.</li><li>ecs:RunTask, iam:PassRole — for running a migration ECS task.</li><li>ecs:DescribeTasks — for waiting a migration ECS task ends.</li><li>ecs:UpdateService — for updating the ECS Django web application.</li></ul><p>Click “Review Policy”, name the policy gitlab-ecs-deploy and click &quot;Create Policy&quot;. Now, the gitlab user will be able to execute the deploy.sh script.</p><p>Add deploy stage to .gitlab-ci.yml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/397bbfee3c979b773fc2a3df2c172243/href">https://medium.com/media/397bbfee3c979b773fc2a3df2c172243/href</a></iframe><p>At the deploy stage, we simply run deploy.sh script. We use the aws-base image to have access to AWS CLI commands.</p><p>Finally, let’s add some changes to Django to see that our application will be updated automatically. Let’s change the Django Admin header text. Add this line to django_aws/urls.py:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5895fa0762bfdf7e9aa5074ac145ba61/href">https://medium.com/media/5895fa0762bfdf7e9aa5074ac145ba61/href</a></iframe><p>Now commit your changes and see how’s your pipeline going.</p><pre>$ git add .<br>$ git commit -m &quot;add deploy stage&quot;<br>$ git push</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H5mLyXSK90CLZ_JX.png" /></figure><p>Check your admin page prod-57218461274.us-east-2.elb.amazonaws.com/admin and see a new title. It can take some time to update the ECS service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/0*9INsADyFWPDaD9ie.png" /></figure><p>Also, do not forget to push infrastructure code to GitLab.</p><p>Congratulations! We’ve successfully set up CI/CD with GitLab for our web Django web application. Now we can commit our code to the main branch, and GitLab CI/CD will automatically test, build and deploy it on the AWS.</p><p>But the prod-57218461274.us-east-2.elb.amazonaws.com domain looks not user-friendly :) Also, we need to secure the connection between a user and the Django application with an SSL certificate. In the next part, we&#39;ll connect the Namecheap domain to AWS and set up an SSL certificate for them.</p><p>You can find the source code of backend and infrastructure projects <a href="https://gitlab.com/django-aws/django-aws-backend">here</a> and <a href="https://gitlab.com/django-aws/django-aws-infrastructure">here</a>.</p><p>If you need technical consulting on your project, check out our <a href="https://daiquiri.team/services/technical-consulting?utm_medium=referral&amp;utm_source=medium_blog&amp;utm_campaign=django_aws_3">website</a> or connect with me directly on <a href="https://www.linkedin.com/in/yevhen-bondar/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbc2bbc0d286" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/deploying-django-application-on-aws-with-terraform-gitlab-ci-cd-fbc2bbc0d286">Deploying Django Application on AWS with Terraform. GitLab CI/CD</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Django Application on AWS with Terraform. Connecting PostgreSQL RDS]]></title>
            <link>https://medium.com/@eugen1j.bondar/deploying-django-application-on-aws-with-terraform-connecting-postgresql-rds-bcd9c29d6276?source=rss-aa0a9baa9910------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcd9c29d6276</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[rds]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Yevhen Bondar]]></dc:creator>
            <pubDate>Fri, 29 Jul 2022 07:34:43 GMT</pubDate>
            <atom:updated>2022-08-11T12:36:47.979Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6nhBc45GXNWl4Rpjr6qEWA.png" /></figure><p>In the previous <a href="https://medium.com/@eugen1j.bondar/deploying-django-application-on-aws-with-terraform-minimal-working-setup-d6075b3b8299">part of this guide</a>, we deployed the Django web application on <a href="https://aws.amazon.com/ecs/">AWS ECS</a>.</p><p>In this part, we’ll create a <a href="https://aws.amazon.com/rds/postgresql/">PostgreSQL RDS</a> instance on AWS, connect it to the Django ECS task and enable access to <a href="https://docs.djangoproject.com/en/3.2/ref/contrib/admin/">Django Admin</a>. We choose PostgreSQL because it supports complex SQL queries, <a href="https://www.postgresql.org/docs/current/mvcc.html">MVCC</a>, good performance for concurrent queries, and has a large community. As AWS says:</p><blockquote><em>PostgreSQL has become the preferred open source relational database for many enterprise developers and start-ups, powering leading business and mobile applications. Amazon RDS makes it easy to set up, operate, and scale PostgreSQL deployments in the cloud.</em></blockquote><h3>Add PostgreSQL to Django project</h3><p>Go to the django-aws-backend folder and activate virtual environment: cd ../django-aws-backend &amp;&amp; . ./venv/bin/activate.</p><p>First, let’s set up PostgreSQL via Docker for local development. Create docker-compose.yml with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e44a5b6ae51fe981dc2b4f212f04945/href">https://medium.com/media/4e44a5b6ae51fe981dc2b4f212f04945/href</a></iframe><p>Then run docker-compose up -d to start a container. Now, let&#39;s connect Django to PostgreSQL.</p><blockquote><em>We use a non-standard 5433 port to avoid potential conflict with your local PostgreSQL</em></blockquote><p>Next, we need to add pip packages: <a href="https://pypi.org/project/psycopg2-binary/">psycopg2-binary</a> for working with PostgreSQL and <a href="https://django-environ.readthedocs.io/en/latest/">django-environ</a> to retrieve PostgreSQL connection string from environment. Also, we’ll add the <a href="http://whitenoise.evans.io/en/stable/">WhiteNoise</a> package to serve static files for Django Admin.</p><p>Add to the requirements.txt file these packages and run pip install -r requirements.txt:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5b9a4e0d399bcc9f9fd419620e91800/href">https://medium.com/media/b5b9a4e0d399bcc9f9fd419620e91800/href</a></iframe><p>Now, change settings.py. First, let&#39;s load env variables. We try to read the .env file in the project root if it exists.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8268c4367ec19425cd736fb290316fbc/href">https://medium.com/media/8268c4367ec19425cd736fb290316fbc/href</a></iframe><p>Now we can use environment variables in settings.py. Let&#39;s provide DATABASES from env:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba62f9cc7973374e6de7934ea3253704/href">https://medium.com/media/ba62f9cc7973374e6de7934ea3253704/href</a></iframe><p>We’ve set a default value for the DATABASE_URL to allow running the Django project locally without specifying this variable in the .env file.</p><p>Third, add the WhiteNoiseMiddleware to serve static files and specify the STATIC_ROOT variable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53603d59c5161ed4750db04a36e2f566/href">https://medium.com/media/53603d59c5161ed4750db04a36e2f566/href</a></iframe><p>Also, add the RUN ./manage.py collectstatic --noinput line to the bottom of Dockerfile to collect static files in the static folder.</p><p>Apply migrations, create a superuser and start a web server:</p><pre>(venv) $ python manage.py migrate<br>Operations to perform:<br>  Apply all migrations: admin, auth, contenttypes, sessions<br>...<br>(venv) $ python manage.py createsuperuser<br>Username: admin<br>Email address:<br>Password:<br>Password (again):<br>Superuser created<br>(venv) $ python manage.py runserver<br>...<br>Starting development server at &lt;http://127.0.0.1:8000/&gt;</pre><p>Go to <a href="http://127.0.0.1:8000/admin/">http://127.0.0.1:8000/admin/</a> and sign in with your user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gPQKY9S9nc5Ri3m5.png" /></figure><p>Finally, let’s commit changes, build and push the docker image.</p><pre>$ git add .<br>$ git commit -m &quot;add postgresql, environ and static files serving&quot;<br>$ docker build . -t 947134793474.dkr.ecr.us-east-2.amazonaws.com/django-aws-backend:latest<br>$ docker push 947134793474.dkr.ecr.us-east-2.amazonaws.com/django-aws-backend:latest</pre><p>We are done with the Django part. Next, we create a PostgreSQL instance on AWS and connect it to the ECS task.</p><h3>Creating RDS</h3><p>AWS provides the <a href="https://aws.amazon.com/rds/postgresql/">Relational Database Service</a> to run a <a href="https://www.postgresql.org/">PostgreSQL</a>. Now, we’ll describe the RDS setup with Terraform. Go to the Terraform folder ../django-aws-infrastructure and add a rds.tf file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fbcd28e80956cf41b77a57147fe6491/href">https://medium.com/media/2fbcd28e80956cf41b77a57147fe6491/href</a></iframe><p>Here we create an RDS instance, a DB subnet group, and a Security Group to allow incoming traffic from ECS 5432 port only. We’ll specify db_name, username, password, and instance_class in the variables.tf:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/848c08134fb6061313a00375c8a10309/href">https://medium.com/media/848c08134fb6061313a00375c8a10309/href</a></iframe><p>Notice that we haven’t provided a default value for the prod_rds_password variable to prevent committing the database password to the repository. Terraform will ask you for a variable value if you try to apply these changes.</p><pre>$ terraform apply<br>var.prod_rds_password<br>  postgres password for production DB</pre><pre>  Enter a value:</pre><p>It’s not convenient and error-prone to type a password every time. Gladly, Terraform can read variable values from the environment. Create .env file with TF_VAR_prod_rds_password=YOUR_PASSWORD variable. Interrupt password prompting, run export $(cat .env | xargs) to load .env variable, and rerun terraform apply. Now Terraform picks the password from the .env file and creates an RDS PostgreSQL instance. Check it in the <a href="https://console.aws.amazon.com/rds#databases:">AWS RDS console</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v7witzUv5fvWmxbt.png" /></figure><h3>Connecting to ECS</h3><p>Let’s connect the RDS instance to ECS tasks.</p><p>Add to backend_container.json.tpl environment var DATABASE_URL</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b262ab89764fb247556019009f094785/href">https://medium.com/media/b262ab89764fb247556019009f094785/href</a></iframe><p>Add RDS variables to the prod_backend_web task definition in the ecs.tf file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a76361372f3e3f0360b45df02a01d137/href">https://medium.com/media/a76361372f3e3f0360b45df02a01d137/href</a></iframe><p>Let’s apply changes and update the ECS service with the new task definition. Run terraform apply, stop current task via web console and wait for the new task to arise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HfnwsMwrfdyzq6Au.png" /></figure><p>Now, go to the admin URL on the load balancer hostname and try to log in with random credentials. You should get the relation &quot;auth_user&quot; does not exist error. This error means that the Django application successfully connected to PostgreSQL, but no migrations was run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/0*f1Xb0J5br4BPM91L.png" /></figure><h3>Running migrations</h3><p>Now, we need to run migrations and create a superuser. But how can we do it? Our infrastructure has no EC2 instances to connect via SSH and run this command. The solution is <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-exec.html">ECS Exec</a>.</p><blockquote><em>With Amazon ECS Exec, you can directly interact with containers without needing to first interact with the host container operating system, open inbound ports, or manage SSH keys.</em></blockquote><p>First, we need to install the Session Manager plugin. For macOS, you can use brew install session-manager-plugin. For other platforms, check this <a href="https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html">link</a>.</p><p>Next, we need to provide an IAM policy to the prod_backend_task role and enable execute_command for the ECS service. Add this code to the ecs.tf and apply changes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/163c6997c936a9ca007bda09b5c5aa3d/href">https://medium.com/media/163c6997c936a9ca007bda09b5c5aa3d/href</a></iframe><p>Stop the old ECS task in web console and wait for the new task.</p><p>Then let’s retrieve the new task_id via CLI and run aws esc execute-command. Create a new file touch backend_web_shell.sh &amp;&amp; chmod 777 backend_web_shell.sh with the content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f084db6cedbe764f8fcf30845d5e8aa2/href">https://medium.com/media/f084db6cedbe764f8fcf30845d5e8aa2/href</a></iframe><p>Run ./backend_web_shell.sh to shell into task. If you have some troubles, please check <a href="https://github.com/aws-containers/amazon-ecs-exec-checker">Amazon ECS Exec Checker</a>. This script checks that your CLI environment and ECS cluster/task are ready for ECS Exec.</p><p>Run migrations and create a superuser from the task’s console:</p><pre>$ ./manage.py migrate<br>$ ./manage.py createsuperuser<br>Username: admin<br>Email address:<br>Password:<br>Password (again):<br>Superuser created</pre><p>After this, check your deployment admin URL and try to sign in with provided credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*03G5fxxcjDruwXUh.png" /></figure><p>Congratulations! We’ve successfully connected PostgreSQL to the ECS service. Now you can commit changes in the Terraform project and move to the next part.</p><p>In the next part, we’ll set up <a href="https://docs.gitlab.com/ee/ci/introduction/index.html#continuous-delivery">CI/CD</a> with GitLab.</p><p>You can find the source code of backend and infrastructure projects <a href="https://gitlab.com/django-aws/django-aws-backend">here</a> and <a href="https://gitlab.com/django-aws/django-aws-infrastructure">here</a>.</p><p>If you need technical consulting on your project, check out our <a href="https://daiquiri.team/services/technical-consulting?utm_medium=referral&amp;utm_source=medium_blog&amp;utm_campaign=django_aws_2">website</a> or connect with me directly on <a href="https://www.linkedin.com/in/yevhen-bondar/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcd9c29d6276" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>