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
    - name: Ensure the HTTPd package is installed 
        name: httpd 
        state: present 
      become: True 
    - name: Ensure the HTTPd service is enabled and running 
        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
    - name: Print OS and version
        msg: '{{ ansible_distribution }} {{ ansible_distribution_version }}'

Creating the Ansible User

- hosts: all 
  user: vagrant 
    - name: Ensure ansible user exists 
        name: ansible 
        state: present 
        comment: Ansible 
      become: True
    - name: Ensure ansible user accepts the SSH key 
        user: ansible 
        state: present 
      become: True
    - name: Ensure the ansible user is sudoer with no password required 
        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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.