Ansible tasks for Sysadmins with 25 examples

Introduction

Ansible tasks are a set of actions, Let’s go through a few of sysadmin tasks require in our daily need. All the below tasks are used by us to manage the Linux hosts in our daily operation. Most of the options will change whenever the ansible version upgrade is released.

Installing Ansible: Install and configure Ansible Automation IT Tool

Ansible
Ansible

We will update this article frequently with more examples of Ansible tasks.

Define Variable Prompts

Defining a variable for Ansible tasks, Below is an example of getting some idea. The whole prompt is much more, define the same as per your requirements.

  vars_prompt:
    - name: "hosts_prompt"
      prompt: "Host or Hostgroup to run this Playbook"
      private: no

    - name: "your_user"
      prompt: "User account to be Created"
      private: no

Few List of Ansible Tasks for Sysadmins

Tasks for Managing SELinux (Module: SELinux)

A handy task to enforce or disable SELinux, this may help in case we have to manage N numbers of clients.

- name: Change SELinux mode to permissive
  remote_user: ansible
  become: yes
  become_method: sudo
  selinux:
    policy: targeted
    state: permissive

These are the available “state” of SELinux we can replace it with enforcing, permissive and disabled. While using disable we don’t require to use “policy” option.

Managing Yum Repositories (Module: Command)

To enable a yum repo below task can be used. The example is shown below for one of Red Hat servers repository.

- name: Enable Red Hat Optional Repository
  remote_user: ansible
  become: yes
  become_method: sudo
  command:
    subscription-manager repos --enable rhel-7-server-optional-rpms

Updating a Yum based Linux Server (Module: Yum)

By using below Updating a RedHat Server

- name: Install system updates for Red Hat systems
  yum: name=* state=latest update_cache=yes
  remote_user: ansible
  become: yes
  become_method: sudo
  when: ansible_distribution == "Red Hat Enterprise Linux"

To update CentOS server replace “when” with “CentOS“.

when: ansible_distribution == "CentOS"

Installing Packages (Yum)

To Install a package using use yum with required packages, this can be specified for one package or for multiple packages by using a comma separated.

- name: Install multiple packages
  yum: 
    name=chrony,vim,net-tools state=latest update_cache=yes
  remote_user: ansible
  become: yes
  become_method: sudo

Installing multiple packages (Yum)

To perform multiple package installation we have another way as well using “with_items“.

- name: Install Sysadmin Packages
  remote_user: ansible
  become: yes
  become_method: sudo
  yum: pkg={{ item }} state=installed update_cache=yes
  with_items:
        - vim
        - wget
        - curl
        - bash
        - ethtool
        - binutils
        - nfs-utils
        - pam
        - procps-ng
        - psmisc
        - smartmontools
        - unzip
        - sysstat

Installing RPM packages (RPM)

In case if we may be required to install any downloaded packages it can be done using yum as well.

- name: Install downloaded RPM packages using YUM.
  remote_user: ansible
  become: yes
  become_method: sudo
  yum: state=present name={{ item }}
  with_items:
        - /home/ansible/httpd-2.4.6-88.el7.centos.x86_64.rpm
        - /home/ansible/httpd-tools-2.4.6-88.el7.centos.x86_64.rpm
        - /home/ansible/httpd-manual-2.4.6-88.el7.centos.noarch.rpm

Removing an installed package using YUM

Like installing a package using yum it’s possible to remove the packages as well, Just by replacing “state=absent” a specific package or number of packages can be removed.

- name: Removing a package from server
  yum: 
    name=ntp state=absent
  remote_user: ansible
  become: yes
  become_method: sudo

Managing Configuration changes using (Module: templates)

We may be required to configure NTP, Chrony, SSHD etc in our daily routines or while doing a post configuration during server builds, In that case using a template is much required to save our time.

- name: Template from source to Destination with ownership and permission.
  remote_user: ansible
  become: yes
  become_method: sudo
  template:
     backup: yes
     src: /home/ansible/server_configs/templates/chrony.conf
     dest: /etc/chrony.conf
     owner: root
     group: root
     mode: 0644

Create or Touch a (Module: file)

In some cases, we required to create a file on a remote server it can be accomplished using “file” module as shown below.

- name: Touch a file under ansible user's home directory.
  remote_user: ansible
  become: yes
  become_method: sudo
  file: 
     path: /home/ansible/some_file.txt
     state: touch
     owner: ansbile
     group: ansible
     mode: 0644

Managing services (Module: Service)

Much required task whenever we need to start, stop or restart a service across the number of servers in a single go.

- name: Enable and Start chrony Service persistently
  remote_user: ansible
  become: yes
  become_method: sudo
  service: 
     name=chronyd state=start enabled=yes

Ansible Tasks for Replacing a String on Remote server (Module: lineinfile)

During configuration changes we require to Search and Replace a string on a configuration file it can be done with “lineinfile” module. There are several options available for this module and not limited to the only search and replace instead it supports to insert after, insert before, EOF or by matching something.

- name: Enable SSHD X11 forwarding
  remote_user: ansible
  become: yes
  become_method: sudo
  lineinfile:
     dest: /etc/ssh/sshd_config
     backup: yes
     regexp: '^#?X11Forwarding'
     backrefs: yes
     line: X11Forwarding yes
     state: present

Ansible Tasks for Creating User accounts (Module: group)

To create a user account using Ansible. first, the group need to be present, so first create the group and by following create the user.

