Understanding Ansible with 5 Basic Examples

Here’s an Ansible playbook with five tasks:

- name: Example Playbook
  hosts: all
  become: yes
    - name: Update package list
        update_cache: yes

    - name: Install nginx
        name: nginx
        state: present

    - name: Start nginx service
        name: nginx
        state: started

    - name: Create a new user
        name: newuser
        state: present

    - name: Add new user to sudoers
        path: /etc/sudoers
        line: 'newuser ALL=(ALL:ALL) ALL'
        validate: 'visudo -cf %s'

Here’s what each task does:

  1. Update package list: This task updates the list of available packages and their versions, but it does not install or upgrade any packages.
  2. Install nginx: This task installs the nginx package. If it’s already installed, Ansible will ensure it’s up to date.
  3. Start nginx service: This task ensures that the nginx service is running.
  4. Create a new user: This task creates a new user named newuser. If the user already exists, Ansible will not change anything.
  5. Add new user to sudoers: This task adds the newuser to the sudoers file, granting them sudo privileges. The validate option is used to check the syntax of the sudoers file before saving changes.

Remember to replace all with your actual host names or IP addresses. Also, ensure that Ansible is installed and properly configured on your control node, and that the control node can connect to the target hosts via SSH. If you’re new to Ansible, I recommend checking out their official documentation for more detailed information and tutorials.

Leave a Comment