Max's notebook

A collection of sorts

Ansible Notes

03 May 2020

A quick and dirty reference for ansible things I find useful.

define inventory

➜  ~ cat server_inventory

[server_group]    ansible_user=myuser ansible_ssh_private_key_file=my_key    ansible_user=not-me ansible_ssh_private_key_file=yo_key

remote ssh ftw

# run `systemctl restart yo-service` as root across all the servers in server_group, 
defined in server_inventory, and do it in groups of 10 at a time
ansible server_group -i server_inventory -b -m shell -a \
    "systemctl restart yo-service" -f10

remote script execution

# run a local script across a bunch of servers
ansible server_group -i server_inventory -b -m script -a

run an ad-hoc command across specific servers

# run `systemctl stop yo-other-service` on these specific hosts
ansible -b -m shell -a "systemctl stop yo-other-service" \\\

playbook structure

➜  ~ cat playbook.yml
- hosts: "{{ hosts }}" # read hosts at runtime
  become: yes # with sudo
  gather_facts: false # don't need server metadata, just go

    - name: install nginx
      apt: name=nginx state=latest
    - name: restart nginx
      service: name=nginx state=restarted
      register: nginx_status
    - name: debug nginx status
        var: nginx_status
    - name: debug message
        msg: "output of nginx restart: "

run the playbook

# run the playbook `playbook.yml` against localhost
ansible-playbook playbook.yml -e hosts=localhost

role structure

➜  ansible-role tree
├── files # static files
│   └── pub_key
├── meta # dependencies on other roles
│   └── main.yml
├── tasks
│   ├── main.yml # top level tasks
│   └── nginx.yml # other tasks, needs to be included in `main.yml`
├── templates # templates ala jinja2
│   └── nginx.conf.j2 
└── vars
    ├── main.yml
    └── secrets.yml # needs to be included in `tasks/main.yml`

5 directories, 6 files