sandeepk

While running your Ansible playbook, we can have the option of passing the argument from the command line. With the help of this, we define a generic playbook and use command line arguments to control the play. Let see how

Let's first start with the playbook, where we have defined the variable x is the playbook.

---
- hosts: all
  vars:
    x: 45
  tasks:
    - debug: var=x

In this playbook, we will pass the value of x from the command line arguments with the help -e “value”.

---
- hosts: all
  tasks:
    - debug: var=x
>> ansible-playbook playbook_nmae.yml -e "x=56"

Now let's write a playbook which can uninstall/install a package with the help of command line arguments.

---
- name: Install/Unistall pacakges with command line
  hosts: all
  became: 'yes'
  tasks:
    - name: 'working with {{pkg}}'
      apt:
        name: '{{pkg}}'
        state: '{{req_state}}'

Now, from the command line, we can pass the package name and state of the package.

>>ansible-playbook playbook_name.yml -e  "pkg=nginx req_state=present"

>>ansible-playbook playbook_name.yml -e  "pkg=nginx req_state=absent"

Cheers!

#100DaysToOffload #Ansible

Inventory(Hosts) file contains the information of the Ansible nodes. We can group based on our use case like web servers, DB servers and uses these groups to execute commands on them. But you have to create a group in the inventory file, let see how to do that.

[webserver]
IP_ADDRESS_1
IP_ADDRESS_2
IP_ADDRESS_3

[webserverduck]
IP_ADDRESS_1

[dbserver]
IP_ADDRESS_1
IP_ADDRESS_2
IP_ADDRESS_3

[clientduck:children]
dbserver
webserverduck

You can even assign variable nodes or group wise in inventory file

[webserverduck:vars]
ansible_connection=ssh
ansible_user=myotheruser
gather_fact=no


[dbserver]
IP_ADDRESS_1 ansible_user=myuser
IP_ADDRESS_2
IP_ADDRESS_3

Cheers!

#100DaysToOffload #Ansible #dgplug

Ansible Architecture

What is Ansible Ansible is a simple IT automation tool that make application and system easier to deploy and maintain. With the help of Ansible, you can automate task like network configuration, code deployment and cloud management. Ansible is an agent less system, which means that you don't need to install any software on the client system.

Inventory Inventory file is the one which contains the lists of the host servers on which Ansible works, it can be the IP Addresses, Domain name ...

Hosts It contains the IP addresses or Fully qualified domain name of the node servers which you want to configure.

Ansible.cfg This file contains the configuration for the Ansible, like the path of the Inventory file and values for the default variable in the Ansible

Ansible Nodes Ansible's nodes are the client system on which we want to execute, deploy or maintain the code(servers on which we want to work).

Ansible Engine Ansible engine/master/controller from which we manage all the server nodes.

Cheers!

#100DaysToOffload #Ansible #dgplug

Able to sneak out sometime today to watch this talk by Brain Chesky. Overall the talk is good worth spending your time on.

Brian Chesky on Launching Airbnb and the Challenges of Scale

My Notes

  • Find > What inside you have that no one else have
  • If you are not passionate about the thing you are doing, you will quit when the hard days come or thing go south
  • First best thing is to watch these all talks, but the second-best thing you can do is go out and build things by yourself.
  • Never wait to learn things before starting, just start and you will learn during the process.

Cheers!

#100DaysToOffload

I came to see this warning a few days back when I was seeing the git diff of a file in reaction to this I open the file and hit enter at the last line to my surprise the warning remains still the same.

What is a new line? The new line is usually \n, aka (CR or CRLF) at the end of the file. It's helpful to identify the last byte of the file.

Why it is good to have a new line at the end of the file?

Quoting from here

A source file that is not empty shall end in a new-line character, which shall not be immediately preceded by a backslash character. Since this is a “shall” clause, we must emit a diagnostic message for a violation of this rule.

So, it turns out that, according to POSIX, every text file should end with a \n, or “newline” (not “a new line”) character. This acts as the eol, or the “end of line” character. It is a line “terminator”.

It's helpful to identify the end of file.

How to automatically add one with your favorite editor?

