Part 9 – Using Roles to Organize Playbook Runs and Tasks

The baseline role is meant to be: “The default setup every machine in my lab should have.” Here we can install common packages, set up ssh , create perm, enable services etc

Create the skeleton framework of a role or collection 

ansible-galaxy init roles/baseline

It will create file structure as shown

awk@ansible:/etc/ansible$ tree roles/
roles/
└── baseline
    ├── README.md
    ├── defaults
    │   └── main.yml
    ├── files
    ├── handlers
    │   └── main.yml
    ├── meta
    │   └── main.yml
    ├── tasks
    │   └── main.yml
    ├── templates
    ├── tests
    │   ├── inventory
    │   └── test.yml
    └── vars
        └── main.yml

This file contains TASKS.

roles/baseline/tasks/main.yml
- name: Baseline role is running
  debug:
    msg: "Baseline tasks executed"

- name: Set system timezone
  timezone:
    name: "Europe/London"

- name: Update package cache
  package:
    update_cache: yes

- name: Upgrade all packages to latest
  package:
    name: "*"
    state: latest

- name: Install baseline packages
  package:
    name: "{{ packages }}"
    state: present

- name: Remove unwanted packages
  package:
    name: "{{ unwanted_packages }}"
    state: absent

- name: Set custom MOTD
  copy:
    dest: /etc/motd
    content: |
      Welcome to this server.
      Managed by Ansible Baseline Role.
      Unauthorized access is prohibited.

- name: Ensure SSH service is running
  service:
    name: sshd
    state: started
    enabled: true
  
- name: Ensure SSH service is running
  service:
    name: "{{ ssh_service }}"
    state: started
    enabled: true

This file contains PACKAGES.

roles/baseline/vars/main.yml
packages:
  - curl
  - wget
  - vim
  - git
  - htop
  - lsof
  - tcpdump
  - traceroute
  - unzip
  - tar
  - gzip
  - jq
  - rsync
  - tree
  - socat
  - bash-completion
  - psmisc
  - open-vm-tools
  - openssh-server

ssh_service: "{{ 'sshd' if ansible_distribution == 'CentOS' else 'ssh' }}"

unwanted_packages:
  - telnet
  - ftp
  - rsh
  - talk
  - ypbind

Define the playbook under

/etc/ansible/playbooks/baseline-init.yml 
---
- hosts: all
  become: true
  roles:
    - baseline

Do a dry run

Run the playbook

(Visited 19 times, 1 visits today)

By Ash Thomas

Ash Thomas is a seasoned IT professional with extensive experience as a technical expert, complemented by a keen interest in blockchain technology.