Ansible Cheatsheet

Ansible Cheatsheet

January 12, 2020
Cheatsheets
★ Star me on GitHub

Ansible is an IT automation tool.


Install Ansible:

python -m virtualenv ansible  # Create a virtualenv if one does not already exist
source ansible/bin/activate   # Activate the virtual environment
pip install ansible

Inventory

Default location: /etc/ansible/hosts.

Use -i <path> to specify a different inventory file. Inventory file example:

Prod ansible_ssh_user=[username] ansible_ssh_host=[ip_address] ansible_ssh_port=22 ansible_ssh_private_key_file=[ssh-key-file-path]

Playbook

In Ansible, a configuration management script is called a playbook.

# playbook.yml
- name: Playbook Example
  hosts: Prod
  tasks:
    - name: Pull GitHub Repo (with SSH ForwardAgent enabled)
      git:
        repo: '[email protected]:xxx/xxx.git'
        dest: /dest/path
    - name: Run shell command in specific directory
      shell: npm install
      args:
        chdir: /git-repo/path
    - name: Sync Files
      synchronize:
        src: source/path
        dest: /source/path
    - name: Mange supervisor processs
      supervisorctl: name=[process-name] state=[start|stopped]
    - name: Update nginx config
      template: src=templates/nginx_conf.j2
                dest=/etc/nginx/conf.d/example.conf
    - name: Reload nginx
      service: name=nginx state=reloaded

Run playbook:

ansible-playbook -i path-to-my-inventory playbook.yml;

ansible.cfg

ansible.cfg lookup order:

  1. File specified by the ANSIBLE_CONFIG environment variable
  2. ./ansible.cfg (current directory)
  3. ~/.ansible.cfg (home directory)
  4. /etc/ansible/ansible.cfg
[defaults]
transport = ssh
log_path=ansible.log

[ssh_connection]
ssh_args = -o ForwardAgent=yes -o IdentitiesOnly=yes -o ControlMaster=auto -o ControlPersist=4h -o ControlPath=~/.ssh/%h-%p-%r

Enable SSH ForwardAgent

~/.ssh/config:

Host [server-address-here] [ip-address-here]
    ForwardAgent yes