<?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[Trinomio - Medium]]></title>
        <description><![CDATA[Software Factory - Medium]]></description>
        <link>https://medium.com/trinomio?source=rss----beb65fed982d---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Trinomio - Medium</title>
            <link>https://medium.com/trinomio?source=rss----beb65fed982d---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:17:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/trinomio" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[PGP Encryption: Securely Sharing Sensitive Company Data]]></title>
            <link>https://medium.com/trinomio/pgp-encryption-securely-sharing-sensitive-company-data-e28cb4dd8352?source=rss----beb65fed982d---4</link>
            <guid isPermaLink="false">https://medium.com/p/e28cb4dd8352</guid>
            <category><![CDATA[gpg-key]]></category>
            <category><![CDATA[gnupg]]></category>
            <category><![CDATA[secret-sharing]]></category>
            <dc:creator><![CDATA[Federico Mieres]]></dc:creator>
            <pubDate>Wed, 25 Jun 2025 01:04:11 GMT</pubDate>
            <atom:updated>2025-06-25T16:01:01.863Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LR92KTViQpEH4BraFdDWoA.png" /><figcaption>illustrative image generated by Gemini</figcaption></figure><p>Have you ever been in a situation where you needed to share an API client secret, a database password, or another critical environment variable with a coworker? And did you, perhaps, instinctively copy-paste it into a chat message, a shared document, or even an email? If so, you’re not alone — it’s a common practice in many development teams. But here’s the uncomfortable truth: <strong>that’s not secure at all.</strong> These seemingly convenient methods expose your most sensitive data to unnecessary risks, making it vulnerable to interception, unauthorized access, or accidental logging.</p><p>But don’t worry, we bring you a solution! This article will introduce you to <strong>OpenPGP</strong>, often simply known as PGP (Pretty Good Privacy), a robust and widely trusted standard for data encryption and digital signatures. We’ll explore how this powerful tool can become your go-to solution for securely exchanging environment variables and other confidential work-related data, significantly improving your team’s security posture.</p><p>We’ll be using my terminal and also a docker container to simulate a coworker’s environment. We’ll exchange keys, sign them and then start sharing files. Hopefully, you’ll start doing the same after this tutorial.</p><p>Jorge Trinomio will be our helper today, so let’s start with a docker image for him in order to simulate a coworker’s environment:</p><pre>docker run --rm -it alpine:latest sh<br>&gt; mkdir app<br>&gt; cd app<br>&gt; apk add --no-cache gnupg</pre><p>Now Jorge has gpg installed in his machine. Let’s generate a personal key for work:</p><pre>&gt; gpg --full-generate-key </pre><p>Jorge will pick the following option RSA and RSA and no expiration:</p><pre>Real name: Jorge Trinomio<br>Email address: jorge.trinomio@trinom.io<br>Comment: Clave para sharear envs en el trabajo<br>You selected this USER-ID:<br>    &quot;Jorge Trinomio (Clave para sharear envs en el trabajo) &lt;jorge.trinomio@trinom.io&gt;&quot;</pre><p>And of course, set up his passphrase but we won’t share it here.</p><p>Now it’s time to share keys, so ill be providing Jorge my personal work public key.</p><pre> gpg --armor --export federico.mieres@trinom.io</pre><p>Since the export returns bytes , the armor option transforms it in a easier to share format such as:</p><pre>-----BEGIN PGP PUBLIC KEY BLOCK-----<br><br>mQGNBGhbMZUBDADNIYLxDP0zzJqMvdXfmfCcSnF0SE5J+2A/TYxCfORW0gFNS9zi<br>baprKB7khmt7618b/dWq2YYO4NGu4Ztn1v959l7AB8GiSMhMRIWiV8SueoaSh3gR<br>xt+sseM9Tkt4CqSrSZtr8tyGiGIf6Vp80K+n+0U66s7JPxbjSNIXVy+h38+jeqk3<br>jSBh6Ay764v8c1g4WhapHm2lrUkKZhXjYMItXCmNePmRc4IZDAy2voBszzasm58F<br>iHSPnFhZFSVtSg==...........................................=9vW7<br>-----END PGP PUBLIC KEY BLOCK-----</pre><p>So, ill share this content with Jorge via company’s chat. Him or anyone who wants to share anything encrypted with me will use it so this doesn’t need to be a hidden message.</p><p>Jorge will paste it in a file called fede.gpg.key and then will use add it to his keyring.</p><blockquote>A <strong>keyring</strong> is your personal, secure database where GnuPG stores all the PGP keys (both public and private) you use for encrypting and decrypting data.</blockquote><pre>&gt; gpg --import fede.gpg.key<br>gpg: key 975CE42E4E1B1877: public key &quot;Federico Mieres (my key to share stuff at work) &lt;federico.mieres@trinom.io&gt;&quot; imported<br>gpg: Total number processed: 1<br>gpg:               imported: 1</pre><p>That should be enough but… what if a man in the middle replace my public key with theirs ? That’s why we check fingerprints as a second validation. This only needs to be done once and we should do it verbally or in a quick call?</p><pre>&gt; gpg --fingerprint federico.mieres@trinom.io<br>gpg: checking the trustdb<br>gpg: marginals needed: 3  completes needed: 1  trust model: pgp<br>gpg: depth: 0  valid:   1  signed:   0  trust: 0-, 0q, 0n, 0m, 0f, 1u<br>pub   rsa3072 2025-06-24 [SC]<br>      D7C8 F1E0 B6A3 9C2D E5F4 0B1A C9D2 3F4E 5A6B 7C8D<br>uid           [ unknown] Federico Mieres (my key to share stuff at work) &lt;federico.mieres@trinom.io&gt;<br>sub   rsa3072 2025-06-24 [E]</pre><blockquote>My fingerprint D7C8 F1E0 B6A3 9C2D E5F4 0B1A C9D2 3F4E 5A6B 7C8Dand pay attention to the unknown tag at my key in Jorge’s keyring.<br>This [ unknown] tag simply means Jorge&#39;s GnuPG doesn&#39;t yet have an established trust relationship with my key, which is what verifying the fingerprint and then signing will address.</blockquote><p>Jorge: hey fede, is your fingerprint ……<br>Fede: yes! exactly!</p><p>So as an additional, optional and recommended step, Jorge now can sign my key in order to set it as trustworthy.</p><pre>&gt; gpg --sign-key federico.mieres@trinom.io<br><br>pub  rsa3072/975CE42E4E1B1877<br>     created: 2025-06-24  expires: never       usage: SC  <br>     trust: unknown       validity: unknown<br>sub  rsa3072/9B9D43B7402FC32B<br>     created: 2025-06-24  expires: never       usage: E   <br>[ unknown] (1). Federico Mieres (my key to share stuff at work) &lt;federico.mieres@trinom.io&gt;<br><br><br>pub  rsa3072/975CE42E4E1B1877<br>     created: 2025-06-24  expires: never       usage: SC  <br>     trust: unknown       validity: unknown<br> Primary key fingerprint: D7C8 F1E0 B6A3 9C2D E5F4 0B1A C9D2 3F4E 5A6B 7C8D<br><br>     Federico Mieres (my key to share stuff at work) &lt;federico.mieres@trinom.io&gt;<br><br>Are you sure that you want to sign this key with your<br>key &quot;Jorge Trinomio (Clave para sharear envs en el trabajo) &lt;jorge.trinomio@trinom.io&gt;&quot; (39BDF440C7EAC437)<br><br>Really sign? (y/N) y<br>                    <br>&gt; gpg --fingerprint federico.mieres@trinom.io<br>gpg: checking the trustdb<br>gpg: marginals needed: 3  completes needed: 1  trust model: pgp<br>gpg: depth: 0  valid:   1  signed:   1  trust: 0-, 0q, 0n, 0m, 0f, 1u<br>gpg: depth: 1  valid:   1  signed:   0  trust: 1-, 0q, 0n, 0m, 0f, 0u<br>pub   rsa3072 2025-06-24 [SC]<br>      D7C8 F1E0 B6A3 9C2D E5F4 0B1A C9D2 3F4E 5A6B 7C8D<br>uid           [  full  ] Federico Mieres (my key to share stuff at work) &lt;federico.mieres@trinom.io&gt;<br>sub   rsa3072 2025-06-24 [E]</pre><p>So, done with the set up. This is something you do only once per new key and now Jorge is ready to securely share the envars of the project I’m being onboarded today.</p><p>Let’s say we have:</p><pre>&gt; cat .env.toml<br># Application Settings<br>APP_NAME=&quot;MyTrinoApp&quot;<br>APP_ENV=&quot;development&quot;<br>APP_DEBUG=true<br>APP_URL=&quot;http://localhost:8000&quot;<br><br># Database Configuration<br>DB_CONNECTION=&quot;mysql&quot;<br>DB_HOST=&quot;127.0.0.1&quot;<br>DB_PORT=&quot;3306&quot;<br>DB_DATABASE=&quot;my_app_db&quot;<br>DB_USERNAME=&quot;app_user&quot;<br>DB_PASSWORD=&quot;rAnd0M_DbP@ssw0rd_hjkL5tY&quot;<br><br># API Keys and Credentials<br>API_KEY_STRIPE=&quot;sk_test_aBcD1eFgH2iJ3kL4mN5oPqR6sT7uV8wXyZ&quot;<br>THIRD_PARTY_SERVICE_TOKEN=&quot;token_xyz123abc456def789ghi0jklmnop&quot;<br><br># AWS Credentials<br>AWS_ACCESS_KEY_ID=&quot;AKIAIOSFODNN7EXAMPLE&quot;<br>AWS_SECRET_ACCESS_KEY=&quot;wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY&quot;<br>AWS_REGION=&quot;us-east-1&quot;<br><br># JWT Secret<br>JWT_SECRET=&quot;super-secret-jwt-key-256bit-randomstring-QvR6sT7uV8wXyZ&quot;<br><br># Cache and Queue<br>CACHE_DRIVER=&quot;redis&quot;<br>REDIS_HOST=&quot;127.0.0.1&quot;<br>REDIS_PORT=&quot;6379&quot;<br>QUEUE_CONNECTION=&quot;sync&quot;<br><br># Other<br>FEATURE_FLAG_ALPHA=false<br>ANALYTICS_ID=&quot;UA-XXXXXXXXX-Y&quot;</pre><p>Jorge will encrypt it using my public key:</p><pre>&gt; gpg --output .env.toml.gpg --encrypt -r federico.mieres@trinom.io .env.toml</pre><p>This will generate a file .env.toml.gpg which only I will be able to decrypt.</p><p>After Jorge shares the file with me via company’s email, I’ll decrypt it with:</p><pre>&gt; gpg --output .env.toml  -d env.toml.gpg<br>gpg: encrypted with rsa3072 key, ID 9B9D43B7402FC32B, created 2025-06-24<br>      &quot;Federico Mieres (my key to share stuff at work) &lt;federico.mieres@trinom.io&gt;&quot;</pre><blockquote>GnuPG will then prompt me for my private key’s passphrase to decrypt the file.</blockquote><p>And voila! Now we know how to share secrets securely and no one will be able to maliciously get them unless i share my secret key (which i won’t, hopefully)</p><p>I hope this helps you and see you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e28cb4dd8352" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trinomio/pgp-encryption-securely-sharing-sensitive-company-data-e28cb4dd8352">PGP Encryption: Securely Sharing Sensitive Company Data</a> was originally published in <a href="https://medium.com/trinomio">Trinomio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cómo Configurar y Gestionar una Infraestructura de AWS para Laravel usando Terraform]]></title>
            <link>https://medium.com/trinomio/c%C3%B3mo-configurar-y-gestionar-una-infraestructura-de-aws-para-laravel-usando-terraform-43b639b74b0d?source=rss----beb65fed982d---4</link>
            <guid isPermaLink="false">https://medium.com/p/43b639b74b0d</guid>
            <dc:creator><![CDATA[Sebastianariell]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 17:05:38 GMT</pubDate>
            <atom:updated>2025-02-26T17:05:38.162Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7hXG-jh2cAzzwgCwYFOZEQ.jpeg" /></figure><p>Definir la infraestructura como código (IaC) ofrece múltiples ventajas, como la capacidad de versionar los cambios y mejorar la replicabilidad. Esto permite, por ejemplo, provisionar fácilmente múltiples entornos para un mismo proyecto (<strong>dev</strong>, <strong>staging</strong>, <strong>prod</strong>, etc.).</p><p>En este post, veremos cómo definir la infraestructura para una <strong>API Laravel</strong> utilizando <strong>AWS</strong> y <strong>Terraform</strong>.</p><h3>Requisitos previos</h3><p>Antes de comenzar, asegúrate de contar con lo siguiente:</p><ul><li>Una <strong>VPC</strong> creada en <strong>AWS</strong>.</li><li><strong>Terraform</strong> instalado en tu sistema.</li><li><strong>AWS CLI</strong> instalado y configurado.</li></ul><p>La VPC es importante que este en al menos 2 subzonas, que tenga un internet gateway para que puedan acceder a internet las subredes publicas y que tenga el acceso habilitado para los puertos de la db y de la imagen de la api en las reglas y en el security group.</p><h3>Arquitectura propuesta</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6EMMV8xyUF1CWu25X2LnYA.png" /></figure><p>Desde Terraform, definiremos los recursos necesarios para la infraestructura, incluyendo <strong>ALB, ECS, ECR, SSM y RDS</strong>. Una vez implementada, el proceso de despliegue en GitLab CI/CD será sencillo:</p><ol><li>Construir la imagen del backend.</li><li>Subirla a <strong>ECR</strong>.</li><li>Desplegar la nueva versión en <strong>ECS</strong> utilizando el servicio previamente creado.</li></ol><p><strong>Descripción de los recursos</strong></p><ul><li><strong>ALB (Application Load Balancer)</strong>: Distribuye el tráfico entre las instancias del backend.</li><li><strong>ECS (Elastic Container Service)</strong>: Orquesta y gestiona la ejecución de los contenedores.</li><li><strong>ECR (Elastic Container Registry)</strong>: Almacena las imágenes Docker utilizadas en el despliegue.</li><li><strong>SSM (AWS Systems Manager)</strong>: Se utilizará para gestionar los <strong>secrets</strong> del archivo .env.</li><li><strong>RDS (Relational Database Service)</strong>: Proporciona la base de datos <strong>MySQL</strong> que usará la aplicación.</li></ul><h3>Empezamos con Terraform</h3><p>Primero, definiremos todos los módulos necesarios y luego exploraremos cómo utilizar <strong>Terraform</strong> para crear o actualizar la infraestructura. Los módulos que crearemos serán los siguientes:</p><ul><li><strong>backend</strong></li><li><strong>backend.ecr</strong> (registro de contenedores)</li><li><strong>backend.ecs</strong> (orquestación de contenedores)</li><li><strong>backend.ssm</strong> (gestión de secretos)</li><li><strong>backend.rds</strong> (base de datos MySQL)</li><li><strong>backend.alb</strong> (balanceador de carga)</li></ul><p>La estructura de la carpeta home y backend debería quedar asi:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*-iVcpxZCIN_O5aY1dvuIAw.png" /><figcaption>Carpeta home</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*cE0msZSWzCvGya1DB7dUig.png" /><figcaption>Carpeta backend</figcaption></figure><p>Para inicializar el proyecto, debemos definir un archivo main.tf, que contendrá la configuración de los módulos. En nuestro caso, especificaremos <strong>AWS</strong> como proveedor y declararemos un módulo principal llamado <strong>backend</strong>.</p><pre>provider &quot;aws&quot; {<br>  region = var.default_region_aws<br>}<br><br>module &quot;backend&quot; {<br>  source = &quot;./backend&quot;<br>  app_key = var.app_key<br>  app_url = var.app_url<br>  db_password = var.db_password<br>  db_username = var.db_username<br>  jwt_secret = var.jwt_secret<br>  vpc_id = var.vpc_id<br>  public_subnet_1_id = var.public_subnet_1_id<br>  public_subnet_2_id = var.public_subnet_2_id<br>  private_subnet_1_id = var.private_subnet_1_id<br>  private_subnet_2_id = var.private_subnet_2_id <br>  security_group_id = var.security_group_id<br>}</pre><p>Además del archivo main.tf, es necesario definir dos archivos adicionales en la carpeta base:</p><ol><li>variables.tf: Contiene la declaración de las variables que se utilizarán en la infraestructura.</li><li>terraform.tfvars: Almacena los valores específicos para cada una de estas variables.</li></ol><p>A continuación, se muestra un ejemplo de ambos archivos:</p><p>variables.tf</p><pre>variable &quot;app_key&quot; {}<br>variable &quot;app_url&quot; {}<br>variable &quot;db_password&quot; {}<br>variable &quot;db_username&quot; {}<br>variable &quot;front_url&quot; {}<br>variable &quot;jwt_secret&quot; {}<br>variable &quot;vpc_id&quot; {}<br>variable &quot;public_subnet_1_id&quot; {}<br>variable &quot;public_subnet_2_id&quot; {}<br>variable &quot;private_subnet_1_id&quot; {}<br>variable &quot;private_subnet_2_id&quot; {}<br>variable &quot;security_group_id&quot; {}</pre><p>terraform.tfvars</p><pre>app_key =<br>app_url = <br>db_host =<br>db_password = <br>db_username = <br>jwt_secret = <br>vpc_id = <br>public_subnet_1_id = <br>public_subnet_2_id = <br>private_subnet_1_id = <br>private_subnet_2_id =<br>security_group_id =</pre><p><strong>Módulo backend</strong></p><p>Posteriormente en la carpeta /backend vamos a definir un archivo main.tf donde se definirán todos los submodulos.</p><pre>module &quot;ecr&quot; {<br>  source = &quot;./ecr&quot;<br>}<br><br>module &quot;ssm&quot; {<br>  source = &quot;./ssm&quot;<br>  access_key_id_aws = var.access_key_id_aws<br>  app_key = var.app_key<br>  app_url = var.app_url<br>  db_host = module.rds.db_url<br>  db_password = var.db_password<br>  db_username = var.db_username<br>  jwt_secret = var.jwt_secret<br>}<br><br>module &quot;alb&quot; {<br>  source = &quot;./alb&quot;<br>  vpc_id = var.vpc_id<br>  subnet_public_1 = var.public_subnet_1_id<br>  subnet_public_2 = var.public_subnet_2_id<br>  security_groups = [var.security_group_id]<br>}<br><br>module &quot;ecs&quot; {<br>  source = &quot;./ecs&quot;<br>  target_group_arn = module.alb.target_group_arn<br>  container_image = module.ecr.container_image<br>  subnets = [var.private_subnet_1_id, var.public_subnet_2_id]<br>  security_groups = [var.security_group_id]<br>  app_key_arn = module.ssm.app_key_arn<br>  app_url_arn = module.ssm.app_url_arn<br>  db_host_arn = module.ssm.db_host_arn<br>  db_password_arn = module.ssm.db_password_arn<br>  db_username_arn = module.ssm.db_username_arn<br>  jwt_secret_arn = module.ssm.jwt_secret_arn<br>}<br><br>module &quot;rds&quot; {<br>  source = &quot;./rds&quot;<br>  db_username = module.ssm.db_username<br>  db_password = module.ssm.db_password<br>  vpc_db = var.vpc_id<br>  db_security_groups = var.security_group_id<br>}</pre><p><strong>Módulo ECR</strong></p><p>Definición del repository en repository.tf</p><pre>resource &quot;aws_ecr_repository&quot; &quot;laravel_repository&quot; {<br>    name = &quot;NAME&quot; <br>    tags = {}<br><br>    encryption_configuration {<br>      encryption_type = &quot;AES256&quot;<br>    }<br><br>    image_scanning_configuration {<br>      scan_on_push = false<br>    }<br>}</pre><p>También agregaremos el archivo output.tf para definir las variables a exportar</p><pre>output &quot;container_image&quot; {<br>  value = &quot;${aws_ecr_repository.laravel_repository.repository_url}:latest&quot;<br>}</pre><p><strong>Módulo SSM</strong></p><p>Lo importante en este módulo es definir los parametros que necesitamos en nuestro .env definimos los parametros enparameter_store.tf</p><pre>resource &quot;aws_ssm_parameter&quot; &quot;APP_KEY&quot; {<br>  name = &quot;APP_KEY&quot;<br>  description = &quot;APP_KEY&quot;<br>  type = &quot;SecureString&quot;<br>  value = var.app_key<br>}<br><br>resource &quot;aws_ssm_parameter&quot; &quot;APP_URL&quot; {<br>  name = &quot;APP_URL&quot;<br>  description = &quot;APP_URL&quot;<br>  type = &quot;String&quot;<br>  value = var.app_url<br>}<br><br>resource &quot;aws_ssm_parameter&quot; &quot;DB_HOST&quot; {<br>  name = &quot;DB_HOST&quot;<br>  description = &quot;DB_HOST&quot;<br>  type = &quot;SecureString&quot;<br>  value = var.db_host<br>}<br><br>resource &quot;aws_ssm_parameter&quot; &quot;DB_PASSWORD&quot; {<br>  name = &quot;DB_PASSWORD&quot;<br>  description = &quot;DB_PASSWORD&quot;<br>  type = &quot;SecureString&quot;<br>  value = var.db_password<br>}<br><br>resource &quot;aws_ssm_parameter&quot; &quot;DB_USERNAME&quot; {<br>  name = &quot;DB_USERNAME&quot;<br>  description = &quot;DB_USERNAME&quot;<br>  type = &quot;SecureString&quot;<br>  value = var.db_username<br>}<br><br>resource &quot;aws_ssm_parameter&quot; &quot;JWT_SECRET&quot; {<br>  name = &quot;JWT_SECRET&quot;<br>  description = &quot;JWT_SECRET&quot;<br>  type = &quot;SecureString&quot;<br>  value = var.jwt_secret<br>}</pre><p>En el .env de tu aplicacion debería quedar algo asi:</p><pre>DB_HOST=${DB_HOST}<br>DB_USERNAME=${DB_USERNAME}<br>DB_PASSWORD=${DB_PASSWORD}</pre><p>Definimos un kms que se utilizará para cifrar las claves enkms.tf</p><pre>data &quot;aws_kms_alias&quot; &quot;ssm&quot; {<br> name = &quot;alias/aws/ssm&quot;<br>}</pre><p>Definimos las variables que necesitamos en variables.tf</p><pre>variable &quot;app_key&quot; {<br>  type        = string<br>  sensitive   = true<br>}<br><br>variable &quot;app_url&quot; {<br>  type        = string<br>  sensitive   = false<br>}<br><br>variable &quot;db_host&quot; {<br>  type        = string<br>  sensitive   = true<br>}<br><br>variable &quot;db_password&quot; {<br>  type        = string<br>  sensitive   = true<br>}<br><br>variable &quot;db_username&quot; {<br>  type        = string<br>  sensitive   = true<br>}<br><br>variable &quot;jwt_secret&quot; {<br>  type        = string<br>  sensitive   = true<br>}</pre><p>Definimos los outputs en outputs.tf</p><pre>output &quot;db_username&quot; {<br>  value = aws_ssm_parameter.DB_USERNAME.value<br>}<br><br>output &quot;db_password&quot; {<br>  value = aws_ssm_parameter.DB_PASSWORD.value<br>}<br><br>output &quot;app_key_arn&quot; {<br>  value = aws_ssm_parameter.APP_KEY.arn<br>}<br><br>output &quot;app_url_arn&quot; {<br>  value = aws_ssm_parameter.APP_URL.arn<br>}<br><br>output &quot;db_host_arn&quot; {<br>  value = aws_ssm_parameter.DB_HOST.arn<br>}<br><br>output &quot;db_password_arn&quot; {<br>  value = aws_ssm_parameter.DB_PASSWORD.arn<br>}<br><br>output &quot;db_username_arn&quot; {<br>  value = aws_ssm_parameter.DB_USERNAME.arn<br>}<br><br>output &quot;jwt_secret_arn&quot; {<br>  value = aws_ssm_parameter.JWT_SECRET.arn<br>}<br><br>output &quot;kms_alias&quot; {<br>  value = data.aws_kms_alias.ssm.arn<br>}</pre><p><strong>Módulo ALB</strong></p><p>Definimos el load balancer en load_balancer.tf load_balancer.tf</p><pre>resource &quot;aws_lb&quot; &quot;load-balancer&quot; {<br>  name = &quot;NAME&quot;<br>  internal = false<br>  load_balancer_type = &quot;application&quot;<br>  security_groups = var.security_groups<br>  subnets = [var.subnet_public_1, var.subnet_public_2]<br>  enable_deletion_protection = false<br>  enable_cross_zone_load_balancing = true<br><br>}</pre><p>Definimos el target group para el load balancer entarget_group.tf</p><pre>resource &quot;aws_lb_target_group&quot; &quot;ecs-service&quot; {<br>  vpc_id   = var.vpc_id<br>  deregistration_delay              = &quot;300&quot;<br>  ip_address_type                   = &quot;ipv4&quot;<br>  load_balancing_algorithm_type     = &quot;round_robin&quot;<br>  load_balancing_anomaly_mitigation = &quot;off&quot;<br>  load_balancing_cross_zone_enabled = &quot;use_load_balancer_configuration&quot;<br>  name                              = &quot;NAME&quot;<br>  name_prefix                       = null<br>  port                              = 80<br>  protocol                          = &quot;HTTP&quot;<br>  protocol_version                  = &quot;HTTP1&quot;<br>  slow_start                        = 0<br>  tags                              = {}<br>  tags_all                          = {}<br>  target_type                       = &quot;ip&quot;<br><br>  health_check {<br>      enabled             = true<br>      healthy_threshold   = 5<br>      interval            = 30<br>      matcher             = &quot;200&quot;<br>      path                = &quot;PATH_TO_ENDPOINT&quot;<br>      port                = &quot;traffic-port&quot;<br>      protocol            = &quot;HTTP&quot;<br>      timeout             = 5<br>      unhealthy_threshold = 2<br>  }<br><br>  stickiness {<br>      cookie_duration = 86400<br>      cookie_name     = null<br>      enabled         = false<br>      type            = &quot;lb_cookie&quot;<br>  }<br><br>  target_group_health {<br>      dns_failover {<br>          minimum_healthy_targets_count      = &quot;1&quot;<br>          minimum_healthy_targets_percentage = &quot;off&quot;<br>      }<br>      unhealthy_state_routing {<br>          minimum_healthy_targets_count      = 1<br>          minimum_healthy_targets_percentage = &quot;off&quot;<br>      }<br>  }<br><br>}</pre><p>Definimos los listeners enlisteners.tf</p><pre>resource &quot;aws_lb_listener&quot; &quot;listener&quot; {<br>  load_balancer_arn = aws_lb.load-balancer.arn<br>  port              = 80<br>  protocol          = &quot;HTTP&quot;<br><br>  default_action {<br>    target_group_arn = aws_lb_target_group.ecs-service.arn<br>    type             = &quot;forward&quot;<br><br>    forward {<br><br>        target_group {<br>            arn    = aws_lb_target_group.ecs-service.arn<br>            weight = 1<br>        }<br>    }<br>  }<br>}</pre><p>Definimos las variables que necesita el módulo en variables.tf</p><pre>variable &quot;vpc_id&quot; {<br>  type = string<br>}<br><br>variable &quot;subnet_public_1&quot; {<br>  type = string<br>}<br><br>variable &quot;subnet_public_2&quot; {<br>  type = string<br>}<br><br>variable &quot;security_groups&quot; {}</pre><p>Definimos los outputs en output.tf</p><pre>output &quot;target_group_arn&quot; {<br>  value = aws_lb_target_group.ecs-service.arn<br>}<br><br>output &quot;lb_dns_name&quot; {<br>  value = aws_lb.load-balancer.dns_name<br>}</pre><p><strong>Módulo ECS</strong></p><p>Definimos el cluster en<em> </em>cluster.tf</p><pre>resource &quot;aws_ecs_cluster&quot; &quot;laravel_cluster&quot; {<br>  name = var.ecs_cluster_name<br>}</pre><p>Definimos el service en service.tf acá en el load balancer tenemos que indicar el puerto adecuado.</p><pre>resource &quot;aws_ecs_service&quot; &quot;laravel_service&quot; {<br>  name = &quot;NAME&quot;<br>  cluster = aws_ecs_cluster.laravel_cluster.id<br>  task_definition = &quot;${aws_ecs_task_definition.laravel_task.family}:${aws_ecs_task_definition.laravel_task.revision}&quot;<br>  desired_count = 1<br>  health_check_grace_period_seconds = 300<br>  availability_zone_rebalancing = &quot;ENABLED&quot;<br>  enable_ecs_managed_tags = true<br>  enable_execute_command = true<br><br>  capacity_provider_strategy {<br>    base = 0 <br>    capacity_provider = &quot;FARGATE&quot;<br>    weight = 1<br>  }<br>  deployment_circuit_breaker {<br>    enable = true<br>    rollback = true<br>  }<br>  network_configuration {<br>    subnets = var.subnets<br>    security_groups = var.security_groups<br>    assign_public_ip = true<br>  }<br>  load_balancer {<br>    container_name = &quot;NAME&quot;<br>    container_port = 80<br>    target_group_arn = var.target_group_arn<br>  }<br>  <br>}</pre><p>Definimos la task definition entask_definition.tf lo mismo que en el servicio hay que indicar los puertos en los cuales tu imagen va a estar escuchando.</p><pre>resource &quot;aws_ecs_task_definition&quot; &quot;laravel_task&quot; {<br>  family = var.task_definition_family<br>  cpu = &quot;1024&quot;<br>  memory = &quot;3072&quot;<br>  network_mode = &quot;awsvpc&quot;<br>  requires_compatibilities = [&quot;FARGATE&quot;]<br>  execution_role_arn = ARN_TASK_EXECUTION_ROLE<br>  task_role_arn = ARN_TASK_EXECUTION_ROLE<br><br>  runtime_platform { <br>    cpu_architecture = &quot;X86_64&quot; <br>    operating_system_family = &quot;LINUX&quot; <br>  }<br>  container_definitions = jsonencode([{<br>    name = &quot;NAME&quot;<br>    image = var.container_image<br>    essential = true<br>    environment = []<br>    mountPoints = []<br>    systemControls = []<br>    volumesFrom = []<br>    portMappings = [<br>      {<br>        appProtocol = &quot;http&quot;<br>        containerPort = 80<br>        hostPort = 80<br>        protocol = &quot;tcp&quot;<br>        name = &quot;NAME&quot;<br>      }<br>    ]<br>    secrets = [<br>      {<br>        name = &quot;APP_KEY&quot;<br>        valueFrom = var.app_key_arn<br>      },<br>      {<br>        name = &quot;APP_URL&quot;<br>        valueFrom = var.app_url_arn<br>      },<br>      {<br>        name = &quot;DB_HOST&quot;<br>        valueFrom = var.db_host_arn<br>      },<br>      {<br>        name = &quot;DB_PASSWORD&quot;<br>        valueFrom = var.db_password_arn<br>      },<br>      {<br>        name = &quot;DB_USERNAME&quot;<br>        valueFrom = var.db_username_arn<br>      },<br>      {<br>        name = &quot;JWT_SECRET&quot;<br>        valueFrom = var.jwt_secret_arn<br>      },<br>    ]<br>  }])<br>}</pre><p>Definimos las variables en variables.tf</p><pre>variable &quot;ecs_cluster_name&quot; {<br>  default = &quot;cluster-name&quot;<br>}<br>variable &quot;task_definition_family&quot; {<br>  default = &quot;family&quot;<br>}<br>variable &quot;container_image&quot; {<br>  type = string<br>}<br>variable &quot;target_group_arn&quot; {}<br>variable &quot;subnets&quot; {}<br>variable &quot;security_groups&quot; {}<br>variable &quot;app_key_arn&quot; {}<br>variable &quot;app_url_arn&quot; {}<br>variable &quot;db_host_arn&quot; {}<br>variable &quot;db_password_arn&quot; {}<br>variable &quot;db_username_arn&quot; {}<br>variable &quot;jwt_secret_arn&quot; {}</pre><p><strong>Módulo RDS</strong></p><p>Se define la db que utilizaremos en database.tf</p><pre>resource &quot;aws_db_instance&quot; &quot;db&quot; {<br>  identifier             = &quot;db&quot;<br>  engine                 = &quot;mysql&quot;<br>  engine_version         = &quot;8.0.39&quot;<br>  instance_class         = &quot;db.t4g.micro&quot;<br>  allocated_storage      = 20<br>  username               = var.db_username<br>  password               = var.db_password<br>  vpc_security_group_ids = [var.db_security_groups]<br>  storage_type           = &quot;gp2&quot;<br>  multi_az               = false<br>  publicly_accessible    = true<br>  backup_retention_period = 7<br>  storage_encrypted      = true<br>  customer_owned_ip_enabled = false<br>  auto_minor_version_upgrade = true<br>  enabled_cloudwatch_logs_exports = []<br>  copy_tags_to_snapshot  = true<br>  deletion_protection    = false<br>  max_allocated_storage  = 1000<br>  iam_database_authentication_enabled = false<br>  network_type           = &quot;IPV4&quot;<br>  tags = {}<br>}</pre><p>Definimos las variables que necesita el módulo en variables.tf</p><pre>variable &quot;db_password&quot; {<br>  type        = string<br>  sensitive   = true<br>}<br><br>variable &quot;db_username&quot; {<br>  type        = string<br>  sensitive   = true<br>}<br>variable &quot;db_security_groups&quot; {}<br>variable &quot;vpc_db&quot; {}</pre><p>Definimos los outputs en outputs.tf</p><pre>output &quot;db_url&quot; {<br>  value = aws_db_instance.db.endpoint<br>}</pre><h3>Cómo crear la infraestructura en AWS</h3><p>Una vez que hayamos definido todos los módulos de Terraform, seguimos estos pasos para desplegar la infraestructura:</p><p><strong>1. Inicializar Terraform</strong></p><p>Antes de comenzar, es necesario inicializar el entorno de Terraform ejecutando el siguiente comando:</p><pre>terraform init</pre><p>Este comando descarga los proveedores necesarios y prepara el entorno para gestionar la infraestructura.</p><p><strong>2. Previsualizar cambios</strong></p><p>Para ver qué cambios se aplicarían en la infraestructura sin ejecutarlos aún, usamos:</p><pre>terraform plan</pre><p>Este comando genera un resumen similar a un git diff, mostrando qué recursos se agregarán, modificarán o eliminarán en la infraestructura.</p><p><strong>3. Aplicar los cambios</strong></p><p>Si el plan es correcto y queremos aplicar los cambios, ejecutamos:</p><pre>terraform apply</pre><p>Terraform solicitará confirmación antes de proceder. Una vez aprobado, creará o actualizará los recursos según la configuración definida.</p><p><strong>4. Modificar la infraestructura</strong></p><p>Para realizar cambios en la infraestructura ya creada, simplemente seguimos estos pasos:</p><ol><li>Modificar el código de Terraform.</li><li>Ejecutar terraform plan para visualizar los cambios.</li><li>Si todo es correcto, aplicar los cambios con terraform apply.</li></ol><p>Todos estos cambios quedarán registrados en el archivo <strong>state</strong>, que mantiene el estado actual de la infraestructura y permite a Terraform gestionar futuras modificaciones de manera eficiente.</p><p><strong>Cómo importar la infraestructura existente</strong></p><p>Si ya tienes infraestructura creada y deseas importarla en Terraform para gestionarla, la mejor forma es crear un script que agrupe todas las referencias necesarias a los recursos existentes. A continuación, te muestro un ejemplo de script que puedes usar para importar los recursos a Terraform:</p><pre>#!/bin/bash<br><br>terraform init<br># ecs imports<br>terraform import module.backend.module.ecs.aws_ecs_cluster.laravel_cluster cluster_name<br>terraform import module.backend.module.ecs.aws_ecs_service.laravel_service service_name<br>terraform import module.backend.module.ecs.aws_ecs_task_definition.laravel_task task_definition_arn<br># ecr imports<br>terraform import module.backend.module.ecr.aws_ecr_repository.laravel_repository nombre_repo_ecr<br># rds imports<br>terraform import module.backend.module.rds.aws_db_instance.db db<br># load balancer imports<br>terraform import module.backend.module.alb.aws_lb.load-balancer arn_load_balancer<br>terraform import module.backend.module.alb.aws_lb_listener.listener arn_listener<br>terraform import module.backend.module.alb.aws_lb_target_group.ecs-service arn_service<br># ssm imports<br>terraform import module.backend.module.ssm.aws_ssm_parameter.APP_KEY APP_KEY<br>terraform import module.backend.module.ssm.aws_ssm_parameter.APP_URL APP_URL<br>terraform import module.backend.module.ssm.aws_ssm_parameter.DB_HOST DB_HOST<br>terraform import module.backend.module.ssm.aws_ssm_parameter.DB_PASSWORD DB_PASSWORD<br>terraform import module.backend.module.ssm.aws_ssm_parameter.DB_USERNAME DB_USERNAME<br>terraform import module.backend.module.ssm.aws_ssm_parameter.JWT_SECRET JWT_SECRET</pre><p><strong>Explicación:</strong></p><ul><li><strong>Inicialización</strong>: El comando terraform init es necesario para preparar el entorno de Terraform, descargando los proveedores necesarios.</li><li><strong>Imports de ECS</strong>: Se importan los recursos relacionados con el servicio ECS, como el clúster, servicio y task definition.</li><li><strong>Imports de ECR</strong>: Se importa el repositorio de imágenes Docker en Amazon Elastic Container Registry (ECR).</li><li><strong>Imports de RDS</strong>: Se importa la instancia de base de datos de RDS.</li><li><strong>Imports de Load Balancer</strong>: Se importan los recursos del Application Load Balancer, incluyendo el listener y el grupo de destino.</li><li><strong>Imports de SSM</strong>: Se importan las variables de entorno y secretos almacenados en AWS Systems Manager (SSM) para mantener la configuración sensible.</li></ul><p>Con este script, Terraform podrá reconocer y gestionar los recursos existentes de AWS como si hubieran sido creados originalmente por Terraform.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43b639b74b0d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trinomio/c%C3%B3mo-configurar-y-gestionar-una-infraestructura-de-aws-para-laravel-usando-terraform-43b639b74b0d">Cómo Configurar y Gestionar una Infraestructura de AWS para Laravel usando Terraform</a> was originally published in <a href="https://medium.com/trinomio">Trinomio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoreo de aplicaciones Laravel con Telescope]]></title>
            <link>https://medium.com/trinomio/monitoreo-de-aplicaciones-laravel-con-telescope-ba654f38173d?source=rss----beb65fed982d---4</link>
            <guid isPermaLink="false">https://medium.com/p/ba654f38173d</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[pulse]]></category>
            <category><![CDATA[telescope]]></category>
            <category><![CDATA[monitoreo]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Sebastianariell]]></dc:creator>
            <pubDate>Thu, 08 Aug 2024 18:23:31 GMT</pubDate>
            <atom:updated>2024-08-08T18:23:31.747Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t7rLmI4HHVF8omx_IU-z3w.png" /></figure><p>En el desarrollo de aplicaciones, la capacidad de monitorear y depurar el comportamiento de la aplicación es esencial para mantener un rendimiento óptimo y resolver problemas rápidamente. Laravel, ofrece una poderosa herramienta para este propósito: <strong>Telescope</strong>. Este paquete proporciona una interfaz intuitiva que permite a los desarrolladores observar las requests, excepciones, queries, y otros eventos clave en tiempo real.</p><p>En este artículo, exploraremos los pros y contras de Laravel Telescope, así como cómo configurarlo y utilizarlo para monitorear tus aplicaciones.</p><h3>Pros:</h3><ol><li>Es gratuito</li><li>Facil instalación</li><li>Es bastante detallado con la información de cada petición</li></ol><p>Dentro de cada solicitud permite por ejemplo ver: que queries se ejecutaron, que modelos fueron invocados, si se realizo una consulta a redis/cache, si se envió algun mail, si devolvio una vista, si devolvio un JSON y que devolvio, headers, payload. Esta información puede ser vital a la hora de identificar un problema y te da la posibilidad de replicar algun error de manera exacta.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SOXyJrMv8TwFYvQrphpR5A.png" /><figcaption>Se puede visualizar la información general de la solicitud</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJje8owMkWzi9YVwo1XCPg.png" /><figcaption>Se puede visualizar información mas detallada de que ocurrió durante el requests, como por ej queries, payload, etc…</figcaption></figure><h3>Contras:</h3><ol><li><strong>Pocas posibilidades a la hora de filtrar los requests</strong></li></ol><p>Por defecto solo guarda 2 tags por requests: status y el id del usuario que realizo la petición. Si bien permite personalizar los tags y agregar otros solo permite filtrar por 1 tag, es decir que por ejemplo podrias filtrar por un usuario pero no filtrar solo los requests del usuario X que devolvieron status 422.</p><p>2. <strong>No fue ideado para utilizar en prod</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*dlf-8koGvC0W3Hn66WD9Lg.png" /></figure><p><strong>Como vemos en el twit de uno de los ideologos de Telescope no fue desarrollado con la intención de monitorear aplicaciones en producción</strong> sino con el fin de identificar y depurar problemas de manera local. Puede ser considerado como una contra pero creo que con los siguientes puntos no habría mayor problema al utilizar el paquete en producción:</p><ol><li>Utilizar otra base de datos para las tablas de Telescope</li><li>Autenticar las rutas de telescope</li></ol><h3>Instalación</h3><p>Para instalar este paquete basta con seguir los siguientes pasos:</p><ol><li><strong>Instalar el paquete con composer</strong></li></ol><pre>composer require laravel/telescope</pre><p>2. <strong>Correr el comando telescope install</strong></p><pre>php artisan telescope:install</pre><p>3. <strong>Modificar el config de telescope <em>(config/telescope.php)</em> para indicar que utilize otra connection de db.</strong></p><pre>&#39;storage&#39; =&gt; [<br>        &#39;database&#39; =&gt; [<br>            &#39;connection&#39; =&gt; env(&#39;YOUR_DB_CONNECTION&#39;, &#39;YOUR_DEFAULT_CONNECTION&#39;),<br>            &#39;chunk&#39; =&gt; 1000,<br>        ],<br>    ],</pre><p>Es importante que esta connection este definida en <em>config/database.php</em></p><p>4. <strong>Correr las migraciones</strong></p><pre>php artisan migrate</pre><p>Desde este punto en una aplicación corriendo localmente, basta con ir a <a href="http://localhost:8000/telescope">http://localhost:8000/telescope</a> y ya se podrá visualizar la herramienta</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q1eWi9WNEug8A6s9a-QcVA.png" /></figure><h3>Autenticar Telescope</h3><p>El siguiente paso es autenticar la ruta de telescope para que no cualquiera pueda acceder a esta información y lo podremos hacer de las siguiente maneras:</p><ol><li><strong>Agregar tu middleware de auth en la config de telescope <em>(config/telescope.php)</em></strong></li></ol><pre>&#39;middleware&#39; =&gt; [<br>        &#39;web&#39;,<br>        &#39;YOUR_CUSTOM_MIDDLEWARE&#39;,<br>        Authorize::class,<br>    ],</pre><p>Una vez seteado el middleware ya no se podrá ingresar a la ruta de telescope sin estar logueado</p><p>2. <strong>Agregar un gate para autorizar los accesos</strong></p><p>Telescope permite agregar un gate para autorizar los accesos, esto método lo tenemos que definir en <em>app/Providers/TelescopeServiceProvider.php</em></p><pre>use App\Models\User;<br> <br>/**<br> * Register the Telescope gate.<br> *<br> * This gate determines who can access Telescope in non-local environments.<br> */<br>protected function gate(): void<br>{<br>    Gate::define(&#39;viewTelescope&#39;, function (User $user) {<br>        return in_array($user-&gt;email, [<br>            &#39;YOUR_ADMIN_EMAIL&#39;,<br>        ]);<br>    });<br>}</pre><p>En este ejemplo estamos simplemente filtrando por email, pero se podria realizar un filtrado con otro tipo de criterio, como por ejemplo si el usuario es admin:</p><pre>use App\Models\User;<br> <br>/**<br> * Register the Telescope gate.<br> *<br> * This gate determines who can access Telescope in non-local environments.<br> */<br>protected function gate(): void<br>{<br>    Gate::define(&#39;viewTelescope&#39;, function (User $user) {<br>        return $user-&gt;isAdmin();<br>    });<br>}</pre><h3>Extras</h3><p>Si bien Telescope permite visualizar las request un punto que se puede considerar negativo es que no tiene muchos filtros por defecto, pero podemos agregarle diferentes tags para filtrar posteriormente. Simplemente hay que modificar el metodo <em>register </em>en <em>app/Providers/TelescopeServiceProvider.php</em> y agregar lo siguiente:</p><pre>public function register(): void<br>{<br>    ...<br>    Telescope::tag(function (IncomingEntry $entry) {<br>        $tags = [];<br>        if ($entry-&gt;type === &#39;request&#39;) {<br>            $tags[] = &#39;status:&#39;.$entry-&gt;content[&#39;response_status&#39;];<br>            if (isset($entry-&gt;content[&#39;uri&#39;])) {<br>                $uri = $entry-&gt;content[&#39;uri&#39;];<br>                $tags[] = &#39;path:&#39;.$uri;<br>            }<br>        }<br>        return $tags;<br>    });<br>    ...<br>}</pre><p>En este caso simplemente estamos agregando un tag con el status y otro con el path de la ruta, pero se puede extender a los casos que consideres necesarios. Una vez realizado este cambio por cada request se guardara estos tags y por ejemplo si se quiere revisar los pedidos que retornaron con un estado 422 bastará con filtrar por el tag <em>status:422.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba654f38173d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trinomio/monitoreo-de-aplicaciones-laravel-con-telescope-ba654f38173d">Monitoreo de aplicaciones Laravel con Telescope</a> was originally published in <a href="https://medium.com/trinomio">Trinomio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aprendiendo sobre WSL]]></title>
            <link>https://medium.com/trinomio/aprendiendo-sobre-wsl-e8b934d0d340?source=rss----beb65fed982d---4</link>
            <guid isPermaLink="false">https://medium.com/p/e8b934d0d340</guid>
            <category><![CDATA[wsl]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[windows]]></category>
            <dc:creator><![CDATA[Nicolas Martinez]]></dc:creator>
            <pubDate>Fri, 21 Oct 2022 15:26:09 GMT</pubDate>
            <atom:updated>2022-10-21T15:26:09.255Z</atom:updated>
            <content:encoded><![CDATA[<p>La discusión sobre el sistema operativo de uso cotidiano siempre fue un tema bastante polémico, sobre todo entre los desarrolladores de software. Está claro que lo que hace bueno a un sistema operativo no solo es su robustez, sino la utilidad que se le vaya a dar y como se sienta el usuario con él. Por eso la elección depende de cada persona.</p><p>Linux siempre fue el sistema operativo por excelencia a la hora de hablar del desarrollo de software. Sus innumerables ventajas, como el hecho de que sea Software libre y la posibilidad que esto da de modificarlo a nuestro gusto, que sea de uso gratuito(en la mayoría de los casos), la infinidad de herramientas que están desarrolladas para linux, el manejo de versiones, entre otras, hace que los desarrolladores lo elijan por sobre el sistema operativo de Microsoft.</p><p>Sin embargo, en los últimos años Microsoft incluyó a su repertorio de tecnologías que no sabiamos que existian el uso de Windows Subsystem for Linux, o mejor conocido como WSL, cuya idea principal es “simular” el kernel de linux para permitir la ejecución de paquetes de Linux. En este post vengo a hablar un poco de WSL, como configurarlo y sobre sus ventajas y desventajas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kvEFbwrU9Yx-XT1I.png" /><figcaption>Arquirectura simple de WSL</figcaption></figure><h4>Instalación</h4><p>Desde Windows 10 en adelante, WSL viene instalado por defecto. No voy a explicar como instalarlo ya que el proceso es bastante largo, pero no complejo por lo que voy a dejar un enlace a la<a href="https://learn.microsoft.com/es-es/windows/wsl/install"> documentación oficial</a>. Para poder sacar el máximo provecho a WSL les recomiendo usar la versión 2.</p><h4>Primeros pasos</h4><p>Algo a tener en cuenta es que WSL es Linux, por lo que sí sabemos cómo manejar Linux sabemos como usar WSL. Una vez instalado es recomendable usar<a href="https://apps.microsoft.com/store/detail/windows-terminal/9N0DX20HK701?hl=es-ar&amp;gl=ar"> la terminal nueva de Windows</a> en lugar de la que viene por defecto con la distribución que hayamos elegido ya que nos permite tener pestañas.</p><h4>Firewall</h4><p>Otra cosa a tener en cuenta es el firewall, ya que WSL utiliza una red interna por lo que tendremos que crear un proxy que mapee la IP interna de WSL con un puerto específico en nuestro localhost si queremos utilizar un servicio interno(por ejemplo, al querer exponer una api). Esto lo podemos hacer con netsh interface portproxy add v4tov4 listenport=puerto_local listenaddress=0.0.0.0 connectport=puerto_de_wsl connectaddress= nuestra_ip_en_wsl . Aca podemos ver como utilizamos el la herramienta de netsh de windows para generar un proxy que enlaza el puerto local(connectport) de WSL al puerto local de nuestra máquina(listenport) utilizando la IP de WSL(connectaddress) y la ip de localhost de windows(0.0.0.0).</p><h4>Ventajas y desventajas</h4><p>La ventaja principal de WSL es que para todos los que quieran usar Windows como su sistema operativo cotidiano pero, así mismo, también quiera tener toda las ventajas de utilizar paquetes Linux pueda hacerlo. Otra ventaja es que, así como sucede con los contenedores docker, WSL genera un entorno que es independiente y totalmente descartable, por lo que si queremos probar algo volátil y luego descartar la distribución podemos hacerlo. Así mismo, podremos tener más de una distribución de linux corriendo, aunque es difícil encontrar distribuciones que varien mucho una de otra con respecto a lo que pueden aportar. Una ventaja que muchos suelen agradecer a la hora de utilizar esta tecnología es la documentación existente, ya que cualquier problema que podemos tener suele estar resuelto por la comunidad o por la propia Microsoft (ni hablar si el problema es particularmente de Linux y no de WSL en sí).</p><p>Bueno todo muy lindo pero ¿ Dónde está el truco ? En realidad no lo hay, WSL es eso. Sin embargo, tiene desventajas como toda tecnología: Una de sus principales desventajas es que depende fuertemente de que tu procesador soporte tecnología de virtualización. Hoy en día los procesadores de nueva generación lo soportan, pero no es el caso de los procesadores más viejos. Otra desventaja es el hecho de tener que configurar un proxy para exponer puertos internos, como se explicó en el apartado anterior. Así mismo, a veces se requiere realizar un paso extra para configurar algún servicio, algo que no sucede en Linux nativo. Para los fundamentalistas, la máxima desventaja de WSL es que corre sobre Windows. Hay cierta verdad en este punto ya que, a veces, Windows puede ser un dolor de cabeza a la hora de configurarlo.</p><p>Existen además casos de procesos de instalación dificultosos que podrían considerarse una desventaja pero no sería la primera vez que una tecnología nueva nos rompe la cabeza hasta que la hacemos funcionar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*65HS6zhaux3Cy7D8Uru7yQ.jpeg" /></figure><h4>Conclusión</h4><p>Para finalizar, siempre está bueno dejar en claro que WSL es como cualquier tecnología que puede ser útil si es lo que estás buscando. Sin embargo debemos tener en cuenta que esta tecnología surgió hace apenas casi 4 años, hay muchas cosas por corregir. Microsoft está pisando fuerte con WSL y no se quiere quedar atrás, por lo que no faltarán actualizaciones ni subidas de nuevas distribuciones.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8b934d0d340" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trinomio/aprendiendo-sobre-wsl-e8b934d0d340">Aprendiendo sobre WSL</a> was originally published in <a href="https://medium.com/trinomio">Trinomio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monkey Patching helping to keep interfaces intact!]]></title>
            <link>https://medium.com/trinomio/monkey-patching-helping-to-keep-interfaces-intact-c58a844901f8?source=rss----beb65fed982d---4</link>
            <guid isPermaLink="false">https://medium.com/p/c58a844901f8</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Federico Mieres]]></dc:creator>
            <pubDate>Mon, 03 Oct 2022 06:35:35 GMT</pubDate>
            <atom:updated>2022-10-03T13:42:26.058Z</atom:updated>
            <content:encoded><![CDATA[<p>Monkey Patching helping to keep interfaces intact!</p><p>This time around I bring you a specific situation We were in a few weeks ago and how We solved it. For some reason we needed to change how requests worked in a frontend while keeping the rest of the code as compatible as possible. We had to change simple attribute calls to function calls. But the callers should never know about this change. So we found Monkey Patching!</p><p>Monkey patching is a technique to change default behaviour of code at runtime, allowing us the keep the source code untouched.</p><p>Basically, our situation was the following:</p><pre>const repository = {<br>  apiClient: apiClientDefinedAtStartUp<br>}<br>export default repository</pre><p>needed to change to :</p><pre>const repository = {<br>  apiClient: runTimeData =&gt; defineApiClient(runTimeData)<br>}<br>export default repository</pre><p>This change would have forced us to change all code that uses this repository and we didn’t want that. So with Monkey Patching:</p><pre>const repository = {<br>  apiClient: undefined<br>}<br>Object.defineProperty(repository, &#39;apiClient&#39;, {<br>  get: () =&gt; {<br>    runTimeData = inject(&#39;runtimedata&#39;)<br>    return defineApiClient(runTimeData)<br>  }<br>})<br>export default repository</pre><p>The above code is illustrative of the challenge we faced so I want to bring a more concrete example that you can try in your browser:</p><p>From:</p><pre>const library = {<br>  theBestNumber: 1<br>}<br>export default library</pre><p>To:</p><pre>const library = {<br>  theBestNumber: () =&gt; parseInt(localStorage.getItem(&#39;best&#39;)||1)<br>}<br>export default library</pre><p>Monkey Patching at work:</p><pre>const library = {<br>  theBestNumber: 1<br>}<br>Object.defineProperty(library, &#39;theBestNumber&#39;, {<br>  get: () =&gt; parseInt(localStorage.getItem(&#39;best&#39;)||1)<br>})<br>export default library</pre><p>Using defineProperty allows us to intercept the get action of an object in order to give a different result as initially defined. This saved us from changing a hundred places where this library was being used.</p><p>Of course before using this, talk to your team so they don’t get any surprises with code not working as defined!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c58a844901f8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trinomio/monkey-patching-helping-to-keep-interfaces-intact-c58a844901f8">Monkey Patching helping to keep interfaces intact!</a> was originally published in <a href="https://medium.com/trinomio">Trinomio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Crash Course Part 1]]></title>
            <link>https://medium.com/trinomio/docker-crash-course-part-1-7de2dbafa4c7?source=rss----beb65fed982d---4</link>
            <guid isPermaLink="false">https://medium.com/p/7de2dbafa4c7</guid>
            <category><![CDATA[docke]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Federico Mieres]]></dc:creator>
            <pubDate>Mon, 27 Jun 2022 20:14:18 GMT</pubDate>
            <atom:updated>2022-06-27T20:39:13.752Z</atom:updated>
            <content:encoded><![CDATA[<p>Docker is a platform to package / build / deliver applications. We run containers, build images, tag versions and publish images for others to use. Its two key players are containers and images.</p><blockquote><em>Docker Overview : </em><a href="https://docs.docker.com/get-started/overview/"><em>https://docs.docker.com/get-started/overview/</em></a></blockquote><blockquote><em>If for some reason you can’t use docker on your local environment, use </em><a href="https://labs.play-with-docker.com/"><em>https://labs.play-with-docker.com/</em></a><em> for the rest of the tutorial.</em></blockquote><h3>Containers</h3><p>Containers are like instances of a class. Once we have a definition, We instance it to do stuff with it. Containers are alive while We use them and may die when We stop. Sometimes they can be resurrected or put to sleep. They also can be put in daemon mode and do stuff in the background.</p><p>A priori Containers are isolated from the host system, so what happens in a container stays in a container. <em>we can tinker with this concept later</em>.</p><p>The first container We will run is : hello-world.</p><h3>Hello World</h3><ul><li>docker run hello-world</li></ul><p>Now let’s have a look at what did this print on our terminal. It should include a brief of what happened.</p><h3>docker ps and inspect</h3><p>Useful command docker ps . This will allow us to see what containers are currently running on docker.</p><p>None to be seen ? try docker ps -a . This flag shows all containers that have been run on our docker host.</p><p>We should see something like</p><pre>CONTAINER ID   IMAGE          COMMAND    CREATED          STATUS                       PORTS      NAMES</pre><pre>78db44e62c89   hello-world    &quot;/hello&quot;   16 minutes ago   Exited (0) 16 minutes ago               dreamy_fermi</pre><p>We can go with our curiosity even further and do a docker inspect 78db44e62c89 and get all sort of info about that particular container.</p><blockquote><em>We can also use its name </em><em>dreamy_fermi instead of the id for most commands that need a container id. These names are randomly generated, but we can specify it with </em><em>--name fancy_name option.</em></blockquote><h3>docker run</h3><p>If we follow hello-world suggestion, we could try docker run -it ubuntu bash</p><blockquote><em>-it are: </em><em>-i for interactive and </em><em>-t for tty allocation. Roughly enough, together they mean: </em><em>I want to run commands on that container now.</em></blockquote><p>It should gives a prompt similar to : root@0a7d78d198e1:/#</p><p>Exit to exit this ubuntu container and kill it.</p><h3>Containers cont.</h3><p>Let’s get deeper with container. We are going to use mongo for a quick tour on some docker concepts.</p><ul><li>docker run --name some-mongo -d mongo</li></ul><blockquote><em>We reviewed </em><em>--name earlier</em></blockquote><blockquote><em>-d means daemon. This will run the container in daemon mode and we wont get any output from it (except the id when the container is created)</em></blockquote><p>Now we can check with docker ps that our container is alive and running.</p><blockquote><em>Not every container will keep working on background if it is called with </em><em>-d flag. It needs to be set up like this. If they haven&#39;t , when We run them with </em><em>-d they will just die after being created (try </em><em>-d with an ubuntu container )</em></blockquote><h3>docker exec</h3><p>Our just created database can be accessed in a few ways but We will use one for now.</p><ul><li>docker exec -it some-mongo mongo</li></ul><blockquote><em>exec command is to run a command (in this case </em><em>mongo as in mongo client) in a specific live container (in this case </em><em>some-mongo)</em></blockquote><blockquote><em>Follow a few examples from </em><a href="https://www.mongodb.com/docs/manual/tutorial/getting-started/,"><em>https://www.mongodb.com/docs/manual/tutorial/getting-started/,</em></a><em> insert some data in a collection.</em></blockquote><ul><li>exit to exit the container. We can re enter our last docker command to get back at our database.</li></ul><p>Now we kill our daemon container. docker rm -f some-mongo</p><blockquote><em>We use </em><em>-f here since we cannot simple delete a living container. We should first </em><em>stop it and then </em><em>rm it.</em></blockquote><h3>docker volumes</h3><p>Now if we re run docker run --name some-mongo -d mongo and get inside our database again, We will see our previous insertions are gone.</p><p>This may no be the desired behavior with a database.</p><p>We have two ways of keeping our documents when we kill our daemon container but they need to be set up <em>before</em> running the daemon container.</p><p>The simplest is creating a docker volume. docker volume create mongodata.</p><p>A Volume is another player in the docker board but We won’t explain much. They don’t depend on the directory structure of the host machine and are managed entirely by docker instead.</p><p>Now with our new volume:</p><ul><li>docker run --name some-mongo -d -v mongodata:/data/db mongo</li></ul><blockquote><em>to use a volume we use the flag </em><em>-v followed by host volume:container path. We need to know before hand where does our database stores its information. For mongo in mongo container, it&#39;s </em><em>/data/db</em></blockquote><p>Now we can get inside, insert documents, exit, kill db container and check again if our data is there. Spoiler alert: <em>it will!</em></p><p>But there is also another way to achieve this which is discouraged for this kind of content (database data) but will come handy later.</p><h3>docker bind volumes</h3><p>Bind volumes are a specific directory on our host machine which will be bound to a directory in our container. If we keep using the same directory on each docker run of our database, we will achieve the same effect as with docker volumes.</p><ul><li>docker run --name some-mongo -d -v $PWD/mongodata:/data/db mongo</li></ul><blockquote><em>$PWD means our current directory. This will create a folder in our current directory called mongodata.</em></blockquote><p>With this, we can check the same steps we did in previous section.</p><h3>docker port</h3><p>Now, let’s say I’m developing an app and want to access my database. If it has a bind volume, does it means i can access those files ? NO! but if it’s isolated, how can i query its data from my app ?</p><p>We use another docker option called port. With this, we expose a container’s port and bind it to the host machine port.</p><ul><li>docker run --name some-mongo -d -v mongodata:/data/db -p 27015:27017 mongo</li></ul><blockquote><em>-p flag is followed by host port:container port</em></blockquote><p>Continue with a second part involving a bit more of docker images here <a href="https://gitlab.trinom.io/trinomio-blog-articles/docker-crash-course">https://gitlab.trinom.io/trinomio-blog-articles/docker-crash-course</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7de2dbafa4c7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trinomio/docker-crash-course-part-1-7de2dbafa4c7">Docker Crash Course Part 1</a> was originally published in <a href="https://medium.com/trinomio">Trinomio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[pre-commit git hook for code style checking]]></title>
            <link>https://medium.com/trinomio/pre-commit-git-hook-for-code-style-checking-6f71c38e9611?source=rss----beb65fed982d---4</link>
            <guid isPermaLink="false">https://medium.com/p/6f71c38e9611</guid>
            <category><![CDATA[pre-commit]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[flake8]]></category>
            <dc:creator><![CDATA[Federico Mieres]]></dc:creator>
            <pubDate>Fri, 03 Jun 2022 21:30:34 GMT</pubDate>
            <atom:updated>2022-06-03T21:30:33.969Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="terminal screenshot showing pre commit hook in action" src="https://cdn-images-1.medium.com/max/1024/1*Cr4G6NxsaZCIS8enzboZDQ.jpeg" /></figure><p>There are some projects where you’ll want to encourage your team to perform a static analysis or check before their code goes to the repository.</p><p>In this article, I would like to share a way to ease the struggle of performing some style checks before committing.</p><p>Have you ever rejected a MR because your peer started using camel case instead of snake case for functions out of the blue ? or someone forgot to remove the trailing commas after refactoring ?</p><p>To save these troubles a style check will take place right before committing. If the style checker says ‘no’, then your commit will fail.</p><p>First and foremost i strongly suggest your teams sit down and agree on some reasonable rules so that everybody’s code style don’t suffer too much.</p><p>This guide will use <a href="https://flake8.pycqa.org/en/latest/">Flake8</a> to check your code. And in order to attach our set of rules to git hooks, we will use <a href="https://pre-commit.com/">pre-commit</a> python library.</p><p>A sample Flake8 config file : .flake8</p><pre>[flake8]<br>per-file-ignores =<br>  tests/*: E501</pre><blockquote>Note: you don’t need any configuration file for flake. If there is no config file, it uses its default set of rules.</blockquote><p>So, we will write a pip installation file : requirements_dev.txt</p><pre>pre-commit<br>flake8</pre><p>Before continuing we need to install our new dependencies: pip install -r requirements_dev.txt</p><p>Then, we will write a pre-commit config file : .pre-commit-config.yaml</p><blockquote>Note: Adjust your watched folder in “files” property.</blockquote><p>Now that we have all config files properly set up, we will run the pre-commit command.</p><pre>$ pre-commit install<br>pre-commit installed at .git/hooks/pre-commit</pre><p>Now your commits won’t succeed unless Flake8 authorizes them.</p><p>We can check this change under the hood peeking inside .git/hooks. There you&#39;ll find a sample file for each hook git exposes. This time we are only interested in pre-commit hook so feel free to cat it and examine it.</p><p>Finally, let’s see it working!</p><p>I created a file $ cat app/non_pep8_compliant.py:</p><p>let’s git add it and then commit this changes :</p><pre>git commit -m flake8...................................................................Failed<br>- hook id: flake8 <br>- exit code: 1 <br>app/non_pep8_compliant.py:2:3: E111 indentation is not a multiple of 4<br>app/non_pep8_compliant.py:2:11: E201 whitespace after &#39;{&#39; <br>app/non_pep8_compliant.py:2:22: E203 whitespace before &#39;:&#39;<br>app/non_pep8_compliant.py:2:35: W292 no newline at end of file</pre><p>Flake won’t let me commit unless i fix this not styled code.</p><p>Well, i do hope this tool will help reduce your team’s stress at code reviewing time since now they can focus on the important parts!!</p><p>Repository with files included in this article: <a href="https://gitlab.trinom.io/trinomio-blog-articles/pre-commit-hook">https://gitlab.trinom.io/trinomio-blog-articles/pre-commit-hook</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f71c38e9611" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trinomio/pre-commit-git-hook-for-code-style-checking-6f71c38e9611">pre-commit git hook for code style checking</a> was originally published in <a href="https://medium.com/trinomio">Trinomio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Usando babel para compilar código a ECMA Script 6 en AngularJS.]]></title>
            <link>https://medium.com/trinomio/usando-babel-para-compilar-c%C3%B3digo-a-ecma-script-6-en-angularjs-65ecada0e1a?source=rss----beb65fed982d---4</link>
            <guid isPermaLink="false">https://medium.com/p/65ecada0e1a</guid>
            <category><![CDATA[babel]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[compilar]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Nicolas Martinez]]></dc:creator>
            <pubDate>Fri, 13 May 2022 18:22:30 GMT</pubDate>
            <atom:updated>2022-05-13T19:14:20.754Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*9DwWWs_t0D8B5Z0oOi8tLw.png" /></figure><p>Actualmente en Trinomio tenemos varios proyectos en funcionamiento que utilizan frameworks de Javascript como Vue o Angular. Uno de ellos utiliza AngularJS como framework base. Esto genera una larga lista de problemas a la hora de querer escribir código con formato<strong> ECMA Script 6</strong> ya que nativamente soporta hasta <strong>ECMA Script 5</strong>. Usualmente, estas tecnologías viejas suelen incluir un transpilador para poder soportar los últimos estandares, sin embargo este no es el caso de AngularJS. Debido a esto, es necesario hacer la transpilacion de forma manual utilizando Babel.</p><p>Una de las ventajas de utilizar un transpilador en AngularJS o en cualquier otro framework viejito es que nuestro código va a seguir funcionando en browsers antiguos debido a que su estructura seguirá estando en formato ES5 o en la forma que nosotros precisemos. Otra potencial ventaja, es que podríamos utilizar<strong> Typescript</strong> en lugar de Javascript (excelente noticia para los maniacos del tipado). En resumen, que transpilar nuestro código podría traernos muchas ventajas además de sumar algo a nuestro CV.</p><p>Todo muy lindo hasta acá, pero, ¡Vamos a ver que necesitamos!</p><p><strong>Requisitos:</strong></p><p>1 BabelJS: Esta de mas mencionarlo, pero para poder hacer la transpilacion necesitaremos un transpilador: Babel en este caso. Para instalarlo con npm podremos utilizar los siguientes comandos: npm install --save-dev babel-core babel-preset-env gulp-babel</p><p>2. GulpJS: Para este caso utilizaremos el automatizador de tareas gulp. Bien se podría utilizar cualquier otro, pero a efectos prácticos la idea sigue siendo la misma. Se puede instalar utilizando npm también: npm install gulp-cli -g y npm install gulp-D</p><p>3. (Opcional) Browser Sync: En este caso, nuestro proyecto utiliza browser sync para volcar los archivos al browser y mantener sincronizados los cambios. Para este ejemplo, no es necesario tenerlo.</p><h4><strong>Noción básica de cómo funciona Gulp</strong></h4><p>Si bien la documentación de Gulp es bastante completa, paso a explicar un poco algunas cosas básicas que necesitamos saber:</p><p>1 Gulp inicialmente necesita un archivo de nombre <strong><em>gulpfile.js</em></strong> donde escribiremos todas las tareas necesarias para correr, buildear y transpilar nuestro proyecto. Dicho archivo puede generarse de manera autumatica utilizando el comando <strong><em>gulp -f &lt;nombre de archivo&gt;</em></strong>. En este caso, la mayoría de blogs que leí indican que como nombre de archivo necesitaremos usar <strong><em>gulpfile.babel.js</em></strong> para decirle a gulp que vamos a utilizar babel. En mi caso no tuve necesidad de hacerlo, basto con utilizar el <em>gulpfile</em>, pero puede que ustedes lo necesiten.</p><p>2 Gulp ejecuta tareas, como cualquier automatizador de tareas. Podemos definir tareas importando el modulo de ‘gulp’ y utilizando la sintaxis <em>gulp.task(‘nombreDeLaTarea’, funcionACorrer(){ … })</em></p><p>3 Podemos ejecutar una tarea desde la consola utilizando el comando de cli: <em>gulp &lt;nombre de la tarea&gt;</em></p><h4><strong>¡A meter mano al codigo!</strong></h4><p><strong>1</strong> Inicialmente, en el directorio principal debemos tener nuestro archivo ‘gulpfile.js’ ya que es ahí adentro donde definiremos las tareas que necesitaremos para transpilar nuestro código. Adentro del ‘gulpfile’ incluiremos las siguientes líneas:</p><pre>var gulp = require(&#39;gulp&#39;);</pre><pre>var babel = require(&#39;gulp-babel&#39;);</pre><p><strong>2</strong> Debemos tener en claro que carpetas queremos que se transpilen para indicarle luego a babel:</p><pre>var carpetas = [&#39;./src/app/**/*.js&#39;]</pre><p><em>Notese como le estoy declarando que de TODOS los sub directorios del directorio app solo queremos transpilar los archivos de tipo .js.</em></p><p><strong>3</strong> Ahora debemos generar nuestra tarea de babel:</p><pre><strong><em>gulp</em></strong>.task(&#39;transpile&#39;, function () {<br>  return <strong><em>gulp</em></strong>.src(carpetas)<br>      .pipe(babel({ presets: [&quot;@babel/preset-env&quot;] })) //opcional<br>      .pipe(<strong><em>gulp</em></strong>.dest(&#39;src/assets/js&#39;));<br>});</pre><p><em>Note que yo decidí utilizar la carpeta assets para incluir el código transpilado y que le estoy indicando donde ponerlo con el comando ‘gulp.dest’, ustedes pueden utilizar la ubicación que quieran.</em></p><p><strong>4</strong> <strong>(Opcional)</strong> En caso de que se esté utilizando browser sync, deberan indicar claramente desde que carpeta deberá volcar los archivos .js a partir de ahora</p><pre>var injectScripts = <strong><em>gulp</em></strong>.src([<br>  path.join(conf.paths.src, &#39;/assets/js/**/*.module.js&#39;),<br>  path.join(conf.paths.src, &#39;/assets/js/**/*.js&#39;),<br>])<br>...<br>return <strong><em>gulp</em></strong>.src(path.join(conf.paths.src, &#39;/index.html&#39;))<br>  .pipe($.inject(injectScripts, injectOptions))<br>  .pipe(<strong><em>gulp</em></strong>.dest(path.join(conf.paths.tmp, &#39;/serve&#39;)));</pre><p>Acá existen dos cosas a notar: Por una parte estamos usando una dependencia llamada path solamente para mezclar el string que se encuentra en la config path.src, con el string que se le pasa como segundo parámetro a la función join, a efectos prácticos es lo mismo que utilizar una ruta como <em>‘src/assets/js/**/*.js’.</em></p><p>Por otra parte, notese que le estamos indicando a gulp a donde queremos que vuelque todos los archivos que acaba de inyectar utilizando otra vez el comando `gulp.dest(‘unPath)’`. Detrás de esto hay mucha mas lógica que se encarga de decirle a browser sync con que archivos queremos que inicie y, que cada vez que haya una actualización, vuelva a volcar los archivos, lógica que no es importante para el objetivo de este primer post.</p><p><strong>5</strong> Por ultimo, deberemos indicar donde queremos que se corra la tarea ‘transpile’. En mi caso, yo voy a correr la tarea cada vez que se hace un ‘inject’ debido a que quiero que cualquier cambio en el código principal se vea reflejado en el navegador:</p><pre><strong><em>gulp</em></strong>.task(&#39;inject&#39;, [&#39;transpile&#39;, ...], function () {...})</pre><p>De esta forma se le dice a gulp que cuando se corra la tarea ‘inject’, antes se corran las tareas en el array que se le paso como segundo parámetro. Ustedes pueden correr esta tarea como parte de otra tarea o desde la misma consola: <em>gulp transpile</em>. Para dar un ejemplo mas general de cómo correrlo en otra tarea, supongamos quiero usar una tarea default:</p><pre>gulp.task(&#39;default&#39;, [&#39;transpile’…]);</pre><p>De esta forma, todo el código principal será transpilado en el formato que hayamos indicado en la carpeta assets de nuestro proyecto. Luego, podremos utilizar este código para volcarlo en el browser en vez de volcar el código principal, o para cualquier otra cosa.</p><p>Y con eso ahora podremos disfrutar de todas las ventajas que ofrece ECMA Script 6 sin tener que temer por los browsers viejitos. En una segunda instancia de este post, explicare como utilizar browser sync con gulp para hacer nuestro desarrollo mucho mas dinámico y automatizado.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65ecada0e1a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trinomio/usando-babel-para-compilar-c%C3%B3digo-a-ecma-script-6-en-angularjs-65ecada0e1a">Usando babel para compilar código a ECMA Script 6 en AngularJS.</a> was originally published in <a href="https://medium.com/trinomio">Trinomio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Login automatico para Postgres en GCP IAM con SQLAlchemy]]></title>
            <link>https://medium.com/trinomio/login-automatico-para-postgres-en-gcp-iam-con-sqlalchemy-4e7c60f61fd1?source=rss----beb65fed982d---4</link>
            <guid isPermaLink="false">https://medium.com/p/4e7c60f61fd1</guid>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[ami]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sebastianariell]]></dc:creator>
            <pubDate>Fri, 29 Apr 2022 20:46:38 GMT</pubDate>
            <atom:updated>2022-04-29T21:19:02.628Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*aAPu8kqALj9VxA5oXec0UQ.png" /></figure><p>Asumiendo que ya está instalado el Google cloud SDK en el entorno en cuestión y ademas ya estas logueado tanto a nivel cuenta de google como aplicación, es decir los siguientes comandos:</p><ul><li>gcloud auth login</li><li>gcloud auth application-default login</li></ul><p>Para automatizar la conexion de una base de datos Postgres a través de GCP IAM tenemos que hacer lo siguientes pasos.</p><ol><li>Crear una funcion que devuelva un SQLAlchamy Engine:</li></ol><pre>import sqlalchemy</pre><pre>def init_connection_engine() -&gt; sqlalchemy.engine.Engine:<br>    def getconn() -&gt; pg8000.dbapi.Connection:<br>        conn: pg8000.dbapi.Connection = connector.connect(<br>            os.environ[&quot;POSTGRES_IAM_CONNECTION_NAME&quot;],<br>            &quot;pg8000&quot;,<br>            user=os.environ[&quot;POSTGRES_IAM_USER&quot;],<br>            db=os.environ[&quot;POSTGRES_DB&quot;],<br>            enable_iam_auth=True,<br>        )<br>        return conn<br><br>    engine = sqlalchemy.create_engine(<br>        &quot;postgresql+pg8000://&quot;,<br>        creator=getconn,<br>    )<br>    engine.dialect.description_encoding = None<br>    return engine</pre><p>2. Reemplazar el engine a la hora de crear la sesion por la funcion que se agregó anteriormente.</p><pre>import sqlalchemy<br>from sqlalchemy.ext.declarative import declarative_base<br>from sqlalchemy.orm import sessionmaker</pre><pre>engine = init_connection_engine()</pre><pre>Base = declarative_base()<br>session = sessionmaker(autocommit=False, autoflush=False, bind=engine)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e7c60f61fd1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trinomio/login-automatico-para-postgres-en-gcp-iam-con-sqlalchemy-4e7c60f61fd1">Login automatico para Postgres en GCP IAM con SQLAlchemy</a> was originally published in <a href="https://medium.com/trinomio">Trinomio</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>