- name: Ensure group "sysadmins" exists
  remote_user: ansible
  become: yes
  become_method: sudo
  group:
    name: sysadmins
    gid: 5055
    state: present

Then create the user by adding him into required groups. (Module: User)

- name: Ensure user "babinlonston" exists
  remote_user: ansible
  become: yes
  become_method: sudo
  user:
    name: babinlonston
    comment: "Managing linuxsysadmins"
    uid: 5055
    group: sysadmins
    groups: backup,healthcheck,ansible
    shell: /bin/bash
    password: "*###########*"
    state: present

In some cases, if you need to add an existing user to a supplementary group we need to use “append:“.

- name: Allow user babinlonston to manage Docker.
  remote_user: ansible
  become: yes
  become_method: sudo
  user:
    name: babinlonston
    groups: docker
    append: yes

Check below video how long it took to create an account across multiple servers.

Read user management: Managing Groups and User creation using Ansible

Using the inline-file module to make changes in a file

Insert, Append and make changes to a file or existing configuration file.

- name: Adding Oracle Kernel Parameters
  remote_user: ansible
  become: yes
  become_method: sudo
  lineinfile:
    owner: root
    group: root
    dest: /etc/sysctl.d/99-sysctl.conf
    line: '{{ item }}'
  with_items: 
    - '#### Oracle Install related kernel parameters ###'
    - 'vm.swappiness = 1'
    - 'vm.dirty_background_ratio = 3'
    - 'vm.dirty_ratio = 80'

Above example can be followed for adding new lines in a file.

Creating a Directory or Mount Point

Sysadmins routine task includes creating a new file system in day to day activity. Below task shows how to create a directory to mount a file system with required ownership and permission.

- name: Create /date mount point with respective Ownership
  remote_user: ansible
  become: yes
  become_method: sudo
  file:
    path: /data
    state: directory
    owner: "{{ mount_owner }}"
    group: "{{ mount_group }}"
    mode: 0755
    recurse: yes

Replace “{{ mount_owner }}”, “{{ mount_group }}” with the owner are define a variable at beginning of the playbook.

Print content of a file

To print the content of a file on the screen.

- name: Register output of a command and print on the screen.
  remote_user: ansible
  become: yes
  become_method: sudo
  command:
    cat /etc/issue
  register: content_of_issue

- debug:
    var: content_of_issue

Partitioning a Disk (Module: shell)

A Partition can be created using the “shellmodule with echo command, option and arguments.

- name: Create a Partition for /data file system
  remote_user: ansible
  become: yes
  become_method: sudo
  shell:
    /bin/echo -e "n\np\n1\n\n\nt\n8e\nw" | sudo fdisk "{{ disk_name }}"

Create a new single partition using fdisk, The partition type will be LVM.

Creating a filesystem (Module: filesystem)

While building the bulk of new servers sure we will get the requirement to create a filesystem. To fulfil the requirement we can create on a logical volume.

- name: Create a file system on newly created Logical volume.
  remote_user: ansible
  become: yes
  become_method: sudo
  filesystem:
    fstype: "{{ file_system }}"
    dev: "/dev/mapper/{{ vg_name }}-{{ lv_name }}"

The variables are defined for the file system type and logical volume.

Creating a Logical volume based file system using Ansible

Mounting a File System (Module: mount)

In our above example we have gone through how to create a mount point or directory with respective owner and permission, Now let us see how to mount a filesystem.

- name: Mount the created filesystem.
  remote_user: ansible
  become: yes
  become_method: sudo
  mount:
    path: "{{ mount_point }}"
    src: "/dev/mapper/{{ vg_name }}-{{ lv_name }}"
    fstype: "{{ file_system }}"
    opts: rw,noatime,noexec,nosuid
    state: mounted

Inputs are in place from variables.

Conclusion

More Ansible tasks are in the queue, The number of tasks can be put in a playbook to accomplish our sysadmin requirement. Subscribe to our newsletters to receive more updates.

5 thoughts on “Ansible tasks for Sysadmins with 25 examples

  1. Hi first let me say your site is great you are providing some real life uses for Ansible. While I know a lot of folks use ansible for the day to day of adding packages and make changes on a server which is great. I want to be able to use Ansible to first build a VM from a template located in a Virtual Center, then after it built to capture the mac address and input this information in Satellite, register, and then bring the server up to the latest patches. So it needs to input all the needed data with Satellite. Then update the server with puppet for the final configuration. Any help would be appreciated

  2. Hi,
    Thanks for the information you’re sharing. Quite handy. Just wondering if there is a systemd module to automate tasks I mean using systemd to automate.

  3. Is there any Ansible module to check the health of a disk using. IN linux we have the command ‘smartctl’ to check health status. When I tried to use this command using the shell module in ansible, I get error “stderr”: “/bin/sh: 1: smartctl: not found”

    1. @priyashree,
      Yet now we don’t have a health check module. You can go through all available monitoring modules from here.
      https://docs.ansible.com/ansible/latest/modules/list_of_monitoring_modules.html

      Find the full path of ‘smartctl’ by running # which smartctl and use the full path while using the shell module, it should work without any issue.

      root@apt:~# which smartctl
      /usr/sbin/smartctl
      root@apt:~#

      $ ansible -b -m shell -a “/usr/sbin/smartctl -a /dev/sda” my_server

      Thanks & Regards,
      Babin Lonston

Comments are closed.