Ansible Snippets

Oct 7, 2017 10:27 · 247 words · 2 minutes read Ansible

Typical structure

├───group_vars
├───inventory
└───roles
    ├───role2
    │   ├───defaults
    │   └───tasks
    ├───role1
    │   ├───defaults
    │   └───tasks
    └───role3
        ├───defaults
        ├───files
        ├───meta
        ├───handlers
        └───tasks

group_vars/all is a special file that can contains variables that extend to any group. group_vars/group_name_here contains variables that include only the group which the file is named after.

Defining playbooks

# site.yaml
---
  - hosts: all
    roles:
      - role1
      - role2
      - role3

# roles/role1/tasks/main.yaml
---
  - name: Name of task 1
    debug:
      msg: "Executing {{variable_here}}"

# roles/role1/defaults/main.yaml
---
  variable_here: "Some variable contents"

Including playbooks in other playbooks

# site.yaml
---
  - include: playbook1.yaml
  - include: playbook2.yaml
  - include: playbook3.yaml

Provisioning a vagrant machine

# Vagrantfile
config.vm.provision :ansible do |ansible|
    ansible.playbook = "ansible/playbook_to_provision_from.yaml"

    # Optional vars to include
    ansible.extra_vars = {
        "deploy_env" => "development"
    }

    # Optionally include verbose output
    ansible.verbose = false
end

with_items iteration

---
  - name: Perform tasks in a loop
    file:
      path: "{{ item.path }}"
      state: "{{ item.state }}"
    with_items:
      - { path: "test.txt", state: "absent" }
      - { path: "test2.txt", state: "present" }

Declaring dependencies on other roles

# roles/role1/meta/main.yaml
---
  dependencies:
    - { role: "role0" }
    - { role: "role2" }

This will cause role0 and role2 to run before role1.

Some flags for running playbooks

ansible-playbook \
    playbook.yaml \
    --tags "tags to run separated by spaces"
    --extra_vars "vars=to_set separated=by_spaces"
    --limit "hosts to limit to separated by spaces

Pinging all servers

ansible --inventory path_to_inventory -m ping all

Sample inventory file

[group_name]
127.0.0.1 

[group_name:vars]
ansible_ssh_user=username
ansible_ssh_private_key_file=path_to_some_key.pem 

[another_group]
hostname.com

[group_name:vars]
ansible_ssh_user=username
ansible_ssh_private_key_file=path_to_some_key.pem