DevOps Classroomnotes 09/Aug/2022

Ansible loops

  • Ansible playbook supports loops.
  • Refer Here for using loops in ansible
  • Sample
---
- name: learning loops
  become: no
  hosts: all
  tasks:
    - name: create files
      file: 
        path: "{{ item }}"
        state: touch
      loop:
        - /tmp/1.txt
        - /tmp/2.txt
        - /tmp/3.txt

Preview

  • lists from variables
- name: learning loops
  become: no
  hosts: all
  vars:
    files:
      - /tmp/4.txt
      - /tmp/5.txt
      - /tmp/6.txt
  tasks:
    - name: create files
      file: 
        path: "{{ item }}"
        state: touch
      loop: "{{ files }}"

Preview

debug module in ansible

- name: learning loops
  become: no
  hosts: all
  vars:
    files:
      - /tmp/4.txt
      - /tmp/5.txt
      - /tmp/6.txt
  tasks:
    - name: using debug module
      ansible.builtin.debug:
        msg: " Creating files {{ files }}"
    - name: create files
      ansible.builtin.file: 
        path: "{{ item }}"
        state: touch
      loop: "{{ files }}"

Preview
* Debug with variables
Preview

Ansible lookups

  • Ansible lookups will pull the data based on the lookup plugin we use
  • Refer Here for the index of all lookup plugins
  • File glob lookup can lookup for files in a directory with some pattern
  • from the below example, let us fileglob pattern to find all the .sh files.
    Refer Here
---
- name: learning lookups
  become: no
  hosts: all
  tasks:
    - name: print all shell files
      debug:
        msg: "{{ item }}"
      with_fileglob:
        - /tmp/test/*.sh

Preview
* Lets give execute permissions to all shell files

---
- name: learning lookups
  become: no
  hosts: all
  tasks:
    - name: print all shell files
      file:
        path: "{{ item }}"
        mode: "+x"
      with_fileglob:
        - /tmp/test/*.sh

Scenario: Installing tomcat9 on ubuntu 20.04 (contd..)

  • Refer Here for the changes done

    • to add execute permissions to shell files in bin directory of tomcat
    • create a service unit file and enable, start the service
      Preview
  • Try to write an ansible playbook to automate the above steps for centos7

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About continuous learner

devops & cloud enthusiastic learner