Ansible, Linux, Technical

Ansible: Copy Agent Keys to Remote Servers

Link: https://dannyman.toldme.com/2016/07/01/ansible-use-ssh-add-to-set-authorized_key/

Background: you use SSH and ssh-agent and you can get a list of keys you presently have “ready to fire” via:

djh@djh-MBP:~/devops$ ssh-add -l
4096 SHA256:JtmLhsoPoSfBsFnrIsZc6XNScJ3ofghvpYmhYGRWwsU .ssh/id_ssh (RSA)

Aaaand, you want to set up passwordless SSH for the remote hosts in your Ansible. There are lots of examples that involve file lookups for blah blah blah dot pub but why not just get a list from the agent?

A playbook:

- hosts: all
  gather_facts: no
    - name: Get my SSH public keys
      local_action: shell ssh-add -L
      register: ssh_keys

    - name: List my SSH public keys
      debug: msg="{{ ssh_keys.stdout }}"

    - name: Install my SSH public keys on Remote Servers
      authorized_key: user={{lookup('env', 'USER')}} key="{{item}}"
      with_items: "{{ ssh_keys.stdout }}"

This is roughly based on a Stack Overflow answer.

The two tricky bits are:
1) Running a local_action to get a list of SSH keys.
2) Doing with_items to iterate if there are multiple keys.

A bonus tricky bit:
3) You may need to install sshpass if you do not already have key access to the remote servers. Last I knew, the brew command on Mac OS will balk at you for trying to install this.

Feedback Welcome

Ansible, Technical

Ansible: Set Conditional Handler

Link: https://dannyman.toldme.com/2014/10/07/ansible-set-conditional-handler/

I have a playbook which installs and configures NRPE. The packages and services are different on Red Hat versus Debian-based systems, but my site configuration is the same. I burnt a fair amount of time trying to figure out how to allow the configuration tasks to notify a single handler. The result looks something like:

# Debian or Ubuntu
- name: Ensure NRPE is installed on Debian or Ubuntu
  when: ansible_pkg_mgr == 'apt'
  apt: pkg=nagios-nrpe-server state=latest

- name: Set nrpe_handler to nagios-nrpe-server
  when: ansible_pkg_mgr == 'apt'
  set_fact: nrpe_handler='nagios-nrpe-server'

# RHEL or CentOS
- name: Ensure NRPE is installed on RHEL or CentOS
  when: ansible_pkg_mgr == 'yum'
  yum: pkg={{item}} state=latest
    - nagios-nrpe
    - nagios-plugins-nrpe

- name: Set nrpe_handler to nrpe
  when: ansible_pkg_mgr == 'yum'
  set_fact: nrpe_handler='nrpe'

# Common
- name: Ensure NRPE will talk to Nagios Server
  lineinfile: dest=/etc/nagios/nrpe.cfg regexp='^allowed_hosts=' line='allowed_hosts=nagios.domain.com'
    - restart nrpe

### A few other common configuration settings ...

Then, over in the handlers file:

# Common
- name: restart nrpe
  service: name={{nrpe_handler}} state=restarted

The trick boiled down to using the set_fact module.

Feedback Welcome

Site Archive