In your favorite editor, you can add newline automatically like this.

  • Emacs : Add (setq require-final-newline t) to your .emacs or .emacs.d/init.el file.
  • VS Code: set “files.insertFinalNewline”: true

#100DaysToOffload #POSIX #Git #NoNewLine

It is an abstract machine that can be in exactly one of a finite number of states at any given time. A state machine is just a specification of how to handle events. It consists of a set of states, one of which is the current state. For each state, we list the events that are significant to that state. For each of those events, we define the new current state of the system.

Let see with an example

Devops:
Stable (DB down) --> Critical (DB up) --> Stable (N/w down) --> Warning (N/w up) --> Stable

FSM

Here we have defined the states Stable, Critical, Warning and events DB down, DB up, and N/W down. In this case, we have a stable state so whenever our database goes down or the network goes down the state changes to critical/warning. We can link some logic with these states to perform any action for transition.

This logic can help in designing a good program around a problem statement that will have less coupled code and easy to maintain. Cheers!

#100DaysToOffload

Git is a version control tool, that helps to track changes in the project. We will discuss a few useful commands which are handy to know while working with the git

Creating a branch with no commits on it

>>> git checkout --orphan <branch_name>
>>> git log
fatal: your current branch '<branch_name>' does not have any commits yet

Remove stale branches In your local, if you have branches that are removed in the remote then you can use the prune command to delete those branches in local also.

>>> git remote prune origin

To pick a commit from another branch If you want to pick a commit from other branches into your current branch you can use the cherry-pick command and -x for when recording the commit, append a line that says “(cherry picked from commit ...)” to the original commit message to indicate which commit this change was cherry-picked from.

>>> git cherry-pick -x <commit SHA1>

To view commits that are not pushed yet

>>> git log @{u}..

Run previous command In Git, we are also switching from one branch to the other. Typing the name, again and again, is tedious. You can use - with the Git command, to save your self from typing the name again

>>>  randomos git:(useless_dict) git checkout add_numbers
Switched to branch 'add_numbers'
Your branch is up-to-date with 'origin/add_numbers'.
>>>  randomos git:(add_numbers) git checkout -
Switched to branch 'useless_dict'
Your branch is up-to-date with 'origin/useless_dict'.

If you have any Git commands which you feel are worth sharing and can save some time. Please do share.

Cheers!

#100DaysToOffload #Git #VersionControl

This Sunday, I attended the workshop on Creating Python modules using Rust by Kushal Das. The workshop started at 0900 UTC 18th April on Twitch.

The GitHub repo we follow along with the workshop can be found over here. Learned many new things in the workshop where we go through

  • Hello World example
  • User passed arguments
  • Exception Handling
  • File I/O
  • System Interaction (Process, System Information)

Enjoyed my time while going through these examples and like the way Kushal has arranged all the examples branch wise.

Cheers!

Useful Links – https://github.com/kushaldas/workshops/issues/2https://kushaldas.in/

#100DaysToOffload #Python #Rust

Today we are gone to talk about the Foreign Key which is used to establish a many-to-one relationship and different args which can be passed.

Syntax to define a Foreign key relationship

from django.db import models

class GSTRate(models.Model):
    # ...
    pass

class PurchaseOrder(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE)

Different args for the Foreign Key

  • on_delete
  • limitchoicesto
  • related_name
  • relatedqueryname
  • to_field
  • db_constraints

on_delete This args handle the process, of what to do if the reference keys are deleted, we have three options – CASCADE: It deletes the objects contains the Foreign key – PROTECT: It prevents the deletion of the referenced object by raising ProtectedError – RESTRICT: Introduced in Django 3.1, It only deletes the object, if another references object is being deleted in the same operation, but with CASCADE flow otherwise raise RestrictedError

from django.db import models

class GSTRate(models.Model):
    # ...
    pass

class PurchaseOrder(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE)

limit_choices_to This is helpful in the form rendering to restrict the option for the reference field. The limited choice can either be a dict, Q object or a callable that return dict or Q object

from django.db import models

class GSTRate(models.Model):
    # ...
    pass

