<?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 Abraham Morales on Medium]]></title>
        <description><![CDATA[Stories by Abraham Morales on Medium]]></description>
        <link>https://medium.com/@abrahamntd?source=rss-a2ef37f4952a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qNSrpJlKV-MeME9U3djbNA.jpeg</url>
            <title>Stories by Abraham Morales on Medium</title>
            <link>https://medium.com/@abrahamntd?source=rss-a2ef37f4952a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 22:33:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abrahamntd/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[Code Review una visión integral]]></title>
            <link>https://abrahamntd.medium.com/code-review-revisi%C3%B3n-de-c%C3%B3digo-una-visi%C3%B3n-integral-y-pr%C3%A1ctica-f875a326ae11?source=rss-a2ef37f4952a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f875a326ae11</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[code-review]]></category>
            <dc:creator><![CDATA[Abraham Morales]]></dc:creator>
            <pubDate>Tue, 11 Nov 2025 00:23:15 GMT</pubDate>
            <atom:updated>2025-11-26T19:43:10.285Z</atom:updated>
            <content:encoded><![CDATA[<h3>Parte 1 Fundamentos</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*iju2PnZlD91Ufv0g_dGURg.png" /><figcaption>Etapas de la práctica del <strong>Code</strong> <strong>Review</strong></figcaption></figure><p>El <strong>Code Review</strong> sirve como un punto de <strong>control</strong> esencial en el ciclo de vida del desarrollo de software, ayudando a detectar y corregir <strong>vulnerabilidades</strong> de seguridad antes de la <strong>liberación</strong> del software.</p><p>En esta serie de artículos se aborda la práctica del <strong>Code Review</strong> (Revisión de Código), en tres partes con la intención de abordar:</p><ul><li><strong>Parte 1 Fundamentos</strong>: se explora la práctica del <strong>Code Review</strong> desde una perspectiva general tocando temas como: Definición, Importancia e Implementación.</li><li><strong>Parte 2 Caso práctico</strong>: se analiza un <strong>API</strong> desarrollada en <strong>Java</strong> utilizando herramientas <strong>open source</strong> así como haciendo uso de <strong>OWASP</strong> como marco de referencia.</li><li><strong>Parte 3 Mejores prácticas</strong>: se muestran las <strong>mejores prácticas</strong> así como <strong>recomendaciones</strong> generales.</li></ul><p>Los elementos mostrados como parte de los ejemplos no representan un esquema nivel producción, estos han sido simplificados con la finalidad de facilitar el entendimiento de los conceptos presentados.</p><p>Las definiciones y conceptos manejados en el presente documento son expresados de forma informal para facilitar su entendimiento sin perder por ello rigor o veracidad.</p><h3>Introducción</h3><p><strong>Vulnerabilidad</strong> Debilidad en un sistema, procedimiento o control interno que puede ser explotada por amenazas para comprometer la <strong>seguridad</strong>.</p><p><strong>SCA</strong> (<strong>Software</strong> <strong>Composition</strong> <strong>Analysis</strong>) <strong>Análisis de composición de software</strong>. Identifica componentes de terceros (como librerías open source) en el código, detectando <strong>vulnerabilidades conocidas</strong>, licencias inseguras o <strong>dependencias obsoletas</strong>.</p><p><strong>SAST</strong> (<strong>Static Application Security Testing</strong>) <strong>Análisis estático de seguridad de aplicaciones</strong>. Examina el <strong>código</strong> fuente o compilado <strong>sin ejecutarlo</strong>, para detectar <strong>vulnerabilidades</strong> como inyecciones, errores de validación o <strong>exposición de secretos</strong>.</p><p>El <strong>Code Review</strong> (<strong>Revisión de Código</strong>) es una técnica de análisis del código fuente de una aplicación, con el fin de detectar <strong>vulnerabilidades</strong> de <strong>seguridad</strong>, <strong>errores</strong> de <strong>lógica</strong>, <strong>configuraciones</strong> <strong>inseguras</strong> y <strong>desviaciones</strong> de estándares de codificación segura.</p><p>Algunos de los beneficios de implementar un <strong>Code Review </strong>son:</p><ul><li>Al identificar vulnerabilidades en las primeras etapas del desarrollo, los desarrolladores pueden corregirlas rápidamente, previniendo así posibles ataques.</li><li>Las revisiones de código seguro ayudan a mantener la calidad del código, ya que promueven buenas prácticas de codificación.</li><li>Cuando los desarrolladores participan regularmente en las revisiones de código, son más conscientes de las implicaciones de seguridad de su código.</li></ul><h3><strong>Implementación</strong></h3><p>Realizar un <strong>Code Review</strong> no es una actividad única, sino un proceso continuo que de forma general se puede conformar por las siguientes etapas:</p><ol><li>Especificación</li><li>Ejecución</li><li>Remediación y seguimiento</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*iju2PnZlD91Ufv0g_dGURg.png" /><figcaption>Etapas de la práctica del <strong>Code</strong> <strong>Review</strong></figcaption></figure><h3>1 Especificación</h3><p>En esta etapa se definen los lineamientos y el alcance del <strong>Code Review</strong>, estableciendo entre otras cosas:</p><p>a). Marcos de referencia</p><p>b). Procedimientos y políticas internas</p><p>c). Actores y responsabilidades</p><p>d). Herramientas</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*MYgroYa0lN80ViQo7KpPRQ.png" /><figcaption>Elementos mínimos de los lineamientos</figcaption></figure><p><strong>a) Marcos de referencia.</strong></p><p>Comprende todos aquellas <strong>normas</strong> y <strong>publicaciones</strong> que puedan ser utilizadas como guía para efectuar la práctica, se suele especificar en qué casos se puede utilizar así como las principales áreas de interés.</p><p><strong>— Por ejemplo</strong> en esta parte se especifica si se usara <a href="https://owasp.org/www-project-code-review-guide/">OWASP Code Review Gide</a> como referencia y que la <strong>estrategia de ramas</strong> a utilizar sera <strong>Gitflow</strong>.</p><p><strong>b) Procedimientos internos.</strong></p><p>Se en listan los procedimientos internos para la práctica que determinan cuándo se realizará y cuáles son los pasos a seguir.</p><p><strong>— Por ejemplo</strong> en esta parte se especifica que el <strong>Code Review</strong> se realizara después de crear un <strong>Merge</strong> <strong>Request </strong>y una vez que el <strong>pipeline</strong> sea exitoso.</p><p><strong>c) Herramientas.</strong></p><p>Se definen las herramientas a ser utilizadas con la finalidad de llevar acabo los análisis estáticos del código.</p><p><strong>— Por ejemplo </strong>en esta parte se especifica que se utilizara <a href="https://www.sonarsource.com/es/">SonarQube</a> para el análisis de <strong>code</strong> <strong>smell</strong> y <strong>cobertura</strong> en <strong>pruebas unitarias</strong>, <a href="https://owasp.org/www-project-dependency-check/">Dependecy-Check</a> para el análisis de composición <strong>SCA </strong>de software y <a href="https://spotbugs.github.io/">SpotBugs</a> para el análisis de seguridad estático <strong>SAST</strong>.</p><p><strong>d) Actores y responsabilidades.</strong></p><p>Se determina quienes participan en cada una de las acciones así como las responsabilidades.</p><p><strong>— Por ejemplo </strong>en esta parte se especifica que el <strong>desarrollador</strong> creara un <strong>Merge</strong> <strong>Request </strong>y avisara a su <strong>líder técnico</strong> para que ambos lleven acabo el <strong>Code Review.</strong></p><h3>2 Ejecución</h3><p>En esta etapa se basa en los lineamientos establecidos en la etapa anterior y suele esta conformada por las siguientes partes:</p><p>a) Proceso inicial.</p><p>b) Análisis automático.</p><p>c) Revisión entre pares.</p><p><strong>a) Proceso inicial.</strong></p><p>Este proceso está relacionado a la <strong>estrategia de ramas</strong> así como a las validaciones que establezcan los <strong>lineamientos</strong>.</p><p><strong>— Por ejemplo</strong> este proceso seguiría el siguiente flujo:</p><ul><li>El <strong>desarrollador</strong> termina de codificar la funcionalidad.</li><li>El <strong>desarrollador</strong> verifica que todas las <strong>pruebas unitarias</strong> pasen.</li><li>El <strong>desarrollador</strong> ejecuta los análisis estáticos (<strong>SCA</strong>, <strong>SAST</strong>, <strong>Linter</strong>) de forma local.</li><li>Genera un <strong>Merge</strong> <strong>Request</strong> de acuerdo a la <strong>estrategia de ramas</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*Q5G_riYqOaTrAL9oHS_6gQ.png" /><figcaption>Proceso inicial (codificación terminada)</figcaption></figure><p><strong>b) Análisis automático</strong></p><p>En función de la <strong>estrategia de ramas</strong> vigente, se ejecutan las validaciones que establezcan los <strong>lineamientos.</strong></p><p><strong>— Por ejemplo</strong> este proceso suele ser ejecutado por un <strong>pipeline</strong> el cual realiza las siguientes tareas de forma controlada:</p><ul><li>Ejecución de pruebas unitarias</li><li><strong>Análisis de composición de software SCA</strong> utilizando las herramientas especificadas en los <strong>lineamientos </strong>(<a href="https://owasp.org/www-project-dependency-check/">Dependecy-Check</a>).</li><li><strong>Análisis estático de seguridad</strong> <strong>SAST</strong> utilizando las herramientas especificadas en los <strong>lineamientos </strong>(<a href="https://spotbugs.github.io/">SpotBugs</a>).</li><li><strong>Análisis estático de código Linter</strong> utilizando las herramientas especificadas en los <strong>lineamientos </strong>(<a href="https://www.sonarsource.com/es/">SonarQube</a>).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*gLOwn7Zv4Lc7COFL2ngwFw.png" /><figcaption>Revisión automatizada (Análisis automático)</figcaption></figure><p><strong>c) Revisión entre pares</strong></p><p>En esta etapa se reúnen los actores especificados en los <strong>lineamientos</strong> para tener una <strong>platica significativa</strong> en donde revisan los <strong>reportes</strong> de las herramientas así como el <strong>código</strong> modificado.</p><p><strong>— Por ejemplo </strong>en esta parte se suelen llevar acabo las siguientes actividades:</p><ul><li>El <strong>desarrollador</strong> y <strong>líder</strong> <strong>técnico</strong> revisan que el <strong>pipeline</strong> sea exitoso y que los reportes de las herramientas no muestren <strong>problemas</strong>.</li><li>El <strong>líder</strong> <strong>técnico</strong> verifica junto al <strong>desarrollador</strong> el <strong>código</strong> modificado con la finalidad de determinar si cumple con los <strong>estándares</strong> requeridos así como si se <strong>implemento</strong> la <strong>funcionalidad</strong> requerida.</li><li>El <strong>líder</strong> <strong>técnico </strong>realiza comentarios con las <strong>observaciones</strong> encontradas para que el <strong>desarrollador</strong> pueda realizar las <strong>correcciones</strong> pertinentes.</li><li>En función de los hallazgos y las correcciones se <strong>determina</strong> si dicho <strong>código</strong> puede o no ser integrado para faces posteriores (pruebas automatizadas y manuales).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*6BLtVlvNKWPxOEzRn0v1xg.png" /><figcaption>Revisión manual entre pares</figcaption></figure><h3>3 Remediación y seguimiento</h3><p>Terminada la revisión entre pares, se procede a clasificar los hallazgos que aún están presentes siguiendo los lineamientos vigentes, para acomodar el plan de acción.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*d4pt_4vYIxwI1xx7S5_oXg.png" /><figcaption>Proceso base para <strong>Seguimiento</strong> y <strong>Remediación</strong></figcaption></figure><p>a) Clasificación de los hallazgos</p><p>b) Planificación</p><p>c) Seguimiento</p><p><strong>a) Clasificación de los hallazgos</strong></p><p>En esta etapa con base en los lineamientos se clasifican los hallazgos en función de su severidad.</p><p><strong>— Por ejemplo </strong>en esta etapa el líder técnico genera una lista con los hallazgos que no se han resuelto indicando la severidad del hallazgo y y la posible acción de mitigación.</p><p><strong>b) Planificación</strong></p><p>Terminada la clasificación de los hallazgos se determina cuando, como y quién realizará las acciones de mitigación así como la verificación de las mismas.</p><p><strong>— Por ejemplo </strong>en esta etapa se agrupan los hallazgos de menor severidad y se integran al plan de mitigación de deuda técnica y los hallazgos de mayor severidad se integran al spring actual para ser atendido por los desarrolladores.</p><p><strong>c) Seguimiento</strong></p><p>Con base en el plan anterior mente creado se da seguimiento a la mitigación de los hallazgos.</p><p><strong>— Por ejemplo El líder técnico junto con el equipo realiza una revisión del plan de mitigación de deuda técnica al inicio de cada spring para determinar que incorporar al spring.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f875a326ae11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TDD About Behavior and Design]]></title>
            <link>https://abrahamntd.medium.com/tdd-about-behavior-and-design-96c82ae37a8f?source=rss-a2ef37f4952a------2</link>
            <guid isPermaLink="false">https://medium.com/p/96c82ae37a8f</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Abraham Morales]]></dc:creator>
            <pubDate>Mon, 25 Nov 2024 09:19:44 GMT</pubDate>
            <atom:updated>2025-11-26T20:57:37.752Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*6_ZRdD4pRJksyb69o52hAw.png" /></figure><p>I have been involved in several projects where the development team had the highest <strong>code coverage</strong> on <strong>Unit Tests</strong> as a goal and used <strong>TDD</strong> to reach it; this is a common <strong>misconception</strong> about <strong>TDD</strong> and the <strong>code coverage</strong> for <strong>Unit Tests</strong>.</p><p>This article will focus on <strong>TDD</strong> as a design technique rather than a testing strategy and why relying on <strong>code coverage</strong> for <strong>Unit Tests</strong> as a quality gate is a bad idea.</p><p>This article doesn’t cover how <strong>Unit Tests</strong> are implemented.</p><h4>Code coverage is not a silver bullet</h4><p><strong>Code coverage</strong> is a <strong>metric</strong> that helps us to understand <strong>how much of the code is tested</strong>, for example, it measures the <strong>amount</strong> of <strong>code</strong> that is <strong>run</strong> by <strong>Unit Tests</strong> either lines, branches, or methods.</p><p>Relying on <strong>code coverage</strong> can give a <strong>false</strong> sense of security that the code has been <strong>tested</strong> and it <strong>works</strong>, but in fact, having a high <strong>code coverage</strong> on <strong>Unit Tests</strong> only shows that it has <strong>Unit Tests</strong>.</p><p><strong>Code coverage</strong> is a useful tool for <strong>finding</strong> <strong>untested</strong> parts of a code then:</p><ul><li>If the <strong>code coverage</strong> is <strong>low</strong>, it <strong>gives</strong> you information about where to test.</li><li>If the <strong>code coverage</strong> is <strong>high</strong> it <strong>doesn’t</strong> give you any information.</li></ul><h4>Well-designed code is easy to: Change, Use, and Test</h4><p>Great code is easy to use and change, because it defines the <strong>inputs</strong> and the expected <strong>outcomes</strong> in a way that <strong>hides</strong> the <strong>implementation</strong>, so we could say it has a well-defined <strong>interface</strong> to interact with.</p><p>This <strong>interface</strong> makes the code easy to test because it allows us to test the behavior no matter what is the implementation.</p><p><strong>Unit Tests</strong> are a great tool to ensure that the code works and is well-designed, but they must be implemented <strong>before</strong> the code is written and <strong>drive</strong> the design, rather than after the code is written and only for the <strong>code coverage</strong> number.</p><blockquote><strong>Tests</strong> should be <strong>coupled</strong> to the <strong>behavior</strong> of code and <strong>decoupled</strong> from the <strong>structure</strong> of code. — <a href="https://medium.com/@kentbeck_7670/test-desiderata-94150638a4b3"><strong>Kent Beck</strong></a></blockquote><p>A good <strong>Unit Test</strong> expresses the expected <strong>behavior</strong> never a specific implementation, therefore as long as the <strong>behavior</strong> and the design don’t change the test will remain valid even if the implementation changes.</p><p>The system under test can be validated at the <strong>Unit Test</strong> level, testing the following:</p><ul><li>Testing the direct <strong>outcome (return value)</strong>.</li><li>Testing how the <strong>stage</strong> has changed.</li><li>Testing the <strong>interactions</strong> between different software units.</li></ul><blockquote><strong>Test-Driven Development</strong> (<strong>TDD</strong>) is a technique for building software that guides software development by writing tests. — <a href="https://martinfowler.com/bliki/TestDrivenDevelopment.html"><strong>Martin Fowler</strong></a></blockquote><p>There are two main styles of <strong>TDD</strong> the <strong>London</strong> school and the <strong>Chicago </strong>school:</p><ul><li>The <strong>London</strong> school or <strong>Top Down</strong> style, is distinguished by providing a <strong>behavior-based</strong> approach to <strong>TDD</strong> that begins outside of the application and works its way down to the model. In this style, the main focus is on testing the <strong>interactions</strong> using <strong>test doubles</strong>.</li><li>The <strong>Chicago</strong> school or <strong>Bottom Up</strong> style, is distinguished by providing a <strong>low-level </strong>approach to <strong>TDD</strong> that begins designing the <strong>inner</strong> parts of the application. In this style, the <strong>main</strong> focus is on testing the <strong>state</strong> changes and the <strong>return</strong> value.</li></ul><p><strong>TDD</strong> practice could benefit from both <strong>London</strong> and <strong>Chicago</strong> styles.</p><h4>TDD as a design method</h4><p>Designing software from the <strong>TDD</strong> perspective involves considering how the software works from the user’s perspective, making the <strong>Test</strong> <strong>first</strong> as a way of expressing the <strong>design</strong> <strong>decision</strong>.</p><p>When using <strong>TDD</strong> as a design method it must follow:</p><ul><li>Work incrementally in small steps.</li><li>Starts defining the problem, not the solutions.</li><li>A simple Test reflects a good design.</li><li>Writing the Test is making decisions about the <strong>interface</strong>, not about the implementation.</li><li>If using a <strong>Test</strong> <strong>double</strong>, it must be as <strong>simple</strong> as possible.</li></ul><p>Remember, as a side effect, <strong>TDD</strong> produces <strong>Unit Tests</strong> during the design, but it isn’t the main goal.</p><h4>Basic TDD workflow</h4><p>The TDD flow consists of the following steps, where as long as the list of scenarios is not empty, you will return to step 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*nvk4b31MKOlMTGvX-QmOtA.png" /><figcaption>TDD Workflow</figcaption></figure><p>Given a system and a change in its behavior (<strong>new functionality</strong>), the <strong>first</strong> <strong>activity</strong> in <strong>TDD</strong> is to <strong>list</strong> all the <strong>variations</strong> in that <strong>behavior</strong>.</p><p>This activity consists of <strong>analyzing</strong> the desired <strong>behavior</strong> of the system in terms of <strong>what it should</strong> and <strong>should not do</strong>, <strong>excluding</strong> <strong>how</strong> it will do it.</p><p>The <strong>result</strong> of this activity is a <strong>list</strong> of <strong>tests</strong> that verify that the new <strong>behavior</strong> is <strong>implemented</strong>.</p><p>The <strong>second</strong> activity in <strong>TDD</strong> consists of the <strong>Red</strong>, <strong>Blue</strong>, and <strong>Green</strong> phases.</p><p>There are two activities that are very important to perform separately:</p><ul><li>Defining how a specific behavior or functionality is invoked (<strong>Red</strong> phase).</li><li>Defining how the system implements a specific functionality or behavior (<strong>Blue</strong> phase).</li></ul><p>These activities should never be mixed or performed simultaneously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*do1LZ2_0Ymkm4oiYAxTEVA.png" /><figcaption>red, green, and blue phases of TDD</figcaption></figure><p>At this point, <strong>one</strong> item from the <strong>list</strong> is selected to be coded as an <strong>automated</strong> <strong>test</strong>.</p><p>The <strong>automated</strong> <strong>test</strong> must <strong>validate</strong> the previously <strong>defined behavior</strong> by implementing some type of <strong>comparison</strong>. <strong>Writing</strong> the <strong>test</strong> is a <strong>design</strong> exercise in which the <strong>system</strong>’s <strong>interface</strong> is <strong>defined</strong>, <strong>but not how it is implemented</strong>.</p><p>In other words, it <strong>specifies</strong> <strong>how</strong> the <strong>functionality</strong> will be <strong>invoked</strong>, what type of <strong>parameters</strong> it receives, and what values ​​it <strong>returns</strong>.</p><p>At this point (<strong>Red</strong> phase), any of the following types of tests can be written:</p><ul><li>Tests that <strong>validate</strong> the value <strong>returned</strong> by the system given certain <strong>parameters</strong> and <strong>initial</strong> <strong>conditions</strong>.</li><li>Tests that <strong>validate</strong> the <strong>change</strong> in the system’s <strong>state</strong> after <strong>invoking</strong> the new functionality.</li><li>Tests that <strong>validate</strong> the <strong>interaction</strong> between system <strong>elements</strong>.</li></ul><p>At this point, any type of test coded <strong>should</strong> <strong>fail</strong>, since the <strong>new functionality has not yet been implemented</strong> and the <strong>existing</strong> tests <strong>must</strong> <strong>still</strong> <strong>pass</strong>.</p><p>At this point (<strong>Blue</strong> phase), based on the previously <strong>coded test</strong>, the <strong>new</strong> <strong>functionality</strong> is <strong>implemented</strong> <strong>following</strong> the <strong>design decisions</strong> made (the <strong>interface defined in the previous step</strong>).</p><p>When <strong>all tests are</strong> <strong>successful</strong>, the next step (<strong>Green</strong> phase) is to <strong>refactor</strong> the <strong>code that was added</strong> to pass the test. This activity is about <strong>improving the design, not implementing new functionality.</strong> In other words, refactoring is changing the implementation without changing the system’s behavior.</p><p>The Red Blue Green phases must be executed for every item of the list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*6_ZRdD4pRJksyb69o52hAw.png" /></figure><p>The core of <strong>TDD</strong> consists of the <strong>Red</strong>, <strong>Green</strong>, and <strong>Blue</strong> phases, however, writing the <strong>list of test cases</strong> based on the requirement is an <strong>important</strong> <strong>design</strong> <strong>decision</strong>, as this activity involves <strong>understanding the new behavior</strong> that needs to be implemented.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96c82ae37a8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing the Security of Your Docker Workflow]]></title>
            <link>https://medium.com/globant/enhancing-the-security-of-your-docker-workflow-f716d68ea170?source=rss-a2ef37f4952a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f716d68ea170</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Abraham Morales]]></dc:creator>
            <pubDate>Fri, 19 May 2023 16:45:10 GMT</pubDate>
            <atom:updated>2023-05-19T16:45:10.174Z</atom:updated>
            <content:encoded><![CDATA[<h4>Essential tools and practices for safeguarding containerized applications</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8CM4-QX6exUU2Tzw" /></figure><p>According to Dynatrace 2022 CISO Research<a href="https://www.dynatrace.com/info/ciso-report/"> Report</a> and Aqua Security 2021 Cloud Security<a href="https://info.aquasec.com/cspm-threat?_ga=2.220992984.1939142680.1681530048-558655997.1681077675&amp;_gl=1*1you3i3*_ga*NTU4NjU1OTk3LjE2ODEwNzc2NzU.*_ga_D2G99SQ9HG*MTY4MTUzMDA0Ni4yLjEuMTY4MTUzMzMzNC42MC4wLjA"> Report</a>, almost 50% of the deployed containers present security vulnerabilities due to misconfigurations and bad practices.</p><p><em>Container Security</em> is the process of implementing a security and compliance feature in all the stages of a container’s lifecycle. The security aspects include base images, the Dockerfile, the container runtime, and securing the Docker daemon.</p><p>In this article, we will focus on scanning the Dockerfile and the Docker image for secret leaks and common bad practices. We will show how to validate best practices for the Dockerfile (code linter) and how to scan Docker images for known vulnerabilities (vulnerability image scanner) and possible secret leaks (secret scanner).</p><p>The prerequisites are basic Docker knowledge, Docker CLI installed, and building and running containers. All the code shown here has been tested on a macOS environment but can be easily adapted to a Windows environment or Linux.</p><h3>Hadolint: Code Linter</h3><p>Code Linters aim to make your Dockerfiles compliant with the image-building best practices suggested by Docker. The one we are using is an open-source tool named <a href="https://github.com/hadolint/hadolint">Hadolint</a>.</p><p>This tool automates the detection of Dockerfile issues. This helps your Docker images adhere to best practices and organizational standards.</p><p>The product can be downloaded like precompiled OSX, Windows, and Linux binaries. However, most of the time it is easy just to run it from a Docker container. Complete installation instructions can be found on the<a href="https://github.com/hadolint/hadolint"> Hadolint</a> main page, but for example, you can use <a href="https://brew.sh/">Brew</a> on OSX.</p><pre>brew install hadolint</pre><p>To scan your Dockerfile using the precompiled binaries, just run:</p><pre>hadolint Dockerfile</pre><p>To analyze your Dockerfile with Hadolint Docker distribution, run the following command:</p><pre>docker run - rm -i hadolint/hadolint Dockerfile</pre><p>Let’s take as an example the following Dockerfile:</p><pre>FROM python<br>LABEL maintainer=&quot;agmc22mx@gmail.com&quot;<br><br>RUN apt-get update<br>RUN apt-get install curl<br>RUN apt-get install -y python3<br>RUN apt-get install -y python3-pip<br>RUN pip3 install pyyaml<br>RUN mkdir app &amp;&amp; cd app<br><br>COPY testing.py ./<br>CMD python testing.py</pre><p>After scanning the Dockerfile, you will see a list of all violation rules and their severity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G6ssRDNHOrMTIPJy17UivA.png" /><figcaption>Generated output after running the scan</figcaption></figure><p>Rules are identified as numbers prefixed with either <em>HL</em> or <em>SC</em>. <em>HL</em> rules are part of <a href="https://github.com/hadolint/hadolint">Hadolint</a>, whereas <em>SC</em> entries come from <a href="https://github.com/koalaman/shellcheck">ShellCheck</a>. Each check is given a severity from <em>Error</em> through to <em>Info</em>. A list of rules can be found on the<a href="https://github.com/hadolint/hadolint"> Hadolint</a> page, and best practices for writing Dockerfiles are<a href="https://docs.docker.com/develop/develop-images/dockerfile_best-practices/"> here</a>.</p><p>Hadolint can be configured through command line parameters, adding comments to the Dockerfile, and using a configuration file. You can pass a custom configuration file in the command line with the--config option.</p><p>Configuration files are written in YML format and look like this:</p><pre>override:<br> error:<br>   - DL3009<br> info:<br>   - DL3006<br>label-schema:<br> maintainer: text<br> version: url<br>strict-labels: true</pre><p>Scanning a Dockerfile using this configuration file is as simple as running:</p><pre>hadolint --config hadolint.yaml Dockerfile</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QSAj53Dqt7hOi9hq8C5rdw.png" /><figcaption>Generated output after running the scan using a configuration file</figcaption></figure><p>When running the scan using the configuration file, we can see, for example, that the rule DL3009 has changed from info to error level.</p><p>To fix bugs on the Dockerfile, we will make the following changes:</p><ul><li>Add version to the base image.</li><li>Add version label.</li><li>Set WORKDIR before copying files to a relative destination.</li><li>Consolidate RUN statement.</li><li>Use arguments JSON notations for CMD and ENTRYPOINT arguments.</li></ul><pre>FROM python:3.10<br>LABEL maintainer=&quot;agmc22mx@gmail.com&quot;<br>LABEL version=&quot;1.0&quot;<br><br>WORKDIR /app<br>RUN apt-get update<br># hadolint ignore=DL3008<br>RUN apt-get install -y curl install -y python3 python3-pip &amp;&amp; pip3 install --no-cache-dir pyyaml==1.1<br>COPY testing.py ./<br>CMD [&quot;python&quot;, &quot;testing.py&quot;]</pre><p>After fixing the bugs on the Dockerfile, we will see a cleaner output if we rerun the scan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xrB8HiUSW5spI4uOACGZJQ.png" /><figcaption>Scanner Output after fixing the Dockerfile.</figcaption></figure><h4>Output Formats</h4><p>Several output formats are supported; just use the -format flag. The default is tty which emits colorized output to your terminal. Colors can be disabled using the -no-colorflag.</p><p>The following alternative formats are available:</p><ul><li>json: formats the output into a JSON with a list of detected issues</li><li>checkstyle: formats the output into a <a href="https://checkstyle.sourceforge.io/">Checkstyle</a>-compatible format.</li><li>codeclimate: formats the output into a <a href="https://codeclimate.com/">Code Climate</a> compatible format.</li><li>gitlab_codeclimate: formats the output into a report compatible with <a href="https://docs.gitlab.com/ee/ci/testing/code_quality.html">GitLab’s</a> integrated code quality.</li></ul><p>So to format the output, we can run hadolint -format &lt;the_format&gt; Dockerfile; for example:</p><pre>hadolint --format json  Dockerfile</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PHtcZCTwKlBDqbp6wgXwQw.png" /><figcaption>Formatting output to JSON</figcaption></figure><h3>Grype: Static Image Vulnerability Scanning</h3><p>Image scanning works by parsing through the container image file, and then it is compared to public security vulnerability databases to see if any known vulnerabilities exist. The one we are using is an open-source tool named<a href="https://github.com/anchore/grype"> Grype</a>.</p><p><a href="https://github.com/anchore/grype">Grype</a> is an open-source vulnerability scanner for container images and filesystems managed by security company<a href="https://anchore.com/"> Anchore</a>; it can be downloaded and installed for OSX and Linux or built directly from sources. Complete installation instructions can be found on the<a href="https://github.com/anchore/grype"> Grype</a> main page, but for example, on OSX, you can use <a href="https://brew.sh/">Brew</a> to install <a href="https://github.com/anchore/grype">Grype</a>:</p><pre>brew tap anchore/grype<br>brew install grype</pre><p>To scan a Docker image after building it, run the following:</p><pre>docker build -t abrahamntd/basic-python:latest .<br>grype abrahamntd/basic-python:latest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iDKQrIJtBJlrRTYx19SOuw.png" /><figcaption>Generated output after running the scanning image</figcaption></figure><p>The above command scans for vulnerabilities in the container. Each package scanned within an image will be listed, and the output includes the following:</p><ul><li>NAME: Name of the package.</li><li>INSTALLED: Version number installed in the image.</li><li>TYPE: Type of package</li><li>SEVERITY: Severity for each vulnerability.</li></ul><p>The generated output from the scanner can be presented in different formats:</p><ul><li>table: Default format (basically a table).</li><li>cyclonedx: XML report compatible with the <a href="https://cyclonedx.org/specification/overview/">CycloneDX</a> 1.2 specification.</li><li>json: A JSON object containing detailed information.</li><li>template: This option allows us to specify the output format using Gotemplates.</li></ul><p>For example:</p><pre>grype abrahamntd/basic-python:latest -o json</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bjUVrzzPp5Aefb6Y09BWIg.png" /><figcaption>Formatting output to JSON</figcaption></figure><p>When <a href="https://github.com/anchore/grype">Grype</a> performs a scan for vulnerabilities, it does, using a vulnerability database. This database is stored on your local filesystem. By default, <a href="https://github.com/anchore/grype">Grype</a> automatically manages this database and checks for updates to be sure that every scan uses up-to-date vulnerability information.</p><h3>SecretScanner: Standalone secrets scanner</h3><p>Secrets are sensitive pieces of information such as credentials, SSH keys, tokens, and TLS certificates. These should not be baked into Docker images without being encrypted since unauthorized users can extract the secrets from the image by examining the layers, for example.</p><p>One of the most common mistakes is leaking Secrets via Docker images or the file system. We will use an open-source secret scanner named<a href="https://github.com/deepfence/SecretScanner"> SecretScanner</a> from <a href="https://deepfence.io/">Deepfence</a> to identify the secret on our container images. It will help us to detect when we are leaking Secrets through the Docker images. According to their official documentation:</p><blockquote>SecretScanner can finds unprotected secrets in container images or file systems.</blockquote><blockquote><a href="https://github.com/deepfence/SecretScanner">SecretScanner is a standalone tool that retrieves and searches container and host filesystems, matching the contents against a database of approximately 140 secret types</a>.</blockquote><p>Let’s introduce some secrets to our Dockerfile and run the scanner:</p><pre>FROM python<br>LABEL maintainer=&quot;agmc22mx@gmail.com&quot;RUN apt-get update<br>RUN apt-get install curl<br>RUN apt-get install -y python3<br>RUN apt-get install -y python3-pip<br>RUN pip3 install pyyaml<br>RUN mkdir app &amp;&amp; cd appCOPY testing.py ./<br>COPY id_ssh id_ssh<br>COPY id_ssh.pub id_ssh.pub<br>ENV DATABASE_PASSWORD &quot;my_password&quot;<br>CMD python testing.py</pre><p>Let’s build the Docker image and then scan it to detect possible secret leaks. To build the image, run the following command:</p><pre>docker build -t abrahamntd/basic-python:latest .</pre><p>Now, scan the Docker Image using the Docker distribution of SecretScanner, and run the following command:</p><pre>docker run -it --rm -v $(pwd):/home/deepfence/output -v /var/run/docker.sock:/var/run/docker.sock deepfenceio/deepfence_secret_scanner:latest -image-name abrahamntd/basic-python:latest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EpnF7NPnmWphaIAZa5S23A.png" /><figcaption>Output from the scanner shows the secret that was found</figcaption></figure><p>The report includes information like the Image Lager IDand Matched Rule Namethat describes the secret it’s detected and also provides Severity, Severity Score, and Matched Contents.</p><h3>Conclusion</h3><p>In this article, we have explored three tools that can enhance the security of Docker containers and address common issues. Misconfigured Docker containers can lead to sluggish performance, excessive resource usage, and challenging maintenance. To mitigate these problems, we discussed the utilization of three specific tools.</p><p>Firstly, <a href="https://github.com/hadolint/hadolint">Hadolint</a> enables the scanning of Dockerfiles, ensuring adherence to best practices and avoiding common mistakes. Secondly, <a href="https://github.com/anchore/grype">Grype</a> facilitates scanning Docker images to identify any known vulnerabilities. Lastly, we explored the utilization of <a href="https://github.com/deepfence/SecretScanner">deepfence/SecretScanner</a>, which aids in detecting secret leaks.</p><p>By incorporating these tools into your Docker processes, you can bolster security and maintain a more efficient and secure container environment.</p><p>You can check the source code for this article <a href="https://github.com/abrahamNtd/poc-docker-security.git">here</a>.</p><h3>References</h3><ul><li><a href="https://github.com/hadolint/hadolint">Hadolint</a></li><li><a href="https://hub.docker.com/r/hadolint/hadolint">Hadolint</a> Docker image</li><li><a href="https://github.com/anchore/grype">Grype</a></li><li><a href="https://hub.docker.com/r/anchore/grype">Grype</a> Docker image</li><li><a href="https://cheatsheetseries.owasp.org/cheatsheets/Docker_Security_Cheat_Sheet.html">Docker Security Cheat Sheet</a></li><li><a href="https://github.com/deepfence/SecretScanner">deepfence/SecretScanner</a></li><li><a href="https://registry.hub.docker.com/r/deepfenceio/deepfence_secret_scanner">deepfence/SecretScanner</a> Docker image</li><li><a href="https://www.dynatrace.com/info/ciso-report/">Dynatrace 2022 CISO Research Report</a>.</li><li><a href="https://info.aquasec.com/cspm-threat?_ga=2.220992984.1939142680.1681530048-558655997.1681077675&amp;_gl=1*1you3i3*_ga*NTU4NjU1OTk3LjE2ODEwNzc2NzU.*_ga_D2G99SQ9HG*MTY4MTUzMDA0Ni4yLjEuMTY4MTUzMzMzNC42MC4wLjA">Aqua Security 2021 Cloud Security Report</a>: Cloud Configuration Risks Exposed.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f716d68ea170" width="1" height="1" alt=""><hr><p><a href="https://medium.com/globant/enhancing-the-security-of-your-docker-workflow-f716d68ea170">Enhancing the Security of Your Docker Workflow</a> was originally published in <a href="https://medium.com/globant">Globant</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatizando la Instalación y Configuración de Jenkins usando Docker y Configuración como Código]]></title>
            <link>https://abrahamntd.medium.com/automatizando-la-instalaci%C3%B3n-y-configuraci%C3%B3n-de-jenkins-usando-docker-y-configuraci%C3%B3n-como-c%C3%B3digo-9651a2d04970?source=rss-a2ef37f4952a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9651a2d04970</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[configuration-as-code]]></category>
            <dc:creator><![CDATA[Abraham Morales]]></dc:creator>
            <pubDate>Tue, 29 Dec 2020 21:43:39 GMT</pubDate>
            <atom:updated>2023-05-19T20:42:57.395Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WiK52axRuSi8hb0qSKIVVA.png" /><figcaption>Automatizando la Instalación y Configuración de Jenkins usando Docker y Configuración como Código</figcaption></figure><h3>Introducción</h3><p>En este artículo, hablaremos sobre cómo automatizar la instalación y configuración de Jenkins, utilizando Docker y Configuración como Código de Jenkins (JCasC). Después de leerlo, usted podrá crear una imagen de personalizada de Jenkins con su configuración básica.</p><p>En este articulo no cubriremos temas como: configuración de Jenkins, plugin Job Dsl, seguridad de Jenkins o uso Docker, nos centraremos en el uso de la configuración de Jenkins como código.</p><h4>Pre requisitos:</h4><p>Los requisitos previos para este artículo son:</p><ul><li>Uso y configuración básicos de Jenkins.</li><li>Uso básico de Docker.</li><li>Tener Docker instalado y poder ejecutar la imagen Docker de Jenkins.</li></ul><h4>Configuración de Jenkins como código</h4><p>El paradigma ‘como código’ se trata de poder reproducir y / o restaurar un entorno completo en minutos basado en automatización, de la forma en la que se maneja el código.</p><p>Configurar Jenkins es un proceso complejo, ya que, tanto Jenkins como sus plugins requieren cierto ajuste y configuración, con docenas de parámetros para configurar, dentro de la sección de administración de la interfaz de usuario web.</p><p>Jenkins Configuración como Código (JCasC) proporciona la capacidad de definir toda esta configuración como una sintaxis YAML simple y amigable para los humanos. Sin ningún paso manual, esta configuración se puede validar y aplicar a un controlador Jenkins de una manera totalmente reproducible.</p><p>JCasC utiliza el plugin Configuración como código, que le permite definir el estado deseado de la configuración de Jenkins como uno o más archivos YAML.</p><p>Durante inicialización de Jenkins, el plugin Configuración como Código, configurará Jenkins de acuerdo con los archivos de configuración YAML.</p><p>En las siguientes secciones, veremos cómo implementar la imagen de Docker personalizada y administrar la configuración de Jenkins usando archivos YMAL.</p><h3>Paso 1. Creación de una imagen personalizada de Docker.</h3><p>Crearemos una imagen personalizada de Jenkins que:</p><ul><li>Tiene el asistente de configuración desactivado.</li><li>Defina la ubicación de los archivos de configuración YAML.</li><li>Copie un archivo con la lista de los plugins necesarios.</li><li>Copie el archivo de configuración YAML.</li><li>Instale todos los plugins enumerados en el archivo.</li></ul><p>Para des habilitar el asistente de configuración tenemos que definir la siguiente variable de entorno:</p><pre>ENV JAVA_OPTS -Djenkins.install.runSetupWizard=false</pre><p>Para que el plugin sea capaz de cargar el archivo que contiene la configuración deseada para Jenkins debemos de definir la siguiente variable de entorno:</p><pre>ENV CASC_JENKINS_CONFIG /var/jenkins_home/jenkins-configuration.yaml</pre><p>Para instalar todos los plugins que queremos, utilizaremos el script que Jenkins provee para tal fin de la siguiente forma:</p><pre>jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.txt</pre><p>De esta forma el archivo Dockerfile que define nuestra imagen quedaria de la siguiente forma:</p><pre>FROM jenkins/jenkins:2.375.3<br>LABEL maintainer=&quot;<a href="/service/mailto:agmc22mx@gmail.com">agmc22mx@gmail.com</a>&quot;<br>USER root<br>RUN apt-get update &amp;&amp; apt-get install -y lsb-release<br>RUN curl -fsSLo /usr/share/keyrings/docker-archive-keyring.asc <a href="https://download.docker.com/linux/debian/gpg">https://download.docker.com/linux/debian/gpg</a><br>RUN echo &quot;deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.asc] \<br>  <a href="https://download.docker.com/linux/debian">https://download.docker.com/linux/debian</a> $(lsb_release -cs) stable&quot; &gt; /etc/apt/sources.list.d/docker.list<br>RUN apt-get update &amp;&amp; apt-get install -y docker-ce-cli<br>USER jenkins<br>ENV JAVA_OPTS -Djenkins.install.runSetupWizard=false<br>ENV CASC_JENKINS_CONFIG /var/jenkins_home/casc.yaml<br>COPY plugins.txt /usr/share/jenkins/ref/plugins.txt<br>COPY casc.yaml /var/jenkins_home/casc.yaml<br>COPY seedjob.groovy /usr/local/seedjob.groovy<br>RUN jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.txt</pre><h3>Paso 2. Definir los archivos de configuración básica</h3><p>Una vez que hemos definido nuestra imagen Docker vamos a definir los archivos plugins.txt y Jenkins-configuration.yml los cuales contienen la lista de los plugins necesarios y la configuración deseada de para Jenkins.</p><p>El archivo plugins.txt es un archivo de texto que contiene. una lista de los plugins a ser instalados, donde cada linea del archivo tiene el nombre del plugin y la version.</p><pre>ant:latest<br>antisamy-markup-formatter:latest<br>build-timeout:latest<br>cloudbees-folder:latest<br>configuration-as-code:latest<br>credentials-binding:latest<br>email-ext:latest<br>git:latest<br>github-branch-source:latest<br>gradle:latest<br>ldap:latest<br>mailer:latest<br>matrix-auth:latest<br>pam-auth:latest<br>pipeline-github-lib:latest<br>pipeline-stage-view:latest<br>ssh-slaves:latest<br>timestamper:latest<br>workflow-aggregator:latest<br>ws-cleanup:latest<br>job-dsl:latest<br>blueocean:latest<br>authorize-project:latest</pre><p>En el archivo Jenkins-configuration.yaml pondremos la configuración deseada para Jenkins; por el momento solo espesificaremos la URL de Jenkins</p><pre>unclassified:<br> location:<br> url: <a href="http://server_ip:8080/">http://server_ip:8080/</a></pre><p>Hasta el momento hemos creado el archivo con la lista de plugins a instalar y el archivo YAML con la configuración de Jenkins, si en este momento usamos docker para construir la imagen y correr el contenedor, veremos en nuestro navegador una instancia de Jenkins con todos los plugins instalados, el asistente de configuración desactivado y la url de Jenkins configurada.</p><pre>docker build -t jenkins:customJenkins .<br>docker run — name jenkins — rm -p 8080:8080 jenkins:customJenkins</pre><h3>Paso 3. Configurando Seguridad básica para Jenkins</h3><p>Hasta el momento nuestro Jenkins no cuenta con ningún mecanismo de autentificación o de autorización, en este paso vamos a configurar un mecanismo básico basado en nombre de usuario y contraseña a si como un esquema de permisos.</p><h4>Autentificación Básica</h4><p>Utilizaremos un esquema bàsico de autentificación basado en nombre de usuario y contraseña y también deshabilitaremos la pagina de registro.</p><p>En lugar de codificar en la configuración el nombre de usuario y su contraseña, definiremos variables de entorno para que en tiempo de ejecución cuando corramos Docker podamos definir estos valores.</p><p>Agregaremos el siguiente fragmento al archivo YAML para definir a nuestro usuario:</p><pre>jenkins:<br> securityRealm:<br> local:<br> allowsSignup: false<br> users:<br> — id: ${JENKINS_ADMIN_ID}<br> password: ${JENKINS_ADMIN_PASSWORD}</pre><p>En este momento si ejecutamos Docker tendremos único usuario cuyos valores especificamos en tiempo de ejecución de la siguiente manera.</p><pre>docker build -t jenkins:custumJenkins .</pre><pre>mkdir jenkins-data</pre><pre>docker run --name jenkins -d --rm --volume jenkins-data:/var/jenkins_home -p 8080:8080 --env JENKINS_ADMIN_ID=admin --env JENKINS_ADMIN_PASSWORD=admin jenkins:custumJenkins </pre><pre><a href="http://localhost:8080/login">http://localhost:8080/login</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fNN3hPfbsU-scsqMA8XJfg.png" /></figure><h4>Estrategia basica de autorización</h4><p>Utilisaremos el plugin Matrix Authorization Strategy para configurar los permisos del usuario que hemos creado con anterioridad agregando el siguiente fragmento de codigo al archivo YAML.</p><pre>authorizationStrategy:<br> globalMatrix:<br> permissions:<br> — “Overall/Administer:admin”<br> — “Overall/Read:authenticated”</pre><p>La propiedad globalMatrix establece los permisos con el siguiente formato:</p><pre>&lt;permission-group&gt;/&lt;permission-name&gt;:&lt;role&gt;</pre><p>Como parte de la seguridad bàsica configuraremos a Jenkins para que todos los Jobs se ejecuten con el mismo usuario que los a lanzado y de esta forma evitaremos problemas de escalación de permisos, para esto agregaremos el siguiente fragmento de codigo al archivo YAML.</p><pre>security:<br> queueItemAuthenticator:<br> authenticators: <br> -global:<br> strategy: triggeringUsersAuthorizationStrategy</pre><p>Para terminar de configurar la seguridad bàsica, habilitaremos el control de acceso para los agentes, de esta forma, podremos determinar que archivos y comandos se le autoriza utilizar, para esto agregaremos el siguiente fragmento de codigo al archivo YAML.</p><pre>remotingSecurity:<br> enabled: true</pre><h3>Paso 4. utilización del plugin JobDSL</h3><p>Ahora que ya hemos configurado y establecido la seguridad de nuestra instancia de Jenkins, crearemos un SedJob, la funcion de este Job es crear todos los Jobs a partir de un conjunto de archivos groovy, con lo cual automatisaremos la creacion de nuestros Jobs. Para esto agregaremos el siguiente fragmento de codigo al archivo YAML.</p><pre>jobs:<br> — file: /usr/local/seedjob.groovy</pre><p>Crearemos tambien un archivo groovy llamado seedjob.groovy con el siguiente codigo:</p><pre>job(‘seed_job’) {<br> scm {<br>  git {<br>   remote {<br>    url(https://medium.com/%E2%80%98%3Ca%20href=%22/service/https://github.com/abrahamNtd/jcasc-poc.git%22%3Ehttps://github.com/abrahamNtd/jcasc-poc.git%3C/a%3E&#39;)<br>   }<br>   branch(‘main’)<br>  }<br> }<br> steps {<br>  dsl {<br>   external(‘hellow_world_job.groovy’)<br>  }<br> }<br>}</pre><p>Finalmente agregaremos el siguiente fragmento al archivo docker:</p><pre>COPY seedjob.groovy /usr/local/seedjob.groovy</pre><p>En este momento si ejecutamos Docker tendremos un servidor Jenkins arriba con la configuración basica de seguridad, un único usuario cuyos valores especificamos en tiempo de ejecución y un job que nos permitira crear todos los jobs que nesecitemos de forma automática.</p><pre>docker build -t jenkins:custumJenkins .</pre><pre>docker run --name jenkins -d --rm --volume jenkins-data:/var/jenkins_home -p 8080:8080 --env JENKINS_ADMIN_ID=admin --env JENKINS_ADMIN_PASSWORD=admin jenkins:custumJenkins </pre><pre><a href="http://localhost:8080/login">http://localhost:8080/login</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0cVVomaDwQXfLKR8TKACg.png" /></figure><p>El codigo completo de este articulo se encuentra en este repositorio de github:</p><p><a href="https://github.com/abrahamNtd/jcasc-poc">https://github.com/abrahamNtd/jcasc-poc</a></p><p>Mas información se puede encontrar aqui:</p><pre>Web Visto 13/02/2023<br><br>https://github.com/jenkinsci/configuration-as-code-plugin/<br><br>Web Visto 13/02/2023<br><br>https://www.jenkins.io/doc/book/managing/plugins/</pre><p>Este articulo es una traduccion de la version original en ingles:</p><p><a href="https://abrahamntd.medium.com/automating-jenkins-setup-using-docker-and-jenkins-configuration-as-code-897e6640af9d">Automating Jenkins Setup using Docker and Jenkins Configuration as Code</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9651a2d04970" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Jenkins Setup using Docker and Jenkins Configuration as Code]]></title>
            <link>https://abrahamntd.medium.com/automating-jenkins-setup-using-docker-and-jenkins-configuration-as-code-897e6640af9d?source=rss-a2ef37f4952a------2</link>
            <guid isPermaLink="false">https://medium.com/p/897e6640af9d</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[configuration-as-code]]></category>
            <dc:creator><![CDATA[Abraham Morales]]></dc:creator>
            <pubDate>Tue, 22 Dec 2020 01:01:37 GMT</pubDate>
            <atom:updated>2023-04-19T01:39:08.578Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Jenkins Configuration as Code (JCasC)" src="https://cdn-images-1.medium.com/max/1024/1*eHdRktddywXtooKz_4DjQg.png" /></figure><h3>Introduction</h3><p>In this article, we will talk about how to automate the installation and configuration of <a href="https://www.jenkins.io/">Jenkins</a>, using <a href="https://www.docker.com/">Docker</a> and the <a href="https://www.jenkins.io/projects/jcasc/">Jenkins Configuration as Code</a> (JCasC) method. After reading it you will be able to create a custom docker image of a Jenkins server with the basic configuration.</p><p>We won’t cover topics like Jenkins setup, Job Dsl plugin, Jenkins security, or Docker, we will focus on using the Jenkins Configuration as Code.</p><h4>Prerequisites</h4><p>The prerequisite for this article are:</p><ul><li>Basic usage and configuration of Jenkins.</li><li>Basic usage of Docker.</li><li>Have Docker installed and been able to run the community Jenkins image.</li><li>All the code shown here has been tested on a Mac OS environment but can be easily adapted to a Windows environment or Linux.</li></ul><h4>Jenkins Configuration as Code</h4><p>The ‘as code’ paradigm is about being able to reproduce and/or restore a full environment within minutes based on recipes and automation, managed as code.</p><p>Setting up Jenkins is a complex process, as both Jenkins and its plugins require some tuning and configuration, with dozens of parameters to set within the web UI manage section.</p><p>Jenkins Configuration as Code (JCasC) provides the ability to define this whole configuration as a simple, human-friendly, plain text YAML syntax. Without any manual steps, this configuration can be validated and applied to a Jenkins controller in a fully reproducible way.</p><p>JCasC makes use of the Configuration as Code plugin, which allows you to define the desired state of your Jenkins configuration as one or more YAML files.</p><p>On the initialization, the Configuration as Code plugin will configure Jenkins according to the YAML configuration files.</p><p>In the following sections, we will see how to implement the custom docker image and manage the configuration of Jenkins using YMAL files.</p><h4>Step 1. Creating a custom Docker image.</h4><p>We will create a custom docker image of Jenkins that:</p><ul><li>Setup initial wizard disabled.</li><li>Update system dependencies.</li><li>Define the location for the YAML configuration files.</li><li>Copy a file with the list of necessary plugins.</li><li>Copy the YAML configuration file.</li><li>Install all the plugins listed on a file.</li></ul><p>In order to disable the setup wizard we have to define the following environment variable:</p><pre>ENV JAVA_OPTS -Djenkins.install.runSetupWizard=false</pre><p>In order to set up the path for the YAML configuration file we have to define the following environment variable:</p><pre>ENV CASC_JENKINS_CONFIG /var/jenkins_home/jenkins-configuration.yaml</pre><p>For installing the plugins from a file we will run the script provided by Jenkins:</p><pre>jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.txt</pre><p>So putting everything together the resultant Dockerfile is:</p><pre>FROM jenkins/jenkins:2.375.3<br>LABEL maintainer=&quot;<a href="/service/mailto:agmc22mx@gmail.com">agmc22mx@gmail.com</a>&quot;<br>USER root<br>RUN apt-get update &amp;&amp; apt-get install -y lsb-release<br>RUN curl -fsSLo /usr/share/keyrings/docker-archive-keyring.asc <a href="https://download.docker.com/linux/debian/gpg">https://download.docker.com/linux/debian/gpg</a><br>RUN echo &quot;deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.asc] \<br>  <a href="https://download.docker.com/linux/debian">https://download.docker.com/linux/debian</a> $(lsb_release -cs) stable&quot; &gt; /etc/apt/sources.list.d/docker.list<br>RUN apt-get update &amp;&amp; apt-get install -y docker-ce-cli<br>USER jenkins<br>COPY plugins.txt /usr/share/jenkins/ref/plugins.txt<br>COPY jenkins-configuration.yaml /var/jenkins_home/jenkins-configuration.yaml<br>COPY seedjob.groovy /usr/local/seedjob.groovy<br>ENV JAVA_OPTS -Djenkins.install.runSetupWizard=false<br>ENV CASC_JENKINS_CONFIG /var/jenkins_home/jenkins-configuration.yaml<br>RUN jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.txt</pre><h4>Step 2. Defining basic configuration files.</h4><p>Once we have defined the docker file, we will define the content for plugins.txt and Jenkins-configuration. YAML files.</p><p>The plugins.txt file is a list of plugins, where every line has the name and version of one plugin to be installed.</p><pre>ant:latest<br>antisamy-markup-formatter:latest<br>build-timeout:latest<br>cloudbees-folder:latest<br>configuration-as-code:latest<br>credentials-binding:latest<br>email-ext:latest<br>git:latest<br>github-branch-source:latest<br>gradle:latest<br>ldap:latest<br>mailer:latest<br>matrix-auth:latest<br>pam-auth:latest<br>pipeline-github-lib:latest<br>pipeline-stage-view:latest<br>ssh-slaves:latest<br>timestamper:latest<br>workflow-aggregator:latest<br>ws-cleanup:latest<br>job-dsl:latest<br>blueocean:latest<br>authorize-project:latest</pre><p>The Jenkins-configuration.YAML file contains the configuration for the Jenkins instance, at this moment we will set the Jenkins URL.</p><pre>unclassified:<br> location:<br> url: <a href="http://server_ip:8080/">http://server_ip:8080/</a></pre><p>We have created a Dockerfile, the plugin list file, and the YAML configuration file. If we build and run the docker image, at this point we will get running a Jenkins instance that has all the plugins installed, disable the setup wizard, and configure the Jenkins URL.</p><pre>docker build -t jenkins:customJenkins .</pre><pre>docker run — name jenkins — rm -p 8080:8080 jenkins:customJenkins</pre><h4>Step 3. Defining basic security.</h4><p>So far, our setup has not implemented any authentication and authorization mechanisms. In this step, we will set up a basic, password-based authentication scheme and configure the authorization strategy.</p><h4>Basic authentication mechanisms</h4><p>We will set up a basic, password-based authentication scheme and create a new user, and we will disable the self-registration form.</p><p>Instead of hard-coding the user ID and password, we are going to use variables that can be filled in at runtime.</p><p>Add the following to the Jenkins-configuration.YAML file:</p><pre>jenkins:<br> securityRealm:<br>  local:<br>   allowsSignup: false<br>   users:<br>    — id: ${JENKINS_ADMIN_ID}<br>     password: ${JENKINS_ADMIN_PASSWORD}</pre><p>At this point, if we build and run the Jenkins image we will have a Jenkins server with only one user that we specify when running the image.</p><p>Before running the container we have to create a directory “jenkins-data” to map the Jenkins Home directory.</p><pre>docker build -t jenkins:custumJenkins .</pre><pre>mkdir jenkins-data</pre><pre>docker run --name jenkins -d --rm --volume jenkins-data:/var/jenkins_home -p 8080:8080 --env JENKINS_ADMIN_ID=admin --env JENKINS_ADMIN_PASSWORD=admin jenkins:custumJenkins </pre><pre><a href="http://localhost:8080/login?from=%2F">http://localhost:8080/login</a></pre><figure><img alt="Jenkins Login Screen" src="https://cdn-images-1.medium.com/max/1024/1*fNN3hPfbsU-scsqMA8XJfg.png" /><figcaption>Jenkins Login Screen</figcaption></figure><h4>Basic authorization strategy</h4><p>We will use the Matrix Authorization Strategy plugin to configure permissions for the user we have created before, adding the following to the Jenkins-configuration.YAML file:</p><pre>authorizationStrategy:<br> globalMatrix:<br> permissions:<br>   — “Overall/Administer:admin”<br>   — “Overall/Read:authenticated”</pre><p>The globalMatrix property sets global permissions, with the format:</p><p>&lt;permission-group&gt;/&lt;permission-name&gt;:&lt;role&gt;</p><p>As part of the basic security settings, we will set up the build authorization, we will set Jenkins to run all the jobs with the same user as the user has triggered to avoid privilege<em> </em>escalation, adding the following to the Jenkins-configuration.YAML file:</p><pre>security:<br> queueItemAuthenticator:<br>  authenticators: <br>   -global:<br>    strategy: triggeringUsersAuthorizationStrategy</pre><p>As final we will enable the agent to controller access control, to be able to control which commands and files the agents have access to.</p><p>Add the following to the Jenkins-configuration.YAML file:</p><pre>remotingSecurity:<br> enabled: true</pre><h4>Step 4. Using the JobDSL plugin.</h4><p>Now that we have configured and secured our Jenkins instance we will create a sed job, this job will create all the necessary from a set of groovy files, stored in one repository.</p><p>Add the following to the Jenkins-configuration.YAML file:</p><pre>jobs:<br>  — file: /usr/local/seedjob.groovy</pre><p>Create a groovy file named seedjob.groovy and add the following code:</p><pre>job(‘seed_job’) {<br> scm {<br>  git {<br>   remote {<br>    url(https://medium.com/%E2%80%98%3Ca%20href=%22/service/https://github.com/abrahamNtd/jcasc-poc.git%22%3Ehttps://github.com/abrahamNtd/jcasc-poc.git%3C/a%3E&#39;)<br>   }<br>   branch(‘main’)<br>  }<br> }<br> steps {<br>  dsl {<br>   external(‘hellow_world_job.groovy’)<br>  }<br> }<br>}</pre><p>Finally, add the following code to the Dockerfile:</p><pre>COPY seedjob.groovy /usr/local/seedjob.groovy</pre><p>At this point, if we build and run, the image we will have a Jenkins server with only one user that we specify when running the image, the basic security is set and we have a sedJob ready to run and build all other projects.</p><pre>docker build -t jenkins:custumJenkins .</pre><pre>docker run --name jenkins -d --rm --volume jenkins-data:/var/jenkins_home -p 8080:8080 --env JENKINS_ADMIN_ID=admin --env JENKINS_ADMIN_PASSWORD=admin jenkins:customJenkins</pre><pre><a href="http://localhost:8080/job/seed_job/">http://localhost:8080/job/seed_job/</a></pre><figure><img alt="Jenkins main page" src="https://cdn-images-1.medium.com/max/1024/1*i0cVVomaDwQXfLKR8TKACg.png" /><figcaption>Jenkins main page</figcaption></figure><p>The full code for this article can be found at:</p><pre><a href="https://github.com/abrahamNtd/poc-jenkins-jcasc">https://github.com/abrahamNtd/poc-jenkins-jcasc</a></pre><p>Reference</p><pre>Web Visited on 02/13/2023</pre><pre><a href="https://github.com/jenkinsci/configuration-as-code-plugin/tree/master/demos">https://github.com/jenkinsci/configuration-as-code-plugin/</a></pre><pre>Web Visited on 02/13/2023</pre><pre><a href="https://www.jenkins.io/doc/book/managing/plugins/">https://www.jenkins.io/doc/book/managing/plugins/</a></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=897e6640af9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>