<?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 Aman Sharma on Medium]]></title>
        <description><![CDATA[Stories by Aman Sharma on Medium]]></description>
        <link>https://medium.com/@aman-devops?source=rss-2af718aae3fe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*lTItZarb9Nj-z8hi</url>
            <title>Stories by Aman Sharma on Medium</title>
            <link>https://medium.com/@aman-devops?source=rss-2af718aae3fe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:39:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aman-devops/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[Mastering Ansible: An Easy Guide for DevOps Beginners]]></title>
            <link>https://medium.com/@aman-devops/mastering-ansible-an-easy-guide-for-devops-beginners-30289e34da29?source=rss-2af718aae3fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/30289e34da29</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Aman Sharma]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 19:48:03 GMT</pubDate>
            <atom:updated>2024-11-10T19:48:03.319Z</atom:updated>
            <content:encoded><![CDATA[<p>Ansible in Action: Deploying Three EC2 Instances on AWS with Ansible</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*5Tti097rakmAvrfHOGdWbg.jpeg" /><figcaption>Ansible architecture</figcaption></figure><p>Today we’ll be learning about one of the most popular automation tool in the DevOps field <strong>— “Ansible”.</strong> With Ansible, you can streamline tasks like application deployment, configuration management, orchestration, and cloud provisioning. Through tasks executed via playbooks, you’ll get hands-on with Ansible’s practical implementation and understand how it works seamlessly . So let’s start learning …! ✌✨</p><h3>What is Ansible?</h3><p>Ansible is an open-source IT automation tool designed for application deployment, configuration management, and orchestration. It operates using a <strong><em>control node</em></strong> to manage remote systems, called <strong><em>managed nodes</em></strong>.</p><p>Ansible can run on both Unix-like systems and Windows based systems. The best feature of Ansible is it being agentless, and can connect to other nodes via SSH or WinRM to carry out tasks.</p><h3>Ansible components:</h3><p>Ansible’s components play crucial roles in how it manages and automates infrastructure.</p><h4>1.<strong> Control Nodes:</strong></h4><p>The “<strong>control node</strong>” is basically the brain of Ansible or in other words it’s the host/instance/machine in which ansible is installed. It’s from the control node all the commands, playbooks and modules are executed on to other machines via SSH connections.</p><p>Runs Ansible ad-hoc commands like ansible, ansible-playbook, ansible-inventory etc., that communicate with the managed nodes.</p><p>Examples:</p><ul><li>Running <strong>ansible -m ping all</strong> from the control node sends a <strong>ping </strong>module to each managed node.</li><li>A playbook executed on the control node distributes its tasks to all specified hosts.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/0*8-ZlGwMMO2JPziWk.jpg" /><figcaption>Guided playbook with proper instructions is executed on controller node</figcaption></figure><h4>2. <strong>Managed Nodes:</strong></h4><p>The “<strong>managed node</strong>” is the target machine on which commands, playbooks &amp; modules are executed by the control node. These can be physical servers, virtual machines, cloud instances, or even network devices.</p><p>Ansible is not installed on the managed node/s as it is agentless. Managed nodes are mentioned in Ansible’s inventory file, where they can be grouped for easy targeting in playbooks.</p><p>Use-case:</p><ul><li>Installing software across and configuring application settings on all instances in a specific group (e.g., web servers, database servers).</li><li>Deploying code or setting up new servers in a cloud environment.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a44BPSPBUHhGpHBu" /><figcaption>As the playbook runs block-by-block the output is generated on the manager node</figcaption></figure><h4>3. <strong>Inventory:</strong></h4><p>The “<strong>inventory</strong>” file contains a list of all the managed nodes Ansible will operate on, grouped for better organization. The inventory can be as simple as a single IP address or hostname, or as complex as a list of hundreds of servers in different groups.</p><p><strong>Inventory File Structure</strong>:</p><ul><li><strong>Default File</strong>: Located at <strong>/etc/ansible/hosts</strong>, but custom inventory files can be used like (<strong>inventory.ini</strong>).</li><li><strong>Grouping</strong>: Allows grouping servers by categories (e.g., webservers, databases), making it easy to apply tasks to specific sets of machines.</li><li><strong>Dynamic Inventory</strong>: Useful for cloud environments, where inventory changes frequently. Ansible can pull data dynamically from cloud providers like AWS, GCP, or Azure.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*htdCKd-iCCi1Z9Fx8QMOWA.png" /><figcaption>basic inventory.ini with grouped servers</figcaption></figure><h4>4. Modules</h4><p>Modules are standalone scripts that Ansible uses to perform tasks on managed nodes. Each module executes a specific function, such as installing software, copying files, or configuring services.</p><p>Modules are the core of Ansible’s functionality; almost every Ansible task requires one. Ansible has many modules for wide range of tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0eLXZmkO4JHMO7JQXDw3LQ.png" /><figcaption>some commonly used modules in Ansible.</figcaption></figure><h4>5. Playbooks</h4><p>Playbooks are YAML files that contain lists of tasks for Ansible to execute on managed nodes. Playbooks support <strong>variables</strong>, <strong>handlers</strong> (triggered by specific events), and <strong>conditionals</strong> to make automation workflows dynamic and reusable.</p><p>Playbooks are readable and follow YAML syntax, making them accessible to those without a programming background.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dz6eGbQbsBPOhqo527m50Q.png" /><figcaption>playbook to install NGINX webserver on a managed node</figcaption></figure><h4>6. Roles</h4><p>Roles are used to organize playbooks into reusable components, providing a way to organize tasks, handlers, variables, and templates logically. When a project becomes large, roles make it easier to manage and modularize the code (like installing web servers or setting up databases).</p><p>Command to initiaize a role named <strong>webserver:</strong></p><pre>#syntax<br>ansible-galaxy init &lt;role_name&gt;<br>#role name webserver<br>ansible-galaxy init webserver </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*Wktd_cubvGqQFYkI4Jy1ww.png" /><figcaption>directory structure for your webserver role</figcaption></figure><p>Other secondary components include Plugins, Variables and Templates. If you need to get an insight you can read at: “<a href="https://docs.ansible.com/"><strong>https://docs.ansible.com/</strong></a>”</p><h3>Ansible Architecture and Installation:</h3><p>Enough with the theoretical part of Ansible — let’s dive into practical learning so you can better understand its real-world use cases for DevOps deployment &amp; configuration.</p><p><strong>Pre-requisite:</strong></p><ul><li>In my case, I’ll be using an <strong>Amazon AWS EC2 Ubuntu 24.04</strong> instance as the <strong>controller node</strong>, where Ansible will be installed. Along with the controller node, we’ll need <strong>2–3 additional EC2 instances or VMs</strong> to set up the work environment and deploy playbooks.</li><li>Basic knowledge of how to write <strong>YAML</strong> files and work in <strong>Linux</strong> terminal using linux commands.</li><li><strong>Git</strong> and <strong>GitHub</strong>, though not that necessary but will help you understand the push, pull, merge, and collaboration management through out the project.</li></ul><h4>Basic Architecture of Distributed Ansible Cluster :</h4><p>Normally, in an organization, there are hundreds or even thousands of servers, and configuring them manually can be a tedious task, even for expert administrators. In such scenarios, Ansible comes into play by allowing us to easily create and configure any number of servers in minutes, streamlining the process and ensuring consistency across the environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*LbN3nbAKKPnjP7Jq.png" /><figcaption>Ansible architcture.</figcaption></figure><ul><li>Ansible operates on a client-server architecture, with the <strong>control node</strong> being the machine where Ansible is installed and where commands or playbooks are executed (here, Ansible Management Node). It doesn’t require any agents on the <strong>managed nodes</strong>, which are the target systems being configured.</li><li>The control node communicates with the managed nodes(here, host 1, host 2, host 3) over <strong>SSH</strong> (for Linux/Unix systems) or <strong>WinRM</strong> (for Windows systems).</li><li>Ansible uses <strong>modules</strong> to perform tasks on the managed nodes, such as installing packages, managing services, or configuring files, and the results are sent back to the control node. The managed nodes simply need <strong>Python</strong> installed (for Linux/Unix systems).</li><li>Ansible’s configuration is defined in an <strong>inventory file</strong>, which lists the managed nodes, and tasks are executed based on <strong>playbooks</strong> written in YAML. This architecture is <strong>agentless</strong> and uses a <strong>push-based model</strong>, where the control node pushes configurations to the managed nodes.</li><li>Additionally, Ansible supports various <strong>plugins</strong> to extend its capabilities, such as connection, callback, and lookup plugins.</li></ul><h3>Installing Ansible:</h3><p>1. Created an Amazon ec2 Ubuntu 22.04 based instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pM5r8kYZmJbdVSx7OQMVtg.png" /><figcaption>Ansible-controller node created.</figcaption></figure><p>2. Installing ansible, but before that python is necessary as Ansible requires <strong>Python</strong> to be installed on both the <strong>control node </strong>and the<strong> managed nodes.</strong></p><pre>sudo apt update<br>sudo apt install python3</pre><p>After installing the python environment, execute the below command.</p><pre>sudo apt update<br>sudo apt install ansible</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*82FGN81TGkk61UPFaqIEhA.png" /><figcaption>ansible installed on the controller node</figcaption></figure><p>I’ve set up a folder called <strong>medium-project</strong> on my Windows 10 laptop to organize all the tasks outlined in the GitHub <strong>README.md</strong> file. I’ll be writing playbooks, inventory files, and other necessary files using VS Code on my laptop. Once complete, I’ll use Git to push the code to GitHub and then pull it onto the Ansible controller node (my AWS EC2 instance). If I make any changes on the instance, I’ll push the updated code back to GitHub, keeping everything in sync.</p><p>To access my GitHub repo visit: <a href="https://github.com/aman1588/medium-project.git"><strong>https://github.com/aman1588/medium-project.git</strong></a></p><p><a href="https://github.com/aman1588/medium-project.git">GitHub - aman1588/medium-project: Ansible Beginner&#39;s Project</a></p><blockquote>Git and GitHub overview: Configured the repo from my Laptop to GitHub by using Git. I’ll attach a screenshot of the commands used in the process.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8TxuhMc1T8jVBlgtvFdjTQ.jpeg" /><figcaption>Git initialization of the working directory</figcaption></figure><p>Now with all set, we can start working on our tasks.</p><h3>Task-1</h3><p>For task 1 we need to create 3 server/instances as mentioned.</p><p>For Task 1, we need to create three EC2 instances. First, we’ll create an IAM user with the <strong>EC2FullAccess</strong> policy (or another policy based on your specific needs) to manage these instances. After creating the IAM user we get the secret_key and access_key to give authorization permissions.</p><blockquote><strong>Quick info:</strong> Ansible uses AWS SDK for Python boto3 python module/lib as it allows to build applications on top of Amazon S3, Amazon EC2, Amazon DynamoDB, and more.</blockquote><h4><strong>IAM user and credentials/token: (step-by-step guide)</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mqfvcx9uubjys_hRDl2Vcw.png" /><figcaption>created user <strong>aman-test-user</strong> and granting <strong>ec2fullaccess</strong> policy</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4MfQREYzAdroxJB5-75F8g.png" /><figcaption>click on user created → security credentials → App outside AWS → Done</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nbnBrRKHZ45CrHUYwQTaAg.png" /><figcaption>save the <strong>access_key </strong>&amp; <strong>secret_key </strong>info as it will be needed later for authentication</figcaption></figure><p>Also, as mentioned above we’ll be installing boto3 now on the controller node. Here I’m in ubuntu user not the root user.</p><p>Boto3 can be installed in 2 ways:</p><p><strong>1. Installing via apt</strong></p><pre>sudo apt-get install python3-pip<br>sudo apt install python3-boto3</pre><p><strong>2. Installing via pipx</strong></p><pre>sudo apt install pipx<br>pipx install boto3</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7h_Db4hYvUWmreBcHGLg1g.png" /><figcaption>boto3 installed and ready to create resources on AWS</figcaption></figure><h4><strong>Ansible Vault:</strong></h4><p>We’ll be utilizing the vault functionality of Ansible so just to brief you about the same. In Ansible, <strong>Vault</strong> is a feature used to encrypt sensitive data such as passwords, API keys, and other confidential information. The data is stored in a file in an encrypted format, and you can later decrypt it when needed during playbook execution.</p><p><strong>1. Creating a Vault file</strong></p><pre>ansible-vault create confidential.yaml</pre><p>You’ll be prompted to enter a password (sample pass: vault@123) to encrypt the file. After entering the password, the editor will open allowing you to add your sensitive data.</p><p><strong>2. Creating the vault.pass file for automation:</strong></p><p>Use the nano text editor to create a <strong>vault.pass</strong> file to securely store the vault password. This way, you won’t need to enter the password manually each time you run the playbook.</p><pre>#To create the vault.pass file<br>nano vault.pass<br>#Run this command directly to create the yaml and pass file.<br>ansible-vault create medium_project/vault/confidential.yaml --vault-password-file vault.pass</pre><blockquote><strong>Quick info: </strong>You can also use below command to edit the details stored inside you vault file in case you need to make some changes.</blockquote><pre>#To edit the vault file 👀<br>ansible-vault edit confidential.yaml<br>#To encrypt the vault file --&gt; enter pass ✅<br>ansible-vault encrypt confidential.yaml<br>#To decrypt the vault file --&gt; enter pass ✅<br>ansible-vault decrypt confidential.yaml<br>#To view the vault file --&gt; decrypt and display the contents 👍<br>ansible-vault view confidential.yaml</pre><p>Now that we’ve covered the basic setup, let’s move on to learning about collections in Ansible.</p><h4>Collections in Ansible:</h4><p>Ansible collections are essentially <strong>directories</strong> containing structured. Ansible components that help users manage specific tasks and configurations. They allow for greater customization and flexibility, especially when automating diverse infrastructure environments. Each collection can include:</p><ul><li><strong>Modules</strong>: Small scripts that perform specific tasks (e.g., installing a package, managing users).</li><li><strong>Roles</strong>: Predefined sets of tasks and configurations.</li><li><strong>Plugins</strong>: Extensions for customizing Ansible’s behavior (e.g., inventory plugins, callback plugins).</li><li><strong>Playbooks</strong>: High-level directives defining workflows and sequences of tasks.</li><li><strong>Documentation</strong>: Information for users to understand and use the collection.</li></ul><p>Ansible collections can be installed from <strong>Ansible Galaxy</strong>, which is the default source:</p><pre>ansible-galaxy collection install &lt;namespace.collection_name&gt;</pre><p>You can view all installed collections on your system using the following command:</p><pre>ansible-galaxy collection list</pre><p>For our project we’ll be using <strong>amazon.aws</strong> collection to manage and automate cloud infrastructure tasks. This collection, provided by Ansible, contains modules and plugins that help you interact with AWS services, allowing you to automate tasks like launching EC2 instances, configuring S3 buckets, managing IAM roles, and more.</p><h4>Setting up the amanzon.aws collection</h4><p>Install the collection from Ansible Galaxy:</p><pre>ansible-galaxy collection install amazon.aws</pre><p>This command downloads the collection and makes AWS-specific modules, plugins, and roles available for use in your Ansible playbooks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5IMBmnEDLTx8LPO8RSbAHA.png" /><figcaption>amazon.aws installed</figcaption></figure><p>For more information about amazon.aws collection, it’s parameters and exmaples you can check the official website of ansible: <a href="https://docs.ansible.com/ansible/latest/collections/amazon/aws/ec2_instance_module.html#ansible-collections-amazon-aws-ec2-instance-module"><strong>https://docs.ansible.com/ansible/latest/collections/amazon/aws/ec2_instance_module.html#ansible-collections-amazon-aws-ec2-instance-module</strong></a></p><p>Now i’ll create the playbook on my laptop via VS-code IDE and then push the yaml file to GitHub and pull it on the aws control node server with git pull.</p><pre>---<br>- name: Creating ec2 instances as per requirement<br>  hosts: localhost  #Specifies that the playbook should run on the local machine.<br>  connection: local  #Ensures that Ansible runs the tasks locally without using SSH or remote execution.<br>  gather_facts: no  #Whether to gather facts (system information)<br>  vars_files:<br>    - /home/ubuntu/medium-project/vault/confidential.yaml<br><br>  tasks:<br>    - name: Start an instance with public-IP (ubuntu)<br>      amazon.aws.ec2_instance:<br>        name: &quot;ansible-instance-1&quot;<br>        key_name: ansible<br>        region: ap-south-1<br>        instance_type: t2.micro<br>        security_group: default<br>        aws_access_key: &quot;{{ ec2_access_key }}&quot;<br>        aws_secret_key: &quot;{{ ec2_secret_key }}&quot;<br>        network:<br>          assign_public_ip: true<br>        image_id: &quot;ami-0dee22c13ea7a9a67&quot;<br><br>    - name: Start an instance with public-IP (ubuntu)<br>      amazon.aws.ec2_instance:<br>        name: &quot;ansible-instance-2&quot;<br>        key_name: ansible<br>        region: ap-south-1<br>        instance_type: t2.micro<br>        security_group: default<br>        aws_access_key: &quot;{{ec2_access_key}}&quot;<br>        aws_secret_key: &quot;{{ec2_secret_key}}&quot;<br>        network:<br>          assign_public_ip: true<br>        image_id: &quot;ami-0dee22c13ea7a9a67&quot;<br><br>    - name: Start an instance with public-IP (amazon-linux)<br>      amazon.aws.ec2_instance:<br>        name: &quot;ansible-instance-3&quot;<br>        key_name: ansible<br>        region: ap-south-1<br>        instance_type: t2.micro<br>        security_group: default<br>        aws_access_key: &quot;{{ec2_access_key}}&quot;<br>        aws_secret_key: &quot;{{ec2_secret_key}}&quot;<br>        network:<br>          assign_public_ip: true<br>        image_id: &quot;ami-08bf489a05e916bbd&quot;</pre><p>The first iteration of the Yaml file is ready. Let’s run this on the control node and see if the instance are being created or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*X_OEcUuVsFaTby3bpR5LSQ.png" /><figcaption>Amazon linux image id</figcaption></figure><p>Create a key-pair, Note down the Image_id, Select the region, Allow public_ip before writing the playbook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*oI8P7zg9fjSJrQDufUGMDw.png" /><figcaption>Ubuntu 24.04 image id</figcaption></figure><blockquote><strong>Quick info: </strong>you can also run the <strong>vault.pass </strong>directly in the adhoc command if you add the environment variable as [defaults] in /etc/ansible/ansible.cfg. Or, you can setup a group_vars directory<strong> “mkdir -p group_vars → touch group_vars/all.yml” </strong>In the file you can define variables in YAML format.</blockquote><p>Example:</p><pre># group_vars/all.yml<br>ec2_access_key: &quot;your_access_key&quot;<br>ec2_secret_key: &quot;your_secret_key&quot;</pre><p>2 ways to run the ad-hoc command:</p><pre>#To execute the playbook if env var aren&#39;t configured<br>ansible-playbook task-1.yaml --vault-password-file ~/medium-project/vault/vault.pass<br>#To execute the playbook if env var are configured<br>ansible-playbook task-1.yaml --vault-password-file vault.pass</pre><p>Playbook running locally, in the localhost (controlle node) and executing instructions as listed down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Euf-LofpJESYnexsEq306g.png" /><figcaption>Playbook executed successfully.</figcaption></figure><p>Before, Only 1 instance (i.e. controller node) running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sPuBFFHkHpONdFFBX8aaaQ.png" /><figcaption>Before</figcaption></figure><p>After, 3 new instances created (2 Ubuntu and 1 Amazon Linux).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HCjK_Oyq9A2cTvsVpNA1Og.png" /><figcaption>After</figcaption></figure><p>Hence, we created the instances via Ansible. 😍🙌</p><p>BUT BUT BUT …! After executing the task-1.yaml playbook, we successfully created three instances as needed. However, this approach isn’t very efficient. In a larger organization with numerous instances and configurations to manage and deploy, this method can quickly become challenging to scale and difficult for the team members to understand.</p><p>So, now we’ll do it in an effective way. using <strong>LOOPS. </strong>But proceeding further we’ll get to know about a little concept called <strong>Idempotency</strong>.</p><h3>Idempotency:</h3><p>Ansible offers idempotency, meaning that if you run a playbook and a resource is created, executing the playbook again will not recreate the resource. In other words, the playbook will not re-run fully, as Ansible detects that the desired state already exists on the target system.</p><h4>Significance of LOOPS:</h4><p>We applied loops on 2 variables that is image and name, which run a complete cycle and create an instance (the loop iterates through three sets of values). For each loop iteration, an EC2 instance is created with specific properties such as instance name, key name (ansible), region (ap-south-1), instance type (t2.micro), security group (default), and a public IP. The AMI IDs differ for the two Ubuntu instances and one Amazon Linux instance.</p><p>By doing this , Ansible ensures that your tasks are <strong>safe to run repeatedly</strong> and avoid unnecessary changes or errors, making it an essential part of automation. Attaching the updated YAML file for reference.</p><pre>---<br>- name: To create 3 ec2 Instances<br>  hosts: localhost<br>  connection: local<br>  become: no<br>  gather_facts: no<br>  vars_files:<br>    - /home/ubuntu/medium-project/vault/confidential.yaml<br><br>  tasks:<br>    - name: Creating 3 instances (2 ubuntu and 1 amazon amazon-linux) via loops<br>      amazon.aws.ec2_instance:<br>        name: &quot;{{ item.name }} }}&quot;<br>        key_name: ansible<br>        region: ap-south-1<br>        instance_type: t2.micro<br>        security_group: default<br>        aws_access_key: &quot;{{ ec2_access_key }}&quot;<br>        aws_secret_key: &quot;{{ ec2_secret_key }}&quot;<br>        network:<br>          assign_public_ip: true<br>        image_id: &quot;{{ item.image }}&quot;<br>      loop:<br>        - { image: &quot;ami-0dee22c13ea7a9a67&quot;, name: &quot;manager-node-1&quot; }<br>        - { image: &quot;ami-0dee22c13ea7a9a67&quot;, name: &quot;manager-node-2&quot; }<br>        - { image: &quot;ami-08bf489a05e916bbd&quot;, name: &quot;manager-node-3&quot; }</pre><p>Running the new playbook (task-1-loops.yaml), to complete the task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xD0LoTKZ1q--24ZnTgdTLg.png" /><figcaption>Playbook executed successfully</figcaption></figure><p>2 ways to run the ad-hoc command:</p><pre>#To execute the playbook if env var aren&#39;t configured<br>ansible-playbook task-1-loops.yaml --vault-password-file ~/medium-project/vault/vault.pass<br>#To execute the playbook if env var are configured<br>ansible-playbook task-1-loops.yaml --vault-password-file vault.pass</pre><p>Deleted (terminated), the previous created instance with long method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ZB89ugbGytMB_aaq0vpbA.png" /><figcaption>Before, Only 1 server runnning.</figcaption></figure><p>Finally! new instances launched in AWS console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*blJ40w5KZrby4LVJD_eY6w.png" /><figcaption>Avoided Idempotency and launched the instances.</figcaption></figure><p><strong>Conclusion</strong></p><p>Although this blog doesn’t cover all the tasks (from task-1 to task-6), don’t worry — I’ll be addressing them in the next blog. The goal of this post was to provide a basic understanding of Ansible through a practical use case. 🚀</p><p>As we’ve seen, Ansible is a powerful automation tool that simplifies complex IT tasks, making them more efficient and repeatable. 🔧 Its idempotent nature ensures that your infrastructure remains consistent and reliable, no matter how many times you run the same playbook. 🔄</p><p>Feel free to drop your comments and questions below if you have any doubts. 💬</p><p>Thanks for reading! 🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30289e34da29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker 101: A Beginner’s Guide to Containerization and Docker Basics]]></title>
            <link>https://medium.com/@aman-devops/docker-101-a-beginners-guide-to-containerization-and-docker-basics-0f7af9b8ad46?source=rss-2af718aae3fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f7af9b8ad46</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[projects]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Aman Sharma]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 10:22:53 GMT</pubDate>
            <atom:updated>2024-11-04T10:22:53.351Z</atom:updated>
            <content:encoded><![CDATA[<p>Complete with Working Examples to Solidify Your Docker Knowledge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/0*r54VAiOuptqLP6Zu.png" /></figure><h3>Why Docker?</h3><p>Decades ago, applications ran directly on hardware with an installed operating system, requiring manual setup of code and dependencies. Scaling meant buying new hardware and configuring everything from scratch. Virtualization introduced hypervisors (which sits between the hardware and the operating system), allowing multiple applications to run in isolated virtual machines with their own OS. However, each VM still needed individual setup, and applications weren’t easily portable.</p><p>To address these challenges, Docker was introduced as a more efficient solution. In this blog, we’ll explore Docker in detail. By the end, you’ll have a comprehensive understanding of Docker and the skills needed to deploy applications easily.</p><h3>What is docker?</h3><p>Docker is an open-source container orchestration tool, which allows us to develop, deploy, and run applications inside containers. Now, you may ask <strong>what’s a container?</strong> (Containers are lightweight, isolated environments that bundle an application with all its necessary dependencies, allowing it to run consistently across different infrastructures. Any system with Docker installed can host and run these containers effortlessly. Containers operate independently from each other and the host, ensuring consistent performance across different environments.)</p><p>Docker supports <strong>isolation at the OS level</strong>, which allows containers to share the host OS kernel, which saves resources and improves performance. This isolation provides consistent environments across deployments, enhances security by isolating containers from each other, and enables faster startup and easier management of applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*xiNbFZ-Fh1eUHzc6.png" /><figcaption>VM schema vs Docker schema</figcaption></figure><h3>VM’s versus Containers:</h3><ul><li><strong>Architecture</strong>: Containers share the host OS kernel, while VMs include a full OS along with a hypervisor layer, making VMs heavier.</li><li><strong>Resource Usage</strong>: Containers are lightweight, consuming fewer resources since they don’t require a separate OS. VMs, on the other hand, use more memory and CPU as each VM has its own OS.</li><li><strong>Portability</strong>: Containers are highly portable and consistent across environments, as they package both the application and its dependencies. VMs can vary by OS, making portability more complex.</li><li><strong>Startup Time</strong>: Containers start almost instantly, while VMs can take minutes to boot because they load a full OS.</li><li><strong>Isolation</strong>: VMs provide stronger isolation with separate OS environments, whereas containers offer process-level isolation, which is lighter but effective for most applications.</li></ul><p>In short, containers are ideal for applications needing fast, scalable, and portable deployment, while VMs are useful for running multiple OSes on the same hardware.</p><blockquote>We will explore this concept through the example demonstrated below, which illustrates the practical advantages of containerization environments like Docker over traditional, resource-intensive virtual machines (VMs).</blockquote><h3><strong>Example: Cooking a Meal</strong></h3><h4><strong>Scenario: Preparing a Meal</strong></h4><h4><strong>Part 1: Virtual Machines</strong></h4><p><strong>Using a Full Kitchen (VM)</strong></p><ol><li><strong>Setup</strong>:</li></ol><ul><li>Imagine you have a <strong>full kitchen</strong> that you use to prepare meals. When you decide to cook, you first need to gather all the necessary ingredients from your pantry and fridge.</li></ul><p>2.<strong> Execution</strong>:</p><ul><li>As you prepare a dish, you need to measure out ingredients, use various pots and pans, and cook everything from scratch.</li><li>For each meal, you have to set up the kitchen, which can take time, and once the meal is done, you have to clean the entire kitchen, including washing dishes and putting away leftovers.</li></ul><p>3.<strong> Drawbacks</strong>:</p><ul><li><strong>Time-Consuming</strong>: The process of gathering ingredients and setting up takes longer, especially if you are making multiple meals.</li><li><strong>Complex Cleanup</strong>: Cleaning the kitchen after cooking is a larger task, requiring more effort.</li><li><strong>Resource Intensive</strong>: You use a lot of kitchen resources (utensils, pots, etc.) for every meal, even if the meals are simple.</li></ul><h4>Part 2: Containers</h4><p><strong>Using Meal Kits (Containers)</strong></p><p>1.<strong> Setup</strong>:</p><ul><li>Now, imagine you decide to use <strong>prepared meal kits</strong> instead of cooking from scratch. Each kit contains all the ingredients needed for a specific dish, such as Kadhai Paneer or Dal Makhani along with a recipe.</li></ul><p>2.<strong> Execution</strong>:</p><ul><li>You take a meal kit out of the fridge, open it up, and everything is already pre-measured and organized. You can start cooking right away without needing to gather or measure ingredients.</li><li>After cooking, cleanup is quick because all the packaging can be thrown away, and there are fewer dishes to wash.</li></ul><p>3.<strong> Benefits</strong>:</p><ul><li><strong>Quick and Efficient</strong>: Since everything is pre-packaged, you can start cooking immediately without the hassle of prep work.</li><li><strong>Easy Cleanup</strong>: After the meal, you simply dispose of the kit’s packaging, making cleanup straightforward.</li><li><strong>Flexibility</strong>: You can easily switch between different meal kits without worrying about how one dish will affect another, allowing for a more efficient cooking experience.</li></ul><h3>Conclusion</h3><p>In this analogy, <strong>using a full kitchen (VM)</strong> represents the traditional method of preparing meals, which requires significant time and effort for setup and cleanup. On the other hand, <strong>using meal kits (containers)</strong> illustrates how containers streamline the cooking process, making it quicker and more efficient. This comparison highlights how containers offer convenience and flexibility, similar to how they work in software deployment, while VMs provide a more resource-intensive and complex environment.</p><p><strong><em>By now, you should understand why Docker is crucial for application deployment and daily tasks. Let’s delve deeper into Docker and explore how to navigate its features, utilize its powerful capabilities, and effectively deploy applications.</em></strong></p><h3>Docker Architecture:</h3><p>Docker uses a <strong>client-server architecture</strong>. It consists of the following components:</p><p><strong>1. Docker engine:</strong> The Docker engine runs on top of the host operating system, and consists of two parts.</p><ol><li><strong>Docker daemon (dockerd):</strong> The background service that manages Docker containers, images, networks, and volumes. It listens for API requests from the Docker client and handles container lifecycle management.</li><li><strong>REST API</strong>: The interface through which clients can interact with the Docker daemon to perform various operations, such as building, running, and managing containers.</li></ol><p><strong>2. Docker Client</strong>: This is the command-line interface (CLI) used to interact with the Docker daemon. Users can run commands like <strong>docker build</strong>, <strong>docker run</strong> and <strong>docker push</strong> to manage containers and images.</p><p><strong>3. Docker Images</strong>: These are read-only templates used to create containers. An image contains the application code, libraries, dependencies, and the environment needed for the application to run. Images are built using a <strong>Dockerfile</strong>, which defines the instructions for assembling the image.</p><p><strong>4. Docker Containers</strong>: A container is a lightweight, executable instance of a Docker image. Containers are isolated environments that run applications and share the host OS kernel. They can be started, stopped, moved, and deleted easily.</p><p><strong>5. Docker Registry</strong>: This is a storage repository for Docker images. The default registry is Docker Hub, where users can pull public images or push their custom images for storage and sharing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/0*gN3X4ah-WOTFzebe" /><figcaption>Docker architecture</figcaption></figure><p>In simple words, The <strong><em>Docker client or CLI</em></strong> is used to give instructions to Docker, like building and running containers. The <strong><em>Docker daemon</em></strong> acts as a server that manages Docker containers, images, networks, and volumes. It listens for API requests from the Docker client and handles the creation, execution, and orchestration of containers.</p><h3>Docker Installation</h3><h4><strong>Pre-requisite:</strong></h4><p>Docker must be installed on your system. In this case, we will create an AWS EC2 instance using an Ubuntu base image (Linux-based).</p><h4><strong>Created the Instance:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FEnWPMTyYtiBKK-03mn6tQ.png" /><figcaption>AWS EC2 instance created</figcaption></figure><h4>Installing Docker:</h4><p>I’ll give you the script to install docker for ubuntu version 24.04 below, but to install for other OS and distributions you can refer the <a href="https://docs.docker.com/engine/install/"><strong>official website</strong></a><strong>.</strong></p><pre>#!/bin/bash<br><br># Update the package index<br>sudo apt-get update<br><br># Install packages to allow apt to use a repository over HTTPS<br>sudo apt-get install -y apt-transport-https ca-certificates curl software-properties-common<br><br># Add Docker&#39;s official GPG key<br>curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -<br><br># Add Docker&#39;s official repository<br>echo &quot;deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable&quot; | sudo tee /etc/apt/sources.list.d/docker.list<br><br># Update the package index again<br>sudo apt-get update<br><br># Install Docker<br>sudo apt-get install -y docker-ce docker-ce-cli containerd.io<br><br># Add your user to the Docker group (optional, allows running Docker without sudo)<br>sudo usermod -aG docker ${USER}<br><br># Inform the user to log out and log back in to apply group changes<br>echo &quot;Docker installation completed. Please log out and log back in to use Docker without sudo.&quot;</pre><p><strong>Make the script executable</strong>:</p><pre>chmod +x install_docker.sh</pre><p><strong>Run the script</strong>:</p><pre>bash install_docker.sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rGkz8Y7cVfd-FYWfxAu1gQ.png" /><figcaption>Installed docker successfully, and checked the service via systemctl</figcaption></figure><p>Docker by default runs on the <strong>root</strong> user (sudo su),if you want to run it on other user you’ll have to create or add user in your server and then add the user to docker group.</p><h3>Step-by-Step Instructions</h3><h4>1. Create a New User on the Host OS</h4><p>You can create a new user using the <strong>adduser</strong> command. Here’s how:</p><pre>sudo adduser newusername</pre><h4>2. Add the New User to the Docker Group</h4><p>After creating the user, you need to add them to the docker group:</p><pre>sudo usermod -aG docker newusername</pre><h4>3. Verify the User is Added to the Docker Group</h4><p>You can check if the user has been added to the docker group:</p><pre>groups newusername</pre><p>You will get an output like,</p><pre>root@ip-172–31–1–83:/home# groups aman <br>aman : aman users docker</pre><p><strong>aman</strong>: The first occurrence of <em>aman </em>in the output indicates that the user <em>aman </em>is a member of their own user group.</p><p><strong>users</strong>: This is a secondary group that <em>aman</em> belongs to. The <em>users </em>group is a common group in Linux systems that can include multiple users.</p><p><strong>docker</strong>: This indicates that the user <em>aman </em>has been added to the <em>docker </em>group. Being part of the <em>docker </em>group allows <em>aman </em>to run Docker commands without needing to use <em>sudo</em>.</p><h4>4. Log Out and Back In</h4><p>After adding the user to the docker group, the user will need to log out and back in for the changes to take effect.</p><h3>Additional information:</h3><blockquote><strong>To list all users in a Linux system:</strong> cat /etc/passwd</blockquote><blockquote><strong>To remove a user in Linux:</strong> sudo deluser username</blockquote><blockquote><strong>To remove the user and their home directory:</strong> sudo userdel -r username</blockquote><blockquote><strong>Verify user after adding to sudo group:</strong> groups username</blockquote><blockquote><strong>To check who is currently logged in using:</strong> who</blockquote><blockquote><strong>aman@ip-172–31–1–83:/$</strong> → This indicates that the current working directory is the <strong>root directory</strong> of the filesystem. In Linux, the root directory is represented by a single forward slash (/).</blockquote><blockquote><strong>aman@ip-172–31–1–83:~$</strong> → This represents the user’s home directory. In most cases, for user “aman,” this would be <strong>/home/aman</strong>. The tilde (~) is a shorthand for the home directory of the currently logged-in user.</blockquote><p>For our easy understanding I’ll be using root user for Docker explanation and demonstration, so that there is no issue of permissions when we deploy our application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v2flwKoSc5DI1UoJ" /><figcaption>docker usecase and implementation</figcaption></figure><h3>Docker Commands:</h3><p>Docker commands are CLI (command-line interface) instructions used to manage Docker containers, images, volumes, and networks, as well as overall Docker operations.</p><h4>Basic Docker commands:</h4><ol><li><strong>docker — — version:</strong> Check the Docker version installed.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QEx_LneJgYviWJDxdM9GhA.png" /><figcaption>Docker version 27.3.1</figcaption></figure><p>2. <strong>docker pull &lt;image&gt;:</strong> Download a Docker image from Docker Hub.</p><p>3. <strong>docker images: </strong>To list all the docker images present in the local system</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pPCGOhah0l2YRtAdcv1QHw.png" /><figcaption>Docker pulled Nginx image from DockerHub repo</figcaption></figure><p>4. <strong>docker ps: </strong>To list the running containers</p><p>5. <strong>docker ps -a: </strong>To list all the conatiners</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*btHKOXFvcFXMAFUBpiaHVQ.png" /><figcaption>No container is shown, as we have not created any container.</figcaption></figure><p>6. <strong>docker run: </strong>Run a container from a specified image.</p><ul><li><strong>— it:</strong> The -it flag combines two options, -i and -t, to allow interactive use of a terminal.</li><li><strong>— d(detached mode): </strong>Runs the container in background.</li><li><strong>— — name: </strong>Assigns a name to a container.</li><li><strong>— p: </strong>Exposes port to map containers on server.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bgv82p0-j23lUJYqKNbQ6g.png" /><figcaption>Now we can see, an NGINX container running on docker daemon.</figcaption></figure><p>7. <strong>docker exec -it &lt;container name&gt; /bin/bash:</strong> Access the running container interactively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G8A2sleeq7f7eZJGGT2Hlw.png" /><figcaption>We enter inside nginx_v1 via docker exec, and check the nginx service status → running perfectly.</figcaption></figure><p>8. <strong>docker start &lt;container name&gt;: </strong>To start an exisiting container.</p><p>9. <strong>docker stop &lt;container name&gt;:</strong> To stop a running container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tW7_Boj8qteGfAO1N0U5pg.png" /><figcaption>Docker stop to stop the container and Docker start to start the stopped container.</figcaption></figure><p>10. <strong>docker restart &lt;container name&gt;:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EutKhkdCfyPPvof03-KzHg.png" /><figcaption>Restarted a running container.</figcaption></figure><p>11. <strong>docker rm &lt;container_id&gt;: </strong>Remove a stopped container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5iiwf09sSeXvS446GPG1yg.png" /><figcaption>Container must be in stopped state before removing.</figcaption></figure><p>12. <strong>docker rmi &lt;image_id&gt;: </strong>Remove a Docker image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FKj7TnT6W5M2tobG5FPywQ.png" /><figcaption>Removed NGINX image from Docker</figcaption></figure><h4>Advanced Docker commands:</h4><p>Dockerfile:</p><p>A Dockerfile is a text document, with a set of instrucitons to create a docker image.</p><p>In Docker, a Dockerfile is like a recipe for creating images. It contains instructions that tell Docker how to set up the environment, install required software, and configure the application to run seamlessly.&quot;</p><h4>Basic Dockerfile Example: Simple Web Server</h4><p>Here for our understanding we’ll deploy a simple web server NGINX via Dockerfile in our Docker.</p><h4>Dockerfile:</h4><pre>#Using an official nginx image from dockerhub<br>FROM nginx:latest<br>#Setting a work directory<br>WORKDIR /home/ubuntu/docker<br>#Copying local HTML file to nginx HTML directory<br>COPY /home/ubuntu/code/index.html /usr/share/nginx/html/<br>#Expose port 80 to allow access to HTTP or internet<br>EXPOSE 80<br>#Define an entrypoint, for the main command<br>ENTRYPOINT [&quot;nginx&quot;]<br>#Define the CMD, for arguments to run NGINX in the foreground<br>CMD [ &quot;-g&quot;, &quot;daemon off;&quot; ]</pre><p>Writing a sample index.html file for our Nginx web-server:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Welcome to Docker Nginx Server&lt;/title&gt;<br>    &lt;style&gt;<br>        body {<br>            font-family: Arial, sans-serif;<br>            text-align: center;<br>            margin-top: 50px;<br>            color: #333;<br>        }<br>        h1 {<br>            color: #3498db;<br>        }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;Welcome to Your Dockerized Nginx Server!&lt;/h1&gt;<br>    &lt;p&gt;This web server is running inside a Docker container.&lt;/p&gt;<br>    &lt;p&gt;Feel free to customize this page to your liking.&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>After this we execute, <strong>docker build -t &lt;image_name&gt; . </strong>command to build the image, which follow the steps listed in the dockerfile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wMdYdTOUmJQ2fSUzkPnh6w.png" /><figcaption>dockerfile → docker build → docker run → docker container created with nginx service running.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dSjx67CFwmum4blD4odZ_w.png" /><figcaption>Webserver running successfully, displays the content of index.html</figcaption></figure><h4>Dockerfile commands/Instructions:</h4><p>Here are some of the most commonly used Dockerfile commands that are essential for building Docker images:</p><p><strong>1. FROM</strong></p><ul><li>Specifies the base image to use for the container.</li><li>Every Dockerfile must start with a FROM command.</li><li>Example: <strong>FROM nginx:latest</strong></li></ul><p><strong>2. RUN</strong></p><ul><li>Executes commands in the container during the image build process.</li><li>Often used to install packages and set up dependencies.</li><li>Example: <strong>RUN apt-get update &amp;&amp; apt-get install -y nginx</strong></li></ul><p><strong>3. COPY</strong></p><ul><li>Copies files or directories from the host machine to the container’s filesystem.</li><li>Example: <strong>COPY index.html /usr/share/nginx/html</strong></li></ul><p><strong>4. ADD</strong></p><ul><li>Similar to COPY but with additional features, like extracting compressed files and also fetch URL’s.</li><li>Example: <strong>ADD code.tar.gz /usr/src/app</strong></li></ul><p><strong>5. WORKDIR</strong></p><ul><li>Sets the working directory.</li><li>Example: <strong>WORKDIR /home/ubuntu/docker/app</strong></li></ul><p><strong>6. CMD</strong></p><ul><li>Specifies the default command to run when the container starts.</li><li>It can be overridden by providing another command when running the container.</li><li>Example: <strong>CMD [“python”, “app.py”]</strong></li></ul><p><strong>7. ENTRYPOINT</strong></p><ul><li>Sets the main command to run in the container.</li><li>Often used with CMD to define default arguments.</li><li>Example: <strong>ENTRYPOINT [“nginx”]</strong></li></ul><p><strong>8. ENV</strong></p><ul><li>Sets environment variables within the container.</li><li>Useful for setting up configuration options.</li><li>Example:</li></ul><pre># Use the official MySQL image from Docker Hub<br>FROM mysql:latest<br><br># Set environment variables<br>ENV MYSQL_ROOT_PASSWORD=my-secret-pw<br>ENV MYSQL_DATABASE=mydatabase<br>ENV MYSQL_USER=myuser<br>ENV MYSQL_PASSWORD=user-secret-pw<br><br># Expose the MySQL port<br>EXPOSE 3306<br><br># Define a volume to persist MySQL data<br>VOLUME /var/lib/mysql</pre><p><strong>9. EXPOSE</strong></p><ul><li>Informs Docker that the container will listen on the specified port at runtime.</li><li>Example: <strong>EXPOSE 3306</strong></li></ul><p><strong>10. VOLUME</strong></p><ul><li>Defines a mount point for persistent storage in the container.</li><li>Example: <strong>VOLUME /var/lib/mysql</strong></li></ul><p><strong>11. LABEL</strong></p><ul><li>Adds metadata to the image, like version, description, or maintainer information.</li><li>Example: <strong>LABEL maintainer=”aman.sharma”</strong></li></ul><h4>Docker commands continued ….</h4><p>13. <strong>docker logs &lt;container_name&gt;: </strong>shows the logs of the container,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YxuFtmL8s4Wz3dD_proRuw.png" /><figcaption>We sent a GET request from our web browser to check the index.html, adn it shows in the log</figcaption></figure><p>14. <strong>docker inspect &lt;container_name&gt;: </strong>shows detailed information about the container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pDr7zKqsxH7uGLpIyd0ioA.png" /></figure><h4>Docker Volumes:</h4><p>Docker volumes are a useful feature of Docker that allows you to persist and manage data generated by and used by Docker containers. When a container is stopped or removed, its data is typically lost unless it is stored in a volume. Volumes are stored outside the container filesystem, allowing data to be there independently of the container lifecycle.</p><h4>Types of Docker Volumes</h4><p><strong>1. Named Volumes</strong>:</p><ul><li>Named volumes have a user-defined name, making them easy to identify, manage, and share among multiple containers.</li><li>Docker stores them in a part of the filesystem managed by Docker (/var/lib/docker/volumes by default).</li><li>Example: — <strong>v mysql_data:/data </strong>→ (mysql_data) being the volume mounted to (/data) directory in the docker.</li></ul><p><strong>2. Bind Mounts</strong>:</p><ul><li>This allows you to specify a host directory to use as the volume. Changes made in the host directory will be reflected in the container and vice versa.</li><li>Example: <strong>— v /host/path:/container/path</strong></li></ul><h4>Example: Using Docker Volumes with MySQL</h4><p>Step 1: Create a Docker volume.</p><pre>#Creating a user-defined volume<br>docker volume create mysql_data</pre><p>Step 2: Writing a <strong>Dockerfile.</strong></p><pre>#Defining a base image to pull<br>FROM mysql:latest<br>#Defining a work directory<br>WORKDIR /app<br>#Executing the app dependency<br>RUN apt-get update -y<br>#Assigning the environment variables<br>ENV MYSQL_ROOT_PASSWORD=mysql@123<br>ENV MYSQL_DATABASE=docker_db<br>ENV MYSQL_USER=aman<br>ENV MYSQL_PASSWORD=aman@123<br>#Expose port<br>EXPOSE 3306<br>#Define a volume to store data<br>VOLUME mysql_data:/var/lib/mysql</pre><p>After this create a docker image via <strong>docker build</strong> and run it via <strong>docker run</strong>, to create a working and running container <strong>(mysql_server_container).</strong></p><p>Step 3:<strong> Create a Sample Table:</strong></p><p>Once in the MySQL prompt, create a sample table and insert some data to see the persistence:</p><pre>mysql&gt; USE docker_db;<br>mysql&gt; CREATE TABLE Users (<br>    -&gt; id INT AUTO_INCREMENT PRIMARY KEY,<br>    -&gt; name VARCHAR(50),<br>    -&gt; email VARCHAR(50)<br>    -&gt; );<br>mysql&gt; INSERT INTO Users (name,email) VALUES (&#39;Aman&#39;, &#39;aman.sharma@gmail.com&#39;), (&#39;Kabir&#39;, &#39;kabir.sharma@gmail.com&#39;);</pre><p>Here we’ve created a database (docker_db), inside which we’ve created 3 records (id, name, email) and inserted sample Values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ok1m-xpMNO5rhgyVH5Os6g.png" /><figcaption>Created a database, added a table, created records, inserted values.</figcaption></figure><p>Since we’ve mounted a persistent volume <strong>(mysql_data)</strong> to the MySQL container <strong>(mysql_server_container)</strong>, our data should be stored in that volume, remaining intact even if the container is deleted. To verify, we’ll delete the existing container, create a new <strong>(mysql_server_container_new)</strong> using the same volume <strong>(mysql_data)</strong>, and check if our original database <strong>(docker_db)</strong> is still available. This will confirm that the data persists across container lifecycle changes due to the mounted Docker volume.</p><p>Step 4: <strong>Stop and Remove the Container:</strong></p><p>Exit the MySQL prompt and stop and remove the container:</p><pre>#To stop the old container<br>docker stop mysql_server_container</pre><p>Step 5:<strong> Re-run the MySQL Container with the Same Volume:</strong></p><p>Start a new container with the same volume to verify data persistence:</p><pre>#To run a new mysql container with an existing persistent volume (mysql_data)<br>docker run -it -d - name mysql_server_container_new -p 3306:3306 -e MYSQL_ROOT_PASSWORD=mysql@123 -e MYSQL_DATABASE=docker_db -e MYSQL_USER=aman -e MYSQL_PASSWORD=aman@123 - volume mysql_data:/var/lib/mysql mysql:latest</pre><blockquote>This time to create a new container we use docker run command and pass all the required tags, environment variables, image name, port expose information in the same.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dHyn4XskIgmvlEXeprjiYQ.png" /><figcaption>docker run command executed.</figcaption></figure><p>Step 6:<strong> Check for Data Persistence:</strong></p><p>Access the database again to verify that the data is still there:</p><pre>#To execute commands inside container<br>docker exec -it mysql_server_container_new bash<br><br>#After entering inside, execute<br>mysql -u root -p<br><br>#enter pass in the next step<br>Enter password: mysql@123</pre><p>Step 7:<strong> Run the following SQL command to confirm that the data persists:</strong></p><pre>USE docker_db;<br>SELECT * FROM Users;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WvDmtmeNFmV2McgP7VvpYw.png" /><figcaption><strong>mysql_server_container_new</strong> created and has the database, table and the records.</figcaption></figure><p>As we can see the old data is available in the new container. This setup showcases how Docker volumes enable data persistence, an essential feature for any database setup in Docker.</p><blockquote>In this article/blog I’ve only explained about volumes in detail if you want info about <strong>BIND MOUNTS</strong>, do comment below.</blockquote><h3>Docker Networking:</h3><p>Docker networking is an imortant aspect for containerizaion, enabling containers not only to communicate with themselves but also with the outer world. Docker offer different types of networking as follows:</p><h4>1. <strong>Bridge Networking:</strong></h4><p>It is the default network driver for containers, when a docker container is created without specifying the network it starts on the <strong>Bridge Network.</strong></p><h4>Working:</h4><p>Bridge network creates a virtual network (docker0) between existing conatiners and host. Each container gets it’s own virtual network of IP address, allowing containers to communicate with eachother directly but are isolated from the host network by default. Custom bridge networks can also be created which provide more isolation and better control in comparison to default bridge network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/0*DoyAVDXADBJ7mxg6.png" /><figcaption>bridge network representation</figcaption></figure><h4>Example: Setting Up a Bridge Network</h4><p>To verify communication between two containers on a bridge network.</p><h4>1. Creating a custom bridge network</h4><pre>#custom bridge network<br>docker network create custom_bridge</pre><h4>2. Execute two containers on the same created network</h4><pre>#container1<br>docker run -it -d --name container1 --network custom_bridge busybox<br>#container2<br>docker run -it -d --name container2 --network custom_bridge busybox</pre><h4>3. Ping the containers</h4><pre>#ping via hostname<br>docker exec -it container1 ping conatiner2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y1c6ODeGLE-ka8p3AxofCA.png" /><figcaption>we can see, container1 can easily ping to container2 via custom bridge network and vice-versa.</figcaption></figure><h4>Advantages of Using a Bridge Network</h4><ul><li><strong>Isolation</strong>: Containers on the bridge network are isolated from other networks.</li><li><strong>Hostname Resolution</strong>: Custom bridge networks support container name resolution, making inter-container communication easy.</li></ul><h4>2. Host Networking:</h4><p>In the host network the container completely shares the network stack of the Docker host, rather than creating a new network. Containers in host network use the host’s IP address directly, and there’s no network isolation between the host and the container.</p><h4>Working:</h4><p>The container shares the host’s network interfaces, meaning it has direct access to the same IP address and ports. This reduces latency and improve performance as there’s no network layer between the container &amp; the host.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/0*Kj8iBVbnGcMlJ_aq.png" /><figcaption>host network representation</figcaption></figure><h4>Example: Using Host Network for a Web Server</h4><p>To run a web server in a container that’s directly accessible on the host’s IP without port mapping.</p><h4>1. <strong>Run a Web Server Container Using Host Network</strong>:</h4><pre>docker run -it -d --name web-server --network host httpd:latest</pre><h4>2. Accessing the web server:</h4><p>Since it’s using the host network, the web server is accessible directly via the host’s IP address on port 80.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zSEw5BsY2CEpBBQuNkPi1A.png" /><figcaption>Directly running via IP with port forwarding</figcaption></figure><h4>3. Overlay Networking:</h4><p>The <strong>overlay network</strong> allows containers running on different Docker hosts to communicate securely as if they are on the same network. This network type is typically used in <strong>Docker Swarm</strong> or <strong>Kubernetes</strong> environments, where you have multiple nodes (hosts) running containers that need to interact across hosts.</p><h4>Working:</h4><p>An overlay network is created on top of the host network, which enables communication across multiple Docker daemons. Each host in the swarm joins the overlay network, making it possible for containers to talk with each other, even if they are on different hosts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/0*JYZfA_1VKj0gL2M0.png" /><figcaption>overlay network representation</figcaption></figure><blockquote>Here, I’ve just explained about the overlay network, in the future I’ll deploy a full fledged project for the same that is a docker swarm project, so that you can have a clear understanding of the concept.</blockquote><p>15. <strong>docker system prune:</strong> Remove unused containers, networks, images, and volumes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-GGQKn0Yydn2HEB3bLvTlg.png" /><figcaption>docker system prune</figcaption></figure><p>16. <strong>docker stats:</strong> Display resource usage statistics for containers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1E8ZeHo2v0PjK-kHUQExIw.png" /><figcaption>statistics data for each container</figcaption></figure><p>In the next blog I’ll cover topics related to:</p><h4>Docker orchestration:</h4><p><strong>* — —Docker compose</strong></p><p><strong>* — —Docker swarm</strong></p><p><strong>* — —3-tier application deployment</strong></p><p><strong>Conclusion</strong></p><p>Docker streamlines app deployment with portable, scalable containerized environments, making development, testing, &amp; production more efficient. That’s all for this blog! Follow me for more content like this. I hope this guide has helped you get started — happy Dockering!</p><p>Thanks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f7af9b8ad46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing DVCS with Git: A Step-by-Step Guide to Version Control with a Full Working Project]]></title>
            <link>https://medium.com/@aman-devops/implementing-dvcs-with-git-a-step-by-step-guide-to-version-control-with-a-full-working-project-9dcc488e579e?source=rss-2af718aae3fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dcc488e579e</guid>
            <category><![CDATA[dvc]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[projects]]></category>
            <dc:creator><![CDATA[Aman Sharma]]></dc:creator>
            <pubDate>Sat, 19 Oct 2024 14:33:02 GMT</pubDate>
            <atom:updated>2024-11-04T15:00:31.533Z</atom:updated>
            <content:encoded><![CDATA[<p>A Practical Guide to Git: A Real-World Example of Distributed Version Control</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5rMsOYEdkqyw7_ebi-ETQ.jpeg" /></figure><p><strong>Git: The Essential Tool for Distributed Version Control</strong></p><p>Git is the leading tool for Distributed Version Control Systems (DVCS) and plays a crucial role in a developer’s daily tasks within organizations. It allows for efficient tracking, management, and organization of code across multiple projects. Git also enables seamless collaboration among team members, offering powerful features such as commits, branching, and merging.</p><p>These functionalities streamline workflows by reducing the time needed for version control management, conflict resolution, and change integration. Ultimately, this enhances productivity and ensures code stability in complex DevOps environments.</p><p><strong>Why is GIT essential in DevOps environment?</strong></p><p>Imagine a team of developers working on different parts of the same project. How do they track each other’s progress and ensure everything fits together? This is where Git comes in. Git is a powerful version control system that effectively manages, tracks, and organizes code, facilitating smooth collaboration.</p><p>Without Git, keeping track of changes would be challenging, leading to confusion and wasted time. Git enables developers to create separate branches for new features or bug fixes, allowing them to work independently and merge their changes into the main codebase when ready.</p><p>Moreover, Git maintains a comprehensive history of all changes, so teams can easily identify who made updates, what was altered, and revert changes if necessary. This makes Git crucial for enhancing collaboration, ensuring code stability, and accelerating development in a DevOps environment.</p><p><strong>GitFlow branching strategy: A Structured Approach to Git Version Control</strong></p><p>GitFlow provides a clear framework for managing feature development, releases, and hotfixes. It is one of the most popular branching strategy developed by Vincent Driessen in 2010.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/0*l-wg8yaNXXqH40sh" /></figure><p>Git flow strategy uses 5 branches: <strong>main, develop, feature, release and hotfix.</strong></p><p><strong>Main branch: </strong>This branch holds the production-ready code. It reflects the state of the software that is currently live.</p><p><strong>Develop branch: </strong>This serves as the integration branch for features. All completed features are merged here before they are released.</p><p><strong>Feature branch: </strong>Created from the develop branch, feature branches allow developers to work on new features in isolation. Once a feature is complete, it is merged back into develop.</p><p><strong>Release branch</strong>: When it’s time to prepare for a release, a release branch is created from develop. This branch is used for final adjustments and testing before merging into master.</p><p><strong>Hotfix branch</strong>: These are created from master to address urgent bugs in production. Once fixed, hotfixes are merged back into both master and develop.</p><h4>Project 1: Demonstrating Git Across Two AWS EC2 Instances in Mumbai and Singapore</h4><p>In this project, we will demonstrate Git by setting up two AWS EC2 instances located in Mumbai and Singapore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*llU35Do9fDTIzuuNuTKYcQ.png" /><figcaption>mumbai-server, created in mumbai region.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GREmA-FEdylN9DICXRY6ZA.png" /><figcaption>singapore-server, created in singapore region.</figcaption></figure><p>Before getting started, you’ll need to install Git on each EC2 instance. We will use a Debian/Ubuntu operating system for this demonstration. To verify your operating system, execute the following command:</p><pre>cat /etc/os-release.</pre><p>This command will display information about your operating system, ensuring you’re in the correct environment before proceeding with the Git installation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AbCTusPeXP-Ax3b7D7zuWQ.png" /><figcaption>cat /etc/os-release shows the Operating system</figcaption></figure><h4>Installing the Git Environment on Your EC2 Instance</h4><p>To install Git on your EC2 instance, navigate to (<a href="https://git-scm.com/downloads"><strong>Git’s official website</strong></a><strong>)</strong> and download the version that suits your system requirements. Since we’re using a Debian/Ubuntu-based system, we will utilize the <strong>apt-get</strong> package manager for installation. Execute the following command to install Git:</p><pre>apt-get install git</pre><p>Once the installation is complete, you can verify the installation and find the location of the Git binary by running:</p><pre>which git</pre><p>This command will display the path to the Git executable (/usr/bin/git). Alternatively, you can check the version of Git installed by executing:</p><pre>git --version</pre><p>This command will confirm that Git is properly installed and provide you with the version number, ensuring your environment is ready for version control tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hJhPzkIG1JyF_XcBOqGzmg.png" /><figcaption>git — version shows 2.43.0</figcaption></figure><h4>Configuring Your Git Username and Email</h4><p>When using Git for version control, it’s essential to configure your identity with a username and email address. This information is stored in every commit you make, allowing Git to associate changes with a specific author. Proper configuration is crucial, especially in team environments, as it maintains accountability and transparency regarding who made changes and when.</p><h4>Why Username and Email Configuration is Important</h4><p>Every commit in Git includes metadata that is crucial for collaboration. This metadata consists of:</p><ul><li><strong>Author Name</strong>: The username that identifies who made the changes.</li><li><strong>Email Address</strong>: The email linked to the author, providing clear identification in collaborative projects.</li></ul><p>Properly configuring this information enhances accountability and makes it easier to track contributions within the team.</p><pre>#configuring username<br>git config --global user.name &quot;user&quot;<br><br>#configuring email<br>git config --global user.email &quot;user@email.com<br><br>#to check whether username and email are created or not<br>git config --list</pre><p><strong>mumbai-server:</strong></p><p>git config — global user.name “Aman”</p><p>git config — global user.email “<a href="/service/mailto:aman.sharma@gmail.com">aman.sharma@gmail.com</a>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2sY4S1NAwrO_Y-J7gCU1QA.png" /><figcaption>configured for mumbai-server</figcaption></figure><p><strong>singapore-server:</strong></p><p>git config — global user.name “Kabir”</p><p>git config — global user.email “<a href="/service/mailto:kabir.sharma@gmail.com">kabir.sharma@gmail.com</a>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mjv7F1BQO4aC3Iigvt3S7g.png" /><figcaption>configured for singapore-server</figcaption></figure><h4>Create a Remote Repository to push the code to remote se</h4><p>Next, you’ll need to create a remote repository on a Git hosting platform such as GitHub, GitLab, or Bitbucket. For this example, let’s assume you’re using GitHub.</p><ol><li>Log in to your GitHub account.</li><li>Click on the “New” button or “Create Repository” link on the homepage.</li><li>Fill in the repository name and description, and choose whether the repository is public or private.</li><li>Click on “Create Repository.”</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*Vb-N2tcDcawa97L2eJIDGw.png" /><figcaption>We create a GitHub repository named <strong>DevOps-Test</strong>, enabling users to push their committed code.</figcaption></figure><p>In this setup, we have created a Git repository named <strong>DevOps-Test</strong>, where code from both the Mumbai and Singapore servers will be pushed. This allows remote team members to collaborate seamlessly on the project, manage changes, and track code versions efficiently. By pushing and pulling the <strong>calculator.sh</strong> file across different geographic locations, team members can work concurrently while maintaining a shared, up-to-date codebase, streamlining the development process.</p><h4><strong>Initializing the GIT environment:</strong></h4><p><strong>git init:</strong></p><p>The <strong>git init</strong> command creates a new repository, it turns a regular directory into git repository, allowing you to track changes and manage version control locally. When you run <strong>git init</strong> in a directory, Git creates a hidden subdirectory named <strong>.git</strong>. This folder contains all the necessary metadata and configuration files that Git needs to manage your project’s version history. After initializing, you can start adding files, committing changes, and creating branches.</p><pre>git init</pre><p>In the image below, before running the <strong>git init</strong>, we can see there is no <strong>.git</strong> file in the directory as we have checked by <strong>ls -la</strong>. But as soon as we run the <strong>git init</strong> command, a new file<strong> (.git)</strong> is added in the (<strong>/home/ubuntu/devops directory).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9oDgbgPty0tzMi1L48-Tkw.png" /><figcaption>.git file is made after git init</figcaption></figure><p><strong>Calculator Shell Script Example to Understand Git Workflow:<br></strong>After initializing the git init, we’ve created a shell script for a basic calculator program in the <strong>(mumbai-server) </strong>where we’ve only added addition and subtraction functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c5KUXyzqKKYEUKWeDngEFA.png" /><figcaption>Additon and Subtraction code only (mumbai-server)</figcaption></figure><p>Now we’ll <strong>add</strong> the partial code from the mumbai-server (<strong>workspace/work</strong>) directory (/home/ubuntu/devops) to the <strong>staging area</strong> of our GIT repository and then <strong>commit</strong> it to our <strong>local repository</strong>, via these steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*n9gUg3OQputbO668OULP4g.png" /><figcaption>3 stages of git init repo workflow</figcaption></figure><p><strong>git add:</strong></p><p>The <strong>git add </strong>command moves changes from the working directory to the staging area, preparing them for commit.</p><pre>git add .</pre><p><strong>git commit:</strong></p><p>After staging, <strong>git commit -m “our commit message</strong>” this command commits the changes to our local repository. This command records a snapshot of the history of changes, creating a point in history we can rollback to in need.</p><pre>git commit -m &quot;Only addition and Subtraction functionality&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iKKLT2LmwG0BKM98e7zJlA.png" /><figcaption>git commit, is used to save your staged changes to the local repository with a commit message explaining the changes made.</figcaption></figure><p><strong>git status:</strong></p><p>The git status command is used to display the state of the working directory and the staging area. It lets us see which changes have been staged, which haven’t, and which files are not being tracked by Git. This command is very useful when you’re working with Git to understand the current state of your repository before committing changes.</p><pre>git status</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jcsX0ZLgl3Y5AXvYNKJIFg.png" /><figcaption><strong>Changes to be committed</strong>: The file calculator.sh is staged and ready to be committed.</figcaption></figure><p><strong>git log:</strong></p><p>The <strong>git log</strong> command is used to display the commit history of a Git repository. It provides a detailed log of all the commits made to the project, including information like the commit hash, author, date, and the commit message.</p><pre>git log</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SAHKr4U6Z3i7L_kTZQgVrg.png" /><figcaption>shows all info related to the commit.</figcaption></figure><p><strong>git show:</strong></p><p>The <strong>git show</strong> command is used to display detailed information about a specific commit or object in a Git repository. It provides a snapshot of the changes introduced in the commit, along with metadata like the author, date, and commit message.</p><pre>#syntax for a specific commit<br>git show &lt;commit-id&gt;<br><br>#we can also use first 8 hexa-numerical value of commit id<br>git show 0ef2a3e331ed182c88406f211eb5b264202bb41a</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uzSFQse8QoPUBQ-UDpfbkw.png" /><figcaption>git show, displays all the info related to the code along with the actual code.</figcaption></figure><h4>Add the Remote Repository</h4><p>Now that your remote Git repository is ready, you need to link it to your local repository. To do this, use the git remote command.</p><h4><strong>1. Add the remote repository URL:</strong></h4><pre>#syntax<br>git remote add origin https://github.com/yourusername/your-repository.git</pre><pre>#for our usecase<br>git remote add origin https://github.com/aman1588/DevOps-Test.git</pre><pre>#Verify that the remote repository has been added:<br>git remote -v</pre><blockquote>The below information is just for exceptional cases</blockquote><h4>2. Verify Your Branch Name</h4><p>In some Git installations, the default branch may be named <strong>master</strong> instead of <strong>main</strong>. Check the current branch name with:</p><pre>git branch</pre><p>To rename <strong>master</strong> to <strong>main</strong>:</p><pre>git branch -M main</pre><h4>3. Push to GitHub</h4><p>Now, push to GitHub with the correct branch name:</p><pre>git push origin main</pre><p><strong>In case you face issue, pull the changes from the remote branch.</strong></p><p>Run the following command to pull any updates from the remote main branch into your local branch:</p><pre>git pull origin main --rebase</pre><p>Then again execute, <strong>git push origin main</strong>.</p><p>Once we execute this command our local repository is linked to the GitHub repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gr4EiTs7c4V_3UHwwA4hDw.png" /><figcaption>copy the https link to add to the git remote add origin command</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HI3q7M3KUAniQHTbW3hwTQ.png" /><figcaption>remote origin connection established</figcaption></figure><p><strong>git push:</strong></p><p>The git push command is a critical part of working with Git, allowing us to transfer our local repository&#39;s commits to a remote repository, such as GitHub. After we’ve made changes to our code, staged, and committed them in our local repository, git push uploads those commits to a remote server, making our changes accessible to other collaborators and ensuring that our work is backed up.</p><pre>#syntax<br>git push &lt;remote&gt; &lt;branch&gt;<br><br>#usecase<br>git push origin master</pre><p>In this case origin, is the URL. master, is the branch. This command syncs the local master branch with the remote, ensuring the remote repository reflects the latest state of your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VRsu0MloSF8iqqb88bn_6g.png" /></figure><p>You’ll need to provide username and password (Git uses <strong>TOKEN</strong>) which can be generated from <strong>developer options</strong> in the settings, then <strong>Pesonal access tokens (classic)</strong>, copy the <strong>generated token</strong> to use as a password while executing the <strong>git push</strong> command. Once this is done the code is pushed to the central repository (<strong>DevOps-Test</strong>) as a commit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*Xcd_oBVxITEGYUUh4XV7Xg.png" /><figcaption>Here, calculator.sh is pushed to central GIT repo (DevOps-Test)</figcaption></figure><p>Below, you can see that the code from our local repository is pushed to the Central Github repository (<strong>DevOps-Test</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*0CQw7tM2ExNmxh4W8t7mNw.png" /><figcaption>calculator.sh code now present on github repository, pushed from mumbai-server repo.</figcaption></figure><h4>Testing the Github connectivity and connection by updating code:</h4><p>After the Mumbai developer completes his part of the code, he will outline the Singapore developer’s tasks by adding comments (using #). The Singapore developer will then pull the latest code from the central repository to review the work done by the Mumbai developer. After analyzing the overall code, he will implement the functionality mentioned in the comments and push the updated code back to the central repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XHRQUkd01NUNhkCKXz8kkA.png" /><figcaption>Singapore developer will add (multiplication and divison) functionality in the code.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eRpdX3ScPmCA_b3eGeOv7Q.png" /><figcaption>Above steps repeated in order, to commit changes to local repo and then push them to central repo. This step is again repeated for the new update of the (#) line which tells the singapore dev about his role in the code.</figcaption></figure><p>Changes reflected in <strong>history, </strong>after executing <strong>git push origin master</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ch7Q9mUutTutGPgLUiFV5w.png" /><figcaption>Second commit message along with the actual input added to the existing file.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*BdHPdgylQRHR44KWpu0IZQ.png" /><figcaption>Comment in the code for singapore user instructing him to add multiplication and divison functionality added.</figcaption></figure><h4>Now, setting up singapore-server:</h4><p>Do the below steps in order that is as follows:</p><ol><li>sudo su</li><li>apt-get update -y</li><li>apt-get install git -y</li><li>mkdir /home/ubuntu/devops</li><li>cd devops/</li><li>git init</li><li>git status → git log (No output would be reflected as the repository is not connected to central Git repository (DevOps-Test).</li><li>git pull origin master</li><li>git log</li><li>git show 224f5c1e1a68499cbf9d4991d2ec03b0a978111f</li></ol><p>Step by step representation of the steps followed in the <strong>singapore-server.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a1WuKovxEYu0qzc-cdbpjA.png" /><figcaption>git init → ls -la</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IyZilNKCybW64x2jzM5hwg.png" /><figcaption>git log → git status</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fB2oufrtfRFub53g6VW9sQ.png" /><figcaption>git pull origin master → ls → shows calculator.sh in our local repo</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5QLv_n2j4hG0NfGuQvcMdw.png" /><figcaption>git log → to check the commit id of the last commit</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LKsvQc0YghIiydmL_C-hgg.png" /><figcaption>git show &lt;commit_id&gt; → to check the last/recent changes in the code.</figcaption></figure><p>Multiplication and Division functionality added in the calculator.sh. Code is tested by performing the execution and runs perfectly. Now, same steps are followed to add, commit and then push the code to the central repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lskReaqSiH56mNUjHJPr9g.png" /><figcaption>code added in calculator.sh and tested. <strong>git status</strong> → shows that as of now changes are not saved to the staging server. Then we execute <strong>git add .</strong> → which adds the code to staging server preparing it for commit to the local repo. Finally <strong>git commit -m “message”</strong> → is executed to add it to the local repository. <strong>git status</strong> → now shows, nothing to commit, as of now. <strong>git log</strong> → shows the commit id of the recently commited code in the local repo.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jZw32EgApj5CaRMyezZNLg.png" /><figcaption><strong>git show &lt;commit_id&gt;</strong> shows the changes that were made to piece of code (-) sign indicates the lines that were removed, (+) sign indicates the lines that were added as the new functionality.</figcaption></figure><p><strong>git push</strong> command sends the updated code to the cenral repo and updates the changes there. Final code is ready for use and provides all the functionality.</p><p>Below is the representation of the update/change history of the code added via user: “Kabir” and email: “kabir.sharma@gmail.com” to the central repo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1X9ApaFIlyCw4bTFncg8NQ.png" /><figcaption>Image shows the latest modified code via user “Kabir”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*H0OT1GYgHNWCxBnii6ynvg.png" /><figcaption>New lines of code have been added to the existing codebase, reflecting the overall objective of the project: to utilize DVCS (Git) for tracking changes and pushing it to a remote server (GitHub). This allows other users to collaborate, manage, and work in parallel to improve code speed, reduce time, and enhance functionality.</figcaption></figure><h4><strong>Conclusion</strong></h4><p>Version Control Systems are essential to modern software development, and Git has transformed the way teams collaborate on code. In this blog post, we showcased a practical example involving our Mumbai and Singapore servers, demonstrating how users can effectively work together using Git as a Distributed Version Control System (DVCS).</p><p>A developer on the Mumbai server wrote and pushed their code to GitHub, enabling seamless collaboration. The Singapore developer then pulled the latest changes, added their enhancements, and pushed the updated code back to the remote repository. This workflow illustrates the core advantages of DVCS: efficient collaboration, easy tracking of changes, and the ability to manage contributions from multiple developers in real-time.</p><p>By leveraging Git, teams can significantly improve their code quality, reduce development time, and enhance overall functionality. This project exemplifies how DVCS can facilitate teamwork across geographical boundaries, empowering developers to work in parallel and innovate faster.</p><p>Thanks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dcc488e579e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Version Control Systems — Centralized vs Distributed]]></title>
            <link>https://medium.com/@aman-devops/version-control-systems-centralized-vs-distributed-f47467e4428e?source=rss-2af718aae3fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/f47467e4428e</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[version-control-system]]></category>
            <category><![CDATA[devops-tool]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Aman Sharma]]></dc:creator>
            <pubDate>Fri, 18 Oct 2024 07:17:28 GMT</pubDate>
            <atom:updated>2024-10-18T07:17:28.737Z</atom:updated>
            <content:encoded><![CDATA[<h3>Version Control Systems — Centralized vs Distributed</h3><h3>Mastering Version Control in DevOps: Essential Tools, Best Practices, and CI/CD Integration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GkKKDlDI7vpY8lni" /></figure><h3>Introduction to Version Control Systems</h3><p>Version Control Systems (VCS) are crucial tools in modern software development and DevOps practices. They help track changes to codebases, enabling developers to collaborate, manage versions, and maintain a history of modifications. By using VCS, teams can work simultaneously on features, ensure smoother collaboration, and revert to previous code versions when needed.</p><p>Through version control systems, developers can maintain a comprehensive history of changes, including details such as:</p><ol><li><strong>who </strong>made a specific modification.</li><li><strong>what </strong>changes were introduced</li><li><strong>when </strong>the changes occurred.</li></ol><h3>Why Version Control is Essential in DevOps</h3><p>In the context of DevOps, version control systems play an integral role in ensuring seamless collaboration, automation, auditability and rollbacks. DevOps emphasizes a continuous delivery pipeline, and VCS allows multiple team members to work on the same project without conflicting changes. It supports automation by enabling Continuous Integration (CI), where new changes are merged, tested, and validated regularly. Furthermore, version control ensures that development history is tracked, changes are audited, and in case of failure, teams can quickly roll back to a previous stable state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*F2AOzaHrFL103r6n" /></figure><h3>Using VCS as an Individual:</h3><h4>Tracking Changes</h4><p><strong>Scenario:</strong> You’re working as a software developer and want to add new features or experiment with ways to make your code run faster and reduce execution time.</p><p><strong>Without Version Control System:</strong> In this situation, you’d have to manually create backups of the files or projects you’re working on. Since there could be many files, it can become challenging to keep track of which files you’ve backed up and which ones you may have missed.</p><p><strong>With Version Control System:</strong> Using a VCS, you can create a new branch to test features or make changes. If the changes don’t work out, you can easily switch back to a previous version, discard the unwanted changes, or merge successful updates into the main codebase.</p><p>This makes development more efficient and ensures that no progress is lost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*rUpwe3QZwxHvoTFe.png" /></figure><h4>Code consistency</h4><p><strong>Scenario: </strong>You’re in the process of developing a new feature, but a bug in the current release requires immediate fixing.</p><p><strong>Without Version Control System:</strong> In this situation, you’d need to either manually back up your changes or risk losing the current progress. You might make changes to the existing code and risk introducing new issues or breaking the feature you’re working on. Restoring your previous progress would be complicated without backups.</p><p><strong>With Version Control System:</strong> Using a VCS, you can easily switch to a previous stable branch (or create a new one) to fix the bug without affecting your current work. Once the bug is resolved, you can return to your feature development branch, ensuring that no progress is lost and the stability of the code is maintained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q1dqaf-xdcr4X28z.png" /></figure><h3>Using VCS as a team:</h3><h4>Collaboration</h4><p><strong>Scenario: </strong>Several team members are working on the same project simultaneously, and a teammate accidentally overwrites your code.</p><p><strong>Without Version Control System:</strong> There’s a chance that code changes will get lost or overwritten. You might have to manually figure out what was changed, which can lead to confusion, loss of productivity, and even breaking the functionality of the project.</p><p><strong>With Version Control System:</strong> Each team member can work in their own branch, merging changes only when they are ready. The VCS tracks every modification, allowing easy rollbacks in case of conflicts. This ensures code stability and keeps the entire project safe from accidental overwrites.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*chJeEnrcXEe0cm24" /></figure><h4><strong>History and Accountability:</strong></h4><p><strong>Scenario:</strong> Your team is collaborating on a project, and after a recent deployment, a bug is discovered. No one is sure who made the change or what exactly caused the issue.</p><p><strong>Without Version Control System:</strong> In this case, tracking who made the changes and identifying the root cause of the bug can be a long and manual process. The team may have to review code files manually or depend on individual memory, leading to confusion and potentially wasting time.</p><p><strong>With Version Control System:</strong> Every commit made by a team member is logged with details such as the author, timestamp, and exact code changes. This history makes it easy to pinpoint which commit introduced the bug and who made the change. You can then discuss it with the responsible team member and work on a solution, ensuring clear accountability and a structured method to track changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pHeJcowWIRX8IWCv" /></figure><blockquote>Now that we have a solid understanding of Version Control Systems (VCS) and their role in optimizing workflows for both organizations and day-to-day development tasks, let’s explore the different types of VCS (such as centralized and distributed) and how to set up a VCS like Git on your local system for version tracking, branching, and collaboration.</blockquote><h3>Types of Version Control Systems</h3><p>Version control systems (VCS) are essential tools in software development, enabling teams to manage changes to their codebase effectively. They can be classified into two main types:</p><ol><li>Centralized Version Control Systems (CVCS)</li><li>Distributed Version Control Systems (DVCS)</li></ol><h4>Centralized Version Control Systems (CVCS)</h4><p>Centralized VCS, such as Subversion (SVN) and Concurrent Versions System (CVS), operate on a model where a single central server holds the codebase. Here’s how they function:</p><ul><li><strong>Central Reference Point:</strong> The central repository acts as the primary source for all code. Developers check files in and out from this central location, which helps maintain a consistent codebase.</li><li><strong>Real-time Collaboration:</strong> Changes are immediately visible to all team members, allowing for straightforward collaboration. However, this also means that if the central server goes down, developers lose access to the entire codebase.</li><li><strong>Limited Offline Access:</strong> Developers need to be connected to the central server to commit changes or retrieve the latest code. This can hinder productivity if network issues arise.</li></ul><p>While CVCS provides a straightforward model, it can be less flexible than its distributed counterpart, especially in environments that require frequent offline work or where teams are remotely located.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*x9SVknsec4H-Susm" /></figure><h4><strong>Distributed Version Control Systems (DVCS)</strong></h4><p>Distributed VCS, like Git and Mercurial, offer a more flexible and robust approach to version control. Here are the key features:</p><ul><li><strong>Local Repositories:</strong> Each developer has a complete local copy of the repository, including its history. This means developers can work independently and commit changes without needing constant access to a central server.</li><li><strong>Enhanced Collaboration:</strong> Developers can create branches for new features or bug fixes without affecting the main codebase. Once changes are verified, they can be merged back into the primary branch. This branching model supports parallel development and improves workflow efficiency.</li><li><strong>Fault Tolerance:</strong> Since every developer has a full copy of the repository, the risk of data loss due to server failure is significantly reduced. If the central server is compromised or goes down, developers can continue working with their local copies.</li></ul><p>In modern DevOps practices, Git has become the most widely adopted VCS due to its distributed nature, powerful branching and merging capabilities. It integrates seamlessly with (CI/CD) workflows, allowing teams to automate testing and deployment processes effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/0*Cl_1JvYCZk1QWL46" /></figure><h3>Best Practices for Version Control in DevOps</h3><p>To optimize version control in a DevOps environment, teams should follow these best practices:</p><h4>1. Commit Often</h4><p>Commit small, incremental changes frequently to isolate bugs, enhance tracking, and improve collaboration. Frequent commits minimize merge conflicts, allowing multiple developers to work efficiently.</p><h4>2. Use Meaningful Commit Messages</h4><p>Craft descriptive commit messages that explain the changes made and their purpose.</p><h4>3. Implement a Branching Strategy</h4><p>Adopt a structured branching model like GitFlow. Use feature branches for new developments, release branches for testing, and hotfix branches for urgent fixes to maintain stability and streamline integration.</p><h3>Conclusion</h3><p>By following these best practices for version control in a DevOps environment, teams can foster a culture of collaboration, maintain high code quality, and streamline their development processes. Embracing these practices not only enhances productivity but also contributes to the overall success of software development projects.</p><p>Next post will cover Introduction to GIT as a (DVCS) and it’s use-case. Please follow me and drop a comment if you liked the blog.</p><p>Thanks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f47467e4428e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>