Ansible “Hello, World”

In this tutorial we’ll create a simple playbook to write a templated file to multiple servers.

This pattern can be used to write configuration files, etc.

  1. Create a directory for the playbook.

    $ mkdir hello_world
    
  2. Create a directory for the role.

    $ mkdir -p hello_world/roles/hello_template
    
  3. Create a directory for the template.

    $ mkdir -p hello_world/roles/hello_template/templates
    
  4. Create the template file.

    $ vim hello_world/roles/hello_template/templates/marker.txt
    

    Contents:

    Hello, {{hello_name}}!
    
  5. Create the task file.

    $ vim hello_world/roles/hello_template/main.yml
    

    Add a task to write the template to tmp/.

    ---
    - name: "Write the template to tmp."
    template:
    src: marker.txt
    dest: /tmp/{{filename}}.txt
    
  6. Create the playbook.

    $ vim hello_world/hello_world.yml
    

    Use the template module to process the template and place it on each box:

    ---
    - hosts: adhoc
    
    roles:
    - hello_template
    
  7. Add filename and hello_name to the inventory as variables.

    $ vim /usr/local/etc/ansible/hosts
    
    [adhoc:vars]
     filename=YOUR_NAME_marker.txt
     hello_name=World
    
  8. Run the playbook!

    ansible-playbook hello_world/hello_world.yml
    
  9. Verify that your marker file is present.

    $ ansible adhoc -m shell -a "echo /tmp/{{filename}}:; cat /tmp/{{filename}}"
    

    Feel free to try other servers, too!

  10. Clean up.

    $ ansible adhoc -m file -a "path=/tmp/{{filename}} state=absent"