Ansible

Agentless Push-based Configuration Management Tool


Pros

  • Agent less
  • YAML is easy to learn

Cons

  • Performance speed less then other tools
  • YAML not as powerful as Ruby

Getting Started

  • Ping all known hosts in group home-lab ansible home-lab -m ping
  • Install Ansible
pmi ansible sshpass
  • Create configuration file and add hosts in /etc/ansible/ansible.cfg or a local repo
[ubuntu]
homelab.wg
  • Run commands
ansible -i hosts ubuntu -m ping --user unfa --ask-pass

Ansible CLI

  • Command Pattern ansible [pattern] -m [module] -a "[module options]"
  • Run one-off / Ad-hoc Commands with
# get hostname
ansible localhost -m command -a hostname
 
# print date
ansible localhost -m command -a date
 
# reboot servers (default module is command)
ansible atlanta -a "/sbin/reboot"`

Ansible Authentication

  • Ansible connects to all remote devices with the user name you are using on the control node.
  • Ansible assumes you are using SSH keys to connect to remote machines
    • use a ssh agent, use the --private-key flag to specify a pem file, or add the private key file to an inventory with ansible_ssh_private_key_file.
  • Understanding privilege escalation: become — Ansible Documentation

Ansible Variables

tasks:
     - name: Run a shell command and register its output as a variable
       ansible.builtin.shell: /usr/bin/foo
       register: foo_result
       ignore_errors: true

Ansible Secrets

  • Interactive Prompts
- hosts: all
  gather_facts: false
  vars_prompt:
    - name: api_key
      prompt: Enter the API key
  tasks:
    - name: Ensure API key is present in config file
      ansible.builtin.lineinfile:
        path: /etc/app/configuration.ini
        line: "API_KEY={{ api_key }}"

Ansible Conditionals

tasks:
  - name: Configure SELinux to start mysql on any port
    ansible.posix.seboolean:
      name: mysql_connect_any
      state: true
      persistent: true
    when: ansible_selinux.status == "enabled"
    # all variables can be used directly in conditionals without double curly braces
 
tasks:
  - name: Shut down Debian flavored systems
    ansible.builtin.command: /sbin/shutdown -t now
    when: ansible_facts['os_family'] == "Debian"

Ansible Filters