Use python script for facts

possibly fixes https://github.com/m4rcu5nl/ansible-role-zerotier/issues/28
pull/39/head
Hannu Teulahti 2021-02-08 10:58:24 +02:00
parent 1def93f756
commit a2063b191c
4 changed files with 57 additions and 51 deletions

View File

@ -1,43 +0,0 @@
#!/bin/bash
FACTS_DIR='/etc/ansible/facts.d'
FACT_FILE="${FACTS_DIR}/zerotier.fact"
NODE_STATUS=($(zerotier-cli status))
NETWORKS=$(zerotier-cli listnetworks | tail -n+2)
function file_content {
if [ ! -z "$NETWORKS" ]; then
network_count=$(echo "$NETWORKS" |wc -l)
counter=1
echo "{"
echo " \"node_id\":\"${NODE_STATUS[2]}\","
echo " \"networks\": {"
while read -r; do
network=($REPLY)
echo " \"${network[2]}\": {"
echo " \"status\":\"${network[5]}\","
echo " \"device\":\"${network[7]}\""
if [ "$counter" -eq "$network_count" ]; then
echo " }"
else
echo " },"
fi
((counter++))
done <<< $NETWORKS
echo " }"
echo "}"
else
echo "{\"node_id\":\"${NODE_STATUS[2]}\",\"networks\":{}}"
fi
}
if [ ! -d "$FACTS_DIR" ]; then
mkdir -p $FACTS_DIR
fi
file_content > $FACT_FILE
# TO-DO
# Handle different states than "OK". Other statuses can mess up positions.

42
files/zerotier.fact.py Normal file
View File

@ -0,0 +1,42 @@
#!/usr/bin/env python3
import json
import subprocess
out = subprocess.Popen(['/usr/sbin/zerotier-cli', '-j', 'info'],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout, stderr = out.communicate()
try:
info = json.loads(stdout)
except:
print('zerotier-cli error. Are you sure you are running this as root?')
exit(1)
j = {
'node_id': info['address']
}
out = subprocess.Popen(['/usr/sbin/zerotier-cli', '-j', 'listnetworks'],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout, stderr = out.communicate()
try:
networks = json.loads(stdout)
except:
print('zerotier-cli error. Are you sure you are running this as root?')
exit(2)
n = {}
for network in networks:
n[network['id']] = {
'status': network['status'],
'device': network['portDeviceName'],
}
j['networks'] = n
print(json.dumps(j, indent=2))

View File

@ -22,6 +22,21 @@
notify: notify:
- enable zerotier-one - enable zerotier-one
- name: create facts.d
file:
path: /etc/ansible/facts.d
recurse: true
state: directory
- name: Install zerotier custom facts
copy:
src: zerotier.fact.py
dest: /etc/ansible/facts.d/zerotier.fact
mode: 0755
- name: Re-gather facts
setup: ~
when: when:
- zerotier_repo is not defined or zerotier_repo is succeeded - zerotier_repo is not defined or zerotier_repo is succeeded
- not ansible_check_mode - not ansible_check_mode

View File

@ -4,14 +4,6 @@
when: when:
- not skip_install | default(false) | bool - not skip_install | default(false) | bool
- block:
- name: Update ansible_local facts
script: set_facts.sh
- name: Re-gather ansible_local facts
setup: filter=ansible_local
- import_tasks: authorize_node.yml - import_tasks: authorize_node.yml
when: when:
- zerotier_api_accesstoken | length > 0 - zerotier_api_accesstoken | length > 0