Skip to content

Ansible

Vlad edited this page Mar 4, 2022 · 24 revisions

Ansible

Install

Ubuntu

# Set PATH to include user's private bin
export PATH="${HOME}/.local/bin:${PATH}"
# Update system
sudo apt-get -qy update
sudo apt-get -qy dist-upgrade
# Make sure pip is installed (sshpass is needed for --ask-pass and acl is needed for become user permissions)
sudo apt install python3-pip sshpass acl
# Install Ansible as user
python3 -m pip install --user --upgrade pip ansible ansible-lint

Provision Ansible on node

# ping host
ansible mynode -m ping -u myuser --ask-pass
# become root
ansible-playbook -u ubuntu --ask-pass --ask-become-pass site.yml --limit mynode
ansible-playbook -u ubuntu --ask-pass --ask-become-pass playbooks/ansible.yml --limit mynode
# with ssh library
ansible-playbook -c paramiko -u vlad --ask-pass --ask-become-pass playbooks/ansible.yml --limit mynode
# with private key
ansible-playbook -u myuser --private-key key_rsa playbooks/ansible.yml --limit mynode

Install / Update Galaxy Roles

ansible-galaxy install --force --role-file requirements.yml

Run Ansible with default settings

ansible-playbook site.yml

Use Ansible's Vault

https://docs.ansible.com/ansible/latest/user_guide/vault.html

# Add `vault_password_file = ./vault_pwd` to ansible.cfg and create the `vault_pwd` file which contains the password
ansible-vault create group_vars/all/vault.yml
ansible-vault edit group_vars/all/vault.yml
# Use VSCode
EDITOR='code --wait' ansible-vault create group_vars/all/vault.yml
EDITOR='code --wait' ansible-vault edit group_vars/all/vault.yml

Use Hashicorp's Vault

https://docs.ansible.com/ansible/latest/plugins/lookup/hashi_vault.html

# Install libraries
python3 -m pip install --user --upgrade hvac

export VAULT_ADDR=https://vault.ghn.me:8200
export VAULT_TOKEN=xxxxx
# For V2, it needs `data` after storage name, and `:data` at the end
- debug:
    msg: "{{ lookup('hashi_vault', 'secret=vgh/data/ansible/logzio:data')['token']}}"

Misc

# Ping hosts
ansible all -m ping

# Gather facts
ansible all -m setup
ansible all -m setup -a 'filter=ansible_*_mb' --limit vbs

# Run ad-hoc commands on hosts
# Where `all` is the group,`-b` is become sudo, `uptime` is the command)
ansible all -b -a uptime

# Run locally
ansible-playbook --connection=local site.yml
ansible-playbook --connection=local --inventory localhost, site.yml

# Inline Ansible encrypted vars
echo -n 'letmein' | ansible-vault encrypt_string --stdin-name 'db_password'
ansible localhost -m debug -a var='db_password' -e "@host_vars/localhost/vars.yml"

Testing

# Install molecule
python3 -m pip install --user  --upgrade "molecule[lint]"

# Create role skeleton
molecule init role myrole

# Test and destroy at the end
molecule test

# Test individual steps
molecule converge  # Just stop after executing the playbook
molecule login  # SSH into the running test instance
molecule destroy  # Destroy everything at the end
Clone this wiki locally