Skip to content

Instantly share code, notes, and snippets.

@ceving
Created January 12, 2017 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ceving/972a0f3d57e69af6d7a37c8fef6e7bb3 to your computer and use it in GitHub Desktop.
Save ceving/972a0f3d57e69af6d7a37c8fef6e7bb3 to your computer and use it in GitHub Desktop.
Tweak Ansible's host inventory.
(defun expand-character (expansion c)
(if (null expansion)
(list (list c))
(mapcar (lambda (item)
(cons c item)) ;; This reverses the string.
expansion)))
(defun expand-sequence (expansion p q)
(apply #'append
(mapcar (lambda (c)
(expand-character expansion c))
(number-sequence p q))))
(defun parse-ansible-bracket (input expansion)
(let ((q (car input)) ;; reverse input
(input (cdr input)))
(let ((colon (car input))
(input (cdr input)))
(if (= colon 58) ;; #\:
(let ((p (car input))
(input (cdr input)))
(let ((close (car input))
(input (cdr input)))
(if (= close 91) ;; #\[
(parse-ansible-pattern input (expand-sequence expansion p q))
(error "no closing bracket"))))
(error "no colon")))))
(defun parse-ansible-pattern (input expansion)
(if (null input)
expansion
(let ((c (car input))
(input (cdr input)))
(if (= c 93) ;; #\]
(parse-ansible-bracket input expansion)
(parse-ansible-pattern input (expand-character expansion c))))))
(defun ansible-expand-host-pattern ()
"Expand Ansible host patterns like 'host-[a:c][1:3]' into nine
host names."
(interactive)
(beginning-of-line)
(let ((bol (point)))
(forward-line)
(let ((eol (point)))
(let ((line (reverse ;; Reversing the input is cheaper than
;; reversing the expansion and the sort
;; order of the expansion is correct.
(string-to-list
(buffer-substring-no-properties bol eol)))))
(let ((expansion (mapcar (lambda (item)
(apply #'string item))
(parse-ansible-pattern line '()))))
(delete-region bol eol)
(dolist (str expansion)
(insert str)))))))
(defun first-token (str)
(let ((tokens (split-string str)))
(if (consp tokens)
(car tokens)
nil)))
(defun getent-hosts (host)
(first-token
(shell-command-to-string
(format "getent hosts '%s'" host))))
(defun ansible-insert-host-address ()
"Append the IP address of the host in the current line to the
line. Example: 'localhost' -> 'localhost ansible_host=127.0.0.1'"
(interactive)
(beginning-of-line)
(let ((bol (point)))
(end-of-line)
(let ((eol (point)))
(let ((line (buffer-substring-no-properties bol eol)))
(let ((name (first-token line)))
(if name
(let ((address (getent-hosts name)))
(if address
(progn (delete-region bol eol)
(insert name)
(insert " ansible_host=")
(insert address)
(forward-line))))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment