Sunday, May 10, 2020

Create user using vault


[ansible@ansiblemaster playbooks]$ cat inventory


[webserver]


web1.mylinuxfriends.blogspot.com



[dbserver]


db1.mylinuxfriends.blogspot.com



[production]


db1.mylinuxfriends.blogspot.com


web1.mylinuxfriends.blogspot.com



[ansible@ansiblemaster playbooks]$



ansible@ansiblemaster vars]$ pwd


/home/ansible/playbooks/vars




NOTE: Give password and remember this as we will use this to run playbook



[ansible@ansiblemaster vars]$ ansible-vault create ../vars/mysecret.yml


New Vault password:


Confirm New Vault password:




newusers:             <========== put following content to mysecret.yml


  - name: myuser1

    pw: welcome@1


  - name: myuser2

    pw: welcome@2




[ansible@ansiblemaster vars]$ ansible-vault view mysecret.yml


Vault password:


newusers:


  - name: myuser1

    pw: welcome@1


  - name: myuser2

    pw: welcome@2




[ansible@ansiblemaster playbooks]$




=====================================================================================================
Now create main yml file useradd.yml, that will use mysecret.yml to create users on webserver group
=====================================================================================================


[ansible@ansiblemaster playbooks]$ vi useradd.yml
---
- name: creating user on webserver.


  hosts: webserver

  remote_user: ansible

  become: yes

  vars_files:
      - vars/mysecret.yml

  tasks:

    - name: creating users using vars/mysecrete.yml

      user:

          name: "{{ item.name }}"
          password: "{{ item.pw | password_hash('sha512') }}"


      with_items: "{{ newusers }}"


[ansible@ansiblemaster playbooks]$





===============================================
Now let`s check syntax of our createuser.yml
===============================================



[ansible@ansiblemaster playbooks]$ ansible-playbook useradd.yml --syntax-check --playbookvault-password-file=playbookvault-pass <---------- give playbookvault-pass i.e welcome in our case

playbook: useradd.yml


[ansible@ansiblemaster playbooks]$




=========================================================================================
Now instead of giving password at command-line again and again we can define it in file
=========================================================================================


[ansible@ansiblemaster playbooks]$ pwd


/home/ansible/playbooks



[ansible@ansiblemaster playbooks]$ echo welcome > playbookvault-pass



[ansible@ansiblemaster playbooks]$ chmod 0400 playbookvault-pass



[ansible@ansiblemaster playbooks]$ ll playbookvault-pass


-r--------. 1 ansible wheel 8 May 10 19:39 playbookvault-pass




=============================================================================
For your reference following are the list of files created in this example
=============================================================================



[ansible@ansiblemaster playbooks]$ tree
.
├── ansible.cfg

├── useradd.yml

├── inventory

├── vars

│   └── mysecret.yml

└── playbookvault-pass


1 directory, 5 files


[ansible@ansiblemaster playbooks]$



===============================================================
Vault password in playbookvault-pass now lets run our playbook
===============================================================


[ansible@ansiblemaster playbooks]$ ansible-playbook useradd.yml -v --vault-password-file=playbookvault-pass  

Using /home/ansible/playbooks/ansible.cfg as config file


PLAY [creating user on webserver.] ************************************************************************************************************************************


TASK [Gathering Facts] ************************************************************************************************************************************************

ok: [web1.mylinuxfriends.blogspot.com]


TASK [creating users using vars/mysecrete.yml] ************************************************************************************************************************

changed: [web1.mylinuxfriends.blogspot.com] => (item={u'name': u'web1', u'pw': u'welcome@1'}) => {"changed": true, "comment": "", "createhome": true, "group": 3003, "home": "/home/web1", "item": {"name": "web1", "pw": "welcome@1"}, "name": "myuser1", "password": "NOT_LOGGING_PASSWORD", "shell": "/bin/bash", "state": "present", "system": false, "uid": 3003}

changed: [web1.mylinuxfriends.blogspot.com] => (item={u'name': u'myuser2', u'pw': u'welcome@2'}) => {"changed": true, "comment": "", "createhome": true, "group": 3004, "home": "/home/myuser2", "item": {"name": "myuser2", "pw": "welcome@2"}, "name": "myuser2", "password": "NOT_LOGGING_PASSWORD", "shell": "/bin/bash", "state": "present", "system": false, "uid": 3004}


PLAY RECAP ************************************************************************************************************************************************************


web1.mylinuxfriends.blogspot.com : ok=2    changed=1    unreachable=0    failed=0



=================================================================================================================================
Let`s try to login on web1.mylinuxfriends.blogspot.com with myuser2 user and give  password as welcome@2, that we have defined in mysecret.yml
=================================================================================================================================


[ansible@ansiblemaster playbooks]$


[ansible@ansiblemaster playbooks]$ ssh myuser2@web1.mylinuxfriends.blogspot.com


myuser2@web1.mylinuxfriends.blogspot.com's password: welcome@2

This system is web1 server of  mylinuxfriends.blogspot.com

Today date is : 2020-04-26


You can drop email to anuj@mylinuxfriends.blogspot.com in case any query.


Thanks......!


[myuser2@web1 ~]$



Sunday, May 3, 2020

Ansible Vault

Ansible Vault allows users to encrypt values and data structures within Ansible, using ansible vault you can secure any sensitive data that is necessary to successfully run Ansible plays and keep it secure it from publicly visible, like passwords or private keys. Ansible automatically decrypts vault-encrypted content at runtime when the key is provided.

Lets see how we can use ANSIBLE VAULT, will demonstrate how to use Ansible Vault, i will try to explain some common ansible vault operations.


[ansible@ansiblemaster ~]$ ansible-playbook motd.yml

PLAY [playbook to check filesystem.] **********************************************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************************************************************
ok: [db1]
ok: [web1]

TASK [command] ********************************************************************************************************************************************************
changed: [db1]
changed: [web1]

TASK [filesystem status] **********************************************************************************************************************************************
ok: [web1] => {
    "msg": [
        "This system is web1 server of  mylinuxfriends.blogspot.com ",
        "Today date is : 2020-04-26",
        "",
        "You can drop email to anuj@mylinuxfriends.blogspot.com in case any query.",
        "Thanks......!"
    ]
}
ok: [db1] => {
    "msg": [
        "This server has Total memory: 1014 MBs.",
        "free memory on this system is : 760 MBs.",
        "",
        "Note: if you see any memory issue email: ansible@localhost"
    ]
}

PLAY RECAP ************************************************************************************************************************************************************
db1                        : ok=3    changed=1    unreachable=0    failed=0  
web1                       : ok=3    changed=1    unreachable=0    failed=0  

[ansible@ansiblemaster ~]$
[ansible@ansiblemaster ~]$
[ansible@ansiblemaster ~]$ ansible-vault encrypt motd.yml
New Vault password:
Confirm New Vault password:
Encryption successful
[ansible@ansiblemaster ~]$
[ansible@ansiblemaster ~]$
[ansible@ansiblemaster ~]$ cat motd.yml
$ANSIBLE_VAULT;1.1;AES256
35623139363930313035646263653432353362346238663034323335666430633263316131383534
6638646230666534303966303736353231636139353665660a353939353265333037303265636636
38663839333831373836653832653763393161333833333132353837636565633461623462666631
3234666465633365620a633335663866653261663730656161336237393833336166326632373363
61333464643039393462623636393065633036373839653435333837613737336564383836353866
37383264653538643335633032356337623866356230303965303064626662353431653638633132
34336566636262326638646461306361363166366361363032623934326135323031366163373431
36633431653965336437373138336361373261303139363736316362656265313766356631343565
33333539386430626135323536633430613166326365303639656335306464643733643634353763
31313736633864653137343739313637323932393031646537393762336433616237633362643236
63663866333462373566343738363338383930656635306531356431383730303234636265313766
65316339356261636232643132613131393030333630316464373332626363663566653339336537
65313834373130343063396463373437363766373330653832346434316362366366336235333132
65353961653537313637386439323061623238626662373562353030366261383136643338393364
32623936613133316433333964386165366537303132613830306433326463346335303762396633
35373961616639303035613565323039353632326562383631623438653731613962633438343165
32633634653566623534363666616138666539336164363038303466633839326230633861383631
63323132353537373930366133633331633738616137303165633335323334366263323065383836
37373662343138653731323266363162646131663964653131666238613137663031373731326338
38343034663934356365653763666435313861393265643763623762306166383533643237376261
34616363386434393032313561373438356637323638613638356332623430636434346662316361
64333831333634343330633466323031316664616435313637663564303438373363346661336562
61616162613937653838356332663834346332363061376666623537333931383033303662663336
61323134383235643339373238363739343639663562363731333365363538323436336433316135
34643535306431383631663736306330323462346333353837386436376634313635343736316139
61323561636262666235333839313565333563623466333834633934326631626565303931326464
61366266306634313462616432363638363766626636343262616439386237326539613064663265
61653835333638396239346635316533626361336436383532653132326633623938326335393435
6662
[ansible@ansiblemaster ~]$
[ansible@ansiblemaster ~]$ ansible-vault view motd.yml
Vault password:                                              <============= lets give incorrect password, and see it should give error for Decryption fail
ERROR! Decryption failed (no vault secrets would found that could decrypt) for motd.yml



