Table of Contents


Loops

---
- name: Loop Register Test
  gather_facts: false
  hosts: localhost
  tasks:
  - name: Looping Echo Task
    ansible.builtin.shell: "echo This is my item: {{ item }}"
    loop:
    - one
    - two

example

loop_example.yml

---
- name: loop exercise
  become: true
  gather_facts: false
  hosts: webservers
  vars:
    packages:
    - httpd
    - cups
  tasks:
  - name: Install {{ packages }} server
    ansible.builtin.dnf:
      name: "{{ item }}"
      state: latest
    loop: "{{ packages }}"
 
  - name: Start service {{ packages }}
    ansible.builtin.service:
      name: "{{ item }}"
      enabled: yes
      state: started
    loop: "{{ packages }}"
 
ansible-playbook loop_example.yml

Conditionals

conditional_example.yml

- name: Install software if loadavg permits
  become: true
  gather_facts: no
  hosts: webservers
 
  vars:
    max_load_avg: 0.5
    
  tasks:
  - name: Get loadavg
    ansible.builtin.shell: cat /proc/loadavg | awk '{ print $1}'
    register: load_avg
    tags: prep
 
  - name: Show loadavg
    ansible.builtin.debug:
      var: load_avg.stdout
    tags: prep
 
  - name: Stop playbok if loadavg to above {{ max_load_avg }}
    ansible.builtin.fail:
      msg: "Loadavg to High. Aborting!"
    when: ( load_avg.stdout | float ) > max_load_avg  # <---- conditional
    tags: prep
 
  - name: Install httpd server
    ansible.builtin.dnf:
      name: httpd
      state: latest
    tags: install
 
# Run the play book 
ansible-playbook conditional_example.yml
 
# only run specific tags
ansible-playbook conditional_example.yml --tags install
 
# Start at specific task
ansible-playbook conditional_example.yml --start-at-task "Install httpd server"

ssh webserver node. Ex. ansible-cfreire-node1 to simulate load

# Create fake load
$ dd if=/dev/zero of=/dev/null

Handlers

handlers_example.yml

- name: Web application deploy
  hosts: webservers
  become: true
  vars:
    packages:
    - httpd
    - php-fpm
      
    web_service: httpd
    app_service: php-fpm
 
  tasks:
  - name: Install {{ packages }}
    ansible.builtin.dnf:
      name: "{{ item }}"
      state: present
    loop: "{{ packages }}"
 
  - name: Deploy index.html with variable info
    ansible.builtin.copy:
      dest: "/var/www/html/index.html"
      content: |
        <h1>Welcome from {{ inventory_hostname }}</h1>
      mode: '0644'
    notify:  # <--- Call only, if task results on "changed"
      - restart app service
        
  - name: Ensure services are running
    ansible.builtin.service:
      name: "{{ item }}"
      state: started
    loop: "{{ packages }}"
    
  handlers:
  - name: restart app service  # <--- Same name as notify
    ansible.builtin.service:
      name: "{{ web_service }}"
      state: restarted
 

Custom Templates

motd.j2

Welcome to {{ ansible_facts['fqdn'] }}
Running on a {{ ansible_facts['distribution'] }}
 
If you have problems please submit a ticket to /dev/null
 

motd.yml

---
- name: Configure message of the day
  become: true
  hosts: webservers
  tasks:
  - name: Configure /etc/motd
    ansible.builtin.template:
      src: motd.j2
      dest: /etc/motd
      owner: root
      group: root
      mode: '0644'

Roles

https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_reuse_roles.html

Roles let you automatically load related vars, files, tasks, handlers, and other Ansible artifacts based on a known file structure. After you group your content in roles, you can easily reuse them and share them with other users.

You can think of a role as a playbook that is split up into multiple different files. Instead of having a single file that contains everything that you need, there’s one file for variables,
one for tasks, and another for handler

roles/
    common/               # this hierarchy represents a "role"
        tasks/            #
            main.yml      #  <-- tasks file can include smaller files if warranted
        handlers/         #
            main.yml      #  <-- handlers file
        templates/        #  <-- files for use with the template resource
            ntp.conf.j2   #  <------- templates end in .j2
        files/            #
            bar.txt       #  <-- files for use with the copy resource
            foo.sh        #  <-- script files for use with the script resource
        vars/             #
            main.yml      #  <-- variables associated with this role
        defaults/         #
            main.yml      #  <-- default lower priority variables for this role
        meta/             #
            main.yml      #  <-- role dependencies
        library/          # roles can also include custom modules
        module_utils/     # roles can also include custom module_utils
        lookup_plugins/   # or other types of plugins, like lookup in this case
 
    webtier/              # same kind of structure as "common" was above, done for the webtier role
    monitoring/           # ""
    fooapp/               # ""
 

ansible.cfg

[defaults]
inventory = hosts
interpreter_python = auto_silent
host_key_checking = false
remote_user = redhat
roles_path = ./roles
collections_path = ./collections
mkdir roles
cd roles
ansible-galaxy role init example
roles/example/
├── defaults
│   └── main.yml
├── files
├── handlers
│   └── main.yml
├── meta
│   └── main.yml
├── README.md
├── tasks
│   └── main.yml
├── templates
├── tests
│   ├── inventory
│   └── test.yml
└── vars
    └── main.yml
    
$ ansible-galaxy role list
# /home/redhat/ansible_roles/roles
- example, (unknown version)

roles_usage.yml

---
- name: using roles
  hosts: localhost
 
  pre_tasks:
  - name: This will run first
    ansible.builtin.debug:
      msg: "I will go first"
      
  roles:
    - role: example
 
  post_tasks:
  - name: This will run last
    ansible.builtin.debug:
      msg: "I will go last"
ansible-playbook roles_usage.yml
 
# Pack with a version in the filename
tar -czvf example.tar.gz example/

Collections

https://galaxy.ansible.com/

ansible.cfg

[defaults]
inventory = hosts
interpreter_python = auto_silent
host_key_checking = False
remote_user = redhat
 
# depends on posix
callbacks_enabled = profile_tasks
roles_path = ./roles
collections_path = ./collections:/usr/share/ansible/collections
 
mkdir -p collections
# verify list is empty
ansible-galaxy collection list
 
ansible-galaxy collection install ansible.posix:2.1.0
ansible-galaxy collection install ansible.windows:2.7.0
 
# verify installations
ansible-galaxy collection list

Order of operations

Regardless of the order in which these blocks are listed in a play, this is the order in which they will be processed

  • Variable loading
  • Fact gathering
  • The pre_tasks execution
  • Handlers notified from the pre_tasks execution
  • Roles execution
  • Tasks execution
  • Handlers notified from roles or tasks execution
  • The post_tasks execution
  • Handlers notified from post_tasks execution