Ansible playbook is a tool for automating documented tasks. These days I use it less since switching to github/gitlab actions, so keeping a cheatsheet here when I need it again...
Installing on Ubuntu
sudo apt update
sudo apt install software-properties-common
sudo add-apt-repository --yes --update ppa:ansible/ansible
sudo apt install ansible
More on other distros and updated info here.
Configuring hosts
Configure remote hosts where you want to automate your tasks.
cat /etc/ansible/hosts
And add a line at the end of the file. Below is just an example what you can use:
[myhost]
<ip_address> environment_key1=<environment_key1> ansible_connection=ssh ansible_ssh_user=<user> ansible_ssh_private_key_file=<absolute_path_to_pem_file> ansible_ssh_port=<necessary_if_diff_22>
You can set environment variables, ssh connection details like in the example, or other variables.
Ansible recipes
Recipes are schema documented automation tasks. Example of such recipe is myservice.deploy.yml.
- hosts: myhost
pre_tasks:
- name: Clean targets
connection: local
local_action: shell ./cli.sh -c
tags:
- tag1
- name: Create distribution
connection: local
local_action: shell ./cli.sh --dist
- tag1
tasks:
- name: Test
shell: date +"%Y-%m-%d"
register: current_date
- name: Copy release
copy:
src: <path_to_dist>
dest: <remote_path_for_dist>-{{current_date.stdout}}.zip
owner: daemon
group: daemon
tags:
- tag2
- name: Unzip release
shell:
cmd: unzip -o <remote_path_for_dist>-{{current_date.stdout}}.zip -d <destination>
chdir: <command_dir_here>
tags:
- tag2
- name: Restart docker
shell:
chdir: <command_dir_here>
cmd: docker-compose stop myservice && docker-compose up -d myservice
tags:
- tag2
Local actions are for executing on your own environment locally, and other tasks are for executing on the remote environment. Tags are there if you don't want to execute all at once. You can register variables in tasks like current_date
and use it in other tasks like calling {{current_date.stdout}}
.
Execute
Call an ansible recipe like:
ansible-playbook myservice.deploy.yml
ansible-playbook --tags tag1
ansible-playbook --skip-tags tag1