A collection of sorts
03 May 2020
A quick and dirty reference for ansible
things I find useful.
➜ ~ cat server_inventory
host1.example.com
host2.example.com
[server_group]
10.10.10.101
10.10.10.102 ansible_user=myuser ansible_ssh_private_key_file=my_key
10.10.10.103 ansible_user=not-me ansible_ssh_private_key_file=yo_key
10.10.10.104
# 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
# run a local script across a bunch of servers
ansible server_group -i server_inventory -b -m script -a my_script.sh
# run `systemctl stop yo-other-service` on these specific hosts
ansible -b -m shell -a "systemctl stop yo-other-service" \
10.10.10.10:\
10.10.10.11:\
10.10.10.12
➜ ~ cat playbook.yml
---
- hosts: "{{ hosts }}" # read hosts at runtime
become: yes # with sudo
gather_facts: false # don't need server metadata, just go
tasks:
- name: install nginx
apt: name=nginx state=latest
- name: restart nginx
service: name=nginx state=restarted
register: nginx_status
- name: debug nginx status
debug:
var: nginx_status
- name: debug message
debug:
msg: "output of nginx restart: "
# run the playbook `playbook.yml` against localhost
ansible-playbook playbook.yml -e hosts=localhost
➜ 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