Followers

Ansible Playbooks Examples

    Prerequisite:   Ansible should be installed on the master node. Should have root access to Master and other nodes Not  mandatory but In ...

  Prerequisite: 

  • Ansible should be installed on the master node.
  • Should have root access to Master and other nodes
  • Not  mandatory but In my example, I am working as a root user
  • Master node and Managed Nodes ( Agent nodes) should be configured and in the network.
  • Master node's public and private ssh should generate (ssh-keygen)
  • Master node's public is to be shared with Agent nodes ( /root/.ssh/authorized_keys) file

Current Setup: 3 Ubuntu Servers ( 1 master and 2 agent nodes)\

   Master server is also a DB server.

   Master IP: 192.168.33.10

   Webserver1 IP: 192.168.33.11

   Webserver2 IP: 192.168.33.12

Host file Setup

Goto /etc/ansible/hosts file and add below entries

 [dbservers]
 192.168.33.10

[webservers]
192.168.33.11
192.168.33.12

Ansible Configuration file
/etc/ansible/ansible.cfg

uncomment(remove #) host file path
inventory      = /etc/ansible/hosts

Example 1: Create a playbook to run an echo "Hello World" command on dbservers.
Playbook: hello.yaml

Create a hello.yaml ( you can give any primary name but the extension should be .yaml or .yml). 

---
 - name: play for running shell commands
   hosts: dbservers
   tasks:
         - name: Executing command module
           command: echo "Hello World"


Execute
             ansible-playbook hello.yaml


Example 2: 

Playbook: hello.yaml
In Example1 playbook was executed successfully but it did not print Hello World. You can use "register" to store the output of the previous command in a variable. Let's modify hello.yaml file

---
 - name: play for running shell commands
   hosts: dbservers
   tasks:
           - name: Executing echo command
             command: echo "Hello World"
             register: output
           - name: Print the output
             debug:
                 msg: "{{ output.stdout }}"


Execute: ansible-playbook hello.yaml

Example 3

Playbook:- hello.yaml
Create a playbook to read a file (/tmp/status.txt) using the command module.

---
 - name: play for running shell commands
   hosts: dbservers
   tasks:
           - name: Executing echo command
             command: cat /tmp/status.txt
             register: output
           - name: Print the output
             debug:
                 msg: "{{ output.stdout }}"


Execute:-  ansible-playbook hello.yaml

Example 4: Create Multiple plays

Playbook:- mul.yaml

Create a playbook mul.yaml, where you need to create below plays

play1: run on dbservers and create a file /tmp/local.txt
play2: run on webservers and create a file /tmp/webserver.txt

#mul.yaml

---
 - name: First play
   hosts: dbservers
   tasks:
         - name: creating /tmp/local.txt
           command: touch /tmp/local.txt
 - name: Sec play
   hosts: webservers
   tasks:
           - name: creating /tmp/webserver.txt
             command: touch /tmp/webserver.txt


Execute:- ansible-playbook mul.yaml 

Example 5: Multiple tasks in a play
Playbook:- multitask.yaml

Create a file called /tmp/myfile.txt and add content as "Hello World". To verify that file is created successfully, print the content of the file. Run it on dbservers.
Playbook:- multitask.yaml
---
 - name: play for dbservers multiple tasks
   hosts: dbservers
   tasks:
         # Task1
        - name: create a file
          command: touch /tmp/myfile.txt
        # Task2
        - name: Add content to the file
          copy:
            content: "Hello World"
            dest: /tmp/myfile.txt
         # Task 3
        - name: Read the content
          command: cat /tmp/myfile.txt
          register: output
          # Task 4
        - name: Print the content
          debug:
             var: output.stdout


Execute: ansible-playbook multitask.yaml

Example 6: Variable Example

Repeat Example 5 but use a variable for the content of the file.

---
 - name: play for dbservers multiple tasks
   hosts: dbservers
   vars:
      data: "Hello World!"
   tasks:
         # Task1
        - name: create a file
          command: touch /tmp/myfile.txt
        # Task2
        - name: Add content to the file
          copy:
              content: "{{ data }}"
              dest: /tmp/myfile.txt
         # Task 3
        - name: Read the content
          command: cat /tmp/myfile.txt
          register: output
          # Task 4
        - name: Print the content
          debug:
             var: output.stdout

Execute: ansible-playbook multitask.yaml

Example 7: Variable with vars_prompt

Repeat Example6 by entering variable value at run time

---
 - name: play for dbservers multiple tasks
   hosts: dbservers
   vars_prompt:
      name: data
      prompt: Enter the value
   tasks:
         # Task1
        - name: create a file
          command: touch /tmp/myfile.txt
        # Task2
        - name: Add content to the file
          copy:
              content: "{{ data }}"
              dest: /tmp/myfile.txt
         # Task 3
        - name: Read the content
          command: cat /tmp/myfile.txt
          register: output
          # Task 4
        - name: Print the content
          debug:
             var: output.stdout

Execute: ansible-playbook multitask.yaml

Dry Run

When ansible-playbook is executed with --check it will not make any changes on remote systems. Instead, any module instrumented to support ‘check mode’ (which contains most of the primary core modules, but it is not required that all modules do this) will report what changes they would have made rather than making them. Other modules that do not support check mode will also take no action, but just will not report what changes they might have made.



Example 8: Dry Run (dryrun.yaml)

Below script is copying /tmp/testing.txt file to webservers /tmp/test.txt. but if you use --check option with ansible-playbook execution it will only do the dry run not actually running the command to copy to webservers.

Playbook:- dryrun.ym

---
 - name: play for dry run
   hosts: webservers
   tasks:
        - name: Copying testing.txt file to webservers
          copy: src=/tmp/testing.txt dest=/tmp/test.txt


Execute :- ansible-playbook dryrun.yml --check

Example 9:- Dry run with check_mode option
Playbook:- multask.yaml
---
 - name: play for dbservers multiple tasks
   hosts: dbservers
   vars_prompt:
      name: data
      prompt: Enter the value
   tasks:
         # Task1
        - name: create a file
          command: touch /tmp/myfile.txt
          check_mode: no
        # Task2
        - name: Add content to the file
          copy:
              content: "{{ data }}"
              dest: /tmp/myfile.txt
          check_mode: yes
         # Task 3
        - name: Read the content
          command: cat /tmp/myfile.txt
          register: output
          # Task 4
        - name: Print the content
          debug:
             var: output.stdout


Execution:-  ansible-playbook multask.yaml

Example 10: logging with logpath

Playbook:- dryrun.yaml

uncomment log_path in ansible.cfg file to store the log output in /var/log/ansible.log

---
 - name: play for dry run
   hosts: webservers
   tasks:
        - name: Copying testing.txt file to webservers
          copy: src=/tmp/testing.txt dest=/tmp/test.txt

Execute:- ansible-playbook dryrun.yaml

After execution check /var/log/ansible.log file it should have the log of this file execution.

Example 11:- no_log attribute

if no_log =True then no log information is recorded in the log file for that particular module.


Example 12: Error handling ( ignore_errors: True)

Playbook: error.yaml

In the below code, Task3 will be executed because Task2 is having the exception handling.


---
 - hosts: webservers
   tasks:
        - name: Task1
          command: date
        - name: Task2
          command: date1
          ignore_errors: True
        - name: Task3
          command: ls

Execution:- ansible-playbook error.yaml

Example 13: Magic variables

Playbook: facts.yaml

Run the below command to find the facts of a host, it also returns the in-built ansible variables. In below command stores the output of these inbuilt variables in facts.log file

ansible dbservers -m ansible.builtin.setup > facts.log


---
 - name: play for finding the facts using ansible magic variables
   hosts: webservers
   tasks:
        - name: Print some facts
          debug:
               msg: "{{ ansible_facts['os_family'], ansible_facts['nodename'], ansible_all_ipv4_addresses }}"


Execution:-   ansible-playbook facts.yaml
It should print the OS Name,node name and all ipv4 addresses of web servers.

Example 14: Conditional Statements (when)

Playbook: conditon.yaml

Create a playbook to install httpd if it is 'RedHat' System

 ---
 - name: play for conditonal statements
   hosts: webservers
   tasks:
         - name: install httpd
           yum:
                name: httpd
                state: present
           when: ansible_facts['os_family']=="RedHat"

Execution :- ansible-playbook condition.yaml 

It should skip for webservers because these are Debian-based OS.

Example 15:  (!= operator)

Create a playbook to install apache2 on OS which doesn't belong to RedHat family

---
 - name: play for conditonal statements
   hosts: webservers
   tasks:
         - name: install apache2
           apt:
                name: apache2
                state: present
           when: ansible_facts['os_family']!="RedHat"

Execute: ansible-playbook condition.yaml 

Example 16: (or logical operator)

Create a playbook to install apache2 on OS which doesn't belong to RedHat family or belongs to Debian OS family

---
 - name: play for conditonal statements
   hosts: webservers
   tasks:
         - name: install apache2
           apt:
                name: apache2
                state: present
           when: ansible_facts['os_family']!="RedHat" or ansible_facts['os_family']=="Debian"

Execute: ansible-playbook condition.yaml 

Example 17: (and logical operator)

Create a playbook to install apache2 on OS which doesn't belong to  Debian OS family and OS is Ubuntu

---
 - name: play for conditonal statements
   hosts: webservers
   tasks:
         - name: install apache2
           apt:
                name: apache2
                state: present
           when: ansible_facts['os_family']=="Debian" and ansible_distribution=="Ubuntu"

Execute: ansible-playbook condition.yaml 


Example 18 (user module with conditional statement)
Create a user John on Debian based OS webservers. (use user module) and verify that user created.(cat /etc/passwd | grep John| wc -l)

Playbook:- user.yaml

---
 - name: User Module
   hosts: dbservers
   tasks:
     - name: adding John user
       user:
          name: John
       when: ansible_facts['os_family']=='Debian'
     - name: find the user
       shell: cat /etc/passwd | grep John | wc -l
       register: output
     - name: User Creation
       debug:
          msg: "Created"
       when: output.stdout=="1"
     - name: User Removed
       debug:
          msg: "Not Created"
       when: output.stdout!="1"

Execute :- ansible-playbook user.yaml

Example 19: multiple conditions

Playbook: mulcond.yaml

---
 - name: multiple condition
   hosts: webservers
   tasks:
       - name: Executing a shell script
         command: sh /home/vagrant/test.sh
         register: output
         ignore_errors: True
    
       - name: Execute when shell script is executed successfully
         debug:
            var: output.stdout
         when: output is succeeded

       - name: Execute when shell script is execution is failed
         debug:
           msg: "Script execution is failed"
         when: output is failed

       - name: Execute when shell script is executed successfully
         debug:
            msg: "Script is skipped"
         when: output is skipped
Execute:- ansible-playbook mulcond.yaml

It will execute the respective task depending upon the output variable value.

Example 20: Loops (with_items)

Item is the keyword which represents current value of the loop.

Playbook: loops.yaml
---
 - name: play for loops
   hosts: dbservers
   tasks:
       - name: Print some values
         debug:
              msg: "{{ item }}"
         with_items:
            - 1
            - 2
            - 3
            - 4


Execute:- ansible-playbook loops.yaml
It will print all the values ( 1 to 4) of loop.

Example 21: Loop ( loop statement)

Playbook: loop.yaml
Create some directories under /tmp using loop statement

---
 - name: play for loops
   hosts: dbservers
   tasks:
    - name: Create Multiple directories
      command: mkdir "{{ item }}"
      loop:
           - /tmp/1
           - /tmp/2
           - /tmp/3
           - /tmp/4


Execute: ansible-playbook loop.yaml


Example 22:- Loop with variables

Delete all the directories which get created in Example 19 using list variable.

Playbook: loop.yaml

---
 - name: play for loops
   hosts: dbservers
   vars:
       dirs:
          - /tmp/1
          - /tmp/2
          - /tmp/3
   tasks:
     - name: Statement
       command: rmdir "{{ item }}"
       with_items: "{{ dirs }}"


Execute: ansible-playbook loop.yaml

Example 23:- Ansible tags

You can run a specific task using ansible tags.

Playbook: tags.yaml

---
 - name: using Tags
   hosts: webservers
   tasks:
        - name: Start a service
          service:
            name: apache2
            state: started
          tags: startservice
        - name: Stop apache service
          service:
             name: apache2
             state: stopped
          tags: stopservice
        - name: Restart apahce service
          service:
             name: apache2
             state: restarted
          tags: restartservice


Execute: ansible-playbook tags.yaml --tags restartservice



COMMENTS

BLOGGER: 1

Name

Ansible,6,AWS,1,Azure DevOps,1,Containerization with docker,2,DevOps,2,Docker Quiz,1,Docker Swarm,1,DockerCompose,1,ELK,2,git,2,Jira,1,Kubernetes,1,Kubernetes Quiz,5,SAST DAST Security Testing,1,SonarQube,3,Splunk,2,vagrant kubernetes,1,YAML Basics,1,
ltr
item
DevOpsWorld: Ansible Playbooks Examples
Ansible Playbooks Examples
DevOpsWorld
https://www.devopsworld.co.in/2022/02/ansible-playbooks.html
https://www.devopsworld.co.in/
https://www.devopsworld.co.in/
https://www.devopsworld.co.in/2022/02/ansible-playbooks.html
true
5997357714110665304
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content