<?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 Shanthi bojja on Medium]]></title>
        <description><![CDATA[Stories by Shanthi bojja on Medium]]></description>
        <link>https://medium.com/@shanbojja?source=rss-c047ef51b3ef------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*oq-bj__VTC41Twzo</url>
            <title>Stories by Shanthi bojja on Medium</title>
            <link>https://medium.com/@shanbojja?source=rss-c047ef51b3ef------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:25:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shanbojja/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[Linux Files, Permissions and Ownership: Real-Time Production Troubleshooting Scenarios]]></title>
            <link>https://medium.com/@shanbojja/linux-files-permissions-and-ownership-real-time-production-troubleshooting-scenarios-29ac106962a1?source=rss-c047ef51b3ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/29ac106962a1</guid>
            <category><![CDATA[linux-troubleshooting]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[linux-administrator]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Shanthi bojja]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 03:11:43 GMT</pubDate>
            <atom:updated>2026-11-23T03:11:43.256Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OhzoOMwopdnnkPyhklnv-w.png" /></figure><p>You are working as a Linux administrator in a production environment. Suddenly, an application team raises an incident:</p><p><strong>“The application is unable to read its configuration file. We are getting Permission Denied errors. Please investigate.”</strong></p><p>You connect to the Linux virtual machine through SSH. The application service is running, but it cannot access one of its required files.</p><p>Where do you start?</p><p>Do you immediately run chmod 777?</p><p>Absolutely not.</p><p>In production environments, changing permissions without understanding the problem can create security risks and introduce additional failures.</p><p>A Linux administrator must understand file ownership, permissions, users, groups, directory access, and access control mechanisms before making changes.</p><p>In this article, we will investigate realistic Linux production scenarios and learn the commands used by Linux administrators and DevOps engineers.</p><h3>1. Understand Linux File Permissions</h3><p>Linux uses a permission model to control who can access files and directories.</p><p>Every file and directory has three important permission categories:</p><ul><li><strong>User (u):</strong> The owner of the file.</li><li><strong>Group (g):</strong> Users belonging to the assigned group.</li><li><strong>Others (o):</strong> Everyone else.</li></ul><p>There are three basic permissions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*KPOhFHS8YjfkWiyb1GApSQ.png" /></figure><p>Let’s inspect a file:</p><pre>ls -l application.conf</pre><p>Example output:</p><pre>-rw-r----- 1 appuser appgroup 2048 Nov 21 10:30 application.conf</pre><p>Let’s understand the output:</p><ul><li>- indicates a regular file.</li><li>rw- represents permissions for the owner.</li><li>r-- represents permissions for the group.</li><li>--- represents permissions for others.</li><li>appuser is the file owner.</li><li>appgroup is the assigned group.</li><li>2048 is the file size in bytes.</li></ul><p>The permissions mean:</p><ul><li>Owner can read and modify the file.</li><li>Group members can read the file.</li><li>Other users have no access.</li></ul><p><strong>Important:</strong> Directory permissions behave differently from file permissions. A directory’s read permission allows listing its entries, while execute permission allows traversing it. Accessing a file also requires appropriate permissions on its parent directories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4yLZvOTW85UkSikZ" /></figure><h3>2. Essential Commands for Inspecting Files and Permissions</h3><p>Before troubleshooting production issues, become comfortable with these commands.</p><h3>Check the current directory</h3><pre>pwd</pre><p>Displays the full path of your current working directory.</p><h3>List files with permissions</h3><pre>ls -l</pre><p>Displays file ownership, permissions, size, and modification time.</p><h3>Display hidden files</h3><pre>ls -la</pre><p>Displays hidden files and directories, including names beginning with ..</p><h3>Check file details</h3><pre>stat application.conf</pre><p>Displays detailed information, including permissions, owner, group, file size, and timestamps.</p><h3>Check the current user</h3><pre>whoami</pre><p>Displays the username of the current session.</p><h3>Check user and group IDs</h3><pre>id</pre><p>Example output:</p><pre>uid=1001(appuser) gid=1001(appgroup) groups=1001(appgroup),1002(devops)</pre><p>This helps identify which user and groups are associated with the current session.</p><h3>Check file type</h3><pre>file application.conf</pre><p>Identifies the type of file.</p><p>These commands are often the first tools used during a Linux permission investigation.</p><h3>3. Scenario 1: Application Cannot Read a Configuration File</h3><p><strong>Production incident:</strong></p><p>The application team reports:</p><pre>Permission denied: /opt/myapp/config/application.conf</pre><p>The application service is running, but it cannot read its configuration file.</p><h3>Step 1: Connect to the VM</h3><pre>ssh adminuser@192.168.1.100</pre><p>Replace the example username and IP address with the actual VM details.</p><h3>Step 2: Check the file permissions</h3><pre>ls -l /opt/myapp/config/application.conf</pre><p>Example output:</p><pre>-rw------- 1 root root 2048 Nov 21 10:30 application.conf</pre><p>What is the problem?</p><p>The file belongs to root, and only root has permission to read or modify it.</p><p>However, the application runs using the appuser account.</p><h3>Step 3: Identify the application process user</h3><pre>ps -ef | grep myapp</pre><p>Example output:</p><pre>appuser  2150  1  0 10:20 ?  00:00:15 /opt/myapp/bin/start.sh</pre><p>The application is running as appuser.</p><h3>Step 4: Check the parent directory permissions</h3><pre>namei -l /opt/myapp/config/application.conf</pre><p>This command displays the permissions and ownership of every directory component in the path.</p><p>Why is this important?</p><p>Even if the configuration file has the correct permissions, the application cannot access it if it cannot traverse one of its parent directories.</p><h3>Step 5: Identify the correct remediation</h3><p>Suppose the intended design is that appuser should read the configuration file, but only administrators should modify it.</p><p>One possible solution is to assign the file to the application group:</p><pre>sudo chown root:appgroup /opt/myapp/config/application.conf</pre><p>Then grant read permission to the group:</p><pre>sudo chmod 640 /opt/myapp/config/application.conf</pre><p>Verify:</p><pre>ls -l /opt/myapp/config/application.conf</pre><p>Expected output:</p><pre>-rw-r----- 1 root appgroup 2048 Nov 21 10:30 application.conf</pre><p>The application user must be a member of appgroup, and the parent directories must allow traversal.</p><h3>Step 6: Verify the application user’s access</h3><pre>sudo -u appuser test -r /opt/myapp/config/application.conf &amp;&amp; echo &quot;Readable&quot; || echo &quot;Not readable&quot;</pre><p>Expected output:</p><pre>Readable</pre><p>This tests file readability as the application account.</p><p>Finally, check the application logs and perform an appropriate application health check.</p><p><strong>L3 insight:</strong> Never assume that changing the file permission alone will resolve the issue. Check the process identity, supplementary groups, parent directory permissions, ACLs, and security controls before deciding on a fix.</p><h3>4. Scenario 2: Application Cannot Write to a Log Directory</h3><p><strong>Production incident:</strong></p><p>The application team reports:</p><pre>ERROR: Unable to write application logs<br>Permission denied: /var/log/myapp/application.log</pre><p>The application is running, but new log entries are not being written.</p><h3>Step 1: Inspect the directory</h3><pre>ls -ld /var/log/myapp</pre><p>Example output:</p><pre>drwxr-xr-x 2 root root 4096 Nov 21 10:00 /var/log/myapp</pre><p>The directory belongs to root.</p><p>The application runs as appuser.</p><h3>Step 2: Check the log file</h3><pre>ls -l /var/log/myapp/</pre><p>Example output:</p><pre>-rw-r--r-- 1 root root 1048576 Nov 21 10:00 application.log</pre><p>The application user does not have permission to write to this file.</p><h3>Step 3: Confirm the application identity</h3><pre>ps -eo user,pid,cmd | grep &#39;[m]yapp&#39;</pre><p>Example:</p><pre>appuser  2150 /opt/myapp/bin/start.sh</pre><h3>Step 4: Apply the appropriate ownership</h3><p>If appuser is the designated account responsible for application logs, an administrator can assign the log directory to that account:</p><pre>sudo chown -R appuser:appgroup /var/log/myapp</pre><p>Set suitable directory and file permissions:</p><pre>sudo find /var/log/myapp -type d -exec chmod 750 {} \;<br>sudo find /var/log/myapp -type f -exec chmod 640 {} \;</pre><h3>Step 5: Verify</h3><pre>ls -ld /var/log/myapp<br>ls -l /var/log/myapp/</pre><p>Test write access as the application user:</p><pre>sudo -u appuser test -w /var/log/myapp &amp;&amp; echo &quot;Writable&quot; || echo &quot;Not writable&quot;</pre><p><strong>Important:</strong> Recursive ownership changes should not be executed blindly on production directories. Confirm that the application is supposed to own these files and check whether log rotation, deployment tools, or other services depend on the existing ownership.</p><h3>5. Understand chmod: Changing File Permissions</h3><p>The chmod command changes file and directory permissions.</p><p>There are two common methods:</p><ol><li>Numeric permissions.</li><li>Symbolic permissions.</li></ol><h3>Numeric permission method</h3><p>Each permission has a numeric value:</p><ul><li>Read = 4</li><li>Write = 2</li><li>Execute = 1</li></ul><p>We add these values to create the permission for each category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*GU2SWDzhBakmpJB4KcKZKA.png" /></figure><p>Example:</p><pre>chmod 755 script.sh</pre><p>This means:</p><ul><li>Owner: read, write, execute.</li><li>Group: read, execute.</li><li>Others: read, execute.</li></ul><p>Another example:</p><pre>chmod 644 application.conf</pre><p>This means:</p><ul><li>Owner: read and write.</li><li>Group: read.</li><li>Others: read.</li></ul><p>For a sensitive configuration file, a more restrictive permission might be appropriate:</p><pre>chmod 600 application.conf</pre><p>Only the owner can read and write the file.</p><h3>Symbolic permission method</h3><p>You can also change permissions using symbols.</p><p>Grant execute permission to the owner:</p><pre>chmod u+x script.sh</pre><p>Remove write permission from others:</p><pre>chmod o-w application.conf</pre><p>Grant read permission to the group:</p><pre>chmod g+r application.conf</pre><p>Grant read and execute permission to everyone:</p><pre>chmod a+rx directory</pre><p>Remove all permissions from others:</p><pre>chmod o-rwx application.conf</pre><p><strong>Production tip:</strong> Avoid chmod 777 as a default fix. It grants read, write, and execute permissions to everyone and can expose sensitive files or allow unauthorized modification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*KMgQH2WHqUj_rsyO" /></figure><h3>6. Scenario 3: Script Is Not Executing</h3><p><strong>Production incident:</strong></p><p>A scheduled automation script fails with:</p><pre>/bin/bash: /opt/scripts/backup.sh: Permission denied</pre><h3>Step 1: Inspect the script</h3><pre>ls -l /opt/scripts/backup.sh</pre><p>Example output:</p><pre>-rw-r--r-- 1 appuser appgroup 512 Nov 21 10:30 backup.sh</pre><p>The file does not have execute permission.</p><h3>Step 2: Grant execute permission</h3><pre>chmod u+x /opt/scripts/backup.sh</pre><h3>Step 3: Verify</h3><pre>ls -l /opt/scripts/backup.sh</pre><p>Expected output:</p><pre>-rwxr--r-- 1 appuser appgroup 512 Nov 21 10:30 backup.sh</pre><h3>Step 4: Execute the script</h3><pre>/opt/scripts/backup.sh</pre><p>Alternatively, when the script is readable and the appropriate interpreter is available:</p><pre>bash /opt/scripts/backup.sh</pre><h3>Step 5: If it still fails</h3><p>Check the following:</p><pre>namei -l /opt/scripts/backup.sh<br>file /opt/scripts/backup.sh<br>head -n 1 /opt/scripts/backup.sh</pre><p>Investigate:</p><ul><li>Parent directory execute permissions.</li><li>Script interpreter path.</li><li>Incorrect line endings.</li><li>Filesystem mounted with noexec.</li><li>Security policies such as SELinux.</li></ul><p><strong>L3 insight:</strong> A file having execute permission does not guarantee that the operating system will execute it. The filesystem mount options, interpreter, parent directories, and security policies also matter.</p><h3>7. Scenario 4: SSH Login Fails Because of Incorrect Key Permissions</h3><p><strong>Production incident:</strong></p><p>An administrator attempts to connect to a VM using an SSH private key:</p><pre>ssh -i production.pem adminuser@192.168.1.100</pre><p>The connection fails with a message similar to:</p><pre>WARNING: UNPROTECTED PRIVATE KEY FILE!<br>Permissions 0644 for &#39;production.pem&#39; are too open.</pre><p>SSH refuses to use the private key because it is accessible to other users.</p><h3>Step 1: Check the key permissions</h3><pre>ls -l production.pem</pre><p>Example:</p><pre>-rw-r--r-- 1 user user 1675 Nov 21 10:30 production.pem</pre><h3>Step 2: Restrict access</h3><pre>chmod 600 production.pem</pre><p>This gives the owner read and write access only.</p><h3>Step 3: Verify</h3><pre>ls -l production.pem</pre><p>Expected output:</p><pre>-rw------- 1 user user 1675 Nov 21 10:30 production.pem</pre><h3>Step 4: Retry the SSH connection</h3><pre>ssh -i production.pem adminuser@192.168.1.100</pre><p><strong>L3 insight:</strong> If SSH still fails, investigate the username, public-key authorization, SSH server logs, network connectivity, and server-side SSH configuration. Do not assume every SSH failure is caused by private-key permissions.</p><h3>8. Scenario 5: Multiple Teams Need Access to a Shared Directory</h3><p><strong>Production scenario:</strong></p><p>Two teams work on the same application:</p><ul><li>Development team</li><li>Operations team</li></ul><p>Both teams need to create and modify files inside:</p><pre>/opt/shared/application</pre><p>Giving everyone full access is not a good solution.</p><p>Linux provides group ownership and special directory permissions to manage shared access.</p><h3>Step 1: Create a shared group</h3><pre>sudo groupadd appteam</pre><h3>Step 2: Add users to the group</h3><pre>sudo usermod -aG appteam devuser<br>sudo usermod -aG appteam opsuser</pre><p>The -aG options add the users to the supplementary group without replacing their existing supplementary group memberships.</p><p>Users generally need to start a new login session for the membership change to take effect.</p><h3>Step 3: Assign group ownership</h3><pre>sudo chown root:appteam /opt/shared/application</pre><h3>Step 4: Set directory permissions</h3><pre>sudo chmod 2770 /opt/shared/application</pre><p>What does 2770 mean?</p><ul><li>2 enables the setgid bit on the directory.</li><li>Owner has read, write, and execute.</li><li>Group has read, write, and execute.</li><li>Others have no access.</li></ul><p>The setgid bit causes new entries created inside the directory to inherit the directory’s group, subject to normal filesystem and access-control behavior.</p><h3>Step 5: Verify</h3><pre>ls -ld /opt/shared/application</pre><p>Expected output:</p><pre>drwxrws--- 2 root appteam 4096 Nov 21 10:30 /opt/shared/application</pre><p>Notice the s in the group permission section.</p><p>This indicates that the setgid bit is enabled.</p><p><strong>L3 insight:</strong> The setgid directory permission helps maintain group ownership in shared environments. However, applications may create files with restrictive permissions. If both teams must edit every newly created file, consider an appropriate default ACL as well.</p><h3>9. Advanced Linux Permissions: Special Bits</h3><p>Linux supports three special permission bits.</p><h3>1. SUID — Set User ID</h3><p>SUID is primarily used on executable files.</p><p>It allows an executable to run with the effective user ID of the file owner.</p><p>Inspect:</p><pre>ls -l /usr/bin/passwd</pre><p>You may see an s in the owner&#39;s execute position.</p><p>Example:</p><pre>-rwsr-xr-x 1 root root ... /usr/bin/passwd</pre><p>This is used by certain system utilities that need elevated privileges for specific operations.</p><h3>2. SGID — Set Group ID</h3><p>SGID on an executable allows it to run with the effective group ID of the file’s group.</p><p>SGID on a directory causes newly created entries to inherit the directory’s group.</p><p>Example:</p><pre>chmod 2775 shared_directory</pre><h3>3. Sticky Bit</h3><p>The sticky bit on a shared directory restricts deletion or renaming of entries to the file owner, directory owner, or a privileged process.</p><p>A common example is /tmp.</p><pre>ls -ld /tmp</pre><p>Typical output:</p><pre>drwxrwxrwt 10 root root 4096 Nov 21 10:30 /tmp</pre><p>The t indicates the sticky bit.</p><p>To set it:</p><pre>chmod +t shared_directory</pre><p>To remove it:</p><pre>chmod -t shared_directory</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*93FJgZmHDTors5cK" /></figure><h3>10. Advanced Troubleshooting: ACLs</h3><p>Sometimes standard Linux permissions appear correct, but a user still cannot access a file.</p><p>One possible reason is an Access Control List (ACL).</p><p>ACLs provide more granular access control for individual users and groups beyond the traditional owner/group/others model.</p><h3>Check existing ACLs</h3><pre>getfacl application.conf</pre><p>Example output:</p><pre># file: application.conf<br># owner: root<br># group: appgroup<br>user::rw-<br>user:devuser:r--<br>group::r--<br>mask::r--<br>other::---</pre><p>This shows that devuser has an additional read permission.</p><h3>Grant access to a specific user</h3><pre>sudo setfacl -m u:devuser:r application.conf</pre><p>This grants the user devuser read permission.</p><h3>Grant access to a group</h3><pre>sudo setfacl -m g:appteam:rw application.conf</pre><h3>Remove a specific ACL entry</h3><pre>sudo setfacl -x u:devuser application.conf</pre><h3>Remove all extended ACL entries</h3><pre>sudo setfacl -b application.conf</pre><p>Be careful: removing ACLs can change access for users who depend on those entries.</p><h3>Understand the ACL mask</h3><p>The ACL mask defines the maximum effective permissions for named users, named groups, and the owning group.</p><p>For example, an ACL entry might show:</p><pre>user:devuser:rw-        #effective:r--</pre><p>Although the named user entry requests read and write, the ACL mask restricts effective access to read only.</p><p>This is a common reason why the displayed ACL entry may not match the permissions actually available to a user.</p><p><strong>L3 troubleshooting tip:</strong> When ordinary ls -l output does not explain an access problem, use getfacl to inspect extended permissions and the ACL mask.</p><h3>11. Advanced Scenario: Permissions Look Correct, but Access Is Still Denied</h3><p><strong>Production incident:</strong></p><p>The application team confirms that the file permissions are correct.</p><pre>-rw-r----- 1 root appgroup 2048 application.conf</pre><p>The application user belongs to appgroup, but access still fails.</p><p>What should an L3 engineer investigate?</p><p>Follow this checklist.</p><h3>Step 1: Confirm group membership</h3><pre>id appuser</pre><p>Check whether appgroup appears in the user&#39;s group list.</p><h3>Step 2: Check directory traversal permissions</h3><pre>namei -l /opt/myapp/config/application.conf</pre><p>Verify execute permission on every parent directory for the application user through its applicable user, group, or ACL permissions.</p><h3>Step 3: Check ACLs</h3><pre>getfacl /opt/myapp/config/application.conf</pre><p>Inspect named-user entries, named-group entries, and the ACL mask.</p><h3>Step 4: Check SELinux status</h3><p>On SELinux-enabled systems:</p><pre>getenforce</pre><p>Possible results:</p><pre>Enforcing</pre><pre>Permissive</pre><pre>Disabled</pre><p>If SELinux is enforcing, inspect relevant security denials:</p><pre>sudo ausearch -m AVC -ts recent</pre><p>You can also inspect recent kernel messages:</p><pre>sudo journalctl -k --since &quot;30 minutes ago&quot;</pre><p>If SELinux is blocking access, investigate the file labels and expected security context:</p><pre>ls -Z /opt/myapp/config/application.conf</pre><p>Where appropriate, restore the expected default context:</p><pre>sudo restorecon -v /opt/myapp/config/application.conf</pre><p>Do not disable SELinux simply to make an application work. Correct the underlying labeling or policy issue.</p><h3>Step 5: Check filesystem mount options</h3><pre>findmnt -T /opt/myapp/config/application.conf</pre><p>Inspect mount options and determine whether they are relevant to the failure. For example, noexec can prevent direct execution of files on a filesystem, but it does not generally prevent ordinary reading of configuration files.</p><h3>Step 6: Test access as the application user</h3><pre>sudo -u appuser test -r /opt/myapp/config/application.conf &amp;&amp; echo &quot;Read access OK&quot; || echo &quot;Read access FAILED&quot;</pre><p>This helps distinguish a filesystem permission problem from an application-specific issue.</p><p><strong>L3 approach:</strong> Investigate the complete access path: process identity, groups, directory traversal, file permissions, ACLs, SELinux policy, filesystem behavior, and application configuration.</p><h3>12. Useful Linux Permission Troubleshooting Commands</h3><p>Keep these commands handy during production incidents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*ktgG5IiNtuukk5zvcO6OWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*JlXoc8IdUE-H19Vrs_vtvw.png" /></figure><h3>13. Understand umask: Default File and Directory Permissions</h3><p>The umask command determines which permission bits are removed from the default permissions when new files and directories are created.</p><p>Check the current value:</p><pre>umask</pre><p>Example output:</p><pre>0022</pre><p>For a typical Linux application process:</p><ul><li>New files start with a base mode of 666.</li><li>New directories start with a base mode of 777.</li></ul><p>With a umask of 022:</p><pre>Files:       666 - 022 = 644<br>Directories: 777 - 022 = 755</pre><p>This means newly created files typically receive 644 and directories receive 755, subject to application behavior and filesystem rules.</p><p>Another example:</p><pre>umask 027</pre><p>This typically results in:</p><pre>Files:       640<br>Directories: 750</pre><p>This is useful when configuring service accounts that should not grant access to other users by default.</p><p><strong>Important:</strong> Do not assume all applications use the shell’s interactive umask. A service manager, startup script, container, or application can configure a different umask.</p><h3>14. Real-Time L3 Troubleshooting Checklist</h3><p>When an application reports a permission issue, follow this sequence.</p><p><strong>Investigation:</strong></p><ol><li>Identify the affected VM and application.</li><li>Identify the application process and its effective user.</li><li>Inspect file and directory permissions.</li><li>Check ownership and group membership.</li><li>Verify parent directory traversal permissions.</li><li>Inspect ACLs.</li><li>Investigate SELinux or other mandatory access controls.</li><li>Inspect filesystem mount options.</li><li>Review application logs and system logs.</li></ol><p><strong>Remediation:</strong></p><ol><li>Identify the intended access policy.</li><li>Make the smallest required permission or ownership change.</li><li>Avoid unnecessary recursive changes.</li><li>Verify access using the application account.</li><li>Check application health and logs.</li><li>Document the root cause and corrective action.</li></ol><p><strong>Prevention:</strong></p><ul><li>Use dedicated service accounts.</li><li>Apply least-privilege permissions.</li><li>Use shared groups and default ACLs where appropriate.</li><li>Review ownership during deployment.</li><li>Monitor permission-related application errors.</li><li>Audit sensitive configuration files.</li><li>Keep production changes documented.</li></ul><h3>15. Linux Interview Questions and Answers</h3><p><strong>1. What is the difference between chmod and chown?</strong></p><p>chmod changes file permissions, while chown changes file ownership.</p><p><strong>2. What does 755 mean in Linux?</strong></p><p>The owner has read, write, and execute permissions. Group and others have read and execute permissions.</p><p><strong>3. What is the difference between 644 and 600?</strong></p><p>644 allows the owner to read and write while others can read. 600 allows only the owner to read and write.</p><p><strong>4. What does chmod 777 do?</strong></p><p>It grants read, write, and execute permissions to the owner, group, and others. It is generally unsafe for sensitive production files.</p><p><strong>5. What is the difference between SUID and SGID?</strong></p><p>SUID on an executable sets the effective user ID to the file owner. SGID on an executable sets the effective group ID to the file’s group. SGID on a directory makes newly created entries inherit the directory’s group.</p><p><strong>6. What is the sticky bit?</strong></p><p>It restricts deletion and renaming of directory entries to the entry owner, directory owner, or a privileged process.</p><p><strong>7. What is umask?</strong></p><p>Umask controls which permission bits are removed from the default permissions assigned to newly created files and directories.</p><p><strong>8. What is an ACL?</strong></p><p>An Access Control List provides more granular permissions for specific users and groups beyond traditional Linux permissions.</p><p><strong>9. Why might an application get Permission Denied even when the file permissions look correct?</strong></p><p>Possible reasons include incorrect group membership, parent directory permissions, ACL restrictions, SELinux policy, or filesystem-related restrictions.</p><p><strong>10. How would you troubleshoot an application permission issue in production?</strong></p><p>I would identify the process user, inspect file and directory permissions, verify group membership and ACLs, inspect SELinux denials, and test access as the application user before making a minimal corrective change.</p><h3>Conclusion</h3><p>Linux file permissions and ownership are fundamental to production server administration.</p><p>A simple permission error can prevent an application from starting, stop log generation, break automation, or interrupt a deployment.</p><p>The important skill is not just knowing chmod or chown. It is understanding how Linux evaluates access and investigating the complete execution environment before changing anything.</p><p>Practice these scenarios on a Linux VM, observe the command outputs, and try reproducing the permission failures yourself.</p><p><strong>In production troubleshooting, the best fix is not the one that grants the most access. It is the one that restores the required functionality with the least privilege.</strong></p><p>#Linux #LinuxAdministration #DevOps #LinuxTroubleshooting #SystemAdministration #CloudComputing #ProductionSupport #LinuxCommands</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29ac106962a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prometheus and Grafana Fundamentals for DevOps Engineers: Metrics, Dashboards, and Alerting]]></title>
            <link>https://medium.com/@shanbojja/prometheus-and-grafana-fundamentals-for-devops-engineers-metrics-dashboards-and-alerting-b87edf092475?source=rss-c047ef51b3ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/b87edf092475</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[prometheus]]></category>
            <dc:creator><![CDATA[Shanthi bojja]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 09:03:13 GMT</pubDate>
            <atom:updated>2026-10-26T09:03:13.008Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern applications run across virtual machines, containers, Kubernetes clusters, and cloud environments. Keeping track of their health is one of the most important responsibilities of a DevOps engineer.</p><p>But how do you know whether an application is becoming slow, a server is running out of resources, or a service has stopped responding?</p><p>That is where <strong>Prometheus and Grafana</strong> come in.</p><p>Prometheus collects and stores metrics from systems and applications, while Grafana turns those metrics into dashboards that help engineers understand what is happening.</p><p>In this article, we’ll learn the fundamentals of both tools, set up a monitoring environment using Docker Compose, create our first dashboard, and understand how alerting works.</p><h3>1. What Is Prometheus?</h3><p>Prometheus is an open-source monitoring and alerting toolkit designed to collect and store time-series metrics.</p><p>A time-series metric is a measurement recorded over time.</p><p>For example:</p><ul><li>CPU utilization every few seconds</li><li>Memory usage over time</li><li>Number of HTTP requests received by an application</li><li>Application response time</li><li>Number of failed requests</li></ul><p>Prometheus collects metrics by periodically requesting them from configured endpoints. This process is called <strong>scraping</strong>.</p><h3>How Prometheus works</h3><ol><li>An application or exporter exposes metrics through an HTTP endpoint.</li><li>Prometheus periodically scrapes that endpoint.</li><li>Prometheus stores the collected metrics as time-series data.</li><li>Engineers query the data using PromQL.</li><li>Alerting rules evaluate metrics and can trigger notifications through Alertmanager.</li></ol><p><strong>Example:</strong> An application exposes its metrics at http://localhost:8000/metrics. Prometheus collects the metrics at regular intervals and stores them for analysis.</p><h3>2. What Is Grafana?</h3><p>Grafana is an open-source analytics and visualization platform.</p><p>It connects to data sources such as Prometheus and displays the collected data through dashboards, charts, tables, and other visualizations.</p><p>For example, a DevOps engineer can create a dashboard displaying:</p><ul><li>CPU and memory usage</li><li>Application request rates</li><li>Error percentages</li><li>API response times</li><li>Service availability</li><li>Infrastructure performance trends</li></ul><p>Instead of manually checking multiple servers, engineers can use a centralized dashboard to understand system health.</p><h3>Prometheus vs. Grafana</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*pnXHpSlK-xqPUxJICnCZIw.png" /></figure><p><strong>Remember:</strong> Prometheus and Grafana complement each other. Prometheus stores and queries metrics; Grafana helps you visualize and analyze them.</p><h3>3. Understand the Monitoring Architecture</h3><p>A typical monitoring architecture looks like this:</p><p>Application or Server → Exporter or Metrics Endpoint → Prometheus → Grafana Dashboard</p><p>An alerting workflow adds another component:</p><p>Prometheus Alerting Rules → Alertmanager → Email or Other Notification Channels</p><p>Here is what each component does:</p><ul><li><strong>Application:</strong> Generates metrics about its behavior.</li><li><strong>Exporter:</strong> Exposes metrics for systems that do not provide a suitable Prometheus endpoint directly.</li><li><strong>Prometheus:</strong> Scrapes and stores metrics.</li><li><strong>Grafana:</strong> Displays metrics using dashboards.</li><li><strong>Alertmanager:</strong> Groups, routes, and manages notifications generated by Prometheus alerting rules.</li></ul><p>For example, Node Exporter exposes Linux system metrics such as CPU, memory, disk, and network statistics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*56VEEqBSdQDjbKEp" /></figure><h3>4. Install Prometheus and Grafana Using Docker Compose</h3><p>Let’s create a local monitoring environment using Docker Compose.</p><p>This setup is useful for learning and experimentation. It is not a production-ready deployment.</p><h3>Prerequisites</h3><p>Install the following tools:</p><ul><li>Docker</li><li>Docker Compose</li><li>A terminal or command prompt</li></ul><p>Verify your installation:</p><pre>docker --version<br>docker compose version</pre><h3>Step 1: Create the project directory</h3><pre>mkdir prometheus-grafana<br>cd prometheus-grafana</pre><p>Create the following directory structure:</p><pre>prometheus-grafana/<br>├── docker-compose.yml<br>├── prometheus/<br>│   └── prometheus.yml<br>└── alert_rules/<br>    └── alerts.yml</pre><h3>Step 2: Configure Prometheus</h3><p>Create prometheus/prometheus.yml:</p><pre>global:<br>  scrape_interval: 15s<br>  evaluation_interval: 15s</pre><pre>rule_files:<br>  - /etc/prometheus/alerts.yml</pre><pre>scrape_configs:<br>  - job_name: prometheus<br>    static_configs:<br>      - targets: [&quot;prometheus:9090&quot;]</pre><p>Let’s understand the configuration:</p><ul><li>scrape_interval: Prometheus collects metrics every 15 seconds.</li><li>evaluation_interval: Prometheus evaluates alerting rules every 15 seconds.</li><li>rule_files: Specifies where the alerting rules are stored.</li><li>scrape_configs: Defines the endpoints Prometheus monitors.</li><li>job_name: Identifies this monitoring target.</li><li>targets: Lists the endpoints Prometheus scrapes.</li></ul><p>Here, Prometheus monitors its own metrics.</p><p><strong>Important:</strong> The hostname prometheus works because Docker Compose provides service-name DNS within its network.</p><h3>Step 3: Configure the alerting rule</h3><p>Create alert_rules/alerts.yml:</p><pre>groups:<br>  - name: example-alerts<br>    rules:<br>      - alert: PrometheusTargetDown<br>        expr: up{job=&quot;prometheus&quot;} == 0<br>        for: 1m<br>        labels:<br>          severity: warning<br>        annotations:<br>          summary: &quot;Prometheus target is down&quot;<br>          description: &quot;The Prometheus scrape target has been unavailable for over one minute.&quot;</pre><p>This rule checks whether the Prometheus target is unavailable.</p><ul><li>expr: The PromQL expression used to evaluate the condition.</li><li>for: The condition must remain true for one minute before the alert becomes firing.</li><li>labels: Adds metadata, such as severity.</li><li>annotations: Provides a readable alert description.</li></ul><p>This is an example of a Prometheus alerting rule. Notifications require a configured Alertmanager and notification receiver.</p><h3>Step 4: Configure Docker Compose</h3><p>Create docker-compose.yml in the project root:</p><pre>services:<br>  prometheus:<br>    image: prom/prometheus:latest<br>    container_name: prometheus<br>    ports:<br>      - &quot;9090:9090&quot;<br>    volumes:<br>      - ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro<br>      - ./alert_rules/alerts.yml:/etc/prometheus/alerts.yml:ro<br>      - prometheus_data:/prometheus<br>    command:<br>      - &quot;--config.file=/etc/prometheus/prometheus.yml&quot;<br>      - &quot;--storage.tsdb.path=/prometheus&quot;<br>    restart: unless-stopped</pre><pre>  grafana:<br>    image: grafana/grafana:latest<br>    container_name: grafana<br>    ports:<br>      - &quot;3000:3000&quot;<br>    volumes:<br>      - grafana_data:/var/lib/grafana<br>    restart: unless-stopped</pre><pre>volumes:<br>  prometheus_data:<br>  grafana_data:</pre><p>This file defines two services:</p><ul><li>Prometheus runs on port 9090.</li><li>Grafana runs on port 3000.</li></ul><p>The named volumes preserve Prometheus and Grafana data when the containers are recreated.</p><p>For a reproducible or production deployment, pin images to specific versions instead of relying on latest. Configure authentication, access controls, and secure network exposure before using these services beyond a local lab.</p><h3>Step 5: Start the services</h3><p>Run:</p><pre>docker compose up -d</pre><p>Check the running containers:</p><pre>docker compose ps</pre><p>View the logs if a service does not start correctly:</p><pre>docker compose logs prometheus<br>docker compose logs grafana</pre><p>To stop the services:</p><pre>docker compose down</pre><p>This command stops and removes the containers but preserves the named volumes. Avoid docker compose down -v if you want to keep the stored monitoring data.</p><h3>5. Access the Prometheus Web Interface</h3><p>Open this URL in your browser:</p><p><a href="http://localhost:9090/">http://localhost:9090</a></p><p>Navigate to the Prometheus query interface.</p><p>Enter the following query:</p><pre>up</pre><p>This query returns the status of monitored targets.</p><ul><li>1 means the most recent scrape succeeded.</li><li>0 means the most recent scrape failed.</li></ul><p>You should see the Prometheus target returning 1.</p><p>Try another query:</p><pre>prometheus_build_info</pre><p>This returns build information exposed by the Prometheus server, provided that the metric is available in your version.</p><h3>Understand the Targets page</h3><p>Open the <strong>Status → Targets</strong> page in Prometheus.</p><p>You can inspect:</p><ul><li>Target endpoint</li><li>Scrape status</li><li>Last scrape time</li><li>Scrape duration</li><li>Error details</li></ul><p>This is one of the first places to check when Prometheus is not collecting metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0r17Dz4iKfTlWm_X" /></figure><h3>6. Learn the Basics of PromQL</h3><p>PromQL stands for Prometheus Query Language. It is used to select, calculate, and analyze time-series data.</p><p>Here are some useful queries.</p><h3>Query 1: Check target availability</h3><pre>up</pre><p>Shows the scrape status of configured targets.</p><h3>Query 2: Count monitored targets</h3><pre>count(up)</pre><p>Counts the currently represented target series.</p><h3>Query 3: Calculate request rate</h3><p>For applications exposing a counter such as http_requests_total:</p><pre>rate(http_requests_total[5m])</pre><p>This estimates the per-second increase in the counter over the last five minutes.</p><p>The metric must be exposed by your application or exporter. It will not automatically exist in our basic Docker Compose setup.</p><h3>Query 4: Calculate the error percentage</h3><p>For an application that exposes http_requests_total with a label named status:</p><pre>100 *<br>sum(rate(http_requests_total{status=~&quot;5..&quot;}[5m]))<br>/<br>sum(rate(http_requests_total[5m]))</pre><p>This calculates the percentage of requests returning 5xx status codes relative to all requests, assuming the metric and labels follow the described structure.</p><p>If no requests exist in the selected time window, the denominator may be zero or the query may return no result. Production dashboards should handle that case appropriately.</p><h3>Query 5: Calculate average request duration</h3><p>For applications exposing a Prometheus histogram named http_request_duration_seconds:</p><pre>histogram_quantile(<br>  0.95,<br>  sum by (le) (<br>    rate(http_request_duration_seconds_bucket[5m])<br>  )<br>)</pre><p>This estimates the 95th-percentile request duration from histogram buckets. It is useful for understanding how long slower requests take.</p><p><strong>DevOps tip:</strong> Learn how to interpret the metric, its labels, its units, and its collection method before copying a PromQL query into a dashboard.</p><h3>7. Connect Grafana to Prometheus</h3><p>Now let’s visualize the metrics.</p><h3>Step 1: Open Grafana</h3><p>Navigate to:</p><p><a href="http://localhost:3000/">http://localhost:3000</a></p><p>For a fresh local installation, the default initial credentials are commonly:</p><ul><li>Username: admin</li><li>Password: admin</li></ul><p>Grafana normally prompts you to change the initial password. If you configured different credentials, use those instead.</p><p>Do not leave default credentials in a shared or production environment.</p><h3>Step 2: Add Prometheus as a data source</h3><p>In Grafana:</p><ol><li>Open <strong>Connections → Data sources</strong>.</li><li>Select <strong>Add data source</strong>.</li><li>Choose <strong>Prometheus</strong>.</li><li>Set the server URL to:</li><li><a href="http://prometheus:9090/">http://prometheus:9090</a></li><li>Select <strong>Save &amp; test</strong>.</li></ol><p>Why not <a href="http://localhost:9090/?">http://localhost:9090?</a></p><p>Grafana is running inside its own container. Within that container, localhost refers to Grafana&#39;s container itself, not the Prometheus container.</p><p>Because both services share a Docker Compose network, Grafana can access Prometheus using the service name prometheus.</p><h3>Step 3: Create your first dashboard</h3><ol><li>Open <strong>Dashboards</strong>.</li><li>Create a new dashboard.</li><li>Add a visualization.</li><li>Select Prometheus as the data source.</li><li>Enter the query:</li></ol><pre>up</pre><ol><li>Choose a suitable visualization, such as a time series or a stat panel.</li><li>Save the dashboard.</li></ol><p>You now have a basic monitoring dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/0*7fSwG_YuEvlq6T2l" /></figure><h3>8. Monitor a Linux Server with Node Exporter</h3><p>Our current setup monitors Prometheus itself. To monitor a Linux server, we can use Node Exporter.</p><p>Node Exporter collects hardware and operating-system metrics, including CPU, memory, filesystem, and network statistics.</p><p>For a quick local demonstration, add the following service to docker-compose.yml:</p><pre>node-exporter:<br>    image: prom/node-exporter:latest<br>    container_name: node-exporter<br>    ports:<br>      - &quot;9100:9100&quot;<br>    restart: unless-stopped</pre><p>This service must be added under the existing top-level services: section, at the same indentation level as prometheus and grafana.</p><p>Next, add this job to the scrape_configs section in prometheus/prometheus.yml:</p><pre>- job_name: node-exporter<br>    static_configs:<br>      - targets: [&quot;node-exporter:9100&quot;]</pre><p>Apply the updated configuration:</p><pre>docker compose up -d</pre><p>Prometheus normally detects changes after the container is recreated with the updated configuration. You can check the target at:</p><p><a href="http://localhost:9090/targets">http://localhost:9090/targets</a></p><p>You should see the Node Exporter target listed.</p><p>Now try:</p><pre>node_cpu_seconds_total</pre><p>This metric reports cumulative CPU time by CPU mode. It is not CPU utilization as a direct percentage.</p><p>To estimate the percentage of CPU time spent in non-idle modes across CPUs, you can use:</p><pre>100 * (<br>  1 - avg by (instance) (<br>    rate(node_cpu_seconds_total{mode=&quot;idle&quot;}[5m])<br>  )<br>)</pre><p>This is an example of transforming raw metrics into a more useful operational measurement.</p><p><strong>Security note:</strong> This example exposes Node Exporter on a host port for learning purposes. In production, restrict access to monitoring endpoints and avoid exposing them publicly.</p><h3>9. Configure Alerts and Notifications</h3><p>Monitoring is most useful when it helps engineers act before an issue becomes a major incident.</p><p>An alerting workflow generally includes:</p><ol><li>Collecting metrics.</li><li>Evaluating an alert condition.</li><li>Determining whether the condition has persisted long enough.</li><li>Routing notifications to the appropriate team or channel.</li></ol><p>Prometheus alerting rules identify conditions. <strong>Alertmanager</strong> handles tasks such as grouping, deduplication, silencing, and routing notifications.</p><p>For example, an application might trigger an alert when its error rate stays above a threshold for five minutes.</p><pre>- alert: HighErrorRate<br>  expr: |<br>    100 *<br>    sum(rate(http_requests_total{status=~&quot;5..&quot;}[5m]))<br>    /<br>    sum(rate(http_requests_total[5m])) &gt; 5<br>  for: 5m<br>  labels:<br>    severity: critical<br>  annotations:<br>    summary: &quot;Application error rate is high&quot;<br>    description: &quot;The application error rate has exceeded 5% for five minutes.&quot;</pre><p>This rule assumes that the application exposes the described request counter and labels. Add it to a configured rule group and validate the query against your actual metrics.</p><p>For this alert to deliver notifications, you must also configure Alertmanager and define a receiver, such as email, Slack through a supported integration, or an incident-management platform.</p><p>Grafana also provides its own alerting system. You can create Grafana-managed alerts from dashboard queries and configure notification policies and contact points. Choose the alerting approach that fits your monitoring architecture and operational needs.</p><h3>10. Common Monitoring Problems and Troubleshooting</h3><p>DevOps engineers often need to troubleshoot the monitoring system itself.</p><h3>Problem 1: Target shows DOWN</h3><p><strong>Possible causes:</strong></p><ul><li>The exporter or application is stopped.</li><li>The target address or port is incorrect.</li><li>The container cannot reach the endpoint.</li><li>Network or firewall rules block the connection.</li></ul><p><strong>What to check:</strong></p><pre>docker compose ps<br>docker compose logs prometheus<br>docker compose logs node-exporter</pre><p>Open the Prometheus Targets page and inspect the reported scrape error.</p><h3>Problem 2: Grafana cannot connect to Prometheus</h3><p>Check that the Grafana data source URL is:</p><pre>http://prometheus:9090</pre><p>Also verify that both services are running and connected to the same Docker Compose network.</p><h3>Problem 3: A query returns no data</h3><p>Possible reasons include:</p><ul><li>The metric name is incorrect.</li><li>The application does not expose that metric.</li><li>Labels do not match the query.</li><li>The selected time range contains no data.</li><li>The target is not being scraped successfully.</li></ul><p>Start with a simple query such as:</p><pre>up</pre><p>Then inspect the available metrics before writing more complex expressions.</p><h3>Problem 4: An alert is not firing</h3><p>Check the following:</p><ul><li>Is the rule loaded?</li><li>Does the PromQL expression return the expected result?</li><li>Has the condition remained true for the configured for duration?</li><li>Is the target being scraped?</li><li>Are the alerting rules reporting errors?</li></ul><p>Remember that an alert in a pending state has not yet satisfied its required duration. Also distinguish between an alert firing and a notification successfully reaching its destination.</p><h3>11. Prometheus and Grafana in Kubernetes</h3><p>Prometheus and Grafana are widely used in Kubernetes environments.</p><p>Prometheus can monitor:</p><ul><li>Node and container resource usage</li><li>Application metrics</li><li>Kubernetes component metrics</li><li>Service availability</li><li>Request rates and errors</li></ul><p>Grafana can display these metrics in dashboards for cluster health, workloads, and application performance.</p><p>In Kubernetes environments, teams often use the <strong>Prometheus Operator</strong> and Helm-based monitoring stacks to manage monitoring resources and configurations.</p><p>A popular option is kube-prometheus-stack, which packages Prometheus, Grafana, Alertmanager, and related monitoring components.</p><p>The exact components and configuration depend on the chart version and deployment requirements.</p><p>For DevOps engineers, learning Prometheus and Grafana provides a foundation for monitoring Kubernetes workloads and troubleshooting production issues.</p><h3>12. Best Practices for DevOps Engineers</h3><p>Keep these principles in mind when building monitoring solutions:</p><ul><li><strong>Monitor the right things:</strong> Track availability, latency, traffic, errors, and resource saturation.</li><li><strong>Use meaningful metric names and labels:</strong> Consistent naming makes queries easier to maintain.</li><li><strong>Avoid high-cardinality labels:</strong> Unique user IDs, request IDs, or unbounded values can create excessive time-series growth.</li><li><strong>Create actionable alerts:</strong> Alert on symptoms that require investigation or action, not every small fluctuation.</li><li><strong>Build dashboards around operational questions:</strong> Make it easy to identify what is failing and where to investigate.</li><li><strong>Protect monitoring endpoints:</strong> Apply authentication, access restrictions, and appropriate network controls.</li><li><strong>Manage retention and storage:</strong> Set retention and capacity limits based on operational and compliance needs.</li><li><strong>Test alerts before relying on them:</strong> Validate both alert conditions and notification delivery.</li><li><strong>Monitor the monitoring stack:</strong> Ensure Prometheus, Grafana, exporters, and notification components remain healthy.</li><li><strong>Use version-controlled configuration:</strong> Store scrape configurations, alerting rules, and dashboard definitions in version control where practical.</li></ul><h3>13. Interview Questions and Answers</h3><p><strong>1. What is Prometheus?</strong></p><p>Prometheus is an open-source monitoring toolkit that collects and stores time-series metrics and supports querying and alert evaluation.</p><p><strong>2. What is Grafana?</strong></p><p>Grafana is a visualization and analytics platform used to create dashboards from Prometheus and other data sources.</p><p><strong>3. What is PromQL?</strong></p><p>PromQL is Prometheus’s query language for selecting, calculating, and analyzing time-series metrics.</p><p><strong>4. What is an exporter?</strong></p><p>An exporter exposes metrics in a format Prometheus can scrape. Node Exporter is a common example for Linux system metrics.</p><p><strong>5. What does the </strong><strong>up metric indicate?</strong></p><p>It indicates the result of a target’s latest scrape: 1 for success and 0 for failure.</p><p><strong>6. What is the difference between Prometheus and Alertmanager?</strong></p><p>Prometheus evaluates alerting rules. Alertmanager groups, deduplicates, silences, and routes notifications for firing alerts.</p><p><strong>7. What is the difference between metrics and logs?</strong></p><p>Metrics are numerical measurements collected over time. Logs are timestamped records of events that help engineers investigate what happened.</p><p><strong>8. Why is Node Exporter used?</strong></p><p>It exposes Linux system metrics, including CPU, memory, filesystem, and network statistics.</p><p><strong>9. Why can Grafana use </strong><strong>http://prometheus:9090 instead of </strong><strong>localhost?</strong></p><p>In Docker Compose, services can communicate through their service names on a shared network. The hostname prometheus resolves to the Prometheus service.</p><p><strong>10. How would you troubleshoot a Prometheus target that is DOWN?</strong></p><p>Check the target’s scrape error, verify the application or exporter is running, validate the endpoint and port, and investigate network connectivity and configuration.</p><h3>Conclusion</h3><p>Prometheus and Grafana are important tools in the DevOps monitoring ecosystem.</p><p>Prometheus helps collect, store, query, and evaluate metrics. Grafana turns those metrics into dashboards that make system behavior easier to understand. With alerting rules and notification integrations, teams can identify problems and respond more effectively.</p><p>Start with the local Docker Compose lab, learn basic PromQL, connect Grafana to Prometheus, and then move on to Linux monitoring and Kubernetes observability.</p><p><strong>The goal of monitoring is not just to collect data. It is to turn that data into useful operational decisions.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b87edf092475" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS CloudWatch Fundamentals for DevOps Engineers: Monitor Metrics, Logs, and Alarms]]></title>
            <link>https://medium.com/@shanbojja/aws-cloudwatch-fundamentals-for-devops-engineers-monitor-metrics-logs-and-alarms-818a4d75b0bf?source=rss-c047ef51b3ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/818a4d75b0bf</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloudwatch]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Shanthi bojja]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 07:00:24 GMT</pubDate>
            <atom:updated>2026-10-26T07:00:24.936Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pXYqSjTuM84exLULwjXIDg.png" /></figure><p>Imagine you deploy an application to AWS. Everything works perfectly during testing, but a few hours later, users start reporting slow response times.</p><p>How do you find the problem?</p><p>Is the server running out of memory? Is CPU utilization too high? Are application errors increasing? Is a service failing?</p><p>Without proper monitoring, troubleshooting becomes guesswork.</p><p>This is where <strong>Amazon CloudWatch</strong> helps.</p><p>Amazon CloudWatch is an AWS monitoring and observability service that helps you collect metrics, monitor logs, create alarms, and understand the health of your applications and infrastructure.</p><p>In this article, we will learn CloudWatch from the basics, explore practical examples, and build a simple monitoring setup that DevOps engineers can use as a starting point.</p><h3>1. What Is Amazon CloudWatch?</h3><p>Amazon CloudWatch is a monitoring service provided by AWS. It collects and visualizes operational data from AWS resources and applications.</p><p>With CloudWatch, you can:</p><ul><li>Monitor EC2 CPU utilization.</li><li>Collect application and system logs.</li><li>Create alarms when metrics cross a threshold.</li><li>Build dashboards to visualize infrastructure health.</li><li>Investigate errors and troubleshoot incidents.</li><li>Trigger notifications through Amazon SNS.</li><li>Monitor custom application metrics.</li></ul><p>For example, you could create an alarm that sends a notification when an EC2 instance’s CPU utilization stays above 80% for several minutes.</p><p>CloudWatch helps answer three important questions:</p><ol><li><strong>What is happening?</strong> — Metrics show resource behavior.</li><li><strong>Why is it happening?</strong> — Logs help investigate events and errors.</li><li><strong>When should we take action?</strong> — Alarms notify us when defined conditions are met.</li></ol><h3>2. Understand the Main CloudWatch Components</h3><p>Before creating alarms, let’s understand the core components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*DBn7IPzteHBv1H8PeOrwxA.png" /></figure><h3>Metrics versus logs</h3><p>Metrics and logs serve different purposes.</p><p><strong>Metrics</strong> are numerical measurements, such as CPU utilization, network traffic, and request counts.</p><p><strong>Logs</strong> contain detailed event records, such as application errors, authentication failures, and debugging messages.</p><p>For example, a metric may show that CPU utilization increased to 95%. Application logs may help you understand what was happening when the CPU usage increased.</p><p>DevOps engineers often use both together to investigate incidents.</p><h3>3. Monitor an EC2 Instance</h3><p>Amazon EC2 provides virtual servers in AWS. Monitoring these servers is one of the most common CloudWatch use cases.</p><p>CloudWatch automatically collects several standard EC2 metrics, including CPU utilization and network activity.</p><p>For example, you can monitor:</p><ul><li>CPU utilization</li><li>Network bytes in and out</li><li>Network packets in and out</li><li>Status check failures</li><li>Disk-related metrics that are available through the relevant monitoring setup</li></ul><p><strong>Important:</strong> EC2 memory utilization and filesystem disk usage are not automatically available as standard EC2 metrics. To collect these operating-system-level measurements, you generally need to configure the CloudWatch Agent.</p><h3>Step 1: Open CloudWatch</h3><ol><li>Sign in to the AWS Management Console.</li><li>Open the CloudWatch service.</li><li>Select <strong>Metrics</strong>.</li><li>Open the EC2 metric namespace.</li><li>Choose the relevant instance metrics.</li></ol><p>You can select an EC2 instance and view its CPU utilization over a chosen time period.</p><h3>Step 2: Understand CPU utilization</h3><p>Suppose your EC2 instance reports the following CPU utilization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*PhoXcOtQSl1JEcX5wOg30Q.png" /></figure><p>This pattern suggests that the server is experiencing sustained high CPU usage.</p><p>However, high CPU utilization does not automatically mean something is broken. You should investigate application traffic, running processes, scheduled jobs, and performance expectations before deciding what action to take.</p><h3>Standard monitoring versus detailed monitoring</h3><p>EC2 provides basic monitoring by default, with metrics generally available at five-minute intervals. Detailed monitoring can provide one-minute metric intervals and may incur additional charges.</p><p>The appropriate setting depends on your monitoring requirements and budget.</p><h3>4. Create a CloudWatch Alarm</h3><p>A CloudWatch alarm watches a metric and evaluates it against a condition you define.</p><p>Let’s create an alarm for high EC2 CPU utilization.</p><h3>Example requirement</h3><p>Create an alarm when:</p><ul><li>CPU utilization exceeds 80%.</li><li>The condition occurs for three consecutive five-minute evaluation periods.</li><li>A notification is sent when the alarm enters the ALARM state.</li></ul><p>The actual behavior depends on the configured metric period, evaluation periods, datapoints to alarm, and missing-data settings.</p><h3>Step 1: Select the metric</h3><p>In CloudWatch:</p><ol><li>Open <strong>Alarms</strong>.</li><li>Choose <strong>Create alarm</strong>.</li><li>Select the EC2 CPU utilization metric for your instance.</li><li>Choose a suitable statistic and period.</li></ol><p>For a straightforward example, use Average CPU Utilization with a five-minute period.</p><h3>Step 2: Configure the condition</h3><p>Set the threshold to:</p><p>CPUUtilization &gt; 80</p><p>Configure the evaluation periods according to your requirement.</p><p>For three consecutive five-minute periods, configure three evaluation periods and require all three datapoints to breach the threshold if you want every period to be above 80%.</p><h3>Step 3: Configure notifications</h3><p>You can configure an alarm action to publish a notification to an Amazon SNS topic.</p><p>An SNS topic can send notifications through supported subscription types, such as email.</p><p>You must create or select the SNS topic and confirm an email subscription where required.</p><h3>Step 4: Name the alarm</h3><p>Use a meaningful name, such as:</p><p>prod-webserver-high-cpu</p><p>Good alarm names should identify the environment, resource, and condition.</p><h3>Step 5: Create and verify the alarm</h3><p>Review the settings and create the alarm.</p><p>The alarm may initially show INSUFFICIENT_DATA while CloudWatch collects enough information to evaluate the condition. Its state will depend on the available metric data and configured evaluation settings.</p><p><strong>Production tip:</strong> Avoid creating alarms based only on arbitrary thresholds. Consider historical patterns, application requirements, and the impact of the condition on users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xTVwdjyqHj5Hf9BejNQDAQ.png" /></figure><h3>5. Understand CloudWatch Alarm States</h3><p>CloudWatch alarms commonly use three states.</p><p>&lt;box border radius=”lg” padding={3} gap={3}&gt;<br> &lt;row align=start gap={3}&gt;<br> &lt;box background=”surface-secondary” radius=”md” size=”40px” align=”center” justify=”center”&gt;<br> &lt;icon name=”check-circle” size=”xl” /&gt;<br> &lt;/box&gt;<br> &lt;box flex=”1&quot; gap={1}&gt;<br> **OK**</p><pre>The metric is not currently breaching the configured alarm condition.<br>&lt;/box&gt;</pre><p>&lt;/row&gt;<br> &lt;divider color=”subtle” /&gt;<br> &lt;row align=start gap={3}&gt;<br> &lt;box background=”surface-secondary” radius=”md” size=”40px” align=”center” justify=”center”&gt;<br> &lt;icon name=”alert-triangle” size=”xl” /&gt;<br> &lt;/box&gt;<br> &lt;box flex=”1&quot; gap={1}&gt;<br> **ALARM**</p><pre>The metric has met the configured alarm condition.<br>&lt;/box&gt;</pre><p>&lt;/row&gt;<br> &lt;divider color=”subtle” /&gt;<br> &lt;row align=start gap={3}&gt;<br> &lt;box background=”surface-secondary” radius=”md” size=”40px” align=”center” justify=”center”&gt;<br> &lt;icon name=”circle-help” size=”xl” /&gt;<br> &lt;/box&gt;<br> &lt;box flex=”1&quot; gap={1}&gt;<br> INSUFFICIENT_DATA</p><pre>There is not enough usable information to determine the alarm state, or the alarm is still initializing.<br>&lt;/box&gt;</pre><p>&lt;/row&gt;<br>&lt;/box&gt;</p><p>An alarm entering the ALARM state does not necessarily mean the server is down. It means the configured condition has been met.</p><p>For example, high CPU usage may indicate heavy traffic, inefficient code, or a resource-intensive background job.</p><p>Your next step should be investigation, not an automatic assumption about the root cause.</p><h3>6. Collect Application and System Logs</h3><p>Metrics tell you that something may be wrong. Logs can provide more context about what happened.</p><p>Amazon CloudWatch Logs stores and analyzes log events from supported AWS services and applications.</p><p>For example, an application might produce logs like:</p><pre>2026-10-24 10:00:01 INFO Application started<br>2026-10-24 10:00:12 INFO Request received: /api/users<br>2026-10-24 10:00:15 ERROR Database connection timeout<br>2026-10-24 10:00:18 ERROR Request failed with status 500</pre><p>The CPU metric alone may not explain the application failure. The log messages provide clues that the application is experiencing database connectivity problems.</p><h3>Understand log groups and log streams</h3><p>A <strong>log group</strong> is a container for related log streams. It can also define settings such as retention and access policies.</p><p>A <strong>log stream</strong> is a sequence of log events from a particular source, such as an instance or application process.</p><p>For example:</p><pre>Log Group: /production/myapp<br>    ├── Log Stream: web-server-01<br>    ├── Log Stream: web-server-02<br>    └── Log Stream: web-server-03</pre><p>This structure helps organize logs from multiple servers running the same application.</p><h3>7. Install and Configure the CloudWatch Agent</h3><p>Standard EC2 metrics do not provide all operating-system metrics. To collect information such as memory usage, filesystem utilization, and application log files, you can install and configure the CloudWatch Agent.</p><p>The agent supports both metrics and log collection, depending on its configuration.</p><h3>Step 1: Prepare the EC2 instance</h3><p>Before installing the agent, ensure that:</p><ul><li>You have permission to administer the instance.</li><li>The instance can reach the required AWS endpoints.</li><li>The instance has an appropriate IAM role and permissions for the metrics and logs you want to publish.</li><li>You have verified the supported installation method for the operating system.</li></ul><p>Use an appropriate IAM role rather than storing long-term AWS credentials on the server.</p><h3>Step 2: Install the agent</h3><p>The installation command depends on your operating system and package source.</p><p>On supported Amazon Linux environments, you can commonly install it using the package manager:</p><pre>sudo yum install amazon-cloudwatch-agent</pre><p>For systems using DNF, you may use:</p><pre>sudo dnf install amazon-cloudwatch-agent</pre><p>These commands apply only when the package is available through the configured repositories. Other Linux distributions may require a different installation procedure.</p><h3>Step 3: Create a configuration</h3><p>A CloudWatch Agent configuration can specify the metrics and log files to collect.</p><p>For example, the following JSON illustrates a basic configuration for memory, filesystem metrics, and an application log file.</p><pre>{<br>  &quot;metrics&quot;: {<br>    &quot;namespace&quot;: &quot;Custom/EC2&quot;,<br>    &quot;metrics_collected&quot;: {<br>      &quot;mem&quot;: {<br>        &quot;measurement&quot;: [<br>          &quot;mem_used_percent&quot;<br>        ]<br>      },<br>      &quot;disk&quot;: {<br>        &quot;measurement&quot;: [<br>          &quot;used_percent&quot;<br>        ],<br>        &quot;resources&quot;: [<br>          &quot;/&quot;<br>        ]<br>      }<br>    }<br>  },<br>  &quot;logs&quot;: {<br>    &quot;logs_collected&quot;: {<br>      &quot;files&quot;: {<br>        &quot;collect_list&quot;: [<br>          {<br>            &quot;file_path&quot;: &quot;/var/log/myapp/application.log&quot;,<br>            &quot;log_group_name&quot;: &quot;/production/myapp&quot;,<br>            &quot;log_stream_name&quot;: &quot;{instance_id}&quot;<br>          }<br>        ]<br>      }<br>    }<br>  }<br>}</pre><p>This is an example configuration, not a universal drop-in file. Verify the target operating system, filesystem paths, required permissions, and metric dimensions before using it.</p><p>The application log path must exist, and the agent must have permission to read it.</p><h3>Step 4: Start the agent</h3><p>The agent supports configuration files and several startup methods. On supported Linux installations, you can start it using the control script:</p><pre>sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl \<br>  -a fetch-config \<br>  -m ec2 \<br>  -c file:/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json \<br>  -s</pre><p>Save the JSON configuration to the path shown in the command before running it.</p><p>The -m ec2 option identifies the environment as EC2. The -c option specifies the configuration source, and -s starts the agent.</p><h3>Step 5: Verify the data</h3><p>After starting the agent:</p><ol><li>Open CloudWatch Metrics.</li><li>Find the configured namespace, such as Custom/EC2.</li><li>Check whether memory and filesystem metrics are arriving.</li><li>Open CloudWatch Logs.</li><li>Check the configured log group for incoming log events.</li></ol><p>Metrics and logs may take some time to appear. If they do not, inspect the agent’s status and logs, IAM permissions, network connectivity, and configuration.</p><h3>8. Analyze Logs with CloudWatch Logs Insights</h3><p>CloudWatch Logs Insights lets you query log data using a purpose-built query language.</p><p>It is useful when you need to find errors, investigate failures, or understand patterns across large volumes of logs.</p><p>Suppose your application logs contain messages with a status field.</p><p>You can run a query like:</p><pre>fields @timestamp, @message<br>| filter @message like /ERROR/<br>| sort @timestamp desc<br>| limit 20</pre><p>This query:</p><ol><li>Selects the timestamp and message fields.</li><li>Filters for log messages containing ERROR.</li><li>Sorts the results with the newest events first.</li><li>Returns up to 20 matching records.</li></ol><h3>Count errors over time</h3><p>You can also group errors into time intervals:</p><pre>filter @message like /ERROR/<br>| stats count(*) as error_count by bin(5m)<br>| sort bin(5m) asc</pre><p>This can help you see whether application errors are increasing during an incident.</p><p>The exact query should match your log format and the fields available in the selected log group.</p><p><strong>DevOps use case:</strong> If users report failures at 10:15 AM, query the relevant log group for errors around that time and compare the results with CPU, memory, and request metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*ovdW5v2g1f5O8V_v" /></figure><h3>9. Build a CloudWatch Dashboard</h3><p>A dashboard brings important metrics together in one view.</p><p>Instead of opening multiple metric pages, you can create a dashboard showing the health of your application and infrastructure.</p><p>For a web application, consider including:</p><ul><li>EC2 CPU utilization</li><li>Network traffic</li><li>Application error counts</li><li>Request latency, where the application or service publishes it</li><li>Memory and disk utilization collected through the agent</li><li>Alarm status for important resources</li></ul><h3>Create a dashboard</h3><ol><li>Open CloudWatch in the AWS Console.</li><li>Select <strong>Dashboards</strong>.</li><li>Choose <strong>Create dashboard</strong>.</li><li>Enter a meaningful name, such as Production-Application.</li><li>Add widgets for the metrics you need.</li><li>Save the dashboard.</li></ol><p>A useful dashboard should answer operational questions quickly. Avoid adding every available metric without considering what your team actually needs to monitor.</p><p>For example, a production dashboard should make it easy to identify high resource usage, service failures, and unusual application behavior.</p><h3>10. Send Alarm Notifications with Amazon SNS</h3><p>CloudWatch alarms can publish notifications through Amazon SNS.</p><p>SNS is a messaging service that distributes messages to subscribers.</p><p>A typical monitoring workflow looks like this:</p><pre>EC2 Instance<br>     |<br>     v<br>CloudWatch Metrics<br>     |<br>     v<br>CloudWatch Alarm<br>     |<br>     v<br>Amazon SNS Topic<br>     |<br>     v<br>Email Notification</pre><p>For example, when a CPU alarm enters the ALARM state, CloudWatch can publish a message to an SNS topic. An email subscriber can then receive the notification.</p><h3>Setup overview</h3><ol><li>Create an SNS topic.</li><li>Add an email subscription.</li><li>Confirm the subscription using the verification email.</li><li>Configure the CloudWatch alarm to publish to that topic.</li><li>Test the notification path in a safe environment.</li></ol><p>CloudWatch alarms can also integrate with other supported actions and automation workflows.</p><p><strong>Important:</strong> An alarm notification does not fix the problem automatically. It tells the team that a condition needs attention. Automated remediation should be designed carefully, tested, and protected against repeated or unsafe actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e1m9j6Q9RwoQDRXx" /></figure><h3>11. Automate CloudWatch with AWS CLI</h3><p>DevOps engineers often automate monitoring tasks instead of performing every operation manually through the AWS Console.</p><p>The AWS Command Line Interface (CLI) allows you to interact with AWS services from scripts and terminals.</p><h3>List CloudWatch alarms</h3><pre>aws cloudwatch describe-alarms \<br>  --region ap-south-1</pre><p>This command retrieves alarm information from the selected region.</p><h3>Query recent CPU metrics</h3><pre>aws cloudwatch get-metric-statistics \<br>  --namespace AWS/EC2 \<br>  --metric-name CPUUtilization \<br>  --dimensions Name=InstanceId,Value=i-0123456789abcdef0 \<br>  --start-time 2026-10-24T10:00:00Z \<br>  --end-time 2026-10-24T11:00:00Z \<br>  --period 300 \<br>  --statistics Average \<br>  --region ap-south-1</pre><p>Replace the example instance ID and time window with your actual values.</p><p>This command requests the average CPU utilization over five-minute intervals for the specified instance.</p><p>The instance must publish the requested metric, and the selected time window must contain available data.</p><h3>Create a metric alarm</h3><p>You can also create an alarm from the CLI:</p><pre>aws cloudwatch put-metric-alarm \<br>  --alarm-name &quot;prod-web-high-cpu&quot; \<br>  --namespace AWS/EC2 \<br>  --metric-name CPUUtilization \<br>  --dimensions Name=InstanceId,Value=i-0123456789abcdef0 \<br>  --statistic Average \<br>  --period 300 \<br>  --evaluation-periods 3 \<br>  --datapoints-to-alarm 3 \<br>  --threshold 80 \<br>  --comparison-operator GreaterThanThreshold \<br>  --treat-missing-data missing \<br>  --region ap-south-1</pre><p>This example configures an alarm for CPU utilization above 80% across three five-minute evaluation periods, requiring all three datapoints to breach the threshold.</p><p>It does not configure an SNS notification action. To send notifications, add the appropriate --alarm-actions option with an existing SNS topic ARN.</p><h3>Automate routine checks</h3><p>AWS CLI commands can be used in shell scripts or scheduled jobs to:</p><ul><li>Retrieve alarm states.</li><li>Export monitoring information.</li><li>Validate that expected alarms exist.</li><li>Support operational reports.</li><li>Integrate monitoring checks into deployment pipelines.</li></ul><p>Use IAM roles and least-privilege permissions wherever possible. Avoid embedding long-term credentials in scripts.</p><h3>12. Practical Troubleshooting Scenario</h3><p>Imagine a production application begins responding slowly.</p><p>Your CloudWatch dashboard shows high CPU utilization, and users report intermittent errors.</p><p>Here is a systematic approach.</p><p><strong>Step 1: Check the metrics.</strong></p><p>Review CPU utilization, network traffic, request counts, and available application metrics around the incident time.</p><p><strong>Step 2: Check the alarms.</strong></p><p>Identify whether any relevant alarms entered the ALARM state and inspect their evaluation periods and history.</p><p><strong>Step 3: Investigate the logs.</strong></p><p>Use CloudWatch Logs Insights to find errors and warnings around the time the problem started.</p><p><strong>Step 4: Check the server.</strong></p><p>If you have authorized access, inspect running processes, resource usage, service status, and application health.</p><p>For example:</p><pre>top<br>free -h<br>df -h<br>systemctl status nginx</pre><p>These commands help inspect CPU processes, memory, disk usage, and Nginx service status on a compatible Linux system.</p><p><strong>Step 5: Identify the likely cause.</strong></p><p>High CPU usage could result from a traffic spike, an inefficient query, a runaway process, or a scheduled job. Use evidence from metrics and logs rather than assuming the first visible symptom is the root cause.</p><p><strong>Step 6: Apply and verify the fix.</strong></p><p>Follow your team’s incident procedures, make an approved change, and verify whether the relevant metrics and application behavior return to expected levels.</p><p>This is how monitoring becomes part of a practical incident response process.</p><h3>13. Best Practices for CloudWatch Monitoring</h3><p><strong>1. Define meaningful thresholds.</strong> Base alarms on service requirements and historical behavior instead of selecting thresholds without context.</p><p><strong>2. Monitor user impact.</strong> Resource metrics are useful, but application errors, request latency, and availability often provide more direct evidence of customer impact.</p><p><strong>3. Configure log retention.</strong> Choose retention periods based on operational, security, and compliance requirements to manage storage costs.</p><p><strong>4. Protect sensitive data.</strong> Avoid logging passwords, access tokens, personal information, or other secrets.</p><p><strong>5. Use descriptive names.</strong> Include the environment, resource, and condition in alarm names.</p><p><strong>6. Reduce notification noise.</strong> Use appropriate evaluation settings and actionable alarms so engineers are not overwhelmed by repeated alerts.</p><p><strong>7. Monitor agent health.</strong> If you depend on custom metrics or logs from the CloudWatch Agent, ensure that collection is working.</p><p><strong>8. Use least-privilege IAM policies.</strong> Give users, instances, and automation only the permissions they need.</p><p><strong>9. Review costs.</strong> Custom metrics, log ingestion, log storage, dashboards, and detailed monitoring can affect your AWS bill. Check current pricing and usage.</p><p><strong>10. Test the entire alert path.</strong> Verify that an alarm can transition as expected and that notifications reach the intended subscribers.</p><h3>14. Common Interview Questions</h3><p><strong>Q1. What is Amazon CloudWatch?</strong></p><p>Amazon CloudWatch is an AWS monitoring and observability service for collecting metrics, analyzing logs, creating alarms, and visualizing operational data.</p><p><strong>Q2. What is the difference between CloudWatch metrics and logs?</strong></p><p>Metrics are numerical measurements over time. Logs are event records that provide detailed information about what happened.</p><p><strong>Q3. What is a CloudWatch alarm?</strong></p><p>A CloudWatch alarm evaluates a metric against a defined condition and changes state based on the configured evaluation settings.</p><p><strong>Q4. Does EC2 automatically send memory utilization to CloudWatch?</strong></p><p>No. Standard EC2 metrics include CPU utilization and other infrastructure metrics, but operating-system memory utilization generally requires the CloudWatch Agent or another suitable collection mechanism.</p><p><strong>Q5. What is CloudWatch Logs Insights?</strong></p><p>It is a query and analysis feature that helps users search, filter, aggregate, and investigate log data.</p><p><strong>Q6. What is Amazon SNS used for in CloudWatch?</strong></p><p>SNS can distribute notifications from CloudWatch alarms to subscribed endpoints, such as email recipients.</p><p><strong>Q7. What is the difference between an alarm and a dashboard?</strong></p><p>An alarm evaluates a condition and can initiate configured actions. A dashboard presents metrics and other monitoring information in a visual interface.</p><p><strong>Q8. How can you monitor disk usage on an EC2 instance?</strong></p><p>Configure the CloudWatch Agent to collect filesystem metrics and publish them to CloudWatch, then create an alarm if required.</p><p><strong>Q9. How do you investigate a production incident using CloudWatch?</strong></p><p>Review relevant metrics, alarm history, and application logs around the incident time. Correlate the evidence with system-level checks to identify the likely cause.</p><p><strong>Q10. Can CloudWatch be automated using the AWS CLI?</strong></p><p>Yes. The AWS CLI supports operations such as querying metrics, listing alarms, and creating or updating alarm configurations.</p><h3>Conclusion</h3><p>Amazon CloudWatch is an important tool for DevOps engineers working with AWS infrastructure and applications.</p><p>By combining metrics, logs, alarms, dashboards, and notifications, you can identify abnormal behavior earlier and investigate incidents using operational evidence.</p><p>Start by monitoring one EC2 instance, create a CPU alarm, collect an application log, and build a small dashboard. Once you understand the workflow, extend it to multiple resources and applications.</p><p>Remember: <strong>effective monitoring is not about collecting every metric. It is about identifying the signals that help you detect, understand, and resolve problems.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=818a4d75b0bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ansible Advanced Concepts for DevOps Engineers: Roles, Variables, Templates, and Handlers]]></title>
            <link>https://medium.com/@shanbojja/ansible-advanced-concepts-for-devops-engineers-roles-variables-templates-and-handlers-60f31f1779e6?source=rss-c047ef51b3ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/60f31f1779e6</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Shanthi bojja]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 13:10:59 GMT</pubDate>
            <atom:updated>2026-10-24T13:10:59.779Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ansible Advanced Concepts for DevOps Engineers: Roles, Variables, Templates, and Handlers</h3><p>If you have learned the basics of Ansible, you already know how to connect to servers, execute commands, install packages, and manage services.</p><p>But what happens when you need to manage 50 servers, deploy applications across multiple environments, or reuse the same automation across different projects?</p><p>Writing one large playbook for everything quickly becomes difficult to maintain.</p><p>This is where <strong>Ansible’s advanced concepts</strong> become useful.</p><p>In this article, we will explore Ansible Roles, Variables, Templates, Handlers, Conditionals, Loops, and Ansible Vault with practical examples you can try in your own lab environment.</p><p>By the end, you will understand how to build reusable, organized, and maintainable Ansible automation.</p><h3>1. What Are We Going to Learn?</h3><p>We will cover:</p><ul><li>Ansible Roles and project structure</li><li>Variables and variable precedence</li><li>Jinja2 templates</li><li>Handlers and change-based execution</li><li>Loops and conditionals</li><li>Ansible Vault for sensitive information</li><li>Tags for selective execution</li><li>A practical Nginx configuration project</li><li>Best practices for production environments</li></ul><h3>2. Why Do We Need Advanced Ansible Concepts?</h3><p>Imagine you need to configure Nginx on 20 servers.</p><p>Your playbook must install Nginx, configure its settings, copy application files, start the service, and make sure everything remains consistent.</p><p>You could write all these tasks in one playbook. However, as the project grows, the playbook becomes harder to understand and reuse.</p><p>Advanced Ansible concepts help solve these problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*s9JxZzv5kQEvAMqVS30gsA.png" /></figure><p>Let’s understand each concept with examples.</p><h3>3. Understanding Ansible Roles</h3><p>An Ansible Role is a structured way to organize related tasks, variables, templates, files, and handlers.</p><p>Instead of keeping everything in one playbook, you separate your automation into reusable components.</p><p>For example, you might create separate roles for:</p><ul><li>Nginx configuration</li><li>Database installation</li><li>Application deployment</li><li>Monitoring agent installation</li><li>Security configuration</li></ul><h3>Create an Ansible Role</h3><p>Run the following command:</p><pre>ansible-galaxy role init nginx</pre><p>This creates a directory structure similar to the following:</p><pre>nginx/<br>├── defaults/<br>│   └── main.yml<br>├── files/<br>├── handlers/<br>│   └── main.yml<br>├── meta/<br>│   └── main.yml<br>├── tasks/<br>│   └── main.yml<br>├── templates/<br>├── tests/<br>├── vars/<br>│   └── main.yml<br>└── README.md</pre><p>Let’s understand the important directories.</p><ul><li>tasks/: Contains the tasks the role executes.</li><li>handlers/: Contains actions triggered by notifications.</li><li>templates/: Stores Jinja2 template files.</li><li>files/: Stores static files copied to managed servers.</li><li>defaults/: Contains default variable values.</li><li>vars/: Contains role variables that generally have higher precedence than defaults.</li><li>meta/: Contains role metadata and dependencies.</li></ul><h3>Add tasks to the role</h3><p>Open nginx/tasks/main.yml and add:</p><pre>---<br>- name: Install Nginx<br>  ansible.builtin.package:<br>    name: nginx<br>    state: present</pre><pre>- name: Ensure Nginx is running<br>  ansible.builtin.service:<br>    name: nginx<br>    state: started<br>    enabled: true</pre><p>This role installs Nginx and ensures that the service is running and enabled at system startup.</p><p>The package module is useful when you want Ansible to select the appropriate package-management backend for the target operating system.</p><h3>Use the role in a playbook</h3><p>Create site.yml:</p><pre>---<br>- name: Configure web servers<br>  hosts: webservers<br>  become: true</pre><pre>  roles:<br>    - nginx</pre><p>Run it using:</p><pre>ansible-playbook -i inventory.ini site.yml</pre><p>Ansible will execute the tasks defined in the nginx role against the hosts in the webservers inventory group.</p><p><strong>Why this matters:</strong> Once you create a role, you can reuse it across multiple playbooks without duplicating the same tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v0fXUQDAySfA9aX_" /></figure><h3>4. Understanding Ansible Variables</h3><p>Variables allow you to change the behavior of a playbook without modifying its task definitions.</p><p>For example, development and production servers might require different application ports or configuration values.</p><p>Instead of hardcoding these values, you can define variables.</p><h3>Define variables in a playbook</h3><pre>---<br>- name: Configure web servers<br>  hosts: webservers<br>  become: true</pre><pre>  vars:<br>    app_name: myapp<br>    app_port: 8080</pre><pre>  tasks:<br>    - name: Display application details<br>      ansible.builtin.debug:<br>        msg: &quot;Application {{ app_name }} uses port {{ app_port }}&quot;</pre><p>Here, {{ app_name }} and {{ app_port }} are variable references.</p><h3>Use role defaults</h3><p>Open nginx/defaults/main.yml:</p><pre>---<br>nginx_port: 80<br>nginx_service_name: nginx</pre><p>Now, your role can use these variables instead of hardcoding values.</p><p>For example:</p><pre>- name: Ensure Nginx is running<br>  ansible.builtin.service:<br>    name: &quot;{{ nginx_service_name }}&quot;<br>    state: started<br>    enabled: true</pre><p>Values in defaults/main.yml are designed to be easy to override.</p><p>You can set different values for different environments without changing the role itself.</p><h3>Pass variables through the command line</h3><p>You can also supply variables when running a playbook:</p><pre>ansible-playbook -i inventory.ini site.yml \<br>  -e &quot;app_port=9090&quot;</pre><p>The -e option supplies extra variables, which have high precedence in Ansible&#39;s variable system.</p><h3>Understand variable precedence</h3><p>Ansible can define the same variable in multiple places. When that happens, variable precedence determines which value is used.</p><p>For example, a simplified practical comparison is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*bqnCehGGucF15AJTKofYBg.png" /></figure><p>This is a simplified guide, not the complete precedence order. Ansible has many additional variable sources and precedence rules.</p><p><strong>Best practice:</strong> Put reusable defaults in defaults/main.yml, environment-specific settings in inventory or dedicated variable files, and use extra variables for intentional runtime overrides.</p><h3>5. Using Jinja2 Templates</h3><p>Real-world configuration files often contain values that differ between environments.</p><p>For example, a development server might use port 8080, while a production server uses port 80.</p><p>Maintaining separate static configuration files for every environment creates duplication.</p><p>Ansible uses the Jinja2 templating engine to generate configuration files dynamically.</p><h3>Create a template</h3><p>Inside your role, create:</p><p>nginx/templates/nginx.conf.j2</p><p>Add the following simplified Nginx server configuration:</p><pre>server {<br>    listen {{ nginx_port }};</pre><pre>    server_name {{ server_name }};</pre><pre>    location / {<br>        root /var/www/html;<br>        index index.html;<br>    }<br>}</pre><p>The .j2 extension indicates that this is a Jinja2 template.</p><p>Ansible replaces the variable expressions with their actual values when it renders the template.</p><h3>Define the variables</h3><p>In nginx/defaults/main.yml:</p><pre>---<br>nginx_port: 80<br>server_name: example.com</pre><h3>Deploy the template</h3><p>Add the following task to nginx/tasks/main.yml:</p><pre>- name: Deploy Nginx configuration<br>  ansible.builtin.template:<br>    src: nginx.conf.j2<br>    dest: /etc/nginx/conf.d/myapp.conf<br>    owner: root<br>    group: root<br>    mode: &quot;0644&quot;<br>  notify: Restart Nginx</pre><p>The template module renders the file on the Ansible control node and transfers the resulting configuration to the managed server.</p><p>Whenever the deployed file changes, the task notifies the Restart Nginx handler.</p><p><strong>Important:</strong> Configuration paths differ between Linux distributions. Verify that the target Nginx installation includes the chosen configuration directory.</p><h3>6. Understanding Handlers</h3><p>Handlers are special tasks that run when another task notifies them.</p><p>They are particularly useful when a configuration change requires a service restart or reload.</p><p>Without handlers, you might restart Nginx after every playbook run, even when nothing has changed.</p><p>With handlers, Ansible can restart it only when a relevant task reports a change.</p><h3>Create a handler</h3><p>Open nginx/handlers/main.yml:</p><pre>---<br>- name: Restart Nginx<br>  ansible.builtin.service:<br>    name: nginx<br>    state: restarted</pre><p>Recall the template task from the previous section:</p><pre>- name: Deploy Nginx configuration<br>  ansible.builtin.template:<br>    src: nginx.conf.j2<br>    dest: /etc/nginx/conf.d/myapp.conf<br>    owner: root<br>    group: root<br>    mode: &quot;0644&quot;<br>  notify: Restart Nginx</pre><p>When the template changes, Ansible notifies the handler.</p><p>By default, notified handlers execute later in the play, usually after the regular tasks have completed.</p><p>If the template remains unchanged, the task normally reports no change, so the handler is not triggered by that task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kEOyWvR1R9oe0FqY" /></figure><h3>Restart versus reload</h3><p>A restart stops and starts the service. A reload asks the service to reload its configuration without a full restart, where supported.</p><p>For production environments, use the appropriate operation for the service and configuration change. Validate configuration before applying it where possible.</p><p><strong>Key takeaway:</strong> Handlers reduce unnecessary service interruptions and make automation more efficient.</p><h3>7. Using Loops in Ansible</h3><p>Loops allow you to execute the same task for multiple items.</p><p>Suppose you need to install several packages on a server.</p><p>Instead of writing one task per package, use a loop.</p><pre>---<br>- name: Install required packages<br>  hosts: webservers<br>  become: true</pre><pre>  tasks:<br>    - name: Install packages<br>      ansible.builtin.package:<br>        name: &quot;{{ item }}&quot;<br>        state: present<br>      loop:<br>        - nginx<br>        - git<br>        - curl</pre><p>Here, item represents the current value in the loop.</p><p>Ansible executes the package task for each item.</p><h3>Create multiple directories</h3><pre>- name: Create application directories<br>  ansible.builtin.file:<br>    path: &quot;{{ item }}&quot;<br>    state: directory<br>    owner: root<br>    group: root<br>    mode: &quot;0755&quot;<br>  loop:<br>    - /opt/myapp<br>    - /opt/myapp/logs<br>    - /opt/myapp/config</pre><p>This is useful for application deployments where several directories must exist before the application starts.</p><p><strong>Best practice:</strong> Use loops when multiple items require the same operation. Use separate tasks when the operations differ significantly.</p><h3>8. Using Conditionals</h3><p>Conditionals allow Ansible to execute tasks only when specific conditions are satisfied.</p><p>For example, you might install a package only on Ubuntu servers or execute a task only when a variable is enabled.</p><h3>Check the operating system</h3><pre>- name: Install a package on Ubuntu<br>  ansible.builtin.apt:<br>    name: nginx<br>    state: present<br>  become: true<br>  when: ansible_facts[&#39;distribution&#39;] == &quot;Ubuntu&quot;</pre><p>This task runs only when the managed server’s distribution is Ubuntu.</p><p>Ansible facts provide information about the target system, including its operating system, memory, network interfaces, and other properties.</p><h3>Use a Boolean variable</h3><pre>---<br>- name: Configure application<br>  hosts: webservers</pre><pre>  vars:<br>    enable_monitoring: true</pre><pre>  tasks:<br>    - name: Display monitoring status<br>      ansible.builtin.debug:<br>        msg: &quot;Monitoring is enabled&quot;<br>      when: enable_monitoring</pre><p>If enable_monitoring is true, the task runs. If it is false, the task is skipped.</p><p>Conditionals are useful when the same playbook must support different operating systems, environments, or deployment requirements.</p><h3>9. Protecting Secrets with Ansible Vault</h3><p>Automation frequently requires sensitive information such as passwords, API keys, and database credentials.</p><p>Storing these values directly in plain-text playbooks or committing them to Git creates security risks.</p><p>Ansible Vault helps encrypt sensitive files and variables.</p><h3>Create an encrypted variables file</h3><p>Run:</p><pre>ansible-vault create secrets.yml</pre><p>Ansible prompts you to set a vault password.</p><p>Inside the file, add:</p><pre>---<br>db_username: app_user<br>db_password: replace_with_your_secret</pre><p>Save and exit the editor. Ansible Vault encrypts the file.</p><p>The example password is a placeholder. Do not use real credentials in public repositories or tutorials.</p><h3>View an encrypted file</h3><pre>ansible-vault view secrets.yml</pre><p>You must provide the correct vault password to view the contents.</p><h3>Use encrypted variables in a playbook</h3><pre>---<br>- name: Demonstrate protected variables<br>  hosts: localhost<br>  connection: local</pre><pre>  vars_files:<br>    - secrets.yml</pre><pre>  tasks:<br>    - name: Display database username<br>      ansible.builtin.debug:<br>        msg: &quot;Database user is {{ db_username }}&quot;</pre><p>Run the playbook using:</p><pre>ansible-playbook site.yml --ask-vault-pass</pre><p>Ansible prompts for the vault password and decrypts the file when needed.</p><h3>Important security practices</h3><ul><li>Never commit vault passwords to source control.</li><li>Avoid printing secrets through debug tasks.</li><li>Restrict access to encrypted files and password sources.</li><li>Consider an approved enterprise secret manager for production workloads.</li><li>Remember that encryption at rest does not automatically protect secrets from being exposed in logs or process output.</li></ul><h3>10. Running Selected Tasks with Tags</h3><p>Sometimes you need to execute only a specific part of a playbook.</p><p>For example, you may want to update a configuration without running every deployment task.</p><p>Tags allow you to select tasks during execution.</p><pre>---<br>- name: Configure web server<br>  hosts: webservers<br>  become: true</pre><pre>  tasks:<br>    - name: Install Nginx<br>      ansible.builtin.package:<br>        name: nginx<br>        state: present<br>      tags:<br>        - install</pre><pre>    - name: Create application directory<br>      ansible.builtin.file:<br>        path: /opt/myapp<br>        state: directory<br>        mode: &quot;0755&quot;<br>      tags:<br>        - configure</pre><p>Run only the installation task:</p><pre>ansible-playbook -i inventory.ini site.yml --tags install</pre><p>Run only the configuration task:</p><pre>ansible-playbook -i inventory.ini site.yml --tags configure</pre><p>You can also skip selected tags using --skip-tags.</p><p><strong>Note:</strong> Tags affect task selection, but they do not replace proper dependency management or testing. Be careful with roles, task imports, and handlers when using selective execution.</p><h3>11. Build a Practical Project Using Roles</h3><p>Now let’s bring the concepts together in a small Nginx configuration project.</p><p>The project will:</p><ol><li>Install Nginx.</li><li>Deploy a configuration generated from a template.</li><li>Restart Nginx when the configuration changes.</li></ol><h3>Step 1: Create the project structure</h3><pre>ansible-nginx/<br>├── inventory.ini<br>├── site.yml<br>└── roles/<br>    └── nginx/<br>        ├── defaults/<br>        │   └── main.yml<br>        ├── handlers/<br>        │   └── main.yml<br>        ├── tasks/<br>        │   └── main.yml<br>        └── templates/<br>            └── nginx.conf.j2</pre><p>You can generate the initial role with ansible-galaxy role init nginx and place it under roles/.</p><h3>Step 2: Configure the inventory</h3><p>Create inventory.ini:</p><pre>[webservers]<br>web1 ansible_host=192.0.2.10 ansible_user=ubuntu</pre><p>Replace the example address and SSH username with the details of a server you are authorized to manage. The address 192.0.2.10 is reserved for documentation and is not a real target for this tutorial.</p><h3>Step 3: Configure role defaults</h3><p>In roles/nginx/defaults/main.yml:</p><pre>---<br>nginx_port: 80<br>server_name: example.com</pre><h3>Step 4: Define the tasks</h3><p>In roles/nginx/tasks/main.yml:</p><pre>---<br>- name: Install Nginx<br>  ansible.builtin.package:<br>    name: nginx<br>    state: present</pre><pre>- name: Deploy Nginx configuration<br>  ansible.builtin.template:<br>    src: nginx.conf.j2<br>    dest: /etc/nginx/conf.d/myapp.conf<br>    owner: root<br>    group: root<br>    mode: &quot;0644&quot;<br>  notify: Restart Nginx</pre><pre>- name: Ensure Nginx is enabled and running<br>  ansible.builtin.service:<br>    name: nginx<br>    state: started<br>    enabled: true</pre><p>This assumes an Nginx installation that loads configuration from /etc/nginx/conf.d/. Verify the path for your target distribution.</p><h3>Step 5: Create the template</h3><p>In roles/nginx/templates/nginx.conf.j2:</p><pre>server {<br>    listen {{ nginx_port }};<br>    server_name {{ server_name }};</pre><pre>    location / {<br>        root /var/www/html;<br>        index index.html;<br>    }<br>}</pre><h3>Step 6: Create the handler</h3><p>In roles/nginx/handlers/main.yml:</p><pre>---<br>- name: Restart Nginx<br>  ansible.builtin.service:<br>    name: nginx<br>    state: restarted</pre><h3>Step 7: Create the main playbook</h3><p>In site.yml:</p><pre>---<br>- name: Configure Nginx servers<br>  hosts: webservers<br>  become: true</pre><pre>  roles:<br>    - nginx</pre><h3>Step 8: Validate and execute</h3><p>First, check connectivity:</p><pre>ansible -i inventory.ini webservers -m ansible.builtin.ping</pre><p>Check the playbook syntax:</p><pre>ansible-playbook -i inventory.ini site.yml --syntax-check</pre><p>Preview changes where supported:</p><pre>ansible-playbook -i inventory.ini site.yml --check --diff</pre><p>Finally, execute the playbook:</p><pre>ansible-playbook -i inventory.ini site.yml</pre><p>Check mode is a preview, not a guarantee that every change will be predicted accurately. Some modules and tasks have limitations in check mode.</p><h3>Expected result</h3><p>After successful execution:</p><ul><li>Nginx is installed.</li><li>The service is enabled and running.</li><li>The configuration file is generated using variables.</li><li>A configuration change triggers the handler.</li><li>Re-running the playbook should generally produce no unnecessary changes when the system already matches the desired state.</li></ul><p>For a production-ready implementation, add configuration validation before reloading or restarting Nginx, test the role against your target distributions, and verify the application endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*yaxAe7rdiPXUbeBq" /></figure><h3>12. Best Practices for Advanced Ansible Automation</h3><p>As your automation grows, following consistent practices makes it easier to maintain and troubleshoot.</p><p><strong>1. Keep roles focused.</strong> Create separate roles for logically distinct responsibilities, such as web servers, monitoring, and application deployment.</p><p><strong>2. Prefer idempotent modules.</strong> Use Ansible modules such as package, service, file, and template rather than shell commands whenever a suitable module exists.</p><p><strong>3. Separate configuration from code.</strong> Use variables for environment-specific settings rather than hardcoding values throughout your playbooks.</p><p><strong>4. Protect sensitive information.</strong> Use Ansible Vault or an approved secret-management system, and avoid logging credentials.</p><p><strong>5. Test before deployment.</strong> Use syntax checks, check mode where supported, and testing environments before applying changes to production.</p><p><strong>6. Use meaningful task names.</strong> Clear names make playbook output easier to understand during troubleshooting.</p><p><strong>7. Reuse roles carefully.</strong> Keep role responsibilities clear, document required variables, and pin external role dependencies to reviewed versions.</p><p><strong>8. Use version control.</strong> Store playbooks and roles in Git, review changes, and maintain a clear deployment history.</p><p><strong>9. Avoid unnecessary service restarts.</strong> Use handlers and validate configuration before applying changes.</p><p><strong>10. Understand the target environment.</strong> Package names, file paths, service names, and configuration layouts can differ across Linux distributions.</p><h3>13. Common Interview Questions</h3><p><strong>Q1. What is an Ansible Role?</strong></p><p>An Ansible Role organizes tasks, variables, handlers, templates, and files into a reusable structure.</p><p><strong>Q2. What is the difference between </strong><strong>defaults and </strong><strong>vars?</strong></p><p>Role defaults provide easy-to-override values and have low precedence. Role variables generally have higher precedence and are less convenient to override.</p><p><strong>Q3. What is a Jinja2 template in Ansible?</strong></p><p>A Jinja2 template is a file containing expressions and variables that Ansible renders into a configuration or other text file.</p><p><strong>Q4. What is a Handler?</strong></p><p>A handler is a special task that runs when notified by another task, typically when a configuration or other managed resource changes.</p><p><strong>Q5. What is Ansible Vault?</strong></p><p>Ansible Vault encrypts sensitive files and variables so that secrets are not stored in plain text.</p><p><strong>Q6. What is the difference between a loop and a conditional?</strong></p><p>A loop repeats a task for multiple items. A conditional determines whether a task should run based on a condition.</p><p><strong>Q7. What does idempotency mean in Ansible?</strong></p><p>Idempotency means that repeatedly applying the same automation should leave the system in the same desired state, rather than continuously introducing additional changes.</p><p><strong>Q8. What is the purpose of Ansible tags?</strong></p><p>Tags allow you to select or skip groups of tasks during playbook execution.</p><p><strong>Q9. What is the difference between a template and a static file?</strong></p><p>A template can contain variables and expressions that are rendered before deployment. A static file is copied as-is.</p><p><strong>Q10. Why are handlers useful in production?</strong></p><p>Handlers help prevent unnecessary service restarts by running only when notified, reducing avoidable interruptions.</p><h3>Conclusion</h3><p>Ansible becomes much more powerful when you move beyond basic playbooks and start using roles, variables, templates, handlers, and secure secret management.</p><p>These concepts help you build automation that is reusable, easier to troubleshoot, and more consistent across environments.</p><p>Start with the Nginx project in this article. Then try creating a separate role for application deployment, adding environment-specific variables, and protecting sensitive values with Ansible Vault.</p><p>The goal is not just to automate commands. It is to build reliable automation that can be maintained as your infrastructure grows.</p><p><strong>What Ansible concept would you like to explore next?</strong> Share your thoughts in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60f31f1779e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shell Scripting Fundamentals for DevOps Engineers: Automate Everyday Tasks with Bash]]></title>
            <link>https://medium.com/@shanbojja/shell-scripting-fundamentals-for-devops-engineers-automate-everyday-tasks-with-bash-37e09156f40e?source=rss-c047ef51b3ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/37e09156f40e</guid>
            <category><![CDATA[shellscripting]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Shanthi bojja]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 11:15:10 GMT</pubDate>
            <atom:updated>2026-10-24T11:15:10.842Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ucGiUy8oVkx-Qaj9tJltg.png" /></figure><p>Imagine checking server health, monitoring disk usage, cleaning temporary files, and collecting application logs manually every day. These tasks may seem simple, but repeating them across multiple servers can consume valuable time.</p><p>What if you could automate these tasks with a few lines of code?</p><p>That’s where <strong>shell scripting</strong> becomes useful.</p><p>Shell scripting is an essential skill for DevOps engineers because it helps automate repetitive tasks, simplify troubleshooting, and connect command-line tools into reliable workflows.</p><p>In this article, we’ll learn Bash scripting fundamentals and build practical scripts step by step.</p><h3>1. What Is Shell Scripting?</h3><p>A shell is a command-line interpreter that allows you to interact with an operating system.</p><p>A shell script is a file containing commands that execute in sequence. Bash, short for Bourne Again SHell, is one of the most widely used shells on Linux systems.</p><p>For example, instead of running three commands individually:</p><pre>date<br>hostname<br>df -h</pre><p>You can save them in a script and execute them together.</p><p>Shell scripts are useful for:</p><ul><li>Monitoring disk and memory usage.</li><li>Checking whether services are running.</li><li>Collecting logs for troubleshooting.</li><li>Automating backups and file operations.</li><li>Scheduling recurring maintenance tasks.</li><li>Supporting CI/CD pipelines.</li></ul><h3>2. Create and Execute Your First Bash Script</h3><p>Create a file named hello.sh:</p><pre>#!/usr/bin/env bash</pre><pre>echo &quot;Hello, DevOps!&quot;<br>echo &quot;Today&#39;s date: $(date)&quot;<br>echo &quot;Server name: $(hostname)&quot;</pre><p>The first line is called the <strong>shebang</strong>. It specifies the interpreter used to execute the script.</p><p>Make the script executable:</p><pre>chmod +x hello.sh</pre><p>Run it:</p><pre>./hello.sh</pre><p>Alternatively, execute it directly through Bash:</p><pre>bash hello.sh</pre><p>You have now created your first shell script.</p><h3>3. Understand Variables</h3><p>Variables store values that you can reuse throughout a script.</p><pre>#!/usr/bin/env bash</pre><pre>APP_NAME=&quot;payment-service&quot;<br>ENVIRONMENT=&quot;development&quot;</pre><pre>echo &quot;Application: $APP_NAME&quot;<br>echo &quot;Environment: $ENVIRONMENT&quot;</pre><p>Notice that there are no spaces around the = when assigning a value.</p><p>You can also capture command output:</p><pre>CURRENT_USER=$(whoami)</pre><pre>echo &quot;Current user: $CURRENT_USER&quot;</pre><p>This is called command substitution.</p><p>Variables make scripts easier to maintain because you can update a value in one place instead of modifying multiple commands.</p><h3>4. Accept User Input and Arguments</h3><p>You can make scripts more flexible by accepting input.</p><h3>Read user input</h3><pre>#!/usr/bin/env bash</pre><pre>read -r -p &quot;Enter application name: &quot; APP_NAME</pre><pre>echo &quot;Checking application: $APP_NAME&quot;</pre><h3>Use command-line arguments</h3><p>Create greet.sh:</p><pre>#!/usr/bin/env bash</pre><pre>NAME=&quot;${1:-Guest}&quot;</pre><pre>echo &quot;Hello, $NAME!&quot;</pre><p>Execute it:</p><pre>bash greet.sh Shanthi</pre><p>Output:</p><pre>Hello, Shanthi!</pre><p>Here, $1 represents the first positional argument. The expression ${1:-Guest} uses Guest when no first argument is provided.</p><p>Other useful special variables include:</p><ul><li>$0 — script name.</li><li>$1, $2 — positional arguments.</li><li>$# — number of positional arguments.</li><li>$? — exit status of the most recently completed command.</li></ul><h3>5. Use Conditions to Make Decisions</h3><p>Conditions allow a script to execute different actions depending on the situation.</p><p>For example, check whether a directory exists:</p><pre>#!/usr/bin/env bash</pre><pre>DIRECTORY=&quot;/var/log&quot;</pre><pre>if [[ -d &quot;$DIRECTORY&quot; ]]; then<br>    echo &quot;Directory exists.&quot;<br>else<br>    echo &quot;Directory does not exist.&quot;<br>fi</pre><p>Common file checks include:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*FHZN-kcW1iqbyKo-MGRq5w.png" /></figure><p>Always quote variables containing paths, particularly when the path might include spaces.</p><h3>6. Use Loops to Repeat Tasks</h3><p>Loops are helpful when you need to perform the same operation for multiple items.</p><h3>For loop</h3><pre>#!/usr/bin/env bash</pre><pre>for SERVICE in nginx ssh cron; do<br>    echo &quot;Checking service: $SERVICE&quot;<br>done</pre><p>This executes the commands once for each service name.</p><h3>While loop</h3><pre>#!/usr/bin/env bash</pre><pre>COUNT=1</pre><pre>while [[ &quot;$COUNT&quot; -le 5 ]]; do<br>    echo &quot;Attempt $COUNT&quot;<br>    COUNT=$((COUNT + 1))<br>done</pre><p>Loops can automate repetitive checks, process lists of files, or retry operations when appropriate.</p><p>For production retries, always define a maximum attempt count and an appropriate delay.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E2A19Rpz2nu5-FCj" /></figure><h3>7. Create Reusable Functions</h3><p>Functions help organize scripts and avoid repeating the same code.</p><pre>#!/usr/bin/env bash</pre><pre>check_directory() {<br>    local DIRECTORY=&quot;$1&quot;</pre><pre>    if [[ -d &quot;$DIRECTORY&quot; ]]; then<br>        echo &quot;Directory exists: $DIRECTORY&quot;<br>    else<br>        echo &quot;Directory missing: $DIRECTORY&quot;<br>        return 1<br>    fi<br>}</pre><pre>check_directory &quot;/var/log&quot;</pre><p>The local keyword limits the variable to the function&#39;s scope.</p><p>Functions become especially useful when scripts contain multiple operational checks.</p><h3>8. Check Exit Codes and Handle Errors</h3><p>A command’s exit status indicates whether it succeeded or failed. Conventionally, 0 means success, while a non-zero value indicates an error or another unsuccessful outcome.</p><p>Example:</p><pre>#!/usr/bin/env bash</pre><pre>if grep -q &quot;ERROR&quot; application.log; then<br>    echo &quot;Error entries found.&quot;<br>else<br>    echo &quot;No matching error entries found.&quot;<br>fi</pre><p>The if statement evaluates the exit status of grep, so the script can respond appropriately.</p><p>For scripts where an unexpected failure should stop execution, consider:</p><pre>#!/usr/bin/env bash</pre><pre>set -Eeuo pipefail</pre><pre>echo &quot;Starting task...&quot;</pre><p>These options help catch many common failures:</p><ul><li>-e — exits when certain commands fail.</li><li>-u — treats unset variables as errors.</li><li>pipefail — makes a pipeline fail if a command within it fails.</li><li>-E — allows an ERR trap to be inherited by functions and certain execution contexts.</li></ul><p>These settings are useful but are not a substitute for explicit error handling. Some commands, such as tests inside if conditions, intentionally return non-zero statuses.</p><h3>9. Practical Script: Monitor Disk Usage</h3><p>Disk usage monitoring is a common operational task.</p><p>Create disk_check.sh:</p><pre>#!/usr/bin/env bash</pre><pre>set -Eeuo pipefail</pre><pre>THRESHOLD=80</pre><pre>df -P | awk &#39;NR &gt; 1 {print $5, $6}&#39; |<br>while read -r USAGE MOUNT; do<br>    PERCENT=&quot;${USAGE%\%}&quot;</pre><pre>    if [[ &quot;$PERCENT&quot; =~ ^[0-9]+$ ]] &amp;&amp;<br>       (( PERCENT &gt;= THRESHOLD )); then<br>        echo &quot;WARNING: $MOUNT is at $USAGE usage&quot;<br>    fi<br>done</pre><p>Make it executable and run it:</p><pre>chmod +x disk_check.sh<br>./disk_check.sh</pre><p>The script reads filesystem usage, extracts the percentage and mount point, and prints a warning when usage reaches the configured threshold.</p><p>This is a basic example. Production monitoring should account for filesystem types, excluded mounts, container environments, and alerting requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*O8ss2zTccBX1PPzQ" /></figure><h3>10. Practical Script: Check Whether a Service Is Running</h3><p>On a Linux system that uses systemd, you can check a service with systemctl.</p><p>Create service_check.sh:</p><pre>#!/usr/bin/env bash</pre><pre>set -u</pre><pre>SERVICE=&quot;${1:-nginx}&quot;</pre><pre>if systemctl is-active --quiet &quot;$SERVICE&quot;; then<br>    echo &quot;$SERVICE is running.&quot;<br>else<br>    echo &quot;WARNING: $SERVICE is not active.&quot;<br>    exit 1<br>fi</pre><p>Run it:</p><pre>bash service_check.sh nginx</pre><p>This checks the service state and returns a non-zero exit status if the service is not active.</p><p>The service name and availability depend on the Linux distribution and installed software. Some systems may use different service-management tools.</p><h3>11. Schedule Scripts with Cron</h3><p>Cron is a scheduler commonly used on Linux to execute recurring tasks.</p><p>Edit your user’s crontab:</p><pre>crontab -e</pre><p>For example, to execute a script every day at 2 AM:</p><pre>0 2 * * * /home/user/scripts/disk_check.sh &gt;&gt; /home/user/logs/disk_check.log 2&gt;&amp;1</pre><p>This example assumes the directories exist and the user has permission to write to the log file.</p><p>The schedule format is:</p><pre>minute hour day-of-month month day-of-week command</pre><p>Cron jobs run with a limited environment, so use absolute paths, ensure the script is executable, and redirect output when you need logs.</p><p>For important production tasks, also monitor whether the scheduled job actually completes successfully.</p><h3>12. Shell Scripting in CI/CD Pipelines</h3><p>Shell scripts are frequently used inside CI/CD systems to automate build and deployment tasks.</p><p>For example, a pipeline might run:</p><pre>#!/usr/bin/env bash</pre><pre>set -Eeuo pipefail</pre><pre>echo &quot;Running application checks...&quot;<br>python3 -m pytest</pre><pre>echo &quot;Validation completed.&quot;</pre><p>A CI/CD platform can execute this script after retrieving the source code. If the test command fails, the script exits rather than continuing to the success message.</p><p>Shell scripts can also prepare environments, package artifacts, validate configuration, and call cloud CLI tools.</p><p>However, deployment scripts should include safeguards, controlled credentials, and explicit checks before modifying production resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4zNeRga4iwRhOjG7" /></figure><h3>13. Best Practices for DevOps Shell Scripts</h3><ol><li><strong>Use a shebang.</strong> Specify the intended interpreter.</li><li><strong>Quote variables.</strong> This helps prevent unexpected word splitting and pathname expansion.</li><li><strong>Validate inputs.</strong> Reject invalid values before running commands.</li><li><strong>Handle errors deliberately.</strong> Check important command results.</li><li><strong>Use meaningful names.</strong> Make variables and functions easy to understand.</li><li><strong>Avoid hardcoded secrets.</strong> Use approved secret-management mechanisms.</li><li><strong>Log useful information.</strong> Make failures easier to investigate.</li><li><strong>Test safely.</strong> Use a test environment before modifying production systems.</li><li><strong>Make scripts idempotent where possible.</strong> Re-running a script should not cause unintended repeated effects.</li><li><strong>Use the right tool.</strong> Bash is excellent for command orchestration, while complex applications may be better suited to Python or another programming language.</li></ol><h3>Conclusion</h3><p>Shell scripting is a practical skill that helps DevOps engineers automate repetitive operations, inspect system health, and connect tools into reliable workflows.</p><p>Start with variables, conditions, loops, and functions. Then practise building monitoring scripts, handling errors, and scheduling recurring tasks.</p><p>The more you practise these fundamentals, the easier it becomes to troubleshoot systems and automate everyday operations.</p><p><strong>In DevOps, small scripts can save significant time when they are designed, tested, and maintained properly.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37e09156f40e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS CLI Fundamentals for DevOps Engineers: Automate Cloud Operations from the Terminal]]></title>
            <link>https://medium.com/@shanbojja/aws-cli-fundamentals-for-devops-engineers-automate-cloud-operations-from-the-terminal-62e59ddb3c77?source=rss-c047ef51b3ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/62e59ddb3c77</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws-cli]]></category>
            <dc:creator><![CDATA[Shanthi bojja]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 17:12:02 GMT</pubDate>
            <atom:updated>2026-10-23T17:12:02.945Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PF-m4FdogWnrOixokPLa5w.jpeg" /></figure><p>Cloud platforms provide powerful interfaces for managing infrastructure, but performing repetitive tasks manually can be time-consuming. DevOps engineers often need to inspect resources, automate routine operations, and integrate cloud commands into scripts and CI/CD pipelines.</p><p>The <strong>AWS Command Line Interface (AWS CLI)</strong> makes these tasks possible directly from a terminal.</p><p>In this article, we’ll learn what AWS CLI is, how to configure it, explore essential commands, and build practical examples for cloud automation.</p><h3>1. What Is AWS CLI?</h3><p>AWS CLI is a command-line tool that lets you interact with Amazon Web Services through commands.</p><p>Instead of navigating through the AWS Management Console for every operation, you can use the CLI to perform supported actions from a terminal or script.</p><p>For example, you can use AWS CLI to:</p><ul><li>List objects in Amazon S3 buckets.</li><li>Inspect EC2 instances.</li><li>Query information about AWS resources.</li><li>Upload and download files.</li><li>Manage selected cloud resources.</li><li>Automate operational tasks using shell scripts.</li><li>Integrate cloud operations into CI/CD pipelines.</li></ul><p>AWS CLI is especially useful when the same task must be performed repeatedly or consistently across environments.</p><h3>2. How AWS CLI Works</h3><p>When you execute an AWS CLI command, the tool sends a request to the relevant AWS service API using your configured credentials and settings.</p><p>A simplified workflow is:</p><p><strong>Terminal → AWS CLI → Authentication and Authorization → AWS Service API → Response</strong></p><p>For example, when you run an S3 command, AWS CLI sends a request to Amazon S3. AWS checks whether the identity is authorized to perform the requested action and returns a response.</p><p>Successful execution depends on several factors:</p><ul><li>Correct CLI installation.</li><li>Valid credentials or an approved authentication method.</li><li>Appropriate IAM permissions.</li><li>Correct AWS Region, when applicable.</li><li>Network connectivity and service availability.</li></ul><p>Remember that installing AWS CLI does not automatically grant access to AWS resources.</p><h3>3. Install AWS CLI</h3><p>AWS CLI version 2 is the recommended starting point for new users.</p><p>Follow the official installation instructions for your operating system:</p><p><a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html</a></p><p>After installation, verify it:</p><pre>aws --version</pre><p>You should see output identifying AWS CLI version 2 and its associated runtime details.</p><p>If the command is not recognized, check that the installation completed successfully and that the executable is available in your system’s PATH.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5veYtzz5-NQBf3yw" /></figure><h3>4. Configure AWS CLI</h3><p>AWS CLI needs an identity to use when making requests to AWS.</p><p>For an initial local setup, you may configure credentials using:</p><pre>aws configure</pre><p>The command prompts you for values such as:</p><ul><li>AWS Access Key ID.</li><li>AWS Secret Access Key.</li><li>Default Region.</li><li>Default output format.</li></ul><p>For example, the Region could be ap-south-1, which represents the Mumbai Region.</p><p>The output format can be json, yaml, text, or table, depending on the command and your preferences.</p><p><strong>Security note:</strong> Do not share access keys, commit them to Git, or store them in scripts. In managed cloud environments, prefer IAM roles or other temporary-credential methods instead of long-lived access keys.</p><h3>5. Use Named AWS CLI Profiles</h3><p>Different projects may use different AWS accounts or environments. Profiles help you keep their configurations separate.</p><p>Create a profile:</p><pre>aws configure --profile dev</pre><p>Create another profile:</p><pre>aws configure --profile test</pre><p>Use a specific profile when running a command:</p><pre>aws sts get-caller-identity --profile dev</pre><p>You can also set the profile for the current terminal session.</p><p>On Linux or macOS:</p><pre>export AWS_PROFILE=dev</pre><p>On Windows PowerShell:</p><pre>$env:AWS_PROFILE = &quot;dev&quot;</pre><p>To remove the setting from the current session, unset the environment variable or close the terminal.</p><p>Before executing an operation that changes resources, verify which identity and account you are using.</p><h3>6. Verify Your AWS Identity</h3><p>One of the most useful commands for checking your current AWS identity is:</p><pre>aws sts get-caller-identity</pre><p>This command returns identity information, including the AWS account ID and the ARN associated with the calling identity.</p><p>For a named profile:</p><pre>aws sts get-caller-identity --profile dev</pre><p>This is a useful safety check before running scripts that create, modify, or delete cloud resources.</p><p>It also helps diagnose authentication problems when a command unexpectedly fails.</p><h3>7. Understand the Basic AWS CLI Command Structure</h3><p>Most AWS CLI commands follow this structure:</p><pre>aws &lt;service&gt; &lt;operation&gt; [options]</pre><p>For example:</p><pre>aws s3 ls</pre><p>Here:</p><ul><li>aws invokes the CLI.</li><li>s3 identifies the service interface.</li><li>ls lists buckets or objects, depending on the target.</li></ul><p>Another example:</p><pre>aws ec2 describe-instances --region ap-south-1</pre><p>This requests information about EC2 instances in the Mumbai Region, subject to the permissions of the current identity.</p><p>Common options include:</p><p>OptionPurpose--regionSelects the AWS Region--profileSelects a named profile--outputControls output formatting--queryFilters response data using JMESPath--helpDisplays command help</p><p>You can explore supported operations using:</p><pre>aws s3 help</pre><p>Or:</p><pre>aws ec2 describe-instances help</pre><h3>8. Work with Amazon S3</h3><p>Amazon S3 is an object storage service frequently used for application files, logs, backups, and data pipelines.</p><h3>List available buckets</h3><pre>aws s3 ls</pre><h3>List objects in a bucket</h3><pre>aws s3 ls s3://your-bucket-name/</pre><p>Replace your-bucket-name with a bucket you are authorized to access.</p><h3>Upload a file</h3><pre>aws s3 cp report.csv s3://your-bucket-name/reports/report.csv</pre><h3>Download a file</h3><pre>aws s3 cp s3://your-bucket-name/reports/report.csv ./report.csv</pre><h3>Synchronize a directory</h3><pre>aws s3 sync ./reports s3://your-bucket-name/reports/</pre><p>The sync command compares the source and destination and transfers files as needed. Understand its behavior before adding options that delete destination objects.</p><p>These commands can support backup processes, data transfers, and scheduled operational tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*_gPMK5jec6VyeIoH" /></figure><h3>9. Inspect EC2 Instances</h3><p>Amazon EC2 provides virtual servers in AWS.</p><p>To list EC2 instances in a specific Region:</p><pre>aws ec2 describe-instances --region ap-south-1</pre><p>The full response can contain a large amount of JSON. You can use --query to extract selected fields.</p><p>For example:</p><pre>aws ec2 describe-instances \<br>  --query &quot;Reservations[].Instances[].[InstanceId,State.Name,InstanceType]&quot; \<br>  --output table</pre><p>This displays instance IDs, states, and instance types in a table.</p><p>To retrieve instances in a particular state, use filters:</p><pre>aws ec2 describe-instances \<br>  --filters &quot;Name=instance-state-name,Values=running&quot; \<br>  --query &quot;Reservations[].Instances[].[InstanceId,State.Name]&quot; \<br>  --output table</pre><p>These are read-only inspection commands. Before using commands that start, stop, or terminate instances, confirm the account, Region, target resources, and authorization.</p><h3>10. Filter Command Output with --query</h3><p>AWS CLI supports JMESPath expressions through the --query option.</p><p>This helps extract the information your script actually needs.</p><p>For example, to list S3 bucket names:</p><pre>aws s3api list-buckets \<br>  --query &quot;Buckets[].Name&quot; \<br>  --output text</pre><p>To retrieve EC2 instance IDs:</p><pre>aws ec2 describe-instances \<br>  --query &quot;Reservations[].Instances[].InstanceId&quot; \<br>  --output text</pre><p>Filtering output can make shell scripts easier to read and reduce the amount of data passed to subsequent commands.</p><p>For more complex automation, remember that the response structure varies by service and operation.</p><h3>11. Automate a Simple AWS Operational Task</h3><p>Let’s create a basic shell script that checks whether AWS CLI can identify the configured caller.</p><p>Create a file named check_aws_identity.sh:</p><pre>#!/usr/bin/env bash</pre><pre>set -euo pipefail</pre><pre>echo &quot;Checking AWS identity...&quot;</pre><pre>aws sts get-caller-identity --output json</pre><pre>echo &quot;Identity check completed.&quot;</pre><p>Make it executable on Linux or macOS:</p><pre>chmod +x check_aws_identity.sh</pre><p>Run it:</p><pre>./check_aws_identity.sh</pre><p>If the command fails because of missing credentials or permissions, set -e causes the script to stop rather than continue as if the check succeeded.</p><p>This example is intentionally simple. It can be extended with logging, profile selection, structured error handling, and notifications.</p><h3>12. Automate S3 File Uploads</h3><p>Consider a situation where a team generates daily reports and uploads them to an S3 bucket.</p><p>The following example uploads a local directory to a configured S3 destination.</p><pre>#!/usr/bin/env bash</pre><pre>set -euo pipefail</pre><pre>SOURCE_DIR=&quot;./reports&quot;<br>S3_DESTINATION=&quot;s3://your-bucket-name/daily-reports/&quot;</pre><pre>if [[ ! -d &quot;$SOURCE_DIR&quot; ]]; then<br>    echo &quot;Error: Reports directory not found.&quot;<br>    exit 1<br>fi</pre><pre>aws sts get-caller-identity &gt;/dev/null</pre><pre>aws s3 sync &quot;$SOURCE_DIR&quot; &quot;$S3_DESTINATION&quot;</pre><pre>echo &quot;Report synchronization completed.&quot;</pre><p>Before running this script:</p><ol><li>Replace the S3 destination with your approved bucket.</li><li>Configure a valid identity with the required permissions.</li><li>Verify that the source directory contains the intended files.</li><li>Test the script in a non-production environment.</li></ol><p>This script does not delete destination files. If you later add --delete, understand that it can remove destination objects that are not present in the source.</p><p>For production automation, add monitoring and alerting so failures are visible to the operations team.</p><h3>13. AWS CLI in CI/CD Pipelines</h3><p>AWS CLI is often used in CI/CD workflows to interact with cloud resources.</p><p>For example, a deployment pipeline might:</p><ol><li>Retrieve application source code from Git.</li><li>Run unit tests.</li><li>Build a Docker image.</li><li>Authenticate to an approved container registry.</li><li>Push the image.</li><li>Deploy the application to the target environment.</li><li>Verify deployment health.</li></ol><p>AWS CLI may support several of these steps, depending on the AWS services involved.</p><p>In Jenkins or another CI/CD platform, use the platform’s approved credential integration or an appropriate role-based authentication mechanism. Do not place access keys directly in a Jenkinsfile or repository.</p><p>Keep development, testing, and production permissions separate, and ensure the pipeline can only perform the operations it needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ip9bjxEix-sZR4Sv" /></figure><h3>14. Common AWS CLI Errors</h3><h3>Unable to locate credentials</h3><p><strong>Possible cause:</strong> No credentials are available through the configured profile or supported identity provider.</p><p><strong>What to check:</strong> Review the selected profile and authentication setup.</p><h3>Access denied</h3><p><strong>Possible cause:</strong> The calling identity lacks the required permission, or another applicable policy blocks the operation.</p><p><strong>What to check:</strong> Verify IAM permissions, resource policies, and the target resource.</p><h3>Incorrect Region</h3><p><strong>Possible cause:</strong> The command is targeting a Region different from the one containing the resource.</p><p><strong>What to check:</strong> Confirm the resource’s Region and specify --region when appropriate.</p><h3>Resource not found</h3><p><strong>Possible cause:</strong> Incorrect resource identifier, account, Region, or resource state.</p><p><strong>What to check:</strong> Verify the current identity, Region, and exact resource name or ID.</p><h3>Invalid command or parameter</h3><p><strong>Possible cause:</strong> A typo or an unsupported parameter value.</p><p><strong>What to check:</strong> Run the command’s --help option and verify the syntax.</p><h3>15. AWS CLI Best Practices for DevOps Engineers</h3><ol><li><strong>Prefer temporary credentials.</strong> Use roles and approved identity mechanisms instead of long-lived access keys wherever possible.</li><li><strong>Apply least privilege.</strong> Grant only the permissions required for each task.</li><li><strong>Verify the target account.</strong> Check the active identity before making changes.</li><li><strong>Specify the Region explicitly.</strong> Avoid accidental operations in the wrong Region.</li><li><strong>Use profiles for local development.</strong> Keep account configurations separate.</li><li><strong>Avoid logging secrets.</strong> Never print credentials or sensitive values in build logs.</li><li><strong>Handle failures.</strong> Make scripts stop or report errors when critical commands fail.</li><li><strong>Test before production.</strong> Validate automation in a safe environment.</li><li><strong>Review destructive operations.</strong> Carefully inspect commands that delete, terminate, or overwrite resources.</li><li><strong>Monitor automation.</strong> Ensure scheduled tasks and pipelines produce observable success and failure signals.</li></ol><h3>Conclusion</h3><p>AWS CLI gives DevOps engineers a practical way to interact with AWS services from terminals and automation scripts. By learning configuration, profiles, identity verification, S3 operations, EC2 inspection, and shell scripting, you can begin replacing repetitive manual tasks with consistent workflows.</p><p>Start with read-only commands, understand the permissions behind each operation, and gradually introduce automation in a test environment.</p><p><strong>Reliable cloud automation begins with repeatable commands, secure credentials, and careful validation.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62e59ddb3c77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jenkins Fundamentals for DevOps Engineers: Build Your First CI/CD Pipeline]]></title>
            <link>https://medium.com/@shanbojja/jenkins-fundamentals-for-devops-engineers-build-your-first-ci-cd-pipeline-7b31f1affb7d?source=rss-c047ef51b3ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b31f1affb7d</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[jenkins]]></category>
            <dc:creator><![CDATA[Shanthi bojja]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 17:04:04 GMT</pubDate>
            <atom:updated>2026-10-23T17:04:04.907Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*0XkWAGs-CGXcbPdbSk3giQ.jpeg" /></figure><p>Modern software teams need to deliver code changes quickly without compromising quality. Manually building applications, running tests, and deploying every change takes time and increases the possibility of human error.</p><p>This is where <strong>Jenkins</strong> becomes useful.</p><p>Jenkins is an automation server that helps teams build, test, and deliver software through continuous integration and continuous delivery pipelines.</p><p>In this article, we’ll learn Jenkins fundamentals, understand CI/CD, explore Jenkins jobs and pipelines, and build a simple pipeline step by step.</p><h3>1. What Is Jenkins?</h3><p>Jenkins is an open-source automation server widely used in DevOps workflows.</p><p>It can automate tasks such as:</p><ul><li>Building applications after code changes.</li><li>Running automated tests.</li><li>Performing code quality checks.</li><li>Building Docker images.</li><li>Triggering security scans.</li><li>Deploying applications to development, testing, and production environments.</li></ul><p>For example, when a developer pushes code to a Git repository, Jenkins can automatically retrieve the code, run tests, and build an application artifact.</p><p>This reduces repetitive manual work and provides faster feedback to developers.</p><h3>2. What Is CI/CD?</h3><p>Before learning Jenkins, let’s understand the two main concepts behind most software delivery pipelines.</p><h3>Continuous Integration (CI)</h3><p>Continuous Integration means frequently integrating code changes into a shared repository and automatically validating those changes.</p><p>A typical CI process includes:</p><ol><li>A developer pushes code to Git.</li><li>The pipeline retrieves the latest changes.</li><li>Automated tests run.</li><li>Code quality checks execute.</li><li>The build succeeds or fails based on the results.</li></ol><p>CI helps teams identify defects earlier.</p><h3>Continuous Delivery and Continuous Deployment (CD)</h3><p>These terms are related but have different meanings.</p><p><strong>Continuous Delivery</strong> keeps software ready for release, with production deployment potentially requiring approval.</p><p><strong>Continuous Deployment</strong> automatically releases qualifying changes to production after all required checks pass.</p><p>A simplified pipeline looks like this:</p><p>Code → Build → Test → Security Scan → Deploy</p><p>Jenkins can orchestrate these stages, while other tools may perform specific tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zj_pWFW5rdRIcU8C" /></figure><h3>3. How Jenkins Works</h3><p>A Jenkins setup commonly includes a controller and one or more agents.</p><p><strong>Jenkins controller:</strong> Manages pipeline execution, job scheduling, configuration, and coordination.</p><p><strong>Jenkins agent:</strong> Executes build and test tasks assigned by the controller.</p><p>Agents allow workloads to run on different machines or environments, depending on the configuration.</p><h3>Important Jenkins Components</h3><ul><li><strong>Job or project:</strong> A configured task Jenkins can execute.</li><li><strong>Pipeline:</strong> A sequence of automated stages.</li><li><strong>Jenkinsfile:</strong> A text file that defines a pipeline as code.</li><li><strong>Plugin:</strong> An extension that adds functionality or integrations.</li><li><strong>Workspace:</strong> A directory where Jenkins performs work for a job.</li><li><strong>Build:</strong> A specific execution of a job or pipeline.</li></ul><h3>4. Install Jenkins or Access an Existing Instance</h3><p>For a beginner, the easiest starting point is an existing Jenkins training instance or a local test environment.</p><p>Jenkins installation requirements and recommended Java versions can change. Follow the official documentation for the current supported setup:</p><p><a href="https://www.jenkins.io/doc/book/installing/">https://www.jenkins<strong>.io/doc/book/installing</strong>/</a></p><p>After Jenkins is running, open its configured web address in a browser. A common local address is:</p><p><a href="http://localhost:8080/">http://localhost:8080</a></p><p>The exact URL and port depend on your configuration.</p><p>Complete the initial setup, install the recommended plugins, and create an administrator account when prompted.</p><p><strong>Important:</strong> Use a test environment for practice. Do not expose an unsecured Jenkins instance to the public internet.</p><h3>5. Explore the Jenkins Dashboard</h3><p>After signing in, you’ll typically work with these areas:</p><ul><li><strong>New Item:</strong> Create a job or pipeline.</li><li><strong>Build History:</strong> View previous executions.</li><li><strong>Manage Jenkins:</strong> Configure system settings, tools, plugins, and security.</li><li><strong>Credentials:</strong> Store credentials for authorized integrations.</li><li><strong>Console Output:</strong> Inspect logs for a specific build.</li></ul><p>The console output is especially useful when troubleshooting failed pipelines because it shows the commands executed and their output.</p><h3>6. Create Your First Jenkins Job</h3><p>Let’s start with a simple Freestyle project.</p><ol><li>Open the Jenkins dashboard.</li><li>Select <strong>New Item</strong>.</li><li>Enter a name such as hello-devops.</li><li>Select <strong>Freestyle project</strong>.</li><li>Choose <strong>OK</strong>.</li><li>In the configuration page, find the build steps section.</li><li>Add an <strong>Execute shell</strong> step on a suitable Linux agent.</li><li>Enter the following commands:</li></ol><pre>echo &quot;Hello, DevOps!&quot;<br>echo &quot;Jenkins is running my first build.&quot;</pre><ol><li>Save the configuration.</li><li>Select <strong>Build Now</strong>.</li><li>Open the latest build and select <strong>Console Output</strong>.</li></ol><p>You should see the messages printed by the commands.</p><p>On a Windows agent, use the appropriate Windows batch or PowerShell build step instead.</p><p>This exercise demonstrates how Jenkins can execute repeatable tasks. However, real-world projects usually benefit from defining pipelines as code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/0*fbeNa7ufYCSwkNe4" /></figure><h3>7. What Is a Jenkins Pipeline?</h3><p>A Jenkins Pipeline defines the steps required to build, test, and deliver an application.</p><p>Instead of configuring every step through the web interface, you can store the pipeline definition in a file named Jenkinsfile.</p><p>This file can live in the same Git repository as the application code.</p><p>Benefits include:</p><ul><li>Version-controlled pipeline changes.</li><li>Easier collaboration and code review.</li><li>Repeatable builds across environments.</li><li>Clear visibility into delivery stages.</li><li>Better integration with Git-based workflows.</li></ul><p>Jenkins supports both Declarative and Scripted Pipeline syntax. Declarative Pipeline is generally a good starting point for beginners.</p><h3>8. Build Your First Jenkinsfile</h3><p>Create a file named Jenkinsfile in the root of a Git repository.</p><p>Add the following example:</p><pre>pipeline {<br>    agent any</pre><pre>    stages {<br>        stage(&#39;Checkout&#39;) {<br>            steps {<br>                echo &#39;Retrieving project source code&#39;<br>            }<br>        }</pre><pre>        stage(&#39;Build&#39;) {<br>            steps {<br>                echo &#39;Building the application&#39;<br>            }<br>        }</pre><pre>        stage(&#39;Test&#39;) {<br>            steps {<br>                echo &#39;Running automated tests&#39;<br>            }<br>        }</pre><pre>        stage(&#39;Complete&#39;) {<br>            steps {<br>                echo &#39;Pipeline completed successfully&#39;<br>            }<br>        }<br>    }<br>}</pre><p>This is a demonstration pipeline. The stages print messages; they do not yet retrieve source code, compile an application, or execute real tests.</p><h3>Understand the Pipeline</h3><p><strong>pipeline</strong> defines the overall pipeline.</p><p><strong>agent any</strong> tells Jenkins to run the pipeline on any available eligible agent.</p><p><strong>stages</strong> contains the major steps of the workflow.</p><p><strong>stage</strong> groups related tasks under a name.</p><p><strong>steps</strong> contains the actions executed within a stage.</p><p><strong>echo</strong> prints a message in the build log.</p><p>When you run this pipeline, Jenkins displays the configured stages and their execution results.</p><h3>9. Connect the Pipeline to Git</h3><p>To run a pipeline from a repository, the repository must contain a Jenkinsfile.</p><p>A typical setup is:</p><ol><li>Push your application and Jenkinsfile to GitHub.</li><li>Create a new Jenkins item.</li><li>Select <strong>Pipeline</strong>.</li><li>Under the pipeline definition, select <strong>Pipeline script from SCM</strong>.</li><li>Select <strong>Git</strong> as the source control system.</li><li>Enter the repository URL.</li><li>Configure credentials if the repository is private.</li><li>Set the branch and script path, usually Jenkinsfile.</li><li>Save and run the pipeline.</li></ol><p>Jenkins can now retrieve the pipeline definition from source control.</p><p>For automated triggering, configure an appropriate webhook or a supported polling mechanism. A webhook requires the Git provider and Jenkins endpoint to be configured correctly.</p><h3>10. Run a Real Python Test Pipeline</h3><p>Let’s make the example more practical with a small Python project.</p><p>Create this structure:</p><pre>python-demo/<br>├── app.py<br>├── test_app.py<br>└── Jenkinsfile</pre><h3>Step 1: Create the application</h3><p>In app.py:</p><pre>def add_numbers(a, b):<br>    return a + b</pre><h3>Step 2: Create a unit test</h3><p>In test_app.py:</p><pre>from app import add_numbers<br></pre><pre>def test_add_numbers():<br>    assert add_numbers(2, 3) == 5</pre><h3>Step 3: Create the Jenkinsfile</h3><pre>pipeline {<br>    agent any</pre><pre>    stages {<br>        stage(&#39;Checkout&#39;) {<br>            steps {<br>                echo &#39;Source code is available in the workspace&#39;<br>            }<br>        }</pre><pre>        stage(&#39;Setup&#39;) {<br>            steps {<br>                sh &#39;&#39;&#39;<br>                    python3 -m venv .venv<br>                    .venv/bin/python -m pip install --upgrade pip<br>                    .venv/bin/python -m pip install pytest<br>                &#39;&#39;&#39;<br>            }<br>        }</pre><pre>        stage(&#39;Test&#39;) {<br>            steps {<br>                sh &#39;.venv/bin/python -m pytest -v&#39;<br>            }<br>        }<br>    }<br>}</pre><p>This example assumes the Jenkins agent is Linux-based, has Python 3 and virtual-environment support installed, and can access the package index.</p><p>The Checkout stage only prints a message; it does not check out code itself. When configuring a Pipeline from SCM, Jenkins normally checks out the repository before executing the stages.</p><p>If you are using a manually configured pipeline, add an appropriate checkout step before running the tests.</p><p>When the environment is configured correctly, Jenkins creates a virtual environment, installs pytest, and runs the unit test.</p><p>A successful run confirms that the test passed. If the test fails, the pipeline should report a failed build.</p><h3>11. Understand Jenkins Plugins</h3><p>Plugins extend Jenkins and help it integrate with other tools.</p><p>Common integration categories include:</p><ul><li><strong>Source control:</strong> Git integrations.</li><li><strong>Build tools:</strong> Maven, Gradle, and other build systems.</li><li><strong>Pipeline:</strong> Pipeline and visualization capabilities.</li><li><strong>Credentials:</strong> Integration with Jenkins credential management.</li><li><strong>Containers:</strong> Docker-related integrations.</li><li><strong>Notifications:</strong> Email or messaging integrations.</li></ul><p>Install only the plugins required by your project, and keep them updated according to your organization’s policies.</p><p>A plugin should not be installed merely because it is popular. Review its purpose, compatibility, maintenance, and security implications first.</p><h3>12. Jenkins Credentials and Security</h3><p>CI/CD pipelines frequently need credentials to access source repositories, registries, cloud resources, or deployment environments.</p><p>Avoid placing passwords, access tokens, private keys, or other secrets directly in a Jenkinsfile.</p><p>Instead, use Jenkins Credentials and bind them to the steps that need them.</p><p>For example, a Declarative Pipeline can access a stored secret using a credentials binding:</p><pre>pipeline {<br>    agent any</pre><pre>    stages {<br>        stage(&#39;Example&#39;) {<br>            steps {<br>                withCredentials([<br>                    string(<br>                        credentialsId: &#39;example-token&#39;,<br>                        variable: &#39;API_TOKEN&#39;<br>                    )<br>                ]) {<br>                    sh &#39;&#39;&#39;<br>                        test -n &quot;$API_TOKEN&quot;<br>                        echo &quot;Credential is available&quot;<br>                    &#39;&#39;&#39;<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Create a Jenkins Secret Text credential with the ID example-token before running this example.</p><p>The script checks that the variable is available without printing its value.</p><p>Credential masking is helpful but does not guarantee that secrets can never leak. Avoid commands that reveal secrets, restrict credential permissions, and use least-privilege access.</p><h3>13. Integrate Security Checks into CI/CD</h3><p>Modern DevOps pipelines often include security checks as part of the build process.</p><p>Examples include:</p><ul><li>Static code analysis.</li><li>Dependency vulnerability scanning.</li><li>Secret detection.</li><li>Container image scanning.</li><li>Dynamic application security testing (DAST).</li><li>Quality gates that prevent unsafe changes from proceeding.</li></ul><p>A simplified DevSecOps workflow is:</p><p>Git Commit → Build → Unit Tests → Security Scans → Quality Gate → Deployment</p><p>For example, a pipeline may stop if a mandatory security scan fails or if a quality gate detects an unacceptable issue.</p><p>The exact checks and thresholds should be defined by the organization’s security policies. A green Jenkins build alone does not prove that an application is secure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gaJCu01jKWtDE3Pq" /></figure><h3>14. Common Jenkins Pipeline Failures</h3><h3>Pipeline fails because a command is not found</h3><p><strong>Possible cause:</strong> The required software is missing from the agent or is not available in its PATH.</p><p><strong>What to check:</strong> Inspect the agent environment and verify the installed tool versions.</p><h3>Git checkout fails</h3><p><strong>Possible cause:</strong> Incorrect repository URL, branch name, credentials, or network access.</p><p><strong>What to check:</strong> Verify the repository configuration and ensure the Jenkins identity has the necessary permissions.</p><h3>Python tests fail</h3><p><strong>Possible cause:</strong> Missing dependencies, incorrect imports, or failing assertions.</p><p><strong>What to check:</strong> Review the console output and reproduce the test in a matching environment.</p><h3>Pipeline cannot find the Jenkinsfile</h3><p><strong>Possible cause:</strong> Incorrect script path or branch selection.</p><p><strong>What to check:</strong> Confirm that the file exists in the selected branch at the configured path.</p><h3>Pipeline remains queued</h3><p><strong>Possible cause:</strong> No eligible agent is available, or the required agent label cannot be satisfied.</p><p><strong>What to check:</strong> Review agent availability, labels, and executor configuration.</p><h3>15. Best Practices for Jenkins</h3><p>Follow these practices when building production pipelines:</p><ol><li><strong>Keep pipelines in source control.</strong> Use a Jenkinsfile so changes can be reviewed.</li><li><strong>Make builds repeatable.</strong> Pin dependencies and define required tools and environments.</li><li><strong>Fail fast.</strong> Run quick validation and unit tests early.</li><li><strong>Protect credentials.</strong> Use the credentials store and least-privilege access.</li><li><strong>Separate environments.</strong> Control which jobs can deploy to development, testing, and production.</li><li><strong>Use agents appropriately.</strong> Isolate workloads and avoid unnecessary privileges.</li><li><strong>Monitor pipeline health.</strong> Review failures, execution times, and recurring problems.</li><li><strong>Include security checks.</strong> Make required scans and quality gates part of the delivery process.</li><li><strong>Avoid unnecessary plugins.</strong> Reduce maintenance and security risk.</li><li><strong>Require appropriate approval.</strong> Production releases should follow organizational change-management policies.</li></ol><h3>Conclusion</h3><p>Jenkins helps automate the journey from source code to tested and deployable software. By understanding jobs, pipelines, Jenkinsfiles, agents, credentials, and CI/CD stages, beginners can start building useful automation workflows.</p><p>Start with a simple pipeline, connect it to Git, and gradually add real tests, quality checks, security scanning, and deployment stages.</p><p><strong>The goal is not just to automate builds. It is to make software delivery consistent, reliable, and repeatable.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b31f1affb7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Fundamentals for DevOps Engineers: A Beginner’s Guide to Version Control]]></title>
            <link>https://medium.com/@shanbojja/git-fundamentals-for-devops-engineers-a-beginners-guide-to-version-control-8ba2bbeea6fc?source=rss-c047ef51b3ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ba2bbeea6fc</guid>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[version-control]]></category>
            <dc:creator><![CDATA[Shanthi bojja]]></dc:creator>
            <pubDate>Fri, 16 Oct 2026 03:16:51 GMT</pubDate>
            <atom:updated>2026-10-16T03:16:51.118Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jzJsxA1frr_dEmgB" /></figure><p>In software development, code changes every day. Developers add features, fix bugs, improve performance, and collaborate with other team members. But how do they track these changes, work on different features simultaneously, and recover earlier versions of their code?</p><p>That’s where <strong>Git</strong> comes in.</p><p>Git is one of the most important tools in a DevOps engineer’s toolkit. It helps teams manage source code, collaborate efficiently, and build automated CI/CD pipelines.</p><p>In this article, we’ll learn Git from scratch, understand its most commonly used commands, and walk through a practical workflow.</p><h3>1. What Is Git?</h3><p>Git is a distributed version control system that tracks changes to files over time.</p><p>It allows developers to:</p><ul><li>Track changes in source code.</li><li>Restore earlier versions when needed.</li><li>Create branches for new features or bug fixes.</li><li>Merge changes from different developers.</li><li>Collaborate through platforms such as GitHub, GitLab, and Bitbucket.</li></ul><h3>Why Is Git Important in DevOps?</h3><p>DevOps connects development and operations through automation and collaboration. Git provides a reliable place to manage the code and configuration files used throughout this process.</p><p>For example, a CI/CD pipeline can automatically start when a developer pushes new code to a repository.</p><h3>2. Git vs. GitHub</h3><p>These terms are related, but they are not the same.</p><p>GitGitHubA version control toolA platform for hosting Git repositoriesWorks locally on your computerEnables collaboration through the internetTracks changes and manages branchesProvides pull requests, reviews, issues, and repository hostingCan be used without GitHubUses Git to manage repository history</p><p>Other platforms, such as GitLab and Bitbucket, provide similar repository-hosting capabilities.</p><h3>3. How Git Works</h3><p>Git uses several important concepts.</p><ul><li><strong>Working directory:</strong> The files you are currently editing.</li><li><strong>Staging area:</strong> The changes you select for your next commit.</li><li><strong>Local repository:</strong> The version history stored on your computer.</li><li><strong>Remote repository:</strong> A shared repository hosted on a platform such as GitHub.</li></ul><p>The basic workflow looks like this:</p><p>Working Directory → Staging Area → Local Repository → Remote Repository</p><p>The commands associated with these steps are git add, git commit, and git push.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/0*0miUZBQbIEC11bB5" /></figure><h3>4. Install and Configure Git</h3><p>First, install Git from the official website: <a href="https://git-scm.com/">https://git-scm.com/</a></p><p>Verify the installation:</p><pre>git --version</pre><p>Configure your name and email address:</p><pre>git config --global user.name &quot;Shanthi Bojja&quot;<br>git config --global user.email &quot;your-email@example.com&quot;</pre><p>Check the configuration:</p><pre>git config --list</pre><p>Use the email address you want associated with your Git commits.</p><h3>5. Create Your First Git Repository</h3><p>Create a project directory:</p><pre>mkdir git-devops-demo<br>cd git-devops-demo</pre><p>Initialize Git:</p><pre>git init</pre><p>Git creates a local repository in the directory.</p><p>Create a sample file:</p><pre>echo &quot;# My DevOps Project&quot; &gt; README.md</pre><p>Check the current status:</p><pre>git status</pre><p>Git will show README.md as an untracked file because it has not yet been added to version control.</p><h3>6. Understand the Core Git Commands</h3><h3>Step 1: Stage your changes</h3><pre>git add README.md</pre><p>To stage all changes in the current directory:</p><pre>git add .</pre><p>Review what is staged:</p><pre>git status</pre><h3>Step 2: Commit your changes</h3><pre>git commit -m &quot;Add project README&quot;</pre><p>A commit records a snapshot of your staged changes in the local repository.</p><p>Write meaningful commit messages that explain what changed.</p><h3>Step 3: View commit history</h3><pre>git log</pre><p>For a compact history:</p><pre>git log --oneline</pre><h3>Step 4: Inspect changes</h3><pre>git diff</pre><p>This displays unstaged changes compared with the current commit.</p><p>To inspect staged changes:</p><pre>git diff --staged</pre><p>These commands are useful when reviewing your work before creating a commit.</p><h3>7. Understand Git Branches</h3><p>A branch allows you to develop a feature or fix a bug without making changes directly to the main development line.</p><p>For example, imagine your team is developing an application. You can create a separate branch to implement a new feature while other developers continue working independently.</p><p>Create and switch to a branch:</p><pre>git switch -c feature/login</pre><p>List branches:</p><pre>git branch</pre><p>Switch back to the main branch:</p><pre>git switch main</pre><p>The branch may be named master or something else in an existing repository, so check the repository before switching.</p><h3>Why Are Branches Useful in DevOps?</h3><p>Branches help teams:</p><ul><li>Develop features independently.</li><li>Fix production issues without mixing unrelated work.</li><li>Review code before merging.</li><li>Trigger different CI/CD workflows based on branch policies.</li></ul><h3>8. Merge Changes Between Branches</h3><p>Suppose you created a feature branch and committed your changes.</p><p>First, switch to the target branch:</p><pre>git switch main</pre><p>Then merge the feature branch:</p><pre>git merge feature/login</pre><p>Git combines the changes where possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CJJ3J-8aaxtDr_YR" /></figure><h3>What Is a Merge Conflict?</h3><p>A merge conflict occurs when Git cannot automatically reconcile competing changes, such as when two branches modify the same lines of a file.</p><p>To resolve a conflict:</p><ol><li>Run the merge and inspect the conflicting files.</li><li>Open each file and choose the correct content.</li><li>Remove the conflict markers.</li><li>Stage the resolved file.</li><li>Complete the merge commit if Git requires one.</li></ol><p>For example:</p><pre>git status<br>git add README.md<br>git commit</pre><p>The exact final step depends on the merge state. Always inspect git status before proceeding.</p><h3>9. Connect Git to GitHub</h3><p>Create an empty repository on GitHub, then connect your local project to it.</p><p>Add the remote URL:</p><pre>git remote add origin https://github.com/USERNAME/REPOSITORY.git</pre><p>Verify the remote:</p><pre>git remote -v</pre><p>Set the main branch name if necessary:</p><pre>git branch -M main</pre><p>Push your code:</p><pre>git push -u origin main</pre><p>Replace USERNAME and REPOSITORY with your actual GitHub details.</p><p>For future commits, you can generally use:</p><pre>git push</pre><p>You may need to authenticate with GitHub using an approved credential method, such as Git Credential Manager or SSH keys.</p><h3>10. Understand Git Pull, Fetch, and Push</h3><p>These commands are frequently used when working with a shared repository.</p><p><strong>git fetch</strong> downloads information about remote changes without integrating them into your current branch.</p><pre>git fetch origin</pre><p><strong>git pull</strong> fetches remote changes and integrates them into the current branch. The integration method depends on your Git configuration and options.</p><pre>git pull</pre><p><strong>git push</strong> sends your local commits to a remote repository.</p><pre>git push</pre><p>A common collaboration workflow is to fetch or pull the latest changes, make your changes, commit them, and push your branch.</p><h3>11. Undo Changes Safely</h3><p>Sometimes you need to discard an edit, unstage a file, or undo a commit. The correct command depends on what you want to preserve.</p><h3>Discard unstaged changes in a file</h3><pre>git restore README.md</pre><p><strong>Warning:</strong> This discards unstaged changes in that file.</p><h3>Unstage a file</h3><pre>git restore --staged README.md</pre><p>This removes the file from the staging area while preserving its working-directory changes.</p><h3>Undo a commit with a new commit</h3><pre>git revert COMMIT_ID</pre><p>Replace COMMIT_ID with the commit hash you want to reverse. This creates a new commit that undoes the selected commit&#39;s changes.</p><p>Be careful with git reset --hard: it can permanently discard uncommitted work. Avoid using destructive commands unless you understand exactly what will be removed.</p><h3>12. What Is a Pull Request?</h3><p>A pull request is a way to propose changes from one branch to another for review. GitHub uses pull requests, while GitLab and Bitbucket offer similar collaboration workflows.</p><p>A typical workflow looks like this:</p><ol><li>Create a feature branch.</li><li>Implement the change.</li><li>Commit and push the branch.</li><li>Open a pull request.</li><li>Review the code and resolve feedback.</li><li>Run automated checks.</li><li>Merge the approved changes.</li></ol><p>Pull requests help teams review code quality, identify defects, and maintain consistent standards before changes are integrated.</p><h3>13. How Git Fits into a CI/CD Pipeline</h3><p>Git is often the starting point of a CI/CD pipeline.</p><p>A simplified workflow is:</p><p><strong>Developer → Git Repository → CI Pipeline → Tests and Quality Checks → Build Artifact or Container Image → Deployment</strong></p><p>For example, a developer pushes a code change to GitHub. A configured pipeline can then run unit tests, perform quality checks, build a Docker image, and deploy the application to an approved environment.</p><p>In a DevSecOps pipeline, additional stages may include dependency checks, secret detection, container image scanning, and security gates.</p><p>Git itself does not perform all these tasks. It stores and tracks the code, while tools such as Jenkins and other CI/CD platforms automate the pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y-M4xRiC9hZfj2jb" /></figure><h3>14. Practical Exercise: Build a Small Git Workflow</h3><p>Let’s practise the main commands.</p><p><strong>Create a repository:</strong></p><pre>mkdir devops-practice<br>cd devops-practice<br>git init</pre><p><strong>Create a file and commit it:</strong></p><pre>echo &quot;Learning Git for DevOps&quot; &gt; notes.txt<br>git add notes.txt<br>git commit -m &quot;Add DevOps learning notes&quot;</pre><p><strong>Create a feature branch:</strong></p><pre>git switch -c feature/update-notes</pre><p>Add another line:</p><pre>echo &quot;Practicing branches and commits&quot; &gt;&gt; notes.txt<br>git add notes.txt<br>git commit -m &quot;Update learning notes&quot;</pre><p><strong>Merge the feature branch:</strong></p><pre>git switch main<br>git merge feature/update-notes</pre><p><strong>Verify your history:</strong></p><pre>git log --oneline --graph --all</pre><p>If your initial branch is not named main, use the actual branch name shown by git branch.</p><p>By completing this exercise, you’ll have practised repository initialization, staging, commits, branches, merging, and history inspection.</p><h3>15. Git Commands Cheat Sheet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*thrKDxKjqZJAoD3q-X7m8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*t8EuBqkDKCF93wmAdtVRIA.png" /></figure><h3>Conclusion</h3><p>Git is more than a tool for storing code. It is a foundation for collaboration, controlled releases, and automated DevOps workflows.</p><p>Start by practising the core commands, then become comfortable with branching, merging, remote repositories, and pull requests. Once these concepts are clear, understanding Git-based CI/CD pipelines becomes much easier.</p><p><strong>Keep learning, keep building, and keep improving.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ba2bbeea6fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Fundamentals for DevOps Engineers: A Beginner’s Guide to Container Orchestration]]></title>
            <link>https://medium.com/@shanbojja/kubernetes-fundamentals-for-devops-engineers-a-beginners-guide-to-container-orchestration-2376fa56ea1d?source=rss-c047ef51b3ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/2376fa56ea1d</guid>
            <category><![CDATA[container-orchestration]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Shanthi bojja]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 15:19:56 GMT</pubDate>
            <atom:updated>2026-10-14T15:19:56.974Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*es3wuK2YyXz5Slc624z67Q.png" /></figure><p>In the previous article, we explored Docker and learned how to package applications into containers.</p><p>But what happens when an application runs across multiple containers? How do you restart failed containers, scale applications when traffic increases, and manage deployments without doing everything manually?</p><p>This is where <strong>Kubernetes</strong> comes in.</p><p>Kubernetes helps automate the deployment, scaling, and management of containerized applications. It is widely used in modern DevOps workflows to run applications reliably across clusters of machines.</p><p>In this article, we’ll explore Kubernetes fundamentals, understand its architecture, and learn the essential commands and YAML configurations every beginner should know.</p><h3>1. What Is Kubernetes?</h3><p>Kubernetes, often called <strong>K8s</strong>, is an open-source container orchestration platform.</p><p>Container orchestration means managing containers across infrastructure, including scheduling, scaling, networking, and recovery from certain failures.</p><p>Kubernetes helps DevOps engineers:</p><ul><li>Deploy containerized applications.</li><li>Scale application replicas up or down.</li><li>Restart containers when supported health checks detect problems.</li><li>Distribute workloads across cluster nodes.</li><li>Manage application configuration and secrets.</li><li>Perform controlled application rollouts and rollbacks.</li><li>Expose applications through Kubernetes networking resources.</li></ul><p><strong>Real-world example:</strong> Suppose an application normally runs three container replicas. If traffic increases, you can scale the application to more replicas. Kubernetes schedules those replicas on available cluster resources, subject to its configuration and capacity.</p><p>Kubernetes automates many operational tasks, but it still requires proper configuration, monitoring, security, and capacity planning.</p><h3>2. Why Do We Need Kubernetes?</h3><p>Docker makes it easier to package and run applications. However, running many containers across multiple servers introduces additional challenges.</p><p>Imagine managing an application that has:</p><ul><li>Multiple API containers.</li><li>Several background workers.</li><li>A database connection.</li><li>A load-balancing requirement.</li><li>Different development and production environments.</li></ul><p>Manually managing every container becomes difficult as the system grows.</p><p>Kubernetes helps by providing a consistent platform for deploying and managing these workloads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*O8bOkdSWy90XO2pRGgW16w.png" /></figure><p>Kubernetes does not eliminate every operational task. It provides mechanisms that help teams automate and standardize them.</p><h3>3. Understanding Kubernetes Architecture</h3><p>A Kubernetes cluster consists of a <strong>control plane</strong> and one or more <strong>worker nodes</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HkfmDWipZAFM-zAr" /></figure><p>&lt;box border radius=”lg” padding={3} gap={3} align=”center”&gt;<br> &lt;box background=”#17365D” theme=”dark” radius=”md” padding={3} width=”100%” align=”center”&gt;<br> **Control Plane**<br> &lt;text size=”sm”&gt;API Server · Scheduler · Controllers · Cluster State Store&lt;/text&gt;<br> &lt;/box&gt;<br> &lt;icon name=”arrow-down-up” color=”#0EA5E9&quot; size=”xl” /&gt;<br> &lt;box border radius=”md” padding={3} width=”100%” gap={2} align=”center”&gt;<br> **Worker Nodes**<br> &lt;grid columns={2} gap={2}&gt;<br> &lt;grid-item&gt;<br> &lt;box background=”surface-secondary” radius=”md” padding={2} align=”center” gap={1}&gt;<br> &lt;icon name=”container” size=”xl” /&gt;<br> **Node 1**<br> &lt;text size=”sm”&gt;Kubelet · Runtime&lt;/text&gt;<br> &lt;text size=”xs” color=”secondary”&gt;Application Pods&lt;/text&gt;<br> &lt;/box&gt;<br> &lt;/grid-item&gt;<br> &lt;grid-item&gt;<br> &lt;box background=”surface-secondary” radius=”md” padding={2} align=”center” gap={1}&gt;<br> &lt;icon name=”container” size=”xl” /&gt;<br> **Node 2**<br> &lt;text size=”sm”&gt;Kubelet · Runtime&lt;/text&gt;<br> &lt;text size=”xs” color=”secondary”&gt;Application Pods&lt;/text&gt;<br> &lt;/box&gt;<br> &lt;/grid-item&gt;<br> &lt;/grid&gt;<br> &lt;/box&gt;<br>&lt;/box&gt;</p><h3>Control plane components</h3><p><strong>API Server</strong></p><p>The API server is the main entry point for Kubernetes operations. Tools such as kubectl communicate with the cluster through the API server.</p><p><strong>Scheduler</strong></p><p>The scheduler selects suitable worker nodes for newly created Pods, based on resource requirements and scheduling constraints.</p><p><strong>Controller Manager</strong></p><p>Controllers continuously compare the current state with the desired state and take action to reconcile differences.</p><p><strong>etcd</strong></p><p>etcd is the distributed key-value store Kubernetes uses to store its cluster data.</p><h3>Worker node components</h3><p><strong>Kubelet</strong></p><p>The kubelet runs on a node and helps ensure that the Pods assigned to that node are running as specified.</p><p><strong>Container runtime</strong></p><p>The container runtime runs containers. Kubernetes commonly uses runtimes that implement the Container Runtime Interface, such as containerd.</p><p><strong>Network components</strong></p><p>Kubernetes networking components provide connectivity between Pods and Services. The exact implementation depends on the cluster setup.</p><p>Understanding these components helps explain how Kubernetes turns configuration into running workloads.</p><h3>4. What Is a Pod?</h3><p>A <strong>Pod</strong> is the smallest deployable unit in Kubernetes.</p><p>A Pod contains one or more containers that share certain resources, including network identity and, when configured, shared storage volumes.</p><p>In many common applications, a Pod contains one main application container. Some Pods include additional containers that support the main application.</p><p>For example, a web application might run in a Pod containing its application container.</p><p>Kubernetes manages Pods through higher-level resources such as Deployments. Pods are generally replaceable, so applications should not depend on an individual Pod remaining permanently available.</p><h3>5. What Is a Deployment?</h3><p>A Deployment manages a set of replicated Pods for an application and supports controlled updates.</p><p>For example, if you want three replicas of a web application, you can declare that desired state in a Deployment.</p><p>Create a file named deployment.yaml:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx-deployment<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: nginx<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx<br>    spec:<br>      containers:<br>        - name: nginx<br>          image: nginx:1.28<br>          ports:<br>            - containerPort: 80</pre><p>This example uses a specific Nginx image tag; select a currently supported image version appropriate for your environment.</p><p>Let’s understand the configuration:</p><ul><li>apiVersion: The Kubernetes API version for this resource.</li><li>kind: Specifies the resource type.</li><li>metadata: Contains the resource name and related information.</li><li>replicas: Defines the desired number of Pods.</li><li>selector: Identifies the Pods managed by the Deployment.</li><li>template: Defines how those Pods should be created.</li><li>image: Specifies the container image.</li><li>containerPort: Documents the port used by the container.</li></ul><p>Apply the configuration:</p><pre>kubectl apply -f deployment.yaml</pre><p>Check the Deployment:</p><pre>kubectl get deployments</pre><p>Check the Pods:</p><pre>kubectl get pods</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/0*qFAG-l0eJ8YheNBI" /></figure><p>If the cluster has sufficient capacity and the image can be pulled, Kubernetes attempts to create and maintain the three replicas.</p><h3>6. Essential kubectl Commands</h3><p>kubectl is the command-line tool used to interact with Kubernetes clusters.</p><p>Here are some commands you’ll use frequently.</p><h3>View cluster nodes</h3><pre>kubectl get nodes</pre><h3>List Pods</h3><pre>kubectl get pods</pre><h3>List Deployments</h3><pre>kubectl get deployments</pre><h3>View Services</h3><pre>kubectl get services</pre><h3>Get detailed resource information</h3><pre>kubectl describe pod &lt;pod-name&gt;</pre><h3>View application logs</h3><pre>kubectl logs &lt;pod-name&gt;</pre><h3>Execute a command inside a container</h3><pre>kubectl exec -it &lt;pod-name&gt; -- sh</pre><p>The last command opens a shell if the container image includes one and the necessary access is available.</p><p>These commands are useful for deployment verification and troubleshooting.</p><h3>7. Scaling Applications in Kubernetes</h3><p>Suppose your application initially runs two replicas. If demand increases, you can increase the number of replicas.</p><p>Run:</p><pre>kubectl scale deployment nginx-deployment --replicas=5</pre><p>Verify the change:</p><pre>kubectl get deployment nginx-deployment<br>kubectl get pods</pre><p>Kubernetes attempts to maintain five replicas according to the Deployment’s desired state.</p><p>You can scale down in the same way:</p><pre>kubectl scale deployment nginx-deployment --replicas=2</pre><p>Manual scaling is useful for learning. In production, teams may use autoscaling based on metrics and defined resource requirements.</p><h3>8. What Is a Kubernetes Service?</h3><p>Pods are replaceable, and their IP addresses can change when they are recreated. Applications therefore need a stable way to communicate with a group of Pods.</p><p>A <strong>Service</strong> provides a stable network endpoint for a selected set of Pods.</p><p>Common Service types include:</p><ul><li><strong>ClusterIP:</strong> Exposes a Service inside the cluster.</li><li><strong>NodePort:</strong> Exposes a port on cluster nodes.</li><li><strong>LoadBalancer:</strong> Requests an external load balancer when supported by the cluster environment.</li></ul><p>For the Nginx Deployment, create service.yaml:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: nginx-service<br>spec:<br>  type: ClusterIP<br>  selector:<br>    app: nginx<br>  ports:<br>    - port: 80<br>      targetPort: 80</pre><p>Apply it:</p><pre>kubectl apply -f service.yaml</pre><p>Check the Service:</p><pre>kubectl get services</pre><p>The Service selector matches the app: nginx label on the Pods created by the Deployment.</p><p>Because this Service uses ClusterIP, it is accessible from within the cluster by default. It does not automatically expose the application publicly.</p><p>For a local learning environment, you can test it using port forwarding:</p><pre>kubectl port-forward service/nginx-service 8080:80</pre><p>Then open http://localhost:8080 while the port-forward command is running.</p><h3>9. Understanding Namespaces</h3><p>Namespaces help organize resources within a Kubernetes cluster.</p><p>For example, teams may separate workloads into namespaces for development, testing, and production.</p><p>List namespaces:</p><pre>kubectl get namespaces</pre><p>Create a namespace:</p><pre>kubectl create namespace development</pre><p>Deploy a resource into that namespace:</p><pre>kubectl apply -f deployment.yaml -n development</pre><p>View Pods in the namespace:</p><pre>kubectl get pods -n development</pre><p>Namespaces are useful for organizing resources and applying policies, but they are not a complete security boundary by themselves. Access controls, network policies, and other safeguards may also be needed.</p><h3>10. ConfigMaps and Secrets</h3><p>Applications often need configuration values that should be managed separately from their container images.</p><p>Kubernetes provides ConfigMaps and Secrets for different types of configuration.</p><h3>ConfigMap</h3><p>A ConfigMap stores non-confidential configuration data.</p><p>Create one from a literal value:</p><pre>kubectl create configmap app-config \<br>  --from-literal=APP_ENV=development</pre><p>List ConfigMaps:</p><pre>kubectl get configmaps</pre><p>A Pod can consume ConfigMap values through environment variables or mounted files.</p><h3>Secret</h3><p>A Kubernetes Secret is designed for sensitive configuration data, such as credentials and tokens.</p><p>However, <strong>creating a Secret does not automatically make its contents secure</strong>. Apply appropriate access controls, encryption at rest, and secret-management practices for your environment. Avoid committing real credentials to Git or including them in public tutorials.</p><h3>11. Rolling Updates and Rollbacks</h3><p>Applications need updates to fix bugs, introduce features, and address security issues.</p><p>Kubernetes Deployments support rolling updates, replacing old Pods with new ones according to the Deployment’s rollout strategy.</p><p>For example, update the image:</p><pre>kubectl set image deployment/nginx-deployment \<br>  nginx=nginx:1.29</pre><p>Check the rollout:</p><pre>kubectl rollout status deployment/nginx-deployment</pre><p>View the rollout history:</p><pre>kubectl rollout history deployment/nginx-deployment</pre><p>If the update causes problems, you can roll back to the previous Deployment revision when a suitable revision is available:</p><pre>kubectl rollout undo deployment/nginx-deployment</pre><p>Always use a supported image version and validate changes in a non-production environment before updating production workloads.</p><h3>12. Health Checks: Liveness and Readiness Probes</h3><p>Kubernetes supports probes that help determine whether an application is healthy and ready to receive traffic.</p><p><strong>Liveness probe:</strong> Helps determine whether a container should be restarted.</p><p><strong>Readiness probe:</strong> Determines whether a container is ready to receive traffic through applicable Services.</p><p><strong>Startup probe:</strong> Gives slow-starting applications time to initialize before liveness or readiness checks take effect.</p><p>Example configuration:</p><pre>containers:<br>  - name: web<br>    image: nginx:1.28<br>    ports:<br>      - containerPort: 80<br>    readinessProbe:<br>      httpGet:<br>        path: /<br>        port: 80<br>      initialDelaySeconds: 5<br>      periodSeconds: 10<br>    livenessProbe:<br>      httpGet:<br>        path: /<br>        port: 80<br>      initialDelaySeconds: 10<br>      periodSeconds: 20</pre><p>These probe definitions can be added to a container specification. Tune the paths, ports, delays, and thresholds to match the actual application’s behavior.</p><p>A poorly configured liveness probe can cause unnecessary restarts, so health checks should reflect meaningful application health rather than merely confirming that a process exists.</p><h3>13. Kubernetes in a DevOps CI/CD Pipeline</h3><p>Kubernetes often forms part of a deployment workflow alongside Git, CI/CD tools, and a container registry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wBEij9wfaubjkRtJ" /></figure><p>A typical workflow is:</p><p>&lt;box border radius=”lg” padding={3} gap={2} align=”center”&gt;<br> {#each [{n:”1&quot;,t:”Code stored in Git”,d:”Developers commit application changes”},{n:”2&quot;,t:”Build and test”,d:”CI validates the application”},{n:”3&quot;,t:”Build and scan image”,d:”Package the application and check security”},{n:”4&quot;,t:”Publish image”,d:”Push the image to a container registry”},{n:”5&quot;,t:”Deploy to Kubernetes”,d:”Apply manifests or a deployment package”},{n:”6&quot;,t:”Monitor the rollout”,d:”Check readiness, logs, and application health”}] as step}<br> &lt;row key={step.n} align=”center” gap={3} width=”100%”&gt;<br> &lt;box background=”#17365D” theme=”dark” radius=”full” size=”34px” align=”center” justify=”center”&gt;<br> &lt;title size=”md” color=”#FFFFFF”&gt;{step.n}&lt;/title&gt;<br> &lt;/box&gt;<br> &lt;box flex=”1&quot; gap={1}&gt;<br> **{step.t}**<br> &lt;text size=”sm” color=”secondary”&gt;{step.d}&lt;/text&gt;<br> &lt;/box&gt;<br> &lt;/row&gt;<br> {#if step.n !== “6”}<br> &lt;box width=”34px” align=”center”&gt;<br> &lt;icon name=”arrow-down” color=”#0EA5E9&quot; /&gt;<br> &lt;/box&gt;<br> {/if}<br> {/each}<br>&lt;/box&gt;</p><p>This workflow connects application development, containerization, deployment, and operational monitoring.</p><p>The precise process varies by team. Some organizations use Helm, GitOps tools, or managed Kubernetes services to standardize deployment workflows.</p><h3>14. Common Kubernetes Troubleshooting Commands</h3><p>When an application does not start or respond as expected, begin by checking its state and events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*kk-zrGsX1oRXAzZfGjcfjQ.png" /></figure><p>Common problems include:</p><ul><li><strong>ImagePullBackOff:</strong> Kubernetes cannot successfully pull the specified image.</li><li><strong>CrashLoopBackOff:</strong> A container repeatedly exits and Kubernetes backs off before restarting it.</li><li><strong>Pending:</strong> A Pod has not been scheduled or cannot proceed, possibly due to resource constraints or storage requirements.</li><li><strong>Service connectivity issues:</strong> The Service selector, target port, application listener, or network policy may be incorrect.</li></ul><p>The status alone does not reveal the complete cause. Use describe, logs, and events to investigate before changing the configuration.</p><h3>15. Kubernetes Best Practices</h3><p>As you learn Kubernetes, develop habits that support secure and reliable workloads.</p><ol><li><strong>Define resource requests and limits.</strong> Set suitable CPU and memory requirements for workloads.</li><li><strong>Use health probes carefully.</strong> Configure readiness, liveness, and startup checks according to application behavior.</li><li><strong>Avoid unnecessary root access.</strong> Use appropriate security contexts and least-privilege permissions.</li><li><strong>Protect secrets.</strong> Apply access controls and suitable encryption and secret-management practices.</li><li><strong>Use meaningful image tags.</strong> Prefer controlled, traceable releases over relying only on mutable tags.</li><li><strong>Monitor applications.</strong> Collect logs, metrics, events, and relevant alerts.</li><li><strong>Use namespaces thoughtfully.</strong> Organize workloads and combine namespaces with appropriate access and network policies.</li><li><strong>Validate deployments.</strong> Check rollout status and application health after each release.</li><li><strong>Test changes first.</strong> Validate manifests and deployment changes in a development environment.</li><li><strong>Keep dependencies maintained.</strong> Use supported Kubernetes versions and maintain the cluster components and application images.</li></ol><h3>Conclusion</h3><p>Kubernetes helps teams deploy, scale, and manage containerized applications. Understanding clusters, Pods, Deployments, Services, namespaces, configuration, health probes, and rollouts gives you a strong foundation for container orchestration.</p><p>Start by deploying a simple Nginx application, exposing it through a Service, scaling its replicas, and practising a rollout. Then explore health checks and troubleshooting.</p><p><strong>The key idea is simple: describe the desired state, and Kubernetes works to maintain it.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2376fa56ea1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Fundamentals for DevOps Engineers: A Beginner’s Guide to Containers]]></title>
            <link>https://medium.com/@shanbojja/docker-fundamentals-for-devops-engineers-a-beginners-guide-to-containers-7c89d4e488f5?source=rss-c047ef51b3ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c89d4e488f5</guid>
            <category><![CDATA[container-orchestration]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Shanthi bojja]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 04:51:38 GMT</pubDate>
            <atom:updated>2026-10-13T04:51:38.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wxceb09zMmyWAinQLLJhvg.png" /></figure><p>Have you ever heard a developer say, “It works on my machine,” only to discover that the application fails in another environment?</p><p>Differences in operating systems, software versions, dependencies, and configuration can make application deployment challenging.</p><p>Docker helps solve this problem by packaging an application and its dependencies into a portable unit called a <strong>container</strong>.</p><p>In this article, we’ll explore Docker fundamentals, learn essential commands, build a simple Docker image, and understand how containers fit into a DevOps workflow.</p><h3>1. What Is Docker?</h3><p>Docker is a platform used to build, package, distribute, and run applications in containers.</p><p>A container includes an application and the dependencies it needs to run. This helps the application behave more consistently across development, testing, and deployment environments.</p><p>Docker is widely used for:</p><ul><li>Application packaging</li><li>Development environment setup</li><li>Microservices deployment</li><li>CI/CD pipelines</li><li>Testing applications in isolated environments</li><li>Running applications consistently across supported environments</li></ul><p><strong>Real-world example:</strong> Instead of asking every developer to install the same Python version and dependencies manually, a team can define the environment in a Dockerfile and build an image from it.</p><h3>2. What Is Containerization?</h3><p>Containerization is the process of packaging an application and its required components into a container image.</p><p>Without containerization, an application may depend on software installed directly on a server. Different servers may have different versions of libraries or runtime environments.</p><p>With Docker, teams can define the application environment and reuse the same image across multiple stages of the software delivery process.</p><p>This improves consistency, simplifies deployment, and reduces environment-related issues.</p><h3>3. Containers vs. Virtual Machines</h3><p>Containers and virtual machines both help isolate workloads, but they work differently.</p><p>&lt;box border radius=”lg” padding={3} gap={3}&gt;<br> &lt;grid columns={2} gap={3}&gt;<br> &lt;grid-item&gt;<br> &lt;AsyncImage query=”Docker containers architecture application libraries container runtime shared host operating system simple technical diagram” aspectRatio=”4:3&quot; width=”100%” /&gt;<br> **Containers**<br> &lt;text size=”sm” color=”secondary”&gt;Share the host operating system kernel and isolate applications and their environments.&lt;/text&gt;<br> &lt;/grid-item&gt;<br> &lt;grid-item&gt;<br> &lt;AsyncImage query=”Virtual machine architecture applications guest operating systems hypervisor hardware technical diagram” aspectRatio=”4:3&quot; width=”100%” /&gt;<br> **Virtual Machines**<br> &lt;text size=”sm” color=”secondary”&gt;Run separate guest operating systems on a virtualized hardware layer.&lt;/text&gt;<br> &lt;/grid-item&gt;<br> &lt;/grid&gt;<br>&lt;/box&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*BpSNvEEccxIKZz1vZFzihQ.png" /></figure><p>Neither approach is universally better. The right choice depends on isolation, security, compatibility, performance, and operational requirements.</p><h3>4. Understanding Docker Architecture</h3><p>Docker uses several components to build and run containers.</p><ul><li><strong>Docker client:</strong> The command-line interface used to issue Docker commands.</li><li><strong>Docker daemon:</strong> The background service that manages images, containers, networks, and volumes.</li><li><strong>Docker image:</strong> A template used to create containers.</li><li><strong>Docker container:</strong> A running or stopped instance created from an image.</li><li><strong>Docker registry:</strong> A service used to store and distribute images, such as Docker Hub.</li></ul><p>A typical workflow looks like this:</p><p>&lt;box border radius=”lg” padding={3} align=”center” gap={2}&gt;<br> &lt;box background=”#17365D” theme=”dark” radius=”md” padding={3} width=”85%” align=”center”&gt;<br> **Docker Client**<br> &lt;text size=”sm”&gt;docker build · docker run · docker push&lt;/text&gt;<br> &lt;/box&gt;<br> &lt;icon name=”arrow-down-up” color=”#0EA5E9&quot; size=”xl” /&gt;<br> &lt;box background=”surface-secondary” radius=”md” padding={3} width=”85%” align=”center”&gt;<br> **Docker Daemon**<br> &lt;text size=”sm”&gt;Builds images and manages containers&lt;/text&gt;<br> &lt;/box&gt;<br> &lt;row gap={2} width=”100%”&gt;<br> &lt;box border radius=”md” padding={2} flex=”1&quot; align=”center”&gt;<br> &lt;icon name=”package” size=”xl” /&gt;<br> **Image**<br> &lt;/box&gt;<br> &lt;box border radius=”md” padding={2} flex=”1&quot; align=”center”&gt;<br> &lt;icon name=”container” size=”xl” /&gt;<br> **Container**<br> &lt;/box&gt;<br> &lt;/row&gt;<br> &lt;icon name=”arrow-up-down” color=”#0EA5E9&quot; size=”xl” /&gt;<br> &lt;box background=”surface” border radius=”md” padding={3} width=”85%” align=”center”&gt;<br> **Container Registry**<br> &lt;text size=”sm”&gt;Push and pull images&lt;/text&gt;<br> &lt;/box&gt;<br>&lt;/box&gt;</p><p>The exact architecture can vary depending on whether Docker is running locally, through a remote daemon, or in a managed environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5cOZ5bRREgi-tNDJ" /></figure><h3>5. Installing Docker</h3><p>Install Docker using the official instructions for your operating system:</p><p><a href="https://docs.docker.com/engine/install/">Docker Installation Guide</a></p><p>On Windows and macOS, Docker Desktop is a common option. On Linux, Docker Engine can be installed using the appropriate distribution-specific instructions.</p><p>Verify the installation:</p><pre>docker --version<br>docker info</pre><p>The first command displays the Docker CLI version. The second displays information about the Docker environment and generally requires access to a running daemon.</p><p>You can also check whether the installation can run a container:</p><pre>docker run hello-world</pre><p>Docker downloads the image if needed, runs it, and displays a confirmation message if the test succeeds.</p><h3>6. Essential Docker Commands</h3><p>Learning Docker commands is an important first step.</p><h3>Check downloaded images</h3><pre>docker images</pre><p>This lists images stored locally.</p><h3>Check running containers</h3><pre>docker ps</pre><h3>Check all containers</h3><pre>docker ps -a</pre><h3>Download an image</h3><pre>docker pull nginx</pre><p>This downloads the Nginx image from the default registry.</p><h3>Run a container</h3><pre>docker run -d --name my-nginx -p 8080:80 nginx</pre><p>Let’s understand the options:</p><ul><li>-d: Runs the container in the background.</li><li>--name my-nginx: Assigns a name to the container.</li><li>-p 8080:80: Maps host port 8080 to container port 80.</li><li>nginx: Specifies the image.</li></ul><p>If the container starts successfully and the port is accessible, open http://localhost:8080 in your browser to see the Nginx welcome page.</p><h3>Stop a container</h3><pre>docker stop my-nginx</pre><h3>Start a stopped container</h3><pre>docker start my-nginx</pre><h3>Remove a container</h3><pre>docker rm my-nginx</pre><p>A running container must normally be stopped before it can be removed. The docker rm -f my-nginx command forcibly stops and removes it, so use it carefully.</p><h3>View container logs</h3><pre>docker logs my-nginx</pre><p>For continuous log output:</p><pre>docker logs -f my-nginx</pre><p>These commands are especially useful when troubleshooting applications.</p><h3>7. What Is a Dockerfile?</h3><p>A Dockerfile is a text file containing instructions for building a Docker image.</p><p>It defines the base image, application files, dependencies, working directory, and startup command.</p><p>Let’s build a simple Python application.</p><p>Create a file named app.py:</p><pre>from http.server import BaseHTTPRequestHandler, HTTPServer<br></pre><pre>class RequestHandler(BaseHTTPRequestHandler):<br>    def do_GET(self):<br>        self.send_response(200)<br>        self.send_header(&quot;Content-type&quot;, &quot;text/plain&quot;)<br>        self.end_headers()<br>        self.wfile.write(b&quot;Hello from Docker!&quot;)<br></pre><pre>server = HTTPServer((&quot;0.0.0.0&quot;, 8000), RequestHandler)<br>print(&quot;Server running on port 8000&quot;)<br>server.serve_forever()</pre><p>This example uses Python’s built-in HTTP server for learning purposes.</p><p>Now create a file named Dockerfile in the same directory:</p><pre>FROM python:3.12-slim</pre><pre>WORKDIR /app</pre><pre>COPY app.py .</pre><pre>EXPOSE 8000</pre><pre>CMD [&quot;python&quot;, &quot;app.py&quot;]</pre><p>Let’s understand the instructions:</p><ul><li>FROM: Defines the base image.</li><li>WORKDIR: Sets the working directory inside the image.</li><li>COPY: Copies the application file into the image.</li><li>EXPOSE: Documents the port the application listens on.</li><li>CMD: Defines the default command used to start the application.</li></ul><p>EXPOSE does not publish the port automatically. Port publishing is configured when you run the container.</p><p>For a production application, select supported and maintained base-image versions, pin dependencies where appropriate, and consider running the application as a non-root user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/0*yy2Z1hjNr3a49cn1" /></figure><h3>8. Build and Run Your First Docker Image</h3><p>Make sure your directory contains these files:</p><pre>docker-demo/<br>├── app.py<br>└── Dockerfile</pre><p>Open a terminal in that directory.</p><h3>Step 1: Build the image</h3><pre>docker build -t python-docker-demo .</pre><p>Here, -t assigns a name to the image, and . tells Docker to use the current directory as the build context.</p><h3>Step 2: Verify the image</h3><pre>docker images</pre><p>You should see python-docker-demo in the image list.</p><h3>Step 3: Run the container</h3><pre>docker run -d --name python-demo -p 8000:8000 python-docker-demo</pre><h3>Step 4: Test the application</h3><p>Open the following URL in your browser:</p><pre>http://localhost:8000</pre><p>Expected response:</p><pre>Hello from Docker!</pre><h3>Step 5: View the logs</h3><pre>docker logs python-demo</pre><h3>Step 6: Clean up</h3><p>When you finish testing:</p><pre>docker stop python-demo<br>docker rm python-demo</pre><p>You can remove the image as well if you no longer need it:</p><pre>docker rmi python-docker-demo</pre><p>This exercise demonstrates the core Docker workflow: write application code, build an image, run a container, test it, and clean up.</p><h3>9. Docker Images vs. Containers</h3><p>These two terms are often confused by beginners.</p><p><strong>A Docker image is a template. A container is an instance created from that template.</strong></p><p>For example, you can download one Nginx image and create several containers from it.</p><p>Each container has its own runtime configuration and writable container layer, while the underlying image layers can be shared.</p><p>Think of an image as a recipe and a container as a running instance created from that recipe.</p><h3>10. Docker Volumes: Persisting Data</h3><p>Containers are often designed to be replaceable. Data stored only in a container’s writable layer may be lost when the container is removed.</p><p>Docker volumes help preserve data outside the lifecycle of an individual container.</p><p>Create a volume:</p><pre>docker volume create app-data</pre><p>Inspect the volume:</p><pre>docker volume inspect app-data</pre><p>Run a container with the volume mounted:</p><pre>docker run -d \<br>  --name nginx-volume-demo \<br>  -p 8081:80 \<br>  -v app-data:/usr/share/nginx/html \<br>  nginx</pre><p>In this example, the named volume is mounted at the Nginx document root. The mount may obscure files that were originally present at that location in the image, so this is best treated as a volume-mount demonstration rather than a complete production web deployment.</p><p>Volumes are useful for data that needs to outlive a container. They should still be backed up and managed according to the application’s data requirements.</p><h3>11. Docker Networking Basics</h3><p>Containers sometimes need to communicate with other containers or external services.</p><p>Docker supports several network types, including:</p><ul><li><strong>Bridge:</strong> A common default for standalone containers.</li><li><strong>Host:</strong> Uses the host network namespace on supported systems.</li><li><strong>None:</strong> Disables normal network connectivity for the container.</li><li><strong>Overlay:</strong> Supports communication across multiple Docker hosts in suitable configurations.</li></ul><p>For example, create a custom bridge network:</p><pre>docker network create devops-network</pre><p>Run a container on that network:</p><pre>docker run -d \<br>  --name web-server \<br>  --network devops-network \<br>  nginx</pre><p>Inspect the network:</p><pre>docker network inspect devops-network</pre><p>Custom bridge networks can provide name-based communication between attached containers. Network configuration should be designed carefully when exposing applications, connecting databases, or separating workloads.</p><h3>12. Docker Compose: Managing Multiple Services</h3><p>Real applications often need multiple components, such as a web service, API, and database.</p><p>Docker Compose allows you to define and manage multi-container applications using a YAML file.</p><p>For example, create a compose.yaml file:</p><pre>services:<br>  web:<br>    image: nginx:alpine<br>    ports:<br>      - &quot;8080:80&quot;</pre><p>Start the service:</p><pre>docker compose up -d</pre><p>View the running services:</p><pre>docker compose ps</pre><p>Stop and remove the Compose-managed containers and network:</p><pre>docker compose down</pre><p>This example runs a single web service. As applications grow, Compose can define multiple services, networks, environment settings, and volumes in one file.</p><p>Be careful not to put production credentials directly into a Compose file committed to source control.</p><h3>13. Docker in a DevOps CI/CD Pipeline</h3><p>Docker is frequently used in CI/CD workflows to package applications consistently.</p><p>A simplified workflow looks like this:</p><p>&lt;box border radius=”lg” padding={3} gap={2} align=”center”&gt;<br> {#each [{n:”1&quot;,t:”Developer commits code”,d:”Source code is stored in Git”},{n:”2&quot;,t:”CI pipeline runs tests”,d:”Validate the application”},{n:”3&quot;,t:”Build Docker image”,d:”Package application and dependencies”},{n:”4&quot;,t:”Scan and publish image”,d:”Check vulnerabilities and push to a registry”},{n:”5&quot;,t:”Deploy application”,d:”Run the image in a target environment”}] as step}<br> &lt;row key={step.n} align=”center” gap={3} width=”100%”&gt;<br> &lt;box background=”#17365D” theme=”dark” radius=”full” size=”34px” align=”center” justify=”center”&gt;<br> &lt;title size=”md” color=”#FFFFFF”&gt;{step.n}&lt;/title&gt;<br> &lt;/box&gt;<br> &lt;box flex=”1&quot; gap={1}&gt;<br> **{step.t}**<br> &lt;text size=”sm” color=”secondary”&gt;{step.d}&lt;/text&gt;<br> &lt;/box&gt;<br> &lt;/row&gt;<br> {#if step.n !== “5”}<br> &lt;box width=”34px” align=”center”&gt;<br> &lt;icon name=”arrow-down” color=”#0EA5E9&quot; /&gt;<br> &lt;/box&gt;<br> {/if}<br> {/each}<br>&lt;/box&gt;</p><p>A container registry stores images so deployment systems can retrieve them. Examples include Docker Hub and cloud-provider container registries.</p><p>A production pipeline should also consider image provenance, vulnerability scanning, access control, secrets, and deployment rollback strategies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*4B_1zfIu93K8aZ_T" /></figure><h3>14. Docker Best Practices</h3><p>As you start working with Docker, build good habits early.</p><ol><li><strong>Use trusted base images.</strong> Choose maintained images from reliable sources.</li><li><strong>Keep images small.</strong> Include only what the application needs.</li><li><strong>Avoid secrets in images.</strong> Do not bake passwords or tokens into Dockerfiles or image layers.</li><li><strong>Use </strong><strong>.dockerignore.</strong> Exclude unnecessary files from the build context.</li><li><strong>Run as a non-root user where possible.</strong> Reduce the impact of compromised applications.</li><li><strong>Scan images for vulnerabilities.</strong> Address relevant security findings before deployment.</li><li><strong>Use tags deliberately.</strong> Avoid relying exclusively on mutable tags such as latest for production releases.</li><li><strong>Persist important data appropriately.</strong> Use volumes or external data services as needed.</li><li><strong>Check logs and resource usage.</strong> Monitor container health and performance.</li><li><strong>Clean up unused resources.</strong> Remove unnecessary containers, images, and volumes carefully.</li></ol><h3>Conclusion</h3><p>Docker makes it easier to package and run applications consistently across environments. Understanding images, containers, Dockerfiles, volumes, networks, and Compose provides a strong foundation for working with containerized applications.</p><p>Start with a simple application, build an image, run a container, inspect its logs, and practise cleaning up resources. Once you understand the basics, you can move toward multi-service applications and automated deployments.</p><p><strong>The main idea is simple: build once, package consistently, and deploy with confidence.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c89d4e488f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>