Basic Ansible Introductory Learning Notes

I have been learning from this book Fabio Alessandro Locati, published under Packt>

I thought I just capture a few learning notes as I read.

Introduction to Playbooks

Playgroups are one of the core features of Ansible and tell what Ansible what to execute. They are like a do-list for Ansible that contains a list of tasks; each task internally links to a piece of code called a module

- hosts: all 
  remote_user: vagrant
  tasks: 
    - name: Ensure the HTTPd package is installed 
      yum: 
        name: httpd 
        state: present 
      become: True 
    - name: Ensure the HTTPd service is enabled and running 
      service: 
        name: httpd 
        state: started 
        enabled: True 
      become: True 

What it means?

  • hosts: List the Host or Host groups. The Host field is required. The –list-hosts-host will let us know which hosts the playbook is using.
  • remote_user: The user Ansible will be using while logging onto the system.
  • There are 2 tasks.
    • The first one is to ensure that the httpd package is present
    • The 2nd one is to enable the httpd service is enabled and running
  • The tasks are quite self-explanatory.
  • become: True. The commands should be executed with sudo access. If the sudo user’s file does not allow the user to run the particular command, the command will fail

Running a Playbook

$ ansible-playbook -i host setup_apache.yml

Ansible Verbosity

You can increase the verbosity by using the parameter -v, -vv or -vvv

Variables in Ansible

---
- hosts: all
  remote_user: vagrant
  tasks: 
    - name: Print OS and version
      debug:
        msg: '{{ ansible_distribution }} {{ ansible_distribution_version }}'

Creating the Ansible User

--- 
- hosts: all 
  user: vagrant 
  tasks: 
    - name: Ensure ansible user exists 
      user: 
        name: ansible 
        state: present 
        comment: Ansible 
      become: True
    - name: Ensure ansible user accepts the SSH key 
      authorized_key: 
        user: ansible 
        key: https://github.com/fale.keys 
        state: present 
      become: True
    - name: Ensure the ansible user is sudoer with no password required 
      lineinfile: 
        dest: /etc/sudoers 
        state: present 
        regexp: '^ansible ALL\=' 
        line: 'ansible ALL=(ALL) NOPASSWD:ALL' 
        validate: 'visudo -cf %s'
      become: True

The lineinfile is an interesting module. It works in a similar way to sed (a stream editor) where you specify the regular expression that will be used to match the line, and then specify the new line that will be used to substitute the matched line.

Advertisement