class PurchaseOrder(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE, limit_choices_to={'tax_type': 'gst'},)
# here we only show the tax of type GST only.

related_name It's the name that can be used for the reverse or backward reference while querying. You can also stop the backward relation by assigning + in related_name.


class GSTRate(models.Model):
    # ...
    pass

class PurchaseOrder(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE, related_name='+',) # IN this case GSTRate cannot backward realte to the Purchase Order obejct.

class PurchaseOrder(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE, related_name='invoice')

# here you can refer to Invoice inside GSTRate query by the related name.
GSTRate.objects.filter(invoice_id=1232)

related_query_name It has the same value as the related_name, unless not specified explicitly. If it is defined then you have to use that name while querying


class GSTRate(models.Model):
    # ...
    pass

class OrderConfirmation(models.Model):
    gst = models.ForeignKey(GSTRate, on_delete=models.CASCADE, related_name='order_confirmation', related_query_name='oc')

# here you can refer to Invoice inside GSTRate query by the related name.
GSTRate.objects.filter(oc_id=112)

to_field This is helpful in the case where you want to refer other the primary key of the modal, but the condition whatever key you referred it should be unique=True

db_constraints This is used to create a constraint at the database level, by default value is true and if the user sets the value to False, then accessing a related object that doesn’t exist will raise its DoesNotExist exception.

Conclusion These args are handy which gives us the possibilities of implementing the additional constraint and functionality to query data in the Django ORM query language.

Cheers!

#100DaysToOffload #Python#Django

I have started my financial journaling a few months back, and I am happy with the simplicity and freedom that I can have with the use of Emacs, ledger-mode, and Ledger. I have written about it before, you can check that here. Today we will talk about report generation.

So, for this post, we will be using this mock data for generating balance and monthly expense reports. Create a new file with the name ledger.dat and paste the data in it given below.

2021/02/14 * Dinner-Party
    Expenses:Food:Party                            1500
    Assets:Bank:Checking

2021/02/21 * Lunch-Party
    Expenses:Food:Party                           1600
    Assets:Bank:Checking

2021/02/22 * Home
    Expenses:Home                                   3000
    Assets:Bank:Checking                       3000
    Assets:Investment:Stocks                 180000
    Assets:Bank:Checking

2021/02/25 * Amazon Shopping
    Expenses:Self                                60000
    Assets:Bank:Checking

So let's start with the balance report, open the Emacs with the ledger.dat file, then press C-c C-o C-r. The buffer will ask the report name type in bal and hit enter, you will get the report.

Report: bal
Command: ledger -f /home/ledger.dat bal

              -66100  Assets
             -246100    Bank:Checking
              180000    Investment:Stocks
	       66100  Expenses
		3100    Food:Party
		3000    Home
	       60000    Self
--------------------
                   0

There is another way which I use mainly is from the terminal itself.

>>>  ledger balance -f ledger.dat
              -66100  Assets
             -246100    Bank:Checking
              180000    Investment:Stocks
               66100  Expenses
                3100    Food:Party
                3000    Home
               60000    Self
--------------------
                   0

If you only want to see a particular type of expense, you can easily do so by

# here we are only seeing the expenses
>>> ledger balance -f ledger.dat Expenses
               66100  Expenses
                3100    Food:Party
                3000    Home
               60000    Self
--------------------
               66100

# here we are seeing the Checking account
>>>ledger balance -f dummy.dat Checking
             -246100  Assets:Bank:Checking

We can also see month-wise expense, for that, I have changed the date in the file ledger.dat.

>>> ledger -M --period-sort "(amount)" reg ^expenses -f ledger.dat
21-Jan-01 - 21-Jan-31                             Expenses:Food:Party                                              1600                    1600
21-Feb-01 - 21-Feb-28                             Expenses:Food:Party                                              1500                    3100
                                                  Expenses:Self                                                   60000                   63100
21-Mar-01 - 21-Mar-31                             Expenses:Home                                                    3000                   66100

Reports help to see your money flow, calculate the expenses and savings.

Cheers!

#100DaysToOffLoad #Emacs #LedgerMode #Ledger