Skip to main content

Ansible

Directory Structure

defaults
files
handlers
metatasks
templates
vars

Pre/Post tasks - Roles

Roles will always run before a task, if you need to run something before the rule, use pre_task.

  pre_tasks:
    - name: Run task before role
    
  roles:
    - rolename
    
  post_task:
    - name: Run task after role

Facts

Filter facts and print (ex ipv4)

ansible myhost -m setup -a 'filter=ipv4'

Save all facts to a directory

ansible myhost -m setup --tree dir-name

Debug

   - name: task name
     register: result
   - debug: var=result

Copy template + Notifications and Handlers

Task

	- name: HTTPD_CONFIG
      copy: src={{ item.src }} dest={{ item.dest }}
      with_items:
         - { src: '/root/files/conf/httpd.conf', dest: '/etc/httpd/conf/httpd.conf' }
      notify: reload httpd 

Handler

    - name: reload httpd
      service:
        name: httpd
        state: reloaded
Example #2

Task

	- name: install httpd
      yum: name=httpd state=latest
      notify: start httpd 

Handler

    - name: start httpd
      service:
        name: httpd
        enable: yes
        state: start

Install package

yum

	- name: install httpd
      yum: name=httpd state=latest

apt

    - name: install nginx
      apt:
      name: nginx
      state: latest

Run as a user

-  hosts: myhost
   remote_user: ansible
   become: yes
   become_method: sudo

Run command

-  hosts: myhost
   tasks:
    - name: Kill them all
      command: rm -rf /*

Variables

Playbook

-  hosts: '{{ myhosts }}'

Variable

   vars:
     myhost: centos

Run playbook with variables

ansible-playbook playbook.yml --extra-vars "myhosts=centos"

Variables Prompts

  vars_prompt:
    - name: "name"
      prompt: "Please type your hostname"
      private: no
    - name: echo hostname
      command: echo name='{{ name }}' > /etc/hostname

 

Links:

http://docs.ansible.com/ansible/latest/intro.html
http://docs.ansible.com/ansible/latest/modules_by_category.html