==================================
Viewing an encrypted file
==================================

[ansible@ansiblemaster ~]$ ansible-vault view motd.yml    <=========== now give correct password, that we have given at "ansible-vault encrypt motd.yml"
Vault password:
---
- name: playbook to check filesystem.
  hosts: all
  tasks:
    - name:
      command: cat '/etc/motd'
      register: fs_out
      when:
        - (ansible_os_family == "RedHat" and ansible_distribution_major_version == "7")
        - ansible_distribution == "CentOS"
#     when: (ansible_facts['distribution'] == "CentOS" and ansible_facts['distribution_major_version'] == "7")
    - name: "filesystem status"
      debug:
        msg: "{{ fs_out.stdout.split('\n') }}"



======================================================================================
You can run you playbook with two method

1.)running a playbook using valut password at run time by using --ask-vault-pass
2.) decrypt your playbook and then run
======================================================================================


******run playbook by METHOD-1 that is  --ask-pass

[ansible@ansiblemaster ~]$ ansible-playbook motd.yml --ask-vault-pass
Vault password:

PLAY [playbook to check filesystem.] **********************************************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************************************************************
ok: [web1]
ok: [db1]

TASK [command] ********************************************************************************************************************************************************
changed: [db1]
changed: [web1]

TASK [filesystem status] **********************************************************************************************************************************************
ok: [web1] => {
    "msg": [
        "This system is web1 server of  mylinuxfriends.blogspot.com ",
        "Today date is : 2020-04-26",
        "",
        "You can drop email to anuj@mylinuxfriends.blogspot.com in case any query.",
        "Thanks......!"
    ]
}
ok: [db1] => {
    "msg": [
        "This server has Total memory: 1014 MBs.",
        "free memory on this system is : 760 MBs.",
        "",
        "Note: if you see any memory issue email: ansible@localhost"
    ]
}

PLAY RECAP ************************************************************************************************************************************************************
db1                        : ok=3    changed=1    unreachable=0    failed=0  
web1                       : ok=3    changed=1    unreachable=0    failed=0  

[ansible@ansiblemaster ~]$


[ansible@ansiblemaster ~]$


********* Run playbook with METHOD-2: Decrypting motd.yml playbook and then run



[ansible@ansiblemaster ~]$ ansible-vault decrypt motd.yml
Vault password:
Decryption successful
[ansible@ansiblemaster ~]$ less motd.yml
[ansible@ansiblemaster ~]$ cat motd.yml
---
- name: playbook to check filesystem.
  hosts: all
  tasks:
    - name:
      command: cat '/etc/motd'
      register: fs_out
      when:
        - (ansible_os_family == "RedHat" and ansible_distribution_major_version == "7")
        - ansible_distribution == "CentOS"
#     when: (ansible_facts['distribution'] == "CentOS" and ansible_facts['distribution_major_version'] == "7")
    - name: "filesystem status"
      debug:
        msg: "{{ fs_out.stdout.split('\n') }}"
[ansible@ansiblemaster ~]$ 



[ansible@ansiblemaster ~]$ ansible-playbook motd.yml

PLAY [playbook to check filesystem.] **********************************************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************************************************************
ok: [db1]
ok: [web1]

TASK [command] ********************************************************************************************************************************************************
changed: [db1]
changed: [web1]

TASK [filesystem status] **********************************************************************************************************************************************
ok: [web1] => {
    "msg": [
        "This system is web1 server of  mylinuxfriends.blogspot.com ",
        "Today date is : 2020-04-26",
        "",
        "You can drop email to anuj@mylinuxfriends.blogspot.com in case any query.",
        "Thanks......!"
    ]
}
ok: [db1] => {
    "msg": [
        "This server has Total memory: 1014 MBs.",
        "free memory on this system is : 760 MBs.",
        "",
        "Note: if you see any memory issue email: ansible@localhost"
    ]
}

PLAY RECAP ************************************************************************************************************************************************************
db1                        : ok=3    changed=1    unreachable=0    failed=0  
web1                       : ok=3    changed=1    unreachable=0    failed=0  

[ansible@ansiblemaster ~]$






==========================================================
How to edit file encrypted with ansible-vault password
==========================================================
[ansible@ansiblemaster ~]$
[ansible@ansiblemaster ~]$ ansible-vault edit motd.yml
Vault password:
[ansible@ansiblemaster ~]$


==========================================================
How to change vault password ansible-vault using ansible-vault rekey
==========================================================

[ansible@ansiblemaster ~]$ ansible-vault rekey motd.yml
Vault password:
New Vault password:
Confirm New Vault password:
Rekey successful

[ansible@ansiblemaster ~]$ ansible-vault view motd.yml
Vault password:           <======let`s give old password & that should not work
ERROR! Decryption failed (no vault secrets would found that could decrypt) for motd.yml
[ansible@ansiblemaster ~]$
[ansible@ansiblemaster ~]$ ansible-vault view motd.yml  <===Now give new password
Vault password:
---
- name: playbook to check filesystem.
  hosts: all
  tasks:
    - name:
      command: cat '/etc/motd'
      register: fs_out
      when:
        - (ansible_os_family == "RedHat" and ansible_distribution_major_version == "7")
        - ansible_distribution == "CentOS"
#     when: (ansible_facts['distribution'] == "CentOS" and ansible_facts['distribution_major_version'] == "7")
    - name: "filesystem status"
      debug:
        msg: "{{ fs_out.stdout.split('\n') }}"
[ansible@ansiblemaster ~]$
[ansible@ansiblemaster ~]$

===================================================
Storing decrypted output is somefile which we can use as needed
===================================================

[ansible@ansiblemaster ~]$ ansible-vault decrypt motd.yml --output=motd.yml-decrypted
Vault password:
Decryption successful
[ansible@ansiblemaster ~]$

[ansible@ansiblemaster ~]$ cat motd.yml-decrypted
---
- name: playbook to check filesystem.
  hosts: all
  tasks:
    - name:
      command: cat '/etc/motd'
      register: fs_out
      when:
        - (ansible_os_family == "RedHat" and ansible_distribution_major_version == "7")
        - ansible_distribution == "CentOS"
#     when: (ansible_facts['distribution'] == "CentOS" and ansible_facts['distribution_major_version'] == "7")
    - name: "filesystem status"
      debug:
        msg: "{{ fs_out.stdout.split('\n') }}"
[ansible@ansiblemaster ~]$
[ansible@ansiblemaster ~]$







Sunday, April 26, 2020

Working with Ansible Roles

As you know in every organisation, we have diffrent envoirment, such as PRODUCTION, DEVLOPMENT, DATABASE and WEB etc., so this ansible roles make your task easy to organise your diffrent playbook and other data which required for playbook,, such as templated, file vars etc.

Using Roles make larger projects are more manageable,Ansible roles allow you to organize their playbooks into smaller playbooks and files.


Following is Ansible role's directory structure.
==============================
[ansible@ansiblemaster roles]$ tree motd/
motd/
├── defaults
│   └── main.yml
├── files
├── handlers
│   └── main.yml
├── meta
│   └── main.yml
├── README.md
├── tasks
│   └── main.yml
├── templates
├── tests
│   ├── inventory
│   └── test.yml
└── vars
    └── main.yml


defaults: The main.yml file in this directory contains the default values of role variables and it can be overwritten when we use the role in playbook.

files:  Static files that are referenced by role tasks are stored in this directory.

handlers: This directory contains the role's handler definitions in main.yml  file.

meta:  This directory contains information about the role, including author, license, platforms, and optional role dependencies under main.yml file.

tasks: This directory contains the role's task definitions in main.yml file.

templates:  Jinja2 templates that are referenced by role tasks stored in this directory.

tests:     test.yml playbook that can be used to test the role.

vars:     This directory defines the role's variable values, in main.yml file


[ansible@ansiblemaster roles]$ pwd
/home/ansible/roles
[ansible@ansiblemaster roles]$
[ansible@ansiblemaster roles]$ cat ../inventory
[webserver]
web1

[dbserver]
db1
[ansible@ansiblemaster roles]$


[ansible@ansiblemaster ~]$ mkdir roles


[ansible@ansiblemaster ~]$ cd roles/


Note: You can create ansible role directory structure  manually or let ansible do this for you using "ansible-galaxy init < role name> "  as mentioned below.
 
[ansible@ansiblemaster roles]$ ansible-galaxy init motd
- motd was created successfully


[ansible@ansiblemaster roles]$ tree motd/
motd/
├── defaults
│   └── main.yml
├── files
├── handlers
│   └── main.yml
├── meta
│   └── main.yml
├── README.md
├── tasks
│   └── main.yml
├── templates
├── tests
│   ├── inventory
│   └── test.yml
└── vars
    └── main.yml

8 directories, 8 files
[ansible@ansiblemaster roles]$



===================================
Let`s create template for motd role:
===================================

[ansible@ansiblemaster roles]$ vi  motd/templates/motd.j2
This system is {{ ansible_hostname }} server of  mylinuxfriends.blogspot.com
Today date is : {{ ansible_date_time.date }}

You can drop email to {{ system_owner }} in case any query.
Thanks......!

======================================================================================
Create default value for the role under default/main.yml  directory of motd role
=====================================================================================

[ansible@ansiblemaster roles]$ vi motd/defaults/main.yml
# defaults file for motd
---
system_owner: anuj@mylinuxfriends.blogspot.com
[ansible@ansiblemaster roles]$


======================================================================================
Now let`s use this role in playbook, create playbook motd.playbook.yml
======================================================================================

[ansible@ansiblemaster roles]$ vi motd.playbook.yml
---
- name: use motd role playbook
  hosts: all
  user: ansible
  become: true
  roles:
    - motd

============================================================
               Lets check current contents of /etc/motd of managed hosts
============================================================


[ansible@ansiblemaster roles]$ ansible all -i  ../inventory -m command -a 'cat /etc/motd'
db1 | SUCCESS | rc=0 >>
This server has Total memory: 1014 MBs.
free memory on this system is : 760 MBs.

Note: if you see any memory issue email: ansible@localhost

web1 | SUCCESS | rc=0 >>


[ansible@ansiblemaster roles]$



======================================
Now lets check syntex for motd.playbook.ymk
 =====================================

[ansible@ansiblemaster roles]$ ansible-playbook -l webserver -i ../inventory motd.playbook.yml -C

PLAY [use motd role playbook] *****************************************************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************************************************************
ok: [web1]

TASK [motd : updating /etc/motd on managed node] **********************************************************************************************************************
changed: [web1]

PLAY RECAP ************************************************************************************************************************************************************
web1                       : ok=2    changed=1    unreachable=0    failed=0 



================================ 
Lets execute playbook
================================
[ansible@ansiblemaster roles]$ ansible-playbook -l webserver -i ../inventory motd.playbook.yml -vv
ansible-playbook 2.4.2.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/home/ansible/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /bin/ansible-playbook
  python version = 2.7.5 (default, Aug  7 2019, 00:51:29) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)]
Using /etc/ansible/ansible.cfg as config file

PLAYBOOK: motd.playbook.yml *******************************************************************************************************************************************
1 plays in motd.playbook.yml

PLAY [use motd role playbook] *****************************************************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************************************************************
ok: [web1]
META: ran handlers

TASK [motd : updating /etc/motd on managed node] **********************************************************************************************************************
task path: /home/ansible/roles/motd/tasks/main.yml:4
changed: [web1] => {"changed": true, "checksum": "bfdfda31a068005d18e7c70a7838e0a425fb194a", "dest": "/etc/motd", "gid": 0, "group": "root", "md5sum": "5cbf58f3aa0bd915548f2606d9cbea11", "mode": "0444", "owner": "root", "secontext": "system_u:object_r:etc_t:s0", "size": 158, "src": "/home/ansible/.ansible/tmp/ansible-tmp-1587895613.12-157428397814000/source", "state": "file", "uid": 0}
META: ran handlers
META: ran handlers

PLAY RECAP ************************************************************************************************************************************************************
web1                       : ok=2    changed=1    unreachable=0    failed=0  

[ansible@ansiblemaster roles]$



=====================================================================================
After execution of our playbook, Lets check contents of /etc/motd of managed hosts
=====================================================================================

[ansible@ansiblemaster roles]$ ansible webserver  -i ../inventory -m command -a 'cat /etc/motd'
web1 | SUCCESS | rc=0 >>
This system is web1 server of  mylinuxfriends.blogspot.com
Today date is : 2020-04-26

You can drop email to anuj@mylinuxfriends.blogspot.com in case any query.
Thanks......!



[ansible@ansiblemaster roles]$
[ansible@ansiblemaster roles]$ ansible dbserver  -i ../inventory -m command -a 'cat /etc/motd'
db1 | SUCCESS | rc=0 >>
This server has Total memory: 1014 MBs.
free memory on this system is : 760 MBs.

Note: if you see any memory issue email: ansible@localhost

[ansible@ansiblemaster roles]$


   

Tuesday, April 21, 2020

Ansible jinja2 template

How to create ansible jinja2 template and use in playbook
======================================

Ansible uses the Jinja2 template to modify files before they are distributed to managed hosts, it is preferable to avoid modifying configuration files through logic in templates and  templates can be useful when systems need to have slightly modified versions of the same file.

Following is tree structure of our jijna2 template, that we will use to create and use template.



Let`s gather some facts it from setup module, and we will use it in jinja template
==================================================

 [ansible@ansiblemaster templates]$ ansible localhost -m setup | grep -i ansible_distribution
        "ansible_distribution": "CentOS",
        "ansible_distribution_file_parsed": true,
        "ansible_distribution_file_path": "/etc/redhat-release",
        "ansible_distribution_file_variety": "RedHat",
        "ansible_distribution_major_version": "7",
        "ansible_distribution_release": "Core",
        "ansible_distribution_version": "7.7.1908",


 [ansible@ansiblemaster templates]$ ansible localhost -m setup | grep -i ansible_distribution_version
        "ansible_distribution_version": "7.7.1908",

[ansible@ansiblemaster templates]$

[ansible@ansiblemaster templates]$ ansible localhost -m setup | grep -i ansible_architecture
        "ansible_architecture": "x86_64",

[ansible@ansiblemaster templates]$

[ansible@ansiblemaster templates]$



1.) [ansible@ansiblemaster ~]$  cd templates
[ansible@ansiblemaster templates]$


[ansible@ansiblemaster templates]$  vi motd-facts.j2

This system is based on {{ ansible_distribution }} {{ ansible_distribution_version }} deployed on a  {{ ansible_architecture }} architecture.

:wq!

2.)  [ansible@ansiblemaster templates]$ cat playbook.yml
---
- hosts: all
  tasks:
    - template:
        src: motd-facts.j2
        dest: /etc/motd
        owner: root
        group: root
        mode: 0644

[ansible@ansiblemaster templates]$


3.) Now let`s  see whats motd showing for all managed hosts, run adhoc command.

 [ansible@ansiblemaster templates]$ ansible all -m command -a 'cat /etc/motd'
db1 | SUCCESS | rc=0 >>
db1 192.168.122.180 52:54:00:cf:9c:08 2

web1 | SUCCESS | rc=0 >>
web1 192.168.122.188 52:54:00:66:0f:09 1

4.) lets check syntax of current playbook  and then will run it if no issue found.

[ansible@ansiblemaster templates]$ ansible-playbook playbook.yml --syntax-check

playbook: playbook.yml

5.) Now run our playbook with jinja2 template

 [ansible@ansiblemaster templates]$ ansible-playbook playbook.yml -vv -b
ansible-playbook 2.4.2.0
  config file = /home/ansible/templates/ansible.cfg
  configured module search path = [u'/home/ansible/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /bin/ansible-playbook
  python version = 2.7.5 (default, Aug  7 2019, 00:51:29) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)]
Using /home/ansible/templates/ansible.cfg as config file

PLAYBOOK: playbook.yml ************************************************************************************************************************************************
1 plays in playbook.yml

PLAY [all] ************************************************************************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************************************************************
ok: [db1]
ok: [web1]
META: ran handlers

TASK [template] *******************************************************************************************************************************************************
task path: /home/ansible/templates/playbook.yml:4
changed: [db1] => {"changed": true, "checksum": "39df069d58782975273f42569700e369bd1b66ee", "dest": "/etc/motd", "gid": 0, "group": "root", "md5sum": "04e8d49e92ec67834a73d1c1b2dff83c", "mode": "0644", "owner": "root", "secontext": "system_u:object_r:etc_t:s0", "size": 76, "src": "/home/ansible/.ansible/tmp/ansible-tmp-1587468294.96-1416932211518/source", "state": "file", "uid": 0}
changed: [web1] => {"changed": true, "checksum": "39df069d58782975273f42569700e369bd1b66ee", "dest": "/etc/motd", "gid": 0, "group": "root", "md5sum": "04e8d49e92ec67834a73d1c1b2dff83c", "mode": "0644", "owner": "root", "secontext": "system_u:object_r:etc_t:s0", "size": 76, "src": "/home/ansible/.ansible/tmp/ansible-tmp-1587468294.95-57618716391126/source", "state": "file", "uid": 0}
META: ran handlers
META: ran handlers

PLAY RECAP ************************************************************************************************************************************************************
db1                        : ok=2    changed=1    unreachable=0    failed=0 
web1                       : ok=2    changed=1    unreachable=0    failed=0 

[ansible@ansiblemaster templates]$


[ansible@ansiblemaster templates]$


[ansible@ansiblemaster templates]$

[ansible@ansiblemaster ~]$ tree templates/
templates/
├── ansible.cfg
├── inventory
├── motd-facts.j2
└── playbook.yml

0 directories, 4 files
[ansible@ansiblemaster ~]$

6.) Now let`s  run adhoc command to see changes are showing in motd file of managed hosts.



[ansible@ansiblemaster templates]$ ansible all -m command -a 'cat /etc/motd'
web1 | SUCCESS | rc=0 >>
This system is based on CentOS 7.7.1908 deployed on a  x86_64 architecture.

db1 | SUCCESS | rc=0 >>
This system is based on CentOS 7.7.1908 deployed on a  x86_64 architecture.

[ansible@ansiblemaster templates]$




==========================================
            Now lets do some more on jinja2 template
==========================================

ansible@ansiblemaster templates]$vi  motd-facts.j2
Today date is {{ ansible_date_time.date }},
system is based on {{ ansible_distribution }} with hostname {{ ansible_hostname }}
{{ ansible_distribution_version }} deployed on a  {{ ansible_architecture }} architecture.
You can ask {{ system_owner }} for access
[ansible@ansiblemaster templates]$

[ansible@ansiblemaster templates]$ vi playbook.yml
---
- hosts: all
  user: ansible
  become: true
  vars:
    system_owner: ansible@localhost
  tasks:
    - template:
        src: motd-facts.j2
        dest: /etc/motd
        owner: root
        group: root
        mode: 0644
[ansible@ansiblemaster templates]$



******** Check syntax and then run playbook ********


[ansible@ansiblemaster templates]$ ansible-playbook playbook.yml --syntax-check

playbook: playbook.yml



[ansible@ansiblemaster templates]$
[ansible@ansiblemaster templates]$

[ansible@ansiblemaster templates]$ ansible-playbook playbook.yml -C

PLAY [all] ************************************************************************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************************************************************
ok: [db1]
ok: [web1]

TASK [template] *******************************************************************************************************************************************************
changed: [web1]
changed: [db1]

PLAY RECAP ************************************************************************************************************************************************************
db1                        : ok=2    changed=1    unreachable=0    failed=0  
web1                       : ok=2    changed=1    unreachable=0    failed=0  

[ansible@ansiblemaster templates]$



******** RUN playbook as no error reported ********

 ansible@ansiblemaster templates]$ ansible-playbook playbook.yml -v
Using /home/ansible/templates/ansible.cfg as config file

PLAY [all] ************************************************************************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************************************************************
ok: [web1]
ok: [db1]

TASK [template] *******************************************************************************************************************************************************
changed: [web1] => {"changed": true, "checksum": "d1c17b727e137320f2e0883c5023eec114d200b1", "dest": "/etc/motd", "gid": 0, "group": "root", "md5sum": "eb738f69de06acabe042739dee765d23", "mode": "0644", "owner": "root", "secontext": "system_u:object_r:etc_t:s0", "size": 158, "src": "/home/ansible/.ansible/tmp/ansible-tmp-1587469475.49-54949771310688/source", "state": "file", "uid": 0}
changed: [db1] => {"changed": true, "checksum": "8f6d3d0305a193bf274f62c2b99698df6b75a816", "dest": "/etc/motd", "gid": 0, "group": "root", "md5sum": "06e2c4fcb023acb78548bf33a77100ed", "mode": "0644", "owner": "root", "secontext": "system_u:object_r:etc_t:s0", "size": 157, "src": "/home/ansible/.ansible/tmp/ansible-tmp-1587469475.5-272023629871730/source", "state": "file", "uid": 0}

PLAY RECAP ************************************************************************************************************************************************************
db1                        : ok=2    changed=1    unreachable=0    failed=0 
web1                       : ok=2    changed=1    unreachable=0    failed=0



******* Now run adhoc command and see /etc/motd of managed hosts ********

[ansible@ansiblemaster templates]$ ansible webserver -m command -a 'cat /etc/motd'
web1 | SUCCESS | rc=0 >>
Today date is 2020-04-21,
system is based on CentOS with hostname web1
7.7.1908 deployed on a  x86_64 architecture.
You can ask ansible@localhost for access

[ansible@ansiblemaster templates]$





          ===========================================
                            
              Lets` do some more handson on  jinja2 template
        ============================================

Now lets caputure some facts that we will use in jinja2 template
===================================================================

[ansible@ansiblemaster]$ ansible localhost -m setup -a 'filter=ansible_memtotal_mb'
localhost | SUCCESS => {
    "ansible_facts": {
        "ansible_memtotal_mb": 1837
    },
    "changed": false
}
[ansible@ansiblemaster jinja2-lab]$
[ansible@ansiblemaster jinja2-lab]$ ansible localhost -m setup -a 'filter=ansible_freemem_mb'
localhost | SUCCESS => {
    "ansible_facts": {},
    "changed": false
}
[ansible@ansiblemaster]$


[ansible@ansiblemaster templates]$ mkdir jinja2-lab

[ansible@ansiblemaster jinja2-lab]$ vi motd-fact.j2  <------ create motd-fact.j2 template
This server has Total memory: {{ ansible_memtotal_mb }} MBs.
free memory on this system is : {{ ansible_memfree_mb }} MBs.

Note: if you see any memory issue email: ansible@localhost


[ansible@ansiblemaster jinja2-lab]$


[ansible@ansiblemaster jinja2-lab]$ vi playbook.yml
---
- hosts: all
  user: ansible
  become: true
  tasks:
    - template:
        src: motd-fact.j2
        dest: /etc/motd
        owner: root
        group: root
        mode: 0644
[ansible@ansiblemaster jinja2-lab]$


***** Now let`s check current message in /etc/mots on managed hosts *********


ansible@ansiblemaster jinja2-lab]$ ansible all -m command -a 'cat /etc/motd'
web1 | SUCCESS | rc=0 >>


db1 | SUCCESS | rc=0 >>



*******************************************************************************
Currently /etc/motd is empty, so now lets do syntax check for playbook 
thereafter will execute if no error reported
*******************************************************************************


ansible@ansiblemaster jinja2-lab]$ ansible-playbook playbook.yml -C

PLAY [all] ************************************************************************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************************************************************
ok: [db1]
ok: [web1]

TASK [template] *******************************************************************************************************************************************************
changed: [web1]
changed: [db1]

PLAY RECAP ************************************************************************************************************************************************************
db1                        : ok=2    changed=1    unreachable=0    failed=0  
web1                       : ok=2    changed=1    unreachable=0    failed=0  

[ansible@ansiblemaster jinja2-lab]$

[ansible@ansiblemaster jinja2-lab]$ ansible-playbook playbook.yml --syntax-check

playbook: playbook.yml
[ansible@ansiblemaster jinja2-lab]$


**************************************
playbook is good to execute,
lets execute on single group "dbserver"
 ***************************************

[ansible@ansiblemaster jinja2-lab]$ ansible-playbook -l dbserver playbook.yml -v
Using /home/ansible/templates/jinja2-lab/ansible.cfg as config file

PLAY [all] ************************************************************************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************************************************************
ok: [db1]

TASK [template] *******************************************************************************************************************************************************
changed: [db1] => {"changed": true, "checksum": "7a05cea115ae70498513822ddd99c5ce55a6e6b2", "dest": "/etc/motd", "gid": 0, "group": "root", "md5sum": "568523a8e84cb5cef937fde8375d3374", "mode": "0644", "owner": "root", "secontext": "system_u:object_r:etc_t:s0", "size": 141, "src": "/home/ansible/.ansible/tmp/ansible-tmp-1587481398.82-161512122431271/source", "state": "file", "uid": 0}

PLAY RECAP ************************************************************************************************************************************************************
db1                        : ok=2    changed=1    unreachable=0    failed=0  



****************************************************************
Now lets check motd of dbserver, its should show updated message *****************************************************************

[ansible@ansiblemaster jinja2-lab]$ ansible dbserver -m command -a 'cat /etc/motd'
db1 | SUCCESS | rc=0 >>
This server has Total memory: 1014 MBs.
free memory on this system is : 760 MBs.

Note: if you see any memory issue email: ansible@localhost


***********************************************************************
lets check motd of webserver showing new motd message or not  
***********************************************************************

[ansible@ansiblemaster jinja2-lab]$
[ansible@ansiblemaster jinja2-lab]$ ansible webserver -m command -a 'cat /etc/motd'
web1 | SUCCESS | rc=0 >>


[ansible@ansiblemaster jinja2-lab]$





kubernetes Pod Scheduling

 ===================   Deployment ================= 1.) Deployment without any nodeName or nodeSelector, pod will spread among all of the av...