<?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 V Ananda Raj on Medium]]></title>
        <description><![CDATA[Stories by V Ananda Raj on Medium]]></description>
        <link>https://medium.com/@v-ananda-raj?source=rss-650078664e6c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Tlkb_37Q-GpKC2fJCFO4-g.png</url>
            <title>Stories by V Ananda Raj on Medium</title>
            <link>https://medium.com/@v-ananda-raj?source=rss-650078664e6c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:40:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@v-ananda-raj/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[Logging All SSH Commands & Sessions on a Bastion Host]]></title>
            <link>https://v-ananda-raj.medium.com/logging-all-ssh-commands-sessions-on-a-bastion-host-9a8ba0a0f9af?source=rss-650078664e6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a8ba0a0f9af</guid>
            <dc:creator><![CDATA[V Ananda Raj]]></dc:creator>
            <pubDate>Mon, 24 Nov 2025 23:02:28 GMT</pubDate>
            <atom:updated>2025-11-24T23:02:28.959Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*FxH8Nel27Zu1OcG4Hj-gqQ.png" /></figure><h4>Complete Guide with Script, Permissions, and Log Rotation</h4><p>When managing multiple users on a bastion (jump) server, it is important to record <strong>everything a user types and sees</strong> during an SSH session. This includes:</p><ul><li>All interactive shell activity</li><li>Any commands executed via non-interactive SSH (e.g., ssh user@host “ls -l”)</li><li>Outputs, errors, and timestamps</li></ul><p>Below is a complete implementation that logs each user’s session separately and securely.</p><h3>1. Create the Session Logging Script</h3><p>Create a script called <strong>/usr/local/bin/session-logger.sh</strong>:</p><pre>vi /usr/local/bin/session-logger.sh</pre><p>Paste the script:</p><pre>#!/bin/bash<br># /usr/local/bin/session-logger.sh<br># Record user sessions (interactive and non-interactive).<br># Exits with the underlying shell/command exit status.<br><br>set -euo pipefail<br><br>USERNAME=$(whoami)<br>TIMESTAMP=$(date +&quot;%Y%m%d_%H%M%S&quot;)<br>LOGDIR=&quot;/var/log/bastion_sessions/$USERNAME&quot;<br>LOGFILE=&quot;$LOGDIR/session_$TIMESTAMP.log&quot;<br><br># Ensure logdir exists and is writable by user (not root-owned in this flow)<br>mkdir -p &quot;$LOGDIR&quot;<br>chown &quot;$USERNAME&quot;:&quot;$USERNAME&quot; &quot;$LOGDIR&quot; 2&gt;/dev/null || true<br>chmod 700 &quot;$LOGDIR&quot; 2&gt;/dev/null || true<br><br># Create logfile as the user via touch (it will be owned by the user)<br>touch &quot;$LOGFILE&quot;<br>chmod 600 &quot;$LOGFILE&quot;<br><br># If SSH session contains a remote command (non-interactive)<br>if [ -n &quot;${SSH_ORIGINAL_COMMAND-}&quot; ]; then<br>    echo &quot;SSH_ORIGINAL_COMMAND: $SSH_ORIGINAL_COMMAND&quot; &gt;&gt; &quot;$LOGFILE&quot;<br>    <br>    # Capture output using script<br>    /usr/bin/script -q -f -a &quot;$LOGFILE&quot; /bin/bash -c &quot;$SSH_ORIGINAL_COMMAND&quot;<br>    exit $?<br>else<br>    # Interactive session: capture everything typed and displayed<br>    exec /usr/bin/script -q -f -a &quot;$LOGFILE&quot; -- &quot;$SHELL&quot; -l<br>fi</pre><blockquote>What this script does</blockquote><ul><li>Creates a timestamped logfile per user: /var/log/bastion_sessions/&lt;username&gt;/session_&lt;timestamp&gt;.log</li><li>Each user gets a private directory readable only by them (700)</li><li>Logs the command passed via SSH (SSH_ORIGINAL_COMMAND)</li><li>Wraps user’s shell inside the script utility to capture full terminal activity</li><li>Users cannot see or modify other users’ logs</li></ul><h3>2. Set Script Permissions</h3><p>This ensures the script is executable and protected:</p><pre>chmod 755 /usr/local/bin/session-logger.sh<br>chown root:root /usr/local/bin/session-logger.sh</pre><h3>3. Prepare the Log Directory</h3><pre>mkdir -p /var/log/bastion_sessions<br>chmod 1777 /var/log/bastion_sessions<br>chown root:root /var/log/bastion_sessions</pre><ul><li>1 = sticky bit → users cannot delete each other’s folders</li><li>777 = every user can create their own directory</li><li>Safe for multi-user systems</li></ul><p>After users start logging in, the directory will look like:</p><pre>/var/log/bastion_sessions/<br>├── abc_user/<br>│   ├── session_20251019_184131.log<br>│   ├── session_20251019_184131.log-20251021<br>├── def_user/<br>├── ghi_user/</pre><p>Each user’s folder is 700 and accessible only by that user.</p><h3>4. Enforce Logging Using ForceCommand</h3><p>Add this line to /etc/ssh/sshd_config:</p><pre>echo &quot;ForceCommand /usr/local/bin/session-logger.sh&quot; &gt;&gt; /etc/ssh/sshd_config</pre><p>It forces every SSH session, interactive or command based to run the logger script first.</p><p>Restart SSH:</p><pre>systemctl restart sshd</pre><h3>5. Configure Log Rotation</h3><p>Create the log rotation config:</p><pre>vi /etc/logrotate.d/bastion_sessions</pre><p>Add:</p><pre>/var/log/bastion_sessions/*/session_*.log {<br>    daily<br>    rotate 30<br>    compress<br>    delaycompress<br>    missingok<br>    notifempty<br>    copytruncate<br>    create 0600 root root<br>}</pre><ul><li><strong>daily — </strong>Rotate logs every day</li><li><strong>rotate 30 — </strong>Keep 30 days of logs</li><li><strong>compress — </strong>Old logs become .gz</li><li><strong>delaycompress — </strong>Compress one day later for safety</li><li><strong>copytruncate — </strong>Truncates the current log without stopping the script</li><li><strong>create 0600 root root — </strong>Secure new logs</li></ul><h3>Conclusion</h3><p>After completing this guide:</p><ul><li>Every SSH login is recorded</li><li>Every command executed remotely is recorded</li><li>Logs are isolated per user</li><li>Logs are automatically rotated</li><li>Security and privacy are preserved (sticky bit + per-user permissions)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a8ba0a0f9af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenVPN Usage Report: Who Used the Most Bandwidth and When?]]></title>
            <link>https://v-ananda-raj.medium.com/openvpn-usage-report-who-used-the-most-bandwidth-and-when-03bcb36a0229?source=rss-650078664e6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/03bcb36a0229</guid>
            <dc:creator><![CDATA[V Ananda Raj]]></dc:creator>
            <pubDate>Thu, 10 Jul 2025 08:42:53 GMT</pubDate>
            <atom:updated>2025-07-10T08:42:53.914Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a4x8DdjMNdZaJCHn5wD34Q.jpeg" /></figure><h3>Step 1: Export Logs from OpenVPN</h3><blockquote>Prerequisite: You need access to the OpenVPN Access Server (root or sudo) and Python 3 installed.</blockquote><p>Get a report of users’ traffic details, execute the command on the OpenVPN Access server.</p><pre>sqlite3 -csv /usr/local/openvpn_as/etc/db/log.db &quot;<br>SELECT log.username, datetime(log.timestamp, &#39;unixepoch&#39;), log.bytes_in, log.bytes_out <br>FROM log <br>WHERE log.timestamp &gt; strftime(&#39;%s&#39;,&#39;now&#39;,&#39;-30 days&#39;) <br>ORDER BY log.timestamp DESC <br>LIMIT 10000000;<br>&quot; &gt; openvpn_usage.csv</pre><p>Below is a sample output. It is in bytes. We will convert it to MB in the next step.</p><pre>abc@domain.net,&quot;2025-07-09 02:38:42&quot;,108475,2267642<br>def@domain.net,&quot;2025-07-09 02:02:37&quot;,318681,332790<br>hij@domain.net,&quot;2025-07-08 19:42:29&quot;,213754,326912<br>klm@domain.net,&quot;2025-07-08 19:42:26&quot;,,</pre><h3>Step 2: Generate Per-User Traffic Report</h3><p>Now with this report get a summary with the below python script:</p><pre>import csv<br>from collections import defaultdict<br><br>## Replace the file name you just created<br>file_path = &quot;openvpn_usage.csv&quot;<br><br># Store per-user data usage<br>usage = defaultdict(lambda: {&quot;in&quot;: 0, &quot;out&quot;: 0})<br><br>with open(file_path, &quot;r&quot;, newline=&#39;&#39;) as csvfile:<br>    reader = csv.reader(csvfile)<br>    for row in reader:<br>        try:<br>            user = row[0].strip()<br>            bytes_in = int(row[2]) if row[2] else 0<br>            bytes_out = int(row[3]) if row[3] else 0<br>            usage[user][&quot;in&quot;] += bytes_in<br>            usage[user][&quot;out&quot;] += bytes_out<br>        except Exception as e:<br>            print(f&quot;Skipping row: {row} → {e}&quot;)<br>            continue<br><br>def to_mb(b):<br>    return round(b / (1024 * 1024), 2)<br><br># Print the header<br>print(f&quot;{&#39;Username&#39;:&lt;35} {&#39;Total MB In&#39;:&gt;13} {&#39;Total MB Out&#39;:&gt;15} {&#39;Total Usage&#39;:&gt;15}&quot;)<br>print(&quot;-&quot; * 80)<br><br># Print sorted by total usage descending<br>for user, data in sorted(usage.items(), key=lambda x: x[1][&quot;in&quot;] + x[1][&quot;out&quot;], reverse=True):<br>    mb_in = to_mb(data[&#39;in&#39;])<br>    mb_out = to_mb(data[&#39;out&#39;])<br>    total = round(mb_in + mb_out, 2)<br>    print(f&quot;{user:&lt;35} {mb_in:&gt;13,.2f} {mb_out:&gt;15,.2f} {total:&gt;15,.2f}&quot;)</pre><p>It will give a output as below:</p><pre>root@vpn:~# python3 openvpn_summary.py <br>Username                   Total MB In    Total MB Out    Total Usage<br>-------------------------------------------------------------------------<br>abc@phobs.net              40.46          169.69          210.15<br>def@phobs.net              41.41          155.09          196.50<br>ghi@phobs.net              26.36          102.88          129.24<br>admin                      0.00            0.00            0.00<br>local_root                 0.00            0.00            0.00</pre><h3>Bonus: Identify Top Usage Day per User</h3><p>To get a summary and to identify which day a user had most usage use this:</p><pre>import csv<br>from collections import defaultdict<br>from datetime import datetime<br><br>file_path = &quot;openvpn_usage.csv&quot;<br><br># Track total per user<br>user_totals = defaultdict(lambda: {&quot;in&quot;: 0, &quot;out&quot;: 0})<br><br># Track per-day usage per user<br>per_day_usage = defaultdict(lambda: defaultdict(lambda: {&quot;in&quot;: 0, &quot;out&quot;: 0}))<br><br>with open(file_path, &quot;r&quot;, newline=&#39;&#39;) as csvfile:<br>    reader = csv.reader(csvfile)<br>    for row in reader:<br>        try:<br>            user = row[0].strip()<br>            timestamp = row[1].strip().strip(&#39;&quot;&#39;)<br>            date = datetime.strptime(timestamp, &quot;%Y-%m-%d %H:%M:%S&quot;).date().isoformat()<br>            bytes_in = int(row[2]) if row[2] else 0<br>            bytes_out = int(row[3]) if row[3] else 0<br>            user_totals[user][&quot;in&quot;] += bytes_in<br>            user_totals[user][&quot;out&quot;] += bytes_out<br>            per_day_usage[user][date][&quot;in&quot;] += bytes_in<br>            per_day_usage[user][date][&quot;out&quot;] += bytes_out<br>        except Exception as e:<br>            print(f&quot;Skipping row: {row} → {e}&quot;)<br>            continue<br><br>def to_mb(b):<br>    return round(b / (1024 * 1024), 2)<br><br># --- Output 1: Per-user total usage ---<br>print(&quot;\nSummary by User:\n&quot;)<br>print(f&quot;{&#39;Username&#39;:&lt;35} {&#39;Total MB In&#39;:&gt;13} {&#39;Total MB Out&#39;:&gt;15} {&#39;Total Usage&#39;:&gt;15}&quot;)<br>print(&quot;-&quot; * 85)<br>for user, data in sorted(user_totals.items(), key=lambda x: x[1][&quot;in&quot;] + x[1][&quot;out&quot;], reverse=True):<br>    mb_in = to_mb(data[&quot;in&quot;])<br>    mb_out = to_mb(data[&quot;out&quot;])<br>    total = round(mb_in + mb_out, 2)<br>    print(f&quot;{user:&lt;35} {mb_in:&gt;13,.2f} {mb_out:&gt;15,.2f} {total:&gt;15,.2f}&quot;)<br><br># --- Output 2: Top usage day per user ---<br>print(&quot;\nTop Usage Day by User:\n&quot;)<br>print(f&quot;{&#39;Username&#39;:&lt;35} {&#39;Top Usage Date&#39;:&gt;15} {&#39;Top Usage (MB)&#39;:&gt;20}&quot;)<br>print(&quot;-&quot; * 75)<br>for user, days in per_day_usage.items():<br>    top_day = None<br>    top_usage = 0<br>    for date, data in days.items():<br>        daily_total = data[&quot;in&quot;] + data[&quot;out&quot;]<br>        if daily_total &gt; top_usage:<br>            top_usage = daily_total<br>            top_day = date<br>    if top_day:<br>        print(f&quot;{user:&lt;35} {top_day:&gt;15} {to_mb(top_usage):&gt;20,.2f}&quot;)<br>    else:<br>        print(f&quot;{user:&lt;35} {&#39;(no data)&#39;:&gt;15} {0.00:&gt;20,.2f}&quot;)</pre><p>Sample output:</p><pre>root@vpn:~# python3 openvpn_summary_full.py <br><br>Summary by User:<br><br>Username                    Total MB In    Total MB Out    Total Usage<br>-------------------------------------------------------------------------<br>abc@domain.net              40.46          169.69          210.15<br>def@domain.net              41.41          155.09          196.50<br>ghi@domain.net              26.36          102.88          129.24<br>admin                        0.00            0.00            0.00<br>local_root                   0.00            0.00            0.00<br><br>Top Usage Day by User:<br><br>Username                    Top Usage Date       Top Usage (MB)<br>-------------------------------------------------------------------------<br>abc@domain.net              2025-07-07                 3.38<br>def@domain.net              2025-06-20                41.74<br>ghi@domain.net              2025-06-10                14.26<br>admin                       (no data)                  0.00<br>local_root                  (no data)                  0.00</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03bcb36a0229" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining CI/CD Deployments to EC2 Instances with GitHub Actions and AWS CodeDeploy]]></title>
            <link>https://v-ananda-raj.medium.com/streamlining-ci-cd-deployments-to-ec2-instances-with-github-actions-and-aws-codedeploy-9e9870c22335?source=rss-650078664e6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e9870c22335</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[codedeploy]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[V Ananda Raj]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 15:09:56 GMT</pubDate>
            <atom:updated>2024-12-26T15:28:51.203Z</atom:updated>
            <content:encoded><![CDATA[<p>Continuous Integration and Continuous Deployment (CI/CD) pipelines streamline the delivery process, ensuring reliable and frequent updates to your applications. In this blog, we’ll explore how to set up a CI/CD pipeline using GitHub Actions to deploy applications to AWS EC2 instances based on tags. The pipeline integrates GitHub Actions, AWS CodeDeploy, and EC2 instances, demonstrating a robust approach to application deployment.</p><blockquote><strong>What We’re Building</strong></blockquote><p>We’ll create a pipeline where:</p><p>Code is pushed to a GitHub branch.<br>GitHub Actions packages the code and uploads it to an AWS S3 bucket.<br>AWS CodeDeploy deploys the code to EC2 instances tagged with specific identifiers.<br>Custom scripts are executed on the EC2 instances during the deployment process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UkGu7xhhIH78E9BWlYu7og.png" /></figure><blockquote><strong>Step-by-Step Implementation</strong></blockquote><h4>Step 1. Create IAM user and Roles</h4><p>Go to the AWS Management Console and navigate to <strong>IAM</strong> console.</p><p><strong>Step 1.1: </strong>Create an IAM user for GitHub actions to have access to S3 and use CodeDeploy. Use the below <strong>permission policy</strong>:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor0&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;logs:DescribeLogStreams&quot;,<br>                &quot;logs:GetLogEvents&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor1&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;s3:PutObject&quot;,<br>                &quot;s3:GetObject&quot;,<br>                &quot;s3:ListBucket&quot;,<br>                &quot;codedeploy:GetDeploymentGroup&quot;,<br>                &quot;codedeploy:CreateDeployment&quot;,<br>                &quot;codedeploy:RegisterApplicationRevision&quot;,<br>                &quot;codedeploy:GetDeployment&quot;,<br>                &quot;codedeploy:GetApplication&quot;,<br>                &quot;codedeploy:GetDeploymentConfig&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3:::s3-prod-app-01-cicd&quot;,<br>                &quot;arn:aws:s3:::s3-prod-app-01-cicd/*&quot;,<br>                &quot;arn:aws:codedeploy:us-east-1:254214173625:application:prod-app-01&quot;,<br>                &quot;arn:aws:codedeploy:us-east-1:254214173625:deploymentgroup:prod-app-01/prod-app-dg-01&quot;,<br>                &quot;arn:aws:codedeploy:us-east-1:254214173625:deploymentconfig:CodeDeployDefault.OneAtATime&quot;<br>            ]<br>        }<br>    ]<br>}</pre><p>Create an <strong>Access Key</strong>, <strong>Secret</strong> and note it down.</p><p><strong>Step 1.2: </strong>Create a new role.</p><p>Choose AWS service and select CodeDeploy in the use case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3bf49cY1CbwFBrcHTkgpg.png" /></figure><p>Click next and provide a name for the role (e.g., AmazonCodeDeployRoleForDeploymentGroup). Click on Create Role.</p><h4><strong>Step 2. Setting Up CodeDeploy</strong></h4><p>AWS CodeDeploy is a service that automates deployments to EC2 instances. Here’s how to configure it:</p><p><strong>Step 2.1: Create a CodeDeploy Application</strong></p><ol><li>Go to the AWS Management Console.</li><li>Navigate to <strong>CodeDeploy</strong>.</li><li>Click on <strong>Create application</strong>. <br><strong>Application name</strong>: Give a meaningful name (e.g., prod-app-01). <br><strong>Compute platform</strong>: Select <strong>EC2/On-premises</strong>.</li><li>Click <strong>Create application</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*prgxbyciKrg9MSpUlSCIBg.png" /></figure><p><strong>Step 2.2: Create a Deployment Group</strong></p><ol><li>Under the application, go to <strong>Deployment groups</strong> and click <strong>Create deployment group</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WldifJiAj6COSnbslKaP2g.png" /></figure><p>2. Configure the following:</p><p><strong>Deployment group name</strong>: Name it (e.g., prod-app-dg-01).<br><strong>Service role</strong>: Attach an IAM role that allows CodeDeploy to access EC2 instances (e.g., AmazonCodeDeployRoleForDeploymentGroup).<br><strong>Environment configuration</strong>:<br>Select <strong>Amazon EC2 instances</strong>.<br>Choose <strong>Key=value</strong> under tags, and define the tag key-value pair (e.g., Deployment=Production).<br><strong>Deployment settings</strong>: Use <strong>CodeDeployDefault.OneAtATime</strong> for sequential deployments.<br><strong>Load balancer</strong> (optional): If you use a load balancer, integrate it here.</p><p>3. Click <strong>Create deployment group</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*Ydu2frGLNjLfGY4P8c7Nlw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*0bMKYY29eiaICQ2XD2dj8g.png" /></figure><h4><strong>Step 3. Configuring EC2 Instances</strong></h4><p><strong>Step 3.1: Tag the Instances</strong>:</p><ol><li>In the EC2 dashboard, select the instances you want to deploy to.</li><li>Add a tag with the same key-value pair used in CodeDeploy (e.g., Deployment=Production).</li></ol><p><strong>Step 3.2: Install CodeDeploy Agent</strong>:</p><p>Run the following commands on each instance to install the CodeDeploy agent:</p><p><em>Replace the S3 bucket URL with the appropriate region if you’re deploying in a region other than us-east-1. For example:</em></p><p><em>https://aws-codedeploy-&lt;region&gt;.s3.&lt;region&gt;.amazonaws.com/latest/install</em></p><pre>sudo yum update -y<br>sudo yum install wget -y<br>cd /home<br>wget https://aws-codedeploy-us-east-1.s3.us-east-1.amazonaws.com/latest/install<br>chmod +x ./install<br>sudo ./install auto<br>sudo systemctl start codedeploy-agent<br>sudo systemctl enable codedeploy-agent<br>sudo service codedeploy-agent status</pre><pre>sudo apt-get update -y<br>sudo apt-get install wget -y<br>cd /home<br>wget https://aws-codedeploy-us-east-1.s3.us-east-1.amazonaws.com/latest/install<br>chmod +x ./install<br>sudo ./install auto<br>sudo systemctl start codedeploy-agent<br>sudo systemctl enable codedeploy-agent<br>sudo service codedeploy-agent status</pre><h4><strong>Step 4: Create Branch and Add Files</strong></h4><p>In the GitHub repository, create a new branch for Actions or choose the one you want to proceed (e.g., deploy_prod) and add the following files:</p><pre>appspec.yml<br>.github/workflows/actions.yaml<br>build/before_install.sh<br>build/after_install.sh</pre><p><strong>Step 4.1: Define appspec.yml</strong></p><p>This file instructs CodeDeploy on how to deploy your application. Example:</p><pre>version: 0.0<br>os: linux<br>files:<br>  - source: /<br>    destination: /home/deploy/deployments/<br>permissions:<br>  - object: /home/deploy/deployments<br>    owner: deploy<br>    group: deploy<br>hooks:<br>  BeforeInstall:<br>    - location: build/before_install.sh<br>      timeout: 300<br>      runas: root<br>  AfterInstall:<br>    - location: build/after_install.sh<br>      timeout: 600<br>      runas: deploy</pre><p><strong>Files Section</strong>: Specifies the source and destination of the files to deploy.<br><strong>Hooks Section</strong>: Contains scripts to execute at different stages.</p><p><strong>Step 4.2: Configure GitHub Actions</strong></p><p>GitHub Actions automates CI/CD workflows. Add the following workflow file in .github/workflows/actions.yaml.</p><pre>name: Deploy to EC2 using CodeDeploy<br><br>on:<br>  push:<br>    branches:<br>      - deploy_prod<br><br>jobs:<br>  deploy:<br>    name: CI/CD Pipeline<br>    runs-on: ubuntu-latest<br>    strategy:<br>      matrix:<br>        prod-appname: [&#39;prod-app-01&#39;]<br>        prod-deploy-group: [&#39;prod-app-dg-01&#39;]<br>        prod-s3-bucket: [&#39;s3-prod-app-01-cicd&#39;]<br>        prod-s3-filename: [&#39;prod-app-01-${{ github.sha }}&#39;]<br><br>    steps:<br>      - uses: actions/checkout@v4<br><br>      - name: Configure AWS credentials<br>        uses: aws-actions/configure-aws-credentials@v2<br>        with:<br>          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}<br>          aws-region: ${{ secrets.AWS_REGION }}<br><br>      - name: Debug matrix variables<br>        run: |<br>          echo &quot;App name: ${{ matrix.prod-appname }}&quot;<br>          echo &quot;S3 bucket: ${{ matrix.prod-s3-bucket }}&quot;<br>          echo &quot;S3 filename: ${{ matrix.prod-s3-filename }}&quot;<br><br>      - name: Deploy push to AWS S3<br>        if: github.ref == &#39;refs/heads/deploy_prod&#39;<br>        run: |<br>          aws deploy push \<br>          --application-name ${{ matrix.prod-appname }} \<br>          --description &quot;This is a revision for the ${{ matrix.prod-appname }}-${{ github.sha }}&quot; \<br>          --s3-location s3://${{ matrix.prod-s3-bucket }}/${{ matrix.prod-s3-filename }}.zip \<br>          --source .<br><br>      - name: Create Deployment for production<br>        if: github.ref == &#39;refs/heads/deploy_prod&#39;<br>        run: |<br>          DEPLOYMENT_ID=$(aws deploy create-deployment \<br>            --application-name ${{ matrix.prod-appname }} \<br>            --deployment-config-name CodeDeployDefault.OneAtATime \<br>            --deployment-group-name ${{ matrix.prod-deploy-group }} \<br>            --file-exists-behavior OVERWRITE \<br>            --s3-location bucket=${{ matrix.prod-s3-bucket }},key=${{ matrix.prod-s3-filename }}.zip,bundleType=zip \<br>            --query &quot;deploymentId&quot; \<br>            --output text || echo &quot;ERROR&quot;)<br>          if [ &quot;$DEPLOYMENT_ID&quot; == &quot;ERROR&quot; ]; then<br>            echo &quot;Deployment failed.&quot;<br>            exit 1<br>          fi<br>          echo &quot;deployment_id=$DEPLOYMENT_ID&quot; &gt;&gt; $GITHUB_ENV<br>                <br>      - name: Deployment Status<br>        run: |<br>          aws deploy wait deployment-successful --deployment-id ${{ env.deployment_id }}</pre><p><strong>Step 4.3: Deployment Scripts</strong></p><p><strong>before_install.sh<br></strong>Executed before the new files are installed. Use this to:<br>• Rollbacks: Backup the current version before installing new files.<br>• Stopping services: Prevent conflicts during deployment.</p><pre>#! /bin/bash<br><br>tar -cvzf /home/deploy/public_html_old.tar.gz /home/deploy/public_html<br>chown deploy: /home/deploy/public_html_old.tar.gz</pre><p><strong>after_install.sh<br></strong>Executed after the new files are installed. Use this to:<br>• Install dependencies.<br>• Start or restart services.<br>• Build the project (e.g., npm run prod).</p><pre>#!/bin/bash<br><br># Determine the branch name using the DEPLOYMENT_GROUP_NAME environment variable<br>deployment_group_name=&quot;${DEPLOYMENT_GROUP_NAME}&quot;<br>echo &quot;$deployment_group_name&quot;<br><br>if [[ &quot;$deployment_group_name&quot; == &quot;prod-app-dg-01&quot; ]]; then<br>    branch_name=&quot;deploy_prod&quot;<br>else<br>    echo &quot;Unknown deployment group: $deployment_group_name&quot;<br>    exit 1<br>fi<br><br>echo &quot;Branch name is: $branch_name&quot;<br><br># Define the site_name variable name based on the branch<br>if [ &quot;$branch_name&quot; = &quot;deploy_prod&quot; ]; then<br>    path=&quot;production&quot;<br>#elif [ &quot;$branch_name&quot; = &quot;deploy_stage&quot; ]; then<br>#    path=&quot;staging&quot;<br>else<br>    echo &quot;Unknown branch: $branch_name&quot;<br>    exit 1<br>fi<br><br>echo &quot;This is in the Environment: $path&quot;<br><br># Error Message<br>exitWithErrorMessage() {<br> echo &quot;ERROR: $1&quot;<br> exit 1<br>}<br><br>rsync -avz --exclude &#39;appspec.yml&#39; --exclude &#39;build&#39; /home/deploy/deployments/ /home/deploy/public_html/<br><br>if ! [ &quot;$?&quot; = &quot;0&quot; ]; then<br>     exitWithErrorMessage &quot;Rsync failed&quot;<br>fi<br><br>cp -p /home/deploy/public_html/.env.production /home/deploy/public_html/.env<br><br>if ! [ &quot;$?&quot; = &quot;0&quot; ]; then<br>    exitWithErrorMessage &quot;Failed to copy .env file&quot;<br>fi<br><br>sudo -u deploy bash -c &quot;source /home/deploy/.bashrc &amp;&amp; cd /home/deploy/public_html &amp;&amp; npm install &amp;&amp; npm run prod&quot;<br><br>if ! [ &quot;$?&quot; = &quot;0&quot; ]; then<br>    exitWithErrorMessage &quot;npm commands failed&quot;<br>fi<br><br><br>sudo service php8.1-fpm restart<br><br>if ! [ &quot;$?&quot; = &quot;0&quot; ]; then<br>     exitWithErrorMessage &quot;PHP service restart failed&quot;<br>fi</pre><h4><strong>Step 5: Add GitHub variables</strong></h4><p>In the repo <strong>settings</strong>, navigate to <strong>Actions</strong> under <strong>Secrets and Variables</strong>. Add new variables there (From Step 1):</p><p>AWS_SECRET_ACCESS_KEY<br>AWS_ACCESS_KEY_ID<br>AWS_REGION</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lulav9nGJcCjYS6BhnfBRQ.png" /></figure><blockquote><strong>How It Works</strong></blockquote><p><strong>Push Trigger</strong>: The pipeline triggers when code is pushed to the deploy_prod branch. You can see it in the <strong>Actions</strong> tab under the repo.</p><p><strong>AWS S3</strong>: Bundles the application and uploads it to an S3 bucket.</p><p><strong>AWS CodeDeploy</strong>: Deploys the application to EC2 instances based on tags.</p><p><strong>Deployment Scripts</strong>: Handle pre- and post-installation tasks on the EC2 instances.</p><blockquote><strong>Conclusion</strong></blockquote><p>This CI/CD pipeline demonstrates a streamlined approach to deploy applications to AWS EC2 instances based on tags using GitHub Actions and CodeDeploy. It ensures a reliable and automated deployment process, reducing manual intervention and minimizing downtime.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e9870c22335" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Cron Tasks with Kubernetes]]></title>
            <link>https://v-ananda-raj.medium.com/running-cron-tasks-with-kubernetes-d3a7734f7e42?source=rss-650078664e6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3a7734f7e42</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[cron]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[V Ananda Raj]]></dc:creator>
            <pubDate>Tue, 07 May 2024 04:20:23 GMT</pubDate>
            <atom:updated>2024-05-30T12:05:42.399Z</atom:updated>
            <content:encoded><![CDATA[<h3>Before you begin</h3><p>To interact with your Kubernetes cluster, you’ll need two things in place: a Kubernetes cluster itself and the kubectl command-line tool configured to communicate with that cluster.</p><h3>Creating a CronJob</h3><p>The Cron jobs require a config file. Here is a manifest for a CronJob that runs the command php artisan update:products every day for a Laravel project:</p><pre>apiVersion: batch/v1<br>kind: CronJob<br>metadata:<br>  name: update-products-admin # put a name of choice here<br>  namespace: namespace_abc # replace ur namespace name here<br>  labels:<br>    app: app_name # replace app name here<br>spec:<br>  schedule: &quot;0 0 * * *&quot;  # Cron expression for running at midnight every day<br>  successfulJobsHistoryLimit: 1<br>  failedJobsHistoryLimit: 1<br>  concurrencyPolicy: Forbid<br>  suspend: false<br>  jobTemplate:<br>    spec:<br>      template:<br>        metadata:<br>          labels:<br>            app: app_name # replace app name here<br>        spec:<br>          containers:<br>          - name: update-products-admin<br>            image: image-name-here:latest # replace the image name here, say like alpine<br>            imagePullPolicy: IfNotPresent<br>            command: [&quot;php&quot;, &quot;artisan&quot;, &quot;update:products&quot;] # This depends on the action you want to perform<br>          restartPolicy: Never</pre><p>Below is a snippet of the pods running at present before adding the cron.</p><pre>$ kubectl get pods -n namespace_abc --show-labels<br>NAME                                              READY   STATUS    RESTARTS   AGE     LABELS<br>app-admin-deployment-7dc9254446-vgrlh      1/1     Running   0          68m     app=app_name-admin,pod-template-hash=7dc9254446<br>app-frontend-deployment-84633664d6-s6tjd   1/1     Running   0          2d18h   app=app_name,pod-template-hash=84633664d6</pre><p>Here is a manifest for a CronJob that runs a simple demonstration task every minute from the Kubernetes <a href="https://kubernetes.io/docs/tasks/job/automated-tasks-with-cron-jobs/">documentation</a>.</p><pre>apiVersion: batch/v1<br>kind: CronJob<br>metadata:<br>  name: hello<br>spec:<br>  schedule: &quot;* * * * *&quot;<br>  jobTemplate:<br>    spec:<br>      template:<br>        spec:<br>          containers:<br>          - name: hello<br>            image: busybox:1.28<br>            imagePullPolicy: IfNotPresent<br>            command:<br>            - /bin/sh<br>            - -c<br>            - date; echo Hello from the Kubernetes cluster<br>          restartPolicy: OnFailure</pre><p>Now, run the CronJob with the below command:</p><pre>$ kubectl apply -f cron_update_products.yaml <br>cronjob.batch/update-products-admin created</pre><h3>Verifying the CronJob</h3><p>We can get the CronJob status as below:</p><pre>$ kubectl get cronjob -n namespace_abc<br>NAME                    SCHEDULE    SUSPEND   ACTIVE   LAST SCHEDULE   AGE<br>update-products-admin   0 0 * * *   False     0        &lt;none&gt;          6s</pre><p>From the results of the command we can see, the cron job has not scheduled or run any jobs yet. We can watch for the job as:</p><pre>$ kubectl get jobs --watch -n namespace_abc<br>NAME                       COMPLETIONS   DURATION   AGE<br>update-products-admin-28562970   1/1           4m41s      4m41s</pre><p>To find the pods that the last scheduled job created.</p><pre># Replace &quot;update-products-admin-28562970&quot; with the job name in your system<br>$ kubectl get pods --selector=job-name=update-products-admin-28562970 --output=jsonpath={.items[*].metadata.name}</pre><p>To get the logs from the pod:</p><pre>kubectl logs $pod_name</pre><h3>Deleting a CronJob</h3><p>You can delete the created job as below:</p><pre>$ kubectl delete cronjob update-products-admin -n namespace_abc<br>cronjob.batch &quot;update-products-admin&quot; deleted</pre><h3>Bonus</h3><p>We can add crons at Docker file as well if the containers are build with Docker.</p><p>Copy over the cron to a file crontab_file</p><pre>*/5 * * * * cd /var/www/html &amp;&amp; source /var/www/html/.env &amp;&amp; /usr/local/bin/php artisan update:products ; echo &quot;update ran completed&quot; &gt;&gt; /var/log/cron_update_products.log 2&gt;&amp;1</pre><p>Now add the below lines in the Dockerfile</p><pre>COPY crontab_file /var/spool/cron/crontabs/root<br>RUN chmod 0644 /var/spool/cron/crontabs/root<br>RUN chown root:crontab /var/spool/cron/crontabs/root<br>RUN crontab /var/spool/cron/crontabs/root<br>RUN touch /var/log/cron.log<br><br>CMD [&quot;sh&quot;, &quot;-c&quot;, &quot;cron&quot;]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3a7734f7e42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clearing Unwanted AMIs with AWS CLI and Bash Script]]></title>
            <link>https://v-ananda-raj.medium.com/clearing-unwanted-amis-with-aws-cli-and-bash-script-68225667bfcc?source=rss-650078664e6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/68225667bfcc</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[V Ananda Raj]]></dc:creator>
            <pubDate>Tue, 16 Apr 2024 06:39:25 GMT</pubDate>
            <atom:updated>2024-04-16T06:39:25.082Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="https://unsplash.com/photos/turned-on-macbook-pro-wit-programming-codes-display-f77Bh3inUpE" src="https://cdn-images-1.medium.com/max/1024/1*mWKDztnIzcpChIEnd6qmFw.png" /></figure><p>This bash script will check the AMIs under and account and delete unused ones. It will verify the AMI has a tag enabling the “DeletionProtection” and also check if it is used in ASG, EC2, LT/LC, Spot and BeanStack.</p><p>For the safe side, a prompt will be asked whether to delete the unused ones.</p><pre>#!/bin/bash<br># Script to Check AMIs and delete unused ones. It will verify the AMI has a tag enabling the DeletionProtection and also check if it is used in ASG, EC2, LT/LC, Spot, BeanStack. <br># Authors: Ananda Raj<br># Date: 02 Apr 2024<br><br># Define the aws config file here.<br>aws_config_file=&quot;/home/$username/.aws/config&quot;<br><br># Loop through the profiles and check individually. <br>for profile in $(cat $aws_config_file | grep &quot;\[profile &quot; | awk &#39;{print $2}&#39; | cut -d &quot;]&quot; -f1)<br>do<br><br>echo -e &quot;\n########## Taking profile $profile ##########\n&quot;<br><br># Take the account ID<br>acc_id=$(aws --profile $profile sts get-caller-identity | jq -r &#39;.Account&#39;)<br>echo -e &quot;Account ID: $acc_id&quot;<br><br># List of AMI without Deletion Protection enabled<br>aws --profile $profile ec2 describe-images --query &quot;Images[?!(Tags[?Key==&#39;DeletionProtection&#39; &amp;&amp; Value==&#39;Yes&#39;] || starts_with(ImageLocation, &#39;$acc_id/AwsBackup_&#39;)) &amp;&amp; OwnerId==&#39;$acc_id&#39;].ImageId&quot; --output text | tr &#39;\t&#39; &#39;\n&#39; &gt; AMI_List<br><br>echo &quot;Completed taking AMI list&quot;<br>cat AMI_List<br><br>for ami_id in `cat AMI_List`;<br>do <br><br>echo -e &quot;\nTaking AMI $ami_id&quot;<br><br># Check if the AMI is used by any EC2 instances<br>instance_count=0<br>instance_count=$(aws --profile $profile ec2 describe-instances --filters &quot;Name=image-id,Values=$ami_id&quot; --query &quot;length(Reservations[].Instances[])&quot; --output text)<br>if [ $instance_count -gt 0 ]; then<br>    echo &quot;This AMI is currently in use for Instance.&quot;<br>fi<br><br># Check if the AMI is used by any Auto Scaling groups<br>auto_scaling_count=0<br>auto_scaling_count=$(aws --profile $profile autoscaling describe-auto-scaling-groups --query &quot;length(AutoScalingGroups[?LaunchConfigurationName == &#39;$ami_id&#39;])&quot; --output text)<br>if [ $auto_scaling_count -gt 0 ]; then<br>    echo &quot;This AMI is currently in use for AutoScaling.&quot;<br>fi<br><br># Check if the AMI is used by any launch configurations<br>launch_config_count=0<br>launch_configurations=$(aws --profile $profile autoscaling describe-launch-configurations --query &quot;LaunchConfigurations[?ImageId == &#39;$ami_id&#39;].{LaunchConfigurationName: LaunchConfigurationName}&quot; --output json)<br>launch_config_count=$(echo &quot;$launch_configurations&quot; | jq length)<br><br>if [ $launch_config_count -gt 0 ]; then<br>    launch_configurations=$(echo &quot;$launch_configurations&quot; | jq -r &#39;.[].LaunchConfigurationName&#39;)<br>    echo &quot;This AMI is currently in use for the Launch Configurations: $launch_configurations&quot;<br>fi<br><br><br># Check if the AMI is used by any launch templates<br>launch_template_count=0<br>launch_templates=$(aws --profile $profile ec2 describe-launch-templates --query &#39;LaunchTemplates[*].[LaunchTemplateName, LaunchTemplateId]&#39; --output json)<br># Iterate through each launch template<br>for lt_info in $(echo &quot;$launch_templates&quot; | jq -r &#39;.[] | @base64&#39;); do<br>    _jq() {<br>        echo &quot;${lt_info}&quot; | base64 --decode | jq -r &quot;${1}&quot;<br>    }<br><br>    lt_name=$(_jq &#39;.[0]&#39;)<br>    lt_id=$(_jq &#39;.[1]&#39;)<br><br>    # Describe first two versions of the launch template<br>    versions=$(aws --profile $profile ec2 describe-launch-template-versions --launch-template-id $lt_id --max-items 2 --query &#39;LaunchTemplateVersions[*].[LaunchTemplateId, LaunchTemplateName, LaunchTemplateData.ImageId]&#39; --output json)<br><br>    # Check if the AMI ID is used by any version of the launch template<br>    if echo &quot;$versions&quot; | jq -r &#39;.[][] | select(. == &quot;&#39;&quot;$ami_id&quot;&#39;&quot;)&#39; | grep -q .; then<br>        echo &quot;This AMI is currently in use for Launch Template: $lt_name&quot;<br>        launch_template_count=1<br>    fi<br>done<br><br><br><br># Check if the AMI is used by any Elastic Beanstalk environments<br>elastic_beanstalk_count=0<br>elastic_beanstalk_count=$(aws --profile $profile elasticbeanstalk describe-environments --query &quot;length(Environments[?PlatformArn | contains(&#39;$ami_id&#39;)])&quot; --output text)<br>if [ $elastic_beanstalk_count -gt 0 ]; then<br>    echo &quot;This AMI is currently in use for Elastic Beanstalk.&quot;<br>fi<br><br><br># Check if the AMI is used by any Spot Instance requests<br>spot_instance_count=None<br>spot_instance_count=$(aws --profile $profile ec2 describe-spot-instance-requests --filters Name=launch.image-id,Values=&quot;$ami_id&quot; --query &quot;SpotInstanceRequests[1].Tags[*].[Value]&quot; --output text)<br>if [ &quot;$spot_instance_count&quot; != &quot;None&quot; ]; then<br>    echo &quot;This AMI is currently in use for Spot Instance requests $spot_instance_count.&quot;<br>fi<br><br><br><br># Delete the AMI from here ## IMPORTANT<br>if [ $instance_count -gt 0 ] || [ $auto_scaling_count -gt 0 ] || [ $launch_config_count -gt 0 ] || [ $launch_template_count -gt 0 ] || [ $elastic_beanstalk_count -gt 0 ] || [ &quot;$spot_instance_count&quot; != &quot;None&quot; ]; then<br>    echo &quot;IN USE - This AMI $ami_id is currently in use, so not deleting.&quot;<br>else<br>    echo &quot;NOT IN USE - This AMI $ami_id is not in use, so deleting.&quot;<br>    echo &quot;Do you want to proceed with deletion? (Y/N)&quot;<br>    read -r confirm_delete<br>    if [ &quot;$confirm_delete&quot; = &quot;Y&quot; ] || [ &quot;$confirm_delete&quot; = &quot;y&quot; ]; then<br>        echo &quot;===================================&quot;<br>        echo &quot;$ami_id&quot; # delete<br>        snapshots_list=&quot;$(aws ec2 --profile $profile describe-images --image-ids $ami_id --query &#39;Images[*].BlockDeviceMappings[*].Ebs.SnapshotId&#39; --output text)&quot;<br>        aws --profile $profile ec2 deregister-image --image-id $ami_id<br>        for snapshot in $snapshots_list; do <br>            echo $snapshot<br>            aws --profile $profile ec2 delete-snapshot --snapshot-id $snapshot<br>        echo &quot;===================================&quot;<br>        done<br>    else<br>        echo &quot;Deletion canceled. Exiting...&quot;<br>    fi<br>fi<br><br>done<br>done<br><br>echo &quot;Script completed execution&quot;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68225667bfcc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Secure Passcodes: A Python3 Script for One-Time Password Challenges]]></title>
            <link>https://v-ananda-raj.medium.com/unlocking-secure-passcodes-a-python3-script-for-one-time-password-challenges-871d5ec28047?source=rss-650078664e6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/871d5ec28047</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[otp-verification]]></category>
            <dc:creator><![CDATA[V Ananda Raj]]></dc:creator>
            <pubDate>Tue, 16 Apr 2024 06:12:25 GMT</pubDate>
            <atom:updated>2024-04-16T06:29:15.396Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="https://unsplash.com/photos/a-close-up-of-a-laptop-keyboard-with-a-blurry-background-EP634JhALnA" src="https://cdn-images-1.medium.com/max/1024/1*5dPgQJF92W4gQkgsgWZyjg.png" /></figure><p>Discover how to automate the generation of one-time passwords (OTPs) with Python.</p><p>The script simplifies the process of creating and displaying secure passcodes, ideal for enhancing authentication systems and bolstering cybersecurity measures. Dive into the world of OTP challenges and streamline your security protocols effortlessly within the command line environment.</p><pre>#!/usr/bin/env python3<br># Script to generate OTP through CLI<br># Author: Ananda Raj<br># Date: 16 Apr 2024<br><br>&#39;&#39;&#39;<br>Shows your OTP challenge<br>The first time the script will create a configuration file<br>&#39;&#39;&#39;<br><br>import platform<br>import subprocess<br>import time<br>import os<br>try:<br>    import onetimepass as otp<br>except ImportError:<br>    print(&quot;Please install onetimepass library: Try pip3 install onetimepass\n&quot;)<br>    quit()<br><br># Constants<br>    # Replace the OTP secret file here. It should in a below format: <br>    # cat ~/scripts/.otp-secret<br>        #OTP SECRET<br>        #otp_secret=&#39;asbcddfdfkadkjadjiusdhiquhdiqsdxxx&#39;<br>    <br>OTP_CONFIG_PATH = os.path.join(os.environ[&#39;HOME&#39;], &#39;scripts&#39;, &#39;.otp-secret&#39;)<br>TIME_RANGES = range(3, 33, 3)<br><br>def check_otp_config():<br>    &quot;&quot;&quot;Check if otp_secret is properly set&quot;&quot;&quot;<br>    if not os.path.isfile(OTP_CONFIG_PATH):<br>        with open(OTP_CONFIG_PATH, &#39;w&#39;) as f:<br>            f.write(&quot;# OTP Secret\notp_secret = &#39;XXXXXXXXXXXXXX&#39;\n&quot;)<br>        print(f&quot;Could not open {OTP_CONFIG_PATH}\nA sample file was created.\n&quot;<br>              &quot;Please put your secret there&quot;)<br>        quit(1)<br><br>def get_otp_secret():<br>    &quot;&quot;&quot;Retrieve otp_secret from config file&quot;&quot;&quot;<br>    otp_secret = None  # Initialize otp_secret variable<br>    with open(OTP_CONFIG_PATH) as f:<br>        for line in f:<br>            if line.startswith(&quot;otp_secret&quot;):<br>                otp_secret = line.split(&quot;=&quot;)[1].strip().strip(&quot;&#39;&quot;)<br>                return otp_secret<br>    print(&quot;\nNo otp_secret found in the config file\n&quot;)<br>    quit(1)<br><br>def show_otp(token, time_raise, time_decimal):<br>    &quot;&quot;&quot;Display OTP token&quot;&quot;&quot;<br>    print(token.decode())<br><br>def main():<br>    &quot;&quot;&quot;Main function&quot;&quot;&quot;<br>    check_otp_config()<br>    otp_secret = get_otp_secret()<br>    otp_token = otp.get_totp(otp_secret, as_string=True)<br>    time_raise = 0<br><br>    # We need to countdown the first cycle<br>    time_decimal = int(time.strftime(&#39;%S&#39;))<br>    if time_decimal &gt; 30:<br>        time_decimal -= 30<br>    if time_decimal:<br>        time_decimal = 100 * time_decimal / 30<br><br>    show_otp(otp_token, time_raise, time_decimal)<br><br>    quit()<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=871d5ec28047" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>