Skip to content

Instantly share code, notes, and snippets.

@craig-m-unsw
Last active August 6, 2020 08:24
Show Gist options
  • Save craig-m-unsw/034c75129ab14de12a0049006a220983 to your computer and use it in GitHub Desktop.
Save craig-m-unsw/034c75129ab14de12a0049006a220983 to your computer and use it in GitHub Desktop.
An ansible role to demo setting and using custom facts
---
# Ansible role to show creating and using custom facts.
# https://docs.ansible.com/ansible/latest/modules/setup_module.html
#
# ansible-playbook --connection=local -i "127.0.0.1," role-custom-facts-demo.yml
- name: Ansible custom facts
hosts: all
gather_facts: no
vars:
somevar: "foobar"
tasks:
- name: create fact
block:
- name: make facts dir
file:
path: /etc/ansible/facts.d/
state: directory
become: true
- name: create script
copy:
dest: "/etc/ansible/facts.d/customtest.fact"
mode: 0755
owner: root
group: root
content: |
#!/usr/bin/env python3
# example of ansible custom fact script
import os
import sys
import platform
import datetime
import json
# var:
date = str(datetime.datetime.now())
# get hostname
host_file = open("/etc/hostname")
bid_line = host_file.read().replace("\n", "")
host_file.close()
# output
print(json.dumps({
"time" : date,
"host_id" : bid_line
}))
become: true
- name: use the new fact
block:
- name: refresh ansible facts
setup: ~
- name: check custom fact was set
assert:
that:
- ansible_local.customtest.host_id is defined
- name: display time from custom fact
debug:
msg: "customtest time var {{ ansible_local.customtest.time }}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment