Merge pull request #133 from wickedyoda/powershell_scripts-add

Powershell scripts add
This commit is contained in:
WickedYoda authored and GitHub committed 2026-10-21 13:27:44 -05:00
commit a73b8d1caf
46 files changed
+2305

No files matched your search

+134
View File
@@ -0,0 +1,134 @@
---
- name: Configure kiosk power behavior and nightly reboot
hosts: all
gather_facts: true
tasks:
- name: Disable system sleep and hibernation targets
ansible.builtin.systemd_service:
name: "{{ item }}"
state: stopped
masked: true
loop:
- sleep.target
- suspend.target
- hibernate.target
- hybrid-sleep.target
become: true
when: ansible_os_family == 'Debian'
- name: Configure GNOME to keep the display on and avoid idle sleep
ansible.builtin.copy:
dest: /etc/dconf/db/local.d/90-kiosk-power
owner: root
group: root
mode: '0644'
content: |
[org/gnome/desktop/session]
idle-delay=uint32 0
[org/gnome/desktop/screensaver]
idle-activation-enabled=false
[org/gnome/settings-daemon/plugins/power]
sleep-inactive-ac-type='nothing'
sleep-inactive-ac-timeout=0
sleep-inactive-battery-type='nothing'
sleep-inactive-battery-timeout=0
become: true
when: ansible_os_family == 'Debian'
- name: Lock GNOME kiosk power settings
ansible.builtin.copy:
dest: /etc/dconf/db/local.d/locks/90-kiosk-power
owner: root
group: root
mode: '0644'
content: |
/org/gnome/desktop/session/idle-delay
/org/gnome/desktop/screensaver/idle-activation-enabled
/org/gnome/settings-daemon/plugins/power/sleep-inactive-ac-type
/org/gnome/settings-daemon/plugins/power/sleep-inactive-ac-timeout
/org/gnome/settings-daemon/plugins/power/sleep-inactive-battery-type
/org/gnome/settings-daemon/plugins/power/sleep-inactive-battery-timeout
become: true
when: ansible_os_family == 'Debian'
- name: Check whether dconf is installed
ansible.builtin.stat:
path: /usr/bin/dconf
register: kiosk_dconf
when: ansible_os_family == 'Debian'
- name: Apply the GNOME system configuration database
ansible.builtin.command: dconf update
changed_when: true
become: true
when:
- ansible_os_family == 'Debian'
- kiosk_dconf.stat.exists
- name: Install the nightly reboot service
ansible.builtin.copy:
dest: /etc/systemd/system/kiosk-nightly-reboot.service
owner: root
group: root
mode: '0644'
content: |
[Unit]
Description=Reboot kiosk every night
[Service]
Type=oneshot
ExecStart=/usr/bin/systemctl reboot
become: true
when: ansible_os_family == 'Debian'
- name: Install the midnight reboot timer
ansible.builtin.copy:
dest: /etc/systemd/system/kiosk-nightly-reboot.timer
owner: root
group: root
mode: '0644'
content: |
[Unit]
Description=Schedule nightly kiosk reboot
[Timer]
OnCalendar=*-*-* 00:00:00
Persistent=true
Unit=kiosk-nightly-reboot.service
[Install]
WantedBy=timers.target
become: true
when: ansible_os_family == 'Debian'
- name: Enable the nightly reboot timer
ansible.builtin.systemd_service:
name: kiosk-nightly-reboot.timer
daemon_reload: true
enabled: true
state: started
become: true
when: ansible_os_family == 'Debian'
- name: Disable Windows automatic sleep and display timeouts
ansible.windows.win_command: "powercfg.exe /change {{ item }} 0"
loop:
- standby-timeout-ac
- standby-timeout-dc
- hibernate-timeout-ac
- hibernate-timeout-dc
- monitor-timeout-ac
- monitor-timeout-dc
changed_when: true
when: ansible_os_family == 'Windows'
- name: Schedule Windows to reboot every night at midnight
ansible.windows.win_command: >-
schtasks.exe /Create /TN "Kiosk nightly reboot"
/TR "shutdown.exe /r /f /t 0"
/SC DAILY /ST 00:00 /RU SYSTEM /RL HIGHEST /F
changed_when: true
when: ansible_os_family == 'Windows'
+39
View File
@@ -0,0 +1,39 @@
- name: Linux system updates
hosts: linux_servers
gather_facts: false
become: true
vars:
apt_purge_patterns: ""
tasks:
- name: Update apt cache
apt:
update_cache: yes
cache_valid_time: 3600
- name: Upgrade installed packages
apt:
upgrade: dist
autoremove: no
clean: no
- name: Remove unused dependencies
apt:
autoremove: yes
purge: yes
- name: Clean apt cache
command: apt clean
changed_when: false
- name: Purge removed packages
shell: |
set -e
{% if apt_purge_patterns %}
dpkg -l | awk '/^rc/ {print $2}' | xargs -r apt purge -y || true
{% else %}
echo "No purge patterns defined; skipping."
{% endif %}
args:
executable: /bin/bash
changed_when: false
+14
View File
@@ -0,0 +1,14 @@
---
- name: Add Home network SSH key to super-hermes
hosts: super-hermes
gather_facts: false
vars:
home_network_key_pub: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIG2wGZTOpvh0s5KmwOxPVaGHCs5NXmVh2X2djrFY9SXJ Home network"
tasks:
- name: Add key to root authorized_keys
authorized_key:
user: root
key: "{{ home_network_key_pub }}"
state: present
exclusive: false
+18
View File
@@ -0,0 +1,18 @@
---
- name: Check hosts
hosts: docker2
gather_facts: false
tasks:
- name: Check config
raw: grep 100.119.225.53 /etc/rsyslog.d/50-remote.conf 2>/dev/null || echo MISSING
register: r1
- name: Check proc
raw: 'pgrep rsyslogd >/dev/null 2>&1 && echo RUNNING || echo NOT_RUNNING'
register: r2
- name: Check cron
raw: crontab -l 2>/dev/null | grep -c refresh-syslog || echo 0
register: r3
- name: Display
debug:
msg: "docker2: config={{r1.stdout|trim}} proc={{r2.stdout|trim}} cron={{r3.stdout|trim}}"
+17
View File
@@ -0,0 +1,17 @@
---
- name: Check nginx on serv1
hosts: serv1
gather_facts: false
tasks:
- name: Check nginx
shell: |
which nginx 2>/dev/null || dpkg -l | grep nginx 2>/dev/null || echo no_nginx
ls /etc/nginx/ 2>/dev/null && cat /etc/nginx/sites-enabled/default 2>/dev/null | head -30 || echo no_nginx_dir
ss -tlnp 2>/dev/null | grep -E ':(80|443|81) ' || netstat -tlnp 2>/dev/null | grep -E ':(80|443|81) ' || echo "no ports listening"
register: result
args:
executable: /bin/bash
- name: Display
debug:
var: result.stdout
+71
View File
@@ -0,0 +1,71 @@
---
# debian_updates.yml
# Runs the canonical apt update suite on every host in the `debian_host`
# inventory group and writes a per-host report to:
# /workspace/debian-update-logs/<host>-update.log
#
# A Hermes cron job (scripts/debian_updates_run.py, every 6h) SSHes into
# docker2, runs this playbook in the ansible-controller container, then reads
# the per-host logs and emails each to alert@tyates.one with subject "<host>- Update Log".
#
# Hosts added to the `debian_host` inventory group are picked up AUTOMATICALLY
# on the next run — no playbook edit required.
#
# Design notes:
# 1. `sudo` is intentionally omitted: the playbook connects as root and runs
# with `become: true`, so each apt subcommand already runs as root.
# docker/docker1/docker2 containers do not have sudo installed.
# 2. `apt purge` is called with no package argument (literal to the request).
# Verified on dank: apt exits 0 and prints a system summary, so the chain
# does NOT self-fail at purge.
# 3. The command may be overridden via the DEBIAN_UPDATE_COMMAND env var
# (read with lookup('env') + default) — used only for safe verification runs.
# 4. No ansible.cfg in the container; ANSIBLE_VAULT_PASSWORD_FILE is exported
# by compose, so `-i /workspace/inventory/ --vault-password-file
# /workspace/vault_pass.txt` resolves vaulted vars automatically.
- name: Debian apt update suite
hosts: debian_host
become: true
gather_facts: false
vars:
debian_update_command: "{{ lookup('env','DEBIAN_UPDATE_COMMAND') | default('apt update && apt upgrade -y && apt full-upgrade && apt autoremove && apt clean && apt purge', true) }}"
report_dir: /workspace/debian-update-logs
tasks:
- name: Ensure per-host report directory exists
delegate_to: localhost
run_once: true
ansible.builtin.file:
path: "{{ report_dir }}"
state: directory
mode: '0755'
- name: Run the Debian update command sequence (verbatim, no sudo)
ansible.builtin.shell: "{{ debian_update_command }}"
args:
executable: /bin/bash
chdir: /
register: update_result
failed_when: false
changed_when: true
- name: Write per-host update report
delegate_to: localhost
ansible.builtin.copy:
dest: "{{ report_dir }}/{{ inventory_hostname }}-update.log"
mode: '0644'
content: |
Host: {{ inventory_hostname }}
Address: {{ ansible_host }}
SSH port: {{ ansible_port | default(22) }}
Run timestamp (UTC): {{ lookup('pipe','date -u +%Y-%m-%dT%H:%M:%SZ') }}
Command: {{ debian_update_command }}
Exit code: {{ update_result.rc }}
Result: {{ "SUCCESS (rc=0)" if update_result.rc == 0 else ("command exited rc=" ~ update_result.rc) }}
--- stdout (tail) ---
{{ update_result.stdout | default("") }}
--- stderr (tail) ---
{{ update_result.stderr | default("") }}
@@ -0,0 +1,63 @@
---
# Deploy Home network SSH key to Linux hosts, routers, and macOS
- name: Deploy Home network SSH key to Linux hosts
hosts: linux_servers
gather_facts: false
vars:
home_network_key_pub: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIG2wGZTOpvh0s5KmwOxPVaGHCs5NXmVh2X2djrFY9SXJ Home network"
tasks:
- name: Ensure .ssh directory exists
file:
path: "~/.ssh"
state: directory
mode: '0700'
- name: Add Home network key to authorized_keys (root)
become: true
authorized_key:
user: root
key: "{{ home_network_key_pub }}"
state: present
exclusive: false
- name: Deploy Home network key to Flint4 router (no Python)
hosts: flint4
gather_facts: false
vars:
home_network_key_pub: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIG2wGZTOpvh0s5KmwOxPVaGHCs5NXmVh2X2djrFY9SXJ Home network"
tasks:
- name: Add Home network key via shell
shell: |
mkdir -p ~/.ssh /etc/dropbear/authorized_keys
echo '{{ home_network_key_pub }}' >> ~/.ssh/authorized_keys
echo '{{ home_network_key_pub }}' >> /etc/dropbear/authorized_keys/authorized_keys
args:
creates: ~/.ssh/authorized_keys
- name: Deploy Home network key to macOS travers-mac-mini
hosts: travers-mac-mini
gather_facts: false
vars:
home_network_key_pub: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIG2wGZTOpvh0s5KmwOxPVaGHCs5NXmVh2X2djrFY9SXJ Home network"
tasks:
- name: Ensure .ssh directory exists
file:
path: "~/.ssh"
state: directory
mode: '0700'
- name: Add Home network key to authorized_keys (traver user)
authorized_key:
user: traver
key: "{{ home_network_key_pub }}"
state: present
exclusive: false
- name: Add Home network key to authorized_keys (root)
become: true
authorized_key:
user: root
key: "{{ home_network_key_pub }}"
state: present
exclusive: false
@@ -0,0 +1,20 @@
---
# Deploy Home network SSH key to macOS travers-mac-mini root
- name: Deploy Home network key to macOS travers-mac-mini root
hosts: travers-mac-mini
gather_facts: false
vars:
home_network_key_pub: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIG2wGZTOpvh0s5KmwOxPVaGHCs5NXmVh2X2djrFY9SXJ Home network"
tasks:
- name: Add Home network key to root authorized_keys
# Use shell since sudo requires password
# The user 'traver' might have passwordless sudo for ssh
shell: |
cat ~/.ssh/authorized_keys 2>/dev/null | grep -q "Home network" || {
mkdir -p ~/.ssh
echo '{{ home_network_key_pub }}' >> ~/.ssh/authorized_keys
}
args:
executable: /bin/zsh
failed_when: false
@@ -0,0 +1,50 @@
---
# Deploy Home network SSH key to Flint4 router (no Python)
- name: Deploy Home network key to Flint4 router
hosts: flint4
gather_facts: false
vars:
ansible_python_interpreter: /nonexistent
home_network_key_pub: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIG2wGZTOpvh0s5KmwOxPVaGHCs5NXmVh2X2djrFY9SXJ Home network"
tasks:
- name: Add Home network key to authorized_keys
raw: |
mkdir -p ~/.ssh
echo '{{ home_network_key_pub }}' >> ~/.ssh/authorized_keys
# Add to root authorized_keys
echo '{{ home_network_key_pub }}' >> /root/.ssh/authorized_keys
# Add to dropbear authorized_keys file (OpenWrt style)
mkdir -p /etc/dropbear
echo '{{ home_network_key_pub }}' >> /etc/dropbear/authorized_keys
args:
executable: /bin/sh
changed_when: true
# Deploy Home network key to macOS travers-mac-mini
- name: Deploy Home network key to macOS travers-mac-mini
hosts: travers-mac-mini
gather_facts: false
vars:
home_network_key_pub: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIG2wGZTOpvh0s5KmwOxPVaGHCs5NXmVh2X2djrFY9SXJ Home network"
tasks:
- name: Ensure .ssh directory exists
file:
path: "~/.ssh"
state: directory
mode: '0700'
- name: Add Home network key to authorized_keys (traver user)
authorized_key:
user: traver
key: "{{ home_network_key_pub }}"
state: present
exclusive: false
- name: Add Home network key to authorized_keys (root)
become: true
authorized_key:
user: root
key: "{{ home_network_key_pub }}"
state: present
exclusive: false
@@ -0,0 +1,21 @@
---
# Deploy Home network SSH key to super-hermes (replaces oc)
- name: Deploy Home network key to super-hermes
hosts: super-hermes
gather_facts: false
vars:
home_network_key_pub: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIG2wGZTOpvh0s5KmwOxPVaGHCs5NXmVh2X2djrFY9SXJ Home network"
tasks:
- name: Ensure .ssh directory exists
file:
path: "~/.ssh"
state: directory
mode: '0700'
- name: Add Home network key to authorized_keys (root)
authorized_key:
user: root
key: "{{ home_network_key_pub }}"
state: present
exclusive: false
@@ -0,0 +1,25 @@
---
- name: Deploy Home network SSH key to all routers
hosts: routers
gather_facts: false
vars:
home_network_key_pub: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIG2wGZTOpvh0s5KmwOxPVaGHCs5NXmVh2X2djrFY9SXJ Home network"
tasks:
- name: Add key to authorized_keys (root)
raw: |
mkdir -p ~/.ssh /root/.ssh
echo '{{ home_network_key_pub }}' >> /root/.ssh/authorized_keys
echo '{{ home_network_key_pub }}' >> ~/.ssh/authorized_keys
args:
executable: /bin/sh
changed_when: true
ignore_errors: true
- name: Add key for dropbear (OpenWrt routers)
raw: |
echo '{{ home_network_key_pub }}' >> /etc/dropbear/authorized_keys 2>/dev/null || true
args:
executable: /bin/sh
changed_when: true
ignore_errors: true
+14
View File
@@ -0,0 +1,14 @@
- name: Diag dee-pc config
hosts: dee-pc
gather_facts: no
tasks:
- name: Read first lines of telegraf.conf
win_shell: |
Get-Content -Path "C:\Program Files\Telegraf\telegraf.conf" -TotalCount 10
args:
executable: powershell
register: head
- name: Show head
debug:
var: head.stdout_lines
+14
View File
@@ -0,0 +1,14 @@
- name: Diag dee-pc eventlog
hosts: dee-pc
gather_facts: no
tasks:
- name: Read latest telegraf event log entries
win_shell: |
Get-EventLog -LogName Application -Source telegraf -Newest 5 | Select-Object TimeGenerated, EntryType, Message | Format-List
args:
executable: powershell
register: ev
- name: Show event log
debug:
var: ev.stdout_lines
+69
View File
@@ -0,0 +1,69 @@
---
# docker_prune.yml
# Removes unused (dangling + unreferenced-but-named) Docker images on every
# Docker host in the `debian_host` group, and writes a per-host report to
# /workspace/docker-prune-logs/<host>-docker-prune.log (bind-mounted to the
# docker2 host so the Hermes cron orchestrator can read + email it).
#
# Scheduled: Hermes cron job `docker-prune-48h` -> 0 0 */2 * * (every 2 days).
# Reaches hosts via docker2 -> ansible-controller container (flint4 key).
#
# `sudo` omitted: runs as root with become:true (containers have no sudo).
# Non-docker hosts (nas, dank) are handled by a shell guard and report
# "DOCKER=NO — nothing to prune" with rc 0 (not a failure). New Docker hosts
# added to debian_host are pruned automatically on the next run.
#
# Safe testing: override the command via env DOCKER_PRUNE_COMMAND (read below).
# Production command (default) = `docker image prune -a -f` (deletes unused).
- name: Docker image prune on Debian/docker hosts
hosts: debian_host
become: true
gather_facts: false
vars:
# Production (destructive). Env-overridable for safe dry-runs.
# shlex-safe: passed via `docker exec -e DOCKER_PRUNE_COMMAND=...` (NOT -e).
docker_prune_command: "{{ lookup('env','DOCKER_PRUNE_COMMAND') | default('docker image prune -a -f', true) }}"
report_dir: /workspace/debian-update-logs
tasks:
- name: Ensure per-host report directory (container-local, bind-mounted to host)
delegate_to: localhost
run_once: true
ansible.builtin.file:
path: "{{ report_dir }}"
state: directory
mode: '0755'
- name: Prune unused docker images (skip cleanly if no docker daemon)
ansible.builtin.shell: |
if command -v docker >/dev/null 2>&1; then
{{ docker_prune_command }}
else
echo "DOCKER=NO — no docker daemon on this host; nothing to prune"
fi
args:
executable: /bin/bash
register: prune_result
failed_when: false
changed_when: true
- name: Write per-host prune report
delegate_to: localhost
ansible.builtin.copy:
dest: "{{ report_dir }}/{{ inventory_hostname }}-docker-prune.log"
mode: '0644'
content: |
Host: {{ inventory_hostname }}
Address: {{ ansible_host }}
SSH port: {{ ansible_port | default(22) }}
Run timestamp (UTC): {{ lookup('pipe','date -u +%Y-%m-%dT%H:%M:%SZ') }}
Command: {{ docker_prune_command }}
Exit code: {{ prune_result.rc }}
Result: {{ "SUCCESS (rc=0)" if prune_result.rc == 0 else ("command exited rc=" ~ prune_result.rc) }}
--- stdout (tail) ---
{{ prune_result.stdout | default("") }}
--- stderr (tail) ---
{{ prune_result.stderr | default("") }}
+17
View File
@@ -0,0 +1,17 @@
---
- name: Verify syslog config on all Linux hosts
hosts: docker, docker1, docker2, serv1, serv2, flint4, travers-mac-mini
gather_facts: false
tasks:
- name: Check syslog config
raw: |
echo "SYSLOG_CONFIG=$(grep -c 100.119.225.53 /etc/rsyslog.d/50-remote.conf 2>/dev/null || echo 0)"
echo "RSYSLOG_PROC=$(pgrep rsyslogd >/dev/null 2>&1 && echo RUNNING || echo NOT_RUNNING)"
echo "CRON=$(crontab -l 2>/dev/null | grep -c refresh-syslog || echo 0)"
register: check
changed_when: false
- name: Display result
debug:
msg: "{{ inventory_hostname }}: {{ check.stdout | trim }}"
+28
View File
@@ -0,0 +1,28 @@
---
- name: Verify syslog config on all hosts
hosts: docker, docker1, docker2, serv1, serv2, flint4, travers-mac-mini
gather_facts: false
tasks:
- name: Check syslog config
raw: |
if [ -f /etc/rsyslog.d/50-remote.conf ]; then
CONFIG=$(grep -c 100.119.225.53 /etc/rsyslog.d/50-remote.conf 2>/dev/null || echo 0)
elif [ -f /etc/syslog.conf ] 2>/dev/null; then
CONFIG=$(grep -c 100.119.225.53 /etc/syslog.conf 2>/dev/null || echo 0)
elif [ -f /etc/asl.conf ] 2>/dev/null; then
CONFIG=$(grep -c '100.119.225.53' /etc/asl.conf 2>/dev/null || echo 0)
else
CONFIG=0
fi
PROC=$(pgrep rsyslogd >/dev/null 2>&1 && echo RUNNING || echo STOPPED)
CRON=$(crontab -l 2>/dev/null | grep -c refresh-syslog || echo 0)
echo "Syslog:CONFIG=${CONFIG} PROC=${PROC} CRON=${CRON}"
register: check
changed_when: false
- name: Display result
debug:
msg: "{{ '{{' }} inventory_hostname }}: {{ '{{' }} check.stdout | trim }}"
+59
View File
@@ -0,0 +1,59 @@
---
- name: Fix Linux Telegraf configs
hosts: linux_servers
gather_facts: false
vars:
influxdb_url: "http://docker2.tail99133.ts.net:8086"
influxdb_org: "homelab"
influxdb_bucket: "telegraf"
telegraf_conf_path: /etc/telegraf/telegraf.conf
secret_path: /etc/telegraf/secrets/token
nas_token_path: /mnt/nas/public/Hermes_Data/secrets/influxdb/token
tasks:
- name: Read InfluxDB token from NAS
local_action:
module: slurp
src: "{{ nas_token_path }}"
register: nas_token
run_once: true
- name: Set InfluxDB token fact
set_fact:
influxdb_token: "{{ nas_token.content | b64decode }}"
- name: Deploy InfluxDB token to secret path
copy:
content: "{{ influxdb_token }}"
dest: "{{ secret_path }}"
mode: "0600"
owner: root
group: root
- name: Update telegraf.conf URL
replace:
path: "{{ telegraf_conf_path }}"
regexp: 'urls = \[.*\]'
replace: 'urls = ["{{ influxdb_url }}"]'
- name: Update telegraf.conf token reference
replace:
path: "{{ telegraf_conf_path }}"
regexp: 'token = ".*"'
replace: 'token = "@{{ secret_path }}"'
- name: Update telegraf.conf org and bucket
replace:
path: "{{ telegraf_conf_path }}"
regexp: "{{ item.regexp }}"
replace: "{{ item.replace }}"
loop:
- regexp: "organization = \".*\""
replace: "organization = \"{{ influxdb_org }}\""
- regexp: "bucket = \".*\""
replace: "bucket = \"{{ influxdb_bucket }}\""
- name: Restart Telegraf to apply changes
service:
name: telegraf
state: restarted
+25
View File
@@ -0,0 +1,25 @@
---
- name: Configure syslog forwarding on Flint4 (OpenWrt)
hosts: flint4
gather_facts: false
vars:
ansible_python_interpreter: /nonexistent
tasks:
- name: Configure syslog forwarding in /etc/config/system
raw: |
# Add remote syslog forwarding to OpenWrt system config
uci set system.@system[0].log_ip='100.119.225.53'
uci set system.@system[0].log_port='514'
uci commit system
# Also create rsyslog config as backup
mkdir -p /etc/rsyslog.d
echo '*.* @@100.119.225.53:514' > /etc/rsyslog.d/50-remote.conf
# Add cron for 15-min refresh
mkdir -p /etc/crontabs
(crontab -l 2>/dev/null; echo "*/15 * * * * uci commit system 2>/dev/null; /etc/init.d/system reload 2>/dev/null || true") | sort -u | crontab -
args:
executable: /bin/sh
changed_when: true
+20
View File
@@ -0,0 +1,20 @@
---
- name: Configure remote syslog on macOS
hosts: travers-mac-mini
gather_facts: false
tasks:
- name: Write syslog.conf via copy (without become)
copy:
dest: /etc/syslog.conf
content: "*.* 100.119.225.53\n"
mode: '0644'
ignore_errors: true
- name: Add cron for 15-min refresh
cron:
name: "refresh-syslog-config"
minute: "*/15"
job: "sudo launchctl stop com.apple.syslogd 2>/dev/null; sudo launchctl start com.apple.syslogd 2>/dev/null || true"
user: traver
ignore_errors: true
+11
View File
@@ -0,0 +1,11 @@
---
- name: Configure remote syslog on macOS
hosts: travers-mac-mini
gather_facts: false
tasks:
- name: Write syslog.conf using sudo tee
shell: |
echo '*.* 100.119.225.53' | sudo tee /etc/syslog.conf 2>/dev/null
timeout: 10
ignore_errors: true
+58
View File
@@ -0,0 +1,58 @@
---
- name: Install and configure rsyslog on serv2
hosts: serv2
gather_facts: false
vars:
syslog_server: "100.119.225.53"
syslog_port: "514"
tasks:
- name: Check rsyslog installation
shell: which rsyslogd 2>/dev/null || echo "NOT_INSTALLED"
register: rsyslog_check
- name: Install rsyslog
package:
name: rsyslog
state: present
when: rsyslog_check.stdout == "NOT_INSTALLED"
ignore_errors: true
- name: Create rsyslog conf directory
file:
path: /etc/rsyslog.d
state: directory
mode: '0755'
ignore_errors: true
- name: Create rsyslog remote conf
copy:
dest: /etc/rsyslog.d/50-remote.conf
content: |
# Forward logs to remote syslog server
*.* @@{{ syslog_server }}:{{ syslog_port }}
mode: '0644'
- name: Restart rsyslog
shell: |
systemctl enable rsyslog 2>/dev/null || true
systemctl restart rsyslog 2>/dev/null || service rsyslog restart 2>/dev/null || rsyslogd -c5 2>/dev/null || true
ignore_errors: true
- name: Create refresh script
copy:
dest: /usr/local/bin/refresh-syslog-config.sh
mode: '0755'
content: |
#!/bin/bash
systemctl reload rsyslog 2>/dev/null || true
service rsyslog restart 2>/dev/null || true
ignore_errors: true
- name: Add cron job for 15-min refresh
cron:
name: "refresh-syslog-config"
minute: "*/15"
job: "/usr/local/bin/refresh-syslog-config.sh 2>/dev/null"
user: root
ignore_errors: true
+85
View File
@@ -0,0 +1,85 @@
- name: Flint 4 OpenWrt standards
hosts: flint4
gather_facts: false
connection: ssh
vars:
lan_ip: "192.168.62.1"
lan_netmask: "255.255.255.0"
wan_proto: "dhcp"
dns_search: "gigi.tyates.one"
dhcp_lan_start: "100"
dhcp_lan_limit: "150"
dhcp_lan_leasetime: "12h"
wifi_country: "US"
wifi_channel_2g: "auto"
wifi_channel_5g: "auto"
wifi_ssid: "Gigi's-Wifi"
wifi_encryption: "psk2+ccmp"
wifi_key: "gigilovesyou"
tasks:
- name: Apply Flint 4 standards idempotently
ansible.builtin.shell: |
set -o pipefail
changed=0
apply() {
section="$1"
option="$2"
desired="$3"
current=$(uci show "$section" 2>/dev/null | grep "^${section}.${option}=" | head -n1 | cut -d= -f2-)
if [ "$current" != "$desired" ]; then
uci set "$section.$option=$desired"
changed=1
fi
}
apply network lan ipaddr "{{ lan_ip }}"
apply network lan netmask "{{ lan_netmask }}"
apply network lan dns_search "{{ dns_search }}"
apply network wan proto "{{ wan_proto }}"
apply network guest disabled "1"
apply dhcp lan start "{{ dhcp_lan_start }}"
apply dhcp lan limit "{{ dhcp_lan_limit }}"
apply dhcp lan leasetime "{{ dhcp_lan_leasetime }}"
apply dhcp lan dhcpv4 "server"
apply firewall @zone[1] network "wan wan6 wwan secondwan"
apply firewall @zone[1] masq "1"
apply firewall @zone[1] mtu_fix "1"
apply firewall @zone[2] input "REJECT"
apply firewall @zone[2] output "ACCEPT"
apply firewall @zone[2] forward "REJECT"
apply firewall @forwarding[0] enabled "1"
apply wireless wifi0 country "{{ wifi_country }}"
apply wireless wifi0 channel "{{ wifi_channel_2g }}"
apply wireless wifi0 hwmode "11beg"
apply wireless wifi0 txpower "30"
apply wireless wifi0 disabled "0"
apply wireless wifi2g ssid "{{ wifi_ssid }}"
apply wireless wifi2g encryption "{{ wifi_encryption }}"
apply wireless wifi2g key "{{ wifi_key }}"
apply wireless wifi2g disabled "0"
apply wireless guest2g disabled "1"
apply wireless wifi1 country "{{ wifi_country }}"
apply wireless wifi1 channel "{{ wifi_channel_5g }}"
apply wireless wifi1 hwmode "11bea"
apply wireless wifi1 txpower "32"
apply wireless wifi1 disabled "0"
apply wireless wifi5g ssid "{{ wifi_ssid }}"
apply wireless wifi5g encryption "{{ wifi_encryption }}"
apply wireless wifi5g key "{{ wifi_key }}"
apply wireless wifi5g disabled "0"
apply wireless guest5g disabled "1"
if [ "$changed" = "1" ]; then
uci commit
/etc/init.d/network reload
/etc/init.d/dnsmasq reload
/etc/init.d/firewall reload
wifi reload
echo "changed"
else
echo "ok"
fi
register: flint4_result
changed_when: flint4_result.stdout == "changed"
@@ -0,0 +1,69 @@
- name: Install and configure Telegraf on Debian/Ubuntu
hosts: linux_servers
gather_facts: true
vars:
influxdb_url: "http://docker2.tail99133.ts.net:8086"
influxdb_org: "homelab"
influxdb_bucket: "telegraf"
telegraf_conf_path: /etc/telegraf/telegraf.conf
secret_search_paths:
- "/etc/telegraf/secrets"
- "/mnt/nas/public/Hermes_Data/secrets/influxdb"
tasks:
- name: Ensure InfluxDB repo key is installed
apt_key:
url: https://repos.influxdata.com/influxdata-archive.key
state: present
- name: Ensure InfluxDB repo is configured
apt_repository:
repo: "deb [signed-by=/etc/apt/keyrings/influxdata-archive.gpg] https://repos.influxdata.com/debian stable main"
state: present
filename: influxdata
- name: Install Telegraf
apt:
name: telegraf
state: present
update_cache: yes
- name: Load InfluxDB token from secret paths
slurp:
src: "{{ item }}/token"
register: token_results
failed_when: false
loop: "{{ secret_search_paths }}"
- name: Set InfluxDB token fact
set_fact:
influxdb_token: "{{ (token_results.results | selectattr('content') | first).content | b64decode | trim }}"
when: token_results.results | selectattr('content') | list | length > 0
- name: Fail if token not found
assert:
that:
- influxdb_token is defined
- influxdb_token | length > 0
fail_msg: "InfluxDB token not found in any secret path"
- name: Deploy telegraf.conf
template:
src: templates/telegraf-debian.conf.j2
dest: "{{ telegraf_conf_path }}"
owner: telegraf
group: telegraf
mode: '0640'
notify: Restart Telegraf
- name: Ensure Telegraf service is enabled and running
service:
name: telegraf
state: started
enabled: yes
handlers:
- name: Restart Telegraf
service:
name: telegraf
state: restarted
@@ -0,0 +1,86 @@
- name: Install and configure Telegraf
hosts: win-pc
gather_facts: true
vars:
influxdb_url: "http://docker2.tail99133.ts.net:8086"
influxdb_org: "homelab"
influxdb_bucket: "telegraf"
telegraf_version: "1.39.2"
telegraf_install_dir: "C:\\Program Files\\Telegraf"
telegraf_conf: "{{ telegraf_install_dir }}\\telegraf.conf"
secret_search_paths:
- "C:\\Program Files\\Telegraf\\secrets"
- "C:\\secrets\\influxdb"
- "\\\\nas\\public\\Hermes_Data\\telegraf-windows\\secrets"
influxdb_token: ""
tasks:
- name: Ensure temp directory exists
win_file:
path: C:\Temp
state: directory
- name: Load InfluxDB token from secret paths
win_shell: |
$paths = {{ secret_search_paths | to_json }}
foreach ($p in $paths) {
$tokenFile = Join-Path $p "token"
if (Test-Path $tokenFile) {
Write-Output (Get-Content $tokenFile -Raw).Trim()
exit 0
}
}
exit 1
register: influx_token_result
changed_when: false
failed_when: influx_token_result.rc not in [0, 1]
when: influxdb_token | length == 0
- name: Set token fact from secrets if not provided
set_fact:
influxdb_token: "{{ influx_token_result.stdout }}"
when:
- influxdb_token | length == 0
- influx_token_result.stdout | length > 0
- name: Ensure InfluxDB token is available
assert:
that:
- influxdb_token | length > 0
fail_msg: "Missing InfluxDB token. Pass influxdb_token or place secrets on the host."
- name: Download Telegraf {{ telegraf_version }} zip
win_get_url:
url: "https://dl.influxdata.com/telegraf/releases/telegraf-{{ telegraf_version }}_windows_amd64.zip"
dest: C:\Temp\telegraf-{{ telegraf_version }}.zip
- name: Extract Telegraf
win_unzip:
src: C:\Temp\telegraf-{{ telegraf_version }}.zip
dest: C:\Temp\telegraf
creates: C:\Temp\telegraf\telegraf-{{ telegraf_version }}\telegraf.exe
- name: Copy Telegraf to Program Files
win_command: cmd /c xcopy /E /I /Y "C:\Temp\telegraf\telegraf-{{ telegraf_version }}" "{{ telegraf_install_dir }}"
- name: Deploy telegraf.conf
win_copy:
src: ../templates/telegraf-windows.conf.j2
dest: "{{ telegraf_conf }}"
force: yes
- name: Install Telegraf service
win_shell: "& '{{ telegraf_install_dir }}\\telegraf.exe' --service install --config '{{ telegraf_conf }}'"
- name: Configure Telegraf service auto-restart
win_shell: |
sc.exe failure telegraf reset= 86400 actions= restart/5000
sc.exe start telegraf
args:
executable: cmd
- name: Ensure Telegraf service is running
win_service:
name: telegraf
state: started
start_mode: auto
@@ -0,0 +1,12 @@
---
- name: Keep Windows from sleeping
hosts: windows
gather_facts: false
tasks:
- name: Disable automatic sleep on AC and battery
ansible.windows.win_command: "powercfg.exe /change {{ item }} 0"
loop:
- standby-timeout-ac
- standby-timeout-dc
changed_when: true
+21
View File
@@ -0,0 +1,21 @@
---
- name: Remount NAS drives (mount -a)
hosts: debian_host
become: true
become_user: root
gather_facts: false
tasks:
- name: Remount all fstab entries
command: mount -a
args:
creates: /proc/mounts
register: mount_result
changed_when: mount_result.rc == 0
- name: Report mount status
debug:
msg:
- "Remount done"
- "Hosts affected: {{ ansible_play_hosts_all }}"
- "Result: {{ mount_result.rc }}"
@@ -0,0 +1,22 @@
---
- name: Remove shutdown commands and disable sleep and hibernation
hosts: windows
gather_facts: false
tasks:
- name: Hide shutdown-related commands for the Ansible user
ansible.windows.win_regedit:
path: HKCU:\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
name: NoClose
data: 1
type: dword
state: present
- name: Disable automatic sleep and hibernation timeouts
ansible.windows.win_command: "powercfg.exe /change {{ item }} 0"
loop:
- standby-timeout-ac
- standby-timeout-dc
- hibernate-timeout-ac
- hibernate-timeout-dc
changed_when: true
+209
View File
@@ -0,0 +1,209 @@
- name: Setup dee-pc
hosts: dee-pc
gather_facts: yes
vars:
telegraf_version: "1.39.2"
telegraf_zip_url: "https://dl.influxdata.com/telegraf/releases/telegraf-{{ telegraf_version }}_windows_amd64.zip"
telegraf_zip_dest: "C:/Temp/telegraf-{{ telegraf_version }}_windows_amd64.zip"
telegraf_extract_dir: "C:/Temp/telegraf"
telegraf_extracted_subdir: "{{ telegraf_extract_dir }}/telegraf-{{ telegraf_version }}"
telegraf_install_dir: "C:/Program Files/Telegraf"
telegraf_exe_install: "{{ telegraf_install_dir }}/telegraf.exe"
telegraf_conf_dest: "{{ telegraf_install_dir }}/telegraf.conf"
ps_version: "7.6.4"
ps_url: "https://github.com/PowerShell/PowerShell/releases/download/v{{ ps_version }}/PowerShell-{{ ps_version }}-win-x64.msi"
ps_msi_dest: "C:/Temp/PowerShell-{{ ps_version }}-win-x64.msi"
influxdb_url: "http://docker2.tail99133.ts.net:8086"
influxdb_org: "homelab"
influxdb_bucket: "telegraf"
influxdb_token: "{{ lookup('env', 'INFLUXDB_TOKEN') }}"
tasks:
- name: Verify WinRM connectivity
win_ping:
- name: Ensure Temp directory exists
win_file:
path: C:/Temp
state: directory
- name: Ensure Telegraf install directory exists
win_file:
path: "{{ telegraf_install_dir }}"
state: directory
- name: Download Telegraf zip
win_get_url:
url: "{{ telegraf_zip_url }}"
dest: "{{ telegraf_zip_dest }}"
- name: Extract Telegraf zip to Temp
win_unzip:
src: "{{ telegraf_zip_dest }}"
dest: "{{ telegraf_extract_dir }}"
creates: "{{ telegraf_extracted_subdir }}/telegraf.exe"
- name: Move Telegraf files into install dir
win_copy:
src: "{{ telegraf_extracted_subdir }}/"
dest: "{{ telegraf_install_dir }}/"
remote_src: yes
- name: Install Telegraf Windows service
win_shell: '"{{ telegraf_exe_install }}" service install'
args:
executable: cmd
register: telegraf_service_install
ignore_errors: true
- name: Download PowerShell MSI
win_get_url:
url: "{{ ps_url }}"
dest: "{{ ps_msi_dest }}"
register: ps_download
- name: Unblock downloaded PowerShell installer
win_shell: Unblock-File -Path "{{ ps_msi_dest }}"
args:
executable: powershell
register: ps_unblock
ignore_errors: true
- name: Install PowerShell silently via scheduled task
win_shell: |
$msiPath = "{{ ps_msi_dest }}"
$action = New-ScheduledTaskAction -Execute "msiexec.exe" -Argument "/i `"$msiPath`" /qn /norestart ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELLPROMPT=1 ADD_PATH=1"
$trigger = New-ScheduledTaskTrigger -At (Get-Date) -Once
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
Register-ScheduledTask -TaskName "InstallPS7" -Action $action -Trigger $trigger -Settings $settings -Description "Install PowerShell 7" -User "SYSTEM" -RunLevel Highest
Start-ScheduledTask -TaskName "InstallPS7"
$task = Get-ScheduledTask -TaskName "InstallPS7"
while ($task.State -ne "Ready" -and $task.State -ne "Failed") {
Start-Sleep -Seconds 5
$task = Get-ScheduledTask -TaskName "InstallPS7"
}
$exitCode = (Get-ScheduledTaskInfo -TaskName "InstallPS7").LastTaskResult
Unregister-ScheduledTask -TaskName "InstallPS7" -Confirm:$false
exit $exitCode
args:
executable: powershell
register: ps_install
ignore_errors: true
- name: Enable auto-restart after power loss
win_shell: |
$regPath = "HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Power"
if (-not (Test-Path $regPath)) {
New-Item -Path $regPath -Force | Out-Null
}
Set-ItemProperty -Path $regPath -Name "HiberbootEnabled" -Value 0 -Type DWord -Force
Set-ItemProperty -Path "HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Reliability" -Name "ShutdownReasonOn" -Value 0 -Type DWord -Force
args:
executable: powershell
register: power_recovery
ignore_errors: true
- name: Write telegraf.conf
win_copy:
dest: "{{ telegraf_conf_dest }}"
content: |
# Telegraf Windows 11 config generated by Ansible
[agent]
interval = "10s"
round_interval = true
metric_batch_size = 1000
metric_buffer_limit = 10000
collection_jitter = "0s"
flush_interval = "10s"
flush_jitter = "0s"
hostname = "{{ ansible_hostname }}"
omit_hostname = false
[global_tags]
host = "{{ ansible_hostname }}"
os = "windows"
[[outputs.influxdb_v2]]
urls = ["{{ influxdb_url }}"]
token = "{{ influxdb_token }}"
organization = "{{ influxdb_org }}"
bucket = "{{ influxdb_bucket }}"
timeout = "5s"
[[inputs.win_perf_counters]]
[[inputs.win_perf_counters.object]]
ObjectName = "Processor"
Instances = ["*"]
Counters = ["% Processor Time"]
Measurement = "win_cpu"
IncludeTotal = true
[[inputs.win_perf_counters.object]]
ObjectName = "Memory"
Instances = ["*"]
Counters = [
"Available Bytes",
"Cache Bytes",
"Committed Bytes",
"Pool Nonpaged Bytes",
"Pool Paged Bytes",
"% Committed Bytes In Use"
]
Measurement = "win_mem"
[[inputs.win_perf_counters.object]]
ObjectName = "LogicalDisk"
Instances = ["*"]
Counters = ["% Free Space", "Free Megabytes", "% Disk Time", "Current Disk Queue Length"]
Measurement = "win_disk"
[[inputs.win_perf_counters.object]]
ObjectName = "Network Interface"
Instances = ["*"]
Counters = ["Bytes Received/sec", "Bytes Sent/sec", "Packets Received/sec", "Packets Sent/sec"]
Measurement = "win_net"
[[inputs.win_perf_counters.object]]
ObjectName = "Process"
Instances = ["*"]
Counters = [
"% Processor Time",
"Working Set",
"Private Bytes",
"Thread Count",
"Handle Count",
"IO Read Bytes/sec",
"IO Write Bytes/sec"
]
Measurement = "win_process"
[[inputs.win_services]]
service_names = ["*"]
register: telegraf_conf
- name: Configure Telegraf service recovery and auto-start
win_shell: sc.exe failure telegraf reset= 86400 actions= restart/5000
args:
executable: cmd
register: telegraf_recovery
ignore_errors: true
- name: Start Telegraf with auto-start
win_service:
name: telegraf
state: started
start_mode: auto
- name: Verify Telegraf service status
win_service:
name: telegraf
register: telegraf_status
- name: Show Telegraf status
debug:
msg:
- "Telegraf service: {{ telegraf_status.state }}"
- "Config written: {{ telegraf_conf.changed | default(false) }}"
- "Config path: {{ telegraf_conf_dest }}"
- "PowerShell installed: {{ ps_install.rc | default('n/a') }}"
- "Power recovery configured: {{ power_recovery.changed | default(false) }}"
+211
View File
@@ -0,0 +1,211 @@
---
- name: Install and configure SSH and SFTP for the Ansible account
hosts: windows
gather_facts: false
vars:
flint4_ssh_public_key_file: /keys/id_ed25519_ansible.pub
tasks:
- name: Read the Flint4 public key on the Ansible controller
ansible.builtin.set_fact:
flint4_ssh_public_key: "{{ lookup('ansible.builtin.file', flint4_ssh_public_key_file) | trim }}"
- name: Validate the supplied OpenSSH public key
ansible.builtin.assert:
that:
- flint4_ssh_public_key is match('^(ssh-ed25519|ssh-rsa|ecdsa-sha2-[^ ]+) [A-Za-z0-9+/]+={0,3}( .*)?$')
fail_msg: The public key file is missing or does not contain a supported OpenSSH public key.
- name: Verify the local ansible account exists and is an administrator
ansible.windows.win_powershell:
script: |
$ErrorActionPreference = 'Stop'
$user = Get-LocalUser -Name 'ansible' -ErrorAction Stop
$administratorSid = [System.Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')
$isAdministrator = Get-LocalGroupMember -SID $administratorSid |
Where-Object { $_.SID.Value -eq $user.SID.Value }
if (-not $isAdministrator) {
throw "The local account 'ansible' must be a member of the Administrators group."
}
$Ansible.Changed = $false
- name: Install the OpenSSH Server Windows capability
ansible.windows.win_powershell:
script: |
$ErrorActionPreference = 'Stop'
$capabilityName = 'OpenSSH.Server~~~~0.0.1.0'
$capability = Get-WindowsCapability -Online -Name $capabilityName
if ($capability.State -ne 'Installed') {
Add-WindowsCapability -Online -Name $capabilityName | Out-Null
$Ansible.Changed = $true
}
else {
$Ansible.Changed = $false
}
notify: Restart OpenSSH server
- name: Configure SSH public-key authentication and SFTP
ansible.windows.win_powershell:
script: |
$ErrorActionPreference = 'Stop'
$configPath = Join-Path $env:ProgramData 'ssh\sshd_config'
$original = [System.IO.File]::ReadAllText($configPath)
$lines = [System.Collections.Generic.List[string]]::new()
Get-Content -LiteralPath $configPath | ForEach-Object { $lines.Add([string]$_) }
function Set-GlobalDirective {
param([string]$Pattern, [string]$Value)
$matchIndex = -1
for ($index = 0; $index -lt $lines.Count; $index++) {
if ($lines[$index] -match '^\s*Match\s+') {
$matchIndex = $index
break
}
}
$limit = if ($matchIndex -ge 0) { $matchIndex } else { $lines.Count }
for ($index = 0; $index -lt $limit; $index++) {
if ($lines[$index] -match $Pattern) {
$lines[$index] = $Value
return
}
}
if ($matchIndex -ge 0) {
$lines.Insert($matchIndex, $Value)
}
else {
$lines.Add($Value)
}
}
Set-GlobalDirective '^\s*#?\s*PubkeyAuthentication\s+\S+' 'PubkeyAuthentication yes'
Set-GlobalDirective '^\s*#?\s*Subsystem\s+sftp\s+.*$' 'Subsystem sftp sftp-server.exe'
$administratorMatch = -1
for ($index = 0; $index -lt $lines.Count; $index++) {
if ($lines[$index] -match '^\s*#?\s*Match\s+Group\s+administrators\s*$') {
$administratorMatch = $index
break
}
}
if ($administratorMatch -lt 0) {
$lines.Add('')
$lines.Add('Match Group administrators')
$lines.Add(' AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys')
}
else {
$lines[$administratorMatch] = 'Match Group administrators'
$authorizedKeysIndex = -1
for ($index = $administratorMatch + 1; $index -lt $lines.Count; $index++) {
if ($lines[$index] -match '^\s*Match\s+') { break }
if ($lines[$index] -match '^\s*#?\s*AuthorizedKeysFile\s+') {
$authorizedKeysIndex = $index
break
}
}
if ($authorizedKeysIndex -ge 0) {
$lines[$authorizedKeysIndex] = ' AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys'
}
else {
$lines.Insert($administratorMatch + 1, ' AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys')
}
}
$updated = [string]::Join("`r`n", $lines) + "`r`n"
if ($updated -ne $original) {
[System.IO.File]::WriteAllText($configPath, $updated, [System.Text.UTF8Encoding]::new($false))
$Ansible.Changed = $true
}
else {
$Ansible.Changed = $false
}
notify: Restart OpenSSH server
- name: Add the Flint4 public key for Windows administrators
ansible.windows.win_powershell:
parameters:
Flint4PublicKey: "{{ flint4_ssh_public_key }}"
script: |
param([string]$Flint4PublicKey)
$ErrorActionPreference = 'Stop'
$authorizedKeys = Join-Path $env:ProgramData 'ssh\administrators_authorized_keys'
if (-not (Test-Path -LiteralPath $authorizedKeys)) {
New-Item -Path $authorizedKeys -ItemType File -Force | Out-Null
}
$existingKeys = @(Get-Content -LiteralPath $authorizedKeys)
if ($existingKeys -notcontains $Flint4PublicKey) {
Add-Content -LiteralPath $authorizedKeys -Value $Flint4PublicKey -Encoding ascii
$Ansible.Changed = $true
}
else {
$Ansible.Changed = $false
}
- name: Restrict administrator authorized-key file permissions
ansible.windows.win_powershell:
script: |
$ErrorActionPreference = 'Stop'
$authorizedKeys = Join-Path $env:ProgramData 'ssh\administrators_authorized_keys'
& icacls.exe $authorizedKeys /inheritance:r /grant:r '*S-1-5-32-544:F' '*S-1-5-18:F' | Out-Null
if ($LASTEXITCODE -ne 0) {
throw 'Could not set the required ACL on administrators_authorized_keys.'
}
$Ansible.Changed = $false
- name: Validate the OpenSSH server configuration
ansible.windows.win_command: C:\Windows\System32\OpenSSH\sshd.exe -t
changed_when: false
- name: Allow SSH from domain and private networks
ansible.windows.win_powershell:
script: |
$ErrorActionPreference = 'Stop'
$displayName = 'Ansible OpenSSH Server TCP 22'
$rule = Get-NetFirewallRule -DisplayName $displayName -ErrorAction SilentlyContinue |
Select-Object -First 1
if (-not $rule) {
New-NetFirewallRule -DisplayName $displayName `
-Description 'Allow SSH and SFTP management from domain and private networks.' `
-Direction Inbound -Action Allow -Protocol TCP -LocalPort 22 `
-Profile Domain,Private | Out-Null
$Ansible.Changed = $true
}
else {
$currentProfiles = @(([string]$rule.Profile -split ',\s*') | Sort-Object)
$expectedProfiles = @('Domain', 'Private')
$profilesDiffer = (@(Compare-Object $currentProfiles $expectedProfiles).Count -gt 0)
$needsUpdate = (-not $rule.Enabled) -or
($rule.Action.ToString() -ne 'Allow') -or
($rule.Direction.ToString() -ne 'Inbound') -or
$profilesDiffer
if ($needsUpdate) {
Set-NetFirewallRule -Name $rule.Name -Enabled True -Action Allow `
-Direction Inbound -Profile Domain,Private
$Ansible.Changed = $true
}
else {
$Ansible.Changed = $false
}
}
- name: Ensure the OpenSSH server service is enabled and running
ansible.windows.win_service:
name: sshd
start_mode: auto
state: started
handlers:
- name: Restart OpenSSH server
ansible.windows.win_service:
name: sshd
state: restarted
+150
View File
@@ -0,0 +1,150 @@
- name: Standard Telegraf deployment for all hosts
hosts: telegraf
gather_facts: true
vars:
telegraf_version: "1.39.2"
influxdb_url: "http://docker2.tail99133.ts.net:8086"
influxdb_org: "homelab"
influxdb_bucket: "telegraf"
linux_secret_path: /etc/telegraf/secrets/token
nas_token_path: /mnt/nas/public/Hermes_Data/secrets/influxdb/token
windows_install_dir: "C:\\Program Files\\Telegraf"
windows_conf: "{{ windows_install_dir }}\\telegraf.conf"
tasks:
- name: LINUX - Install Telegraf via apt
when: ansible_os_family == "Debian" or ansible_system == "Linux"
block:
- name: Ensure InfluxDB repo key is installed
apt_key:
url: https://repos.influxdata.com/influxdata-archive.key
state: present
- name: Ensure InfluxDB repo is configured
apt_repository:
repo: "deb [signed-by=/etc/apt/keyrings/influxdata-archive.gpg] https://repos.influxdata.com/debian stable main"
state: present
filename: influxdata
- name: Install Telegraf
apt:
name: telegraf
state: present
update_cache: yes
- name: Ensure secrets directory exists
file:
path: "{{ linux_secret_path | dirname }}"
state: directory
mode: "0700"
owner: root
group: root
- name: Read InfluxDB token from NAS
local_action:
module: slurp
src: "{{ nas_token_path }}"
register: nas_token
run_once: true
- name: Set InfluxDB token fact
set_fact:
influxdb_token: "{{ nas_token.content | b64decode }}"
- name: Deploy InfluxDB token to secrets directory
copy:
content: "{{ influxdb_token }}"
dest: "{{ linux_secret_path }}"
mode: "0600"
owner: root
group: root
- name: Deploy Linux Telegraf config
template:
src: ../templates/telegraf-debian.conf.j2
dest: /etc/telegraf/telegraf.conf
owner: telegraf
group: telegraf
mode: "0640"
notify: Restart Linux Telegraf
- name: Ensure Telegraf service is enabled and running
service:
name: telegraf
state: started
enabled: yes
- name: WINDOWS - Configure power settings
when: ansible_os_family == "Windows"
block:
- name: Disable sleep
win_shell: powercfg /change standby-timeout-ac 0; powercfg /change monitor-timeout-ac 30; powercfg /change hibernate-timeout-ac 0; powercfg /change standby-timeout-dc 0; powercfg /change monitor-timeout-dc 30; powercfg /change hibernate-timeout-dc 0
- name: Set active power scheme to always on
win_shell: powercfg /setactive 8c5e7fda-e8bf-45a6-a7cc-4e54e757e0d4
ignore_errors: true
- name: WINDOWS - Deploy Telegraf
when: ansible_os_family == "Windows"
block:
- name: Ensure temp directory exists
win_file:
path: C:\Temp
state: directory
- name: Download Telegraf {{ telegraf_version }} zip
win_get_url:
url: "https://dl.influxdata.com/telegraf/releases/telegraf-{{ telegraf_version }}_windows_amd64.zip"
dest: C:\Temp\telegraf-{{ telegraf_version }}.zip
- name: Extract Telegraf
win_unzip:
src: C:\Temp\telegraf-{{ telegraf_version }}.zip
dest: C:\Temp\telegraf
creates: C:\Temp\telegraf\telegraf-{{ telegraf_version }}\telegraf.exe
- name: Copy Telegraf to Program Files
win_command: cmd /c xcopy /E /I /Y "C:\Temp\telegraf\telegraf-{{ telegraf_version }}" "{{ windows_install_dir }}"
- name: Deploy Windows Telegraf config
win_copy:
src: ../templates/telegraf-windows.conf.j2
dest: "{{ windows_conf }}"
force: yes
notify: Restart Windows Telegraf
- name: Install Telegraf service if missing
win_shell: |
if (Get-Service -Name telegraf -ErrorAction SilentlyContinue) {
Write-Output "telegraf service already exists"
} else {
& '{{ windows_install_dir }}\telegraf.exe' --service install --config '{{ windows_conf }}' --non-strict-env-handling
}
args:
executable: powershell
- name: Configure Telegraf service auto-restart
win_shell: |
sc.exe failure telegraf reset= 86400 actions= restart/5000
sc.exe start telegraf
args:
executable: cmd
- name: Ensure Telegraf service is running
win_service:
name: telegraf
state: started
start_mode: auto
handlers:
- name: Restart Linux Telegraf
when: ansible_os_family == "Debian" or ansible_system == "Linux"
service:
name: telegraf
state: restarted
- name: Restart Windows Telegraf
when: ansible_os_family == "Windows"
win_service:
name: telegraf
state: restarted
+35
View File
@@ -0,0 +1,35 @@
---
- name: Configure Debian syslog clients
hosts: debian_host:!docker1
become: true
gather_facts: true
tasks:
- name: Install rsyslog
ansible.builtin.apt:
name: rsyslog
state: present
update_cache: true
when: ansible_facts['os_family'] == "Debian"
- name: Configure UDP syslog forwarding
ansible.builtin.copy:
dest: /etc/rsyslog.d/50-remote.conf
content: "*.* @docker1:514\n"
owner: root
group: root
mode: "0644"
notify: Restart rsyslog
when: ansible_facts['os_family'] == "Debian"
- name: Ensure rsyslog is enabled and running
ansible.builtin.service:
name: rsyslog
state: started
enabled: true
when: ansible_facts['os_family'] == "Debian"
handlers:
- name: Restart rsyslog
ansible.builtin.service:
name: rsyslog
state: restarted
@@ -0,0 +1,64 @@
---
- name: Configure Windows clients to forward Event Logs over syslog
hosts: windows
gather_facts: false
vars:
syslog_server: docker1
syslog_port: 514
nxlog_msi_source: "{{ playbook_dir }}/nxlog-ce-3.2.2329.msi"
nxlog_msi_dest: C:\Temp\nxlog-ce-3.2.2329.msi
nxlog_config_path: C:\Program Files\nxlog\conf\nxlog.conf
tasks:
- name: Create temporary installer directory
ansible.windows.win_file:
path: C:\Temp
state: directory
- name: Copy NXLog Community Edition installer to client
ansible.windows.win_copy:
src: "{{ nxlog_msi_source }}"
dest: "{{ nxlog_msi_dest }}"
- name: Install NXLog Community Edition
ansible.windows.win_package:
path: "{{ nxlog_msi_dest }}"
state: present
arguments: /qn /norestart
- name: Configure NXLog to send Windows Event Logs over UDP
ansible.windows.win_copy:
dest: "{{ nxlog_config_path }}"
content: |
<Extension syslog>
Module xm_syslog
</Extension>
<Input eventlog>
Module im_msvistalog
ReadFromLast TRUE
</Input>
<Output syslog_out>
Module om_udp
Host {{ syslog_server }}
Port {{ syslog_port }}
Exec to_syslog_ietf();
</Output>
<Route eventlog_to_syslog>
Path eventlog => syslog_out
</Route>
notify: Restart NXLog
- name: Ensure NXLog service is enabled and running
ansible.windows.win_service:
name: nxlog
start_mode: auto
state: started
handlers:
- name: Restart NXLog
ansible.windows.win_service:
name: nxlog
state: restarted
@@ -0,0 +1,49 @@
---
- name: Restore shutdown, sleep, and hibernation options
hosts: windows
gather_facts: false
tasks:
- name: Allow shutdown without logging on
ansible.windows.win_regedit:
path: HKLM:\SOFTWARE\Policies\Microsoft\Windows\System
name: ShutdownWithoutLogon
data: 1
type: dword
state: present
- name: Remove shutdown and related restrictions set by policy
ansible.windows.win_regedit:
path: "{{ item.path }}"
name: "{{ item.name }}"
state: absent
loop:
- path: HKCU:\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
name: NoClose
- path: HKLM:\SOFTWARE\Policies\Microsoft\Windows\System
name: DisableShutdownOption
- path: HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer
name: NoShutdown
- path: HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer
name: CloseSystemNoShutdown
- path: HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
name: DisableCACheck
- path: HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
name: DisableTaskMgr
- name: Restore automatic sleep and hibernation timeouts
ansible.windows.win_command: "powercfg.exe /change {{ item.setting }} {{ item.minutes }}"
loop:
- setting: standby-timeout-ac
minutes: 120
- setting: standby-timeout-dc
minutes: 120
- setting: hibernate-timeout-ac
minutes: 180
- setting: hibernate-timeout-dc
minutes: 30
changed_when: true
- name: Enable hibernation
ansible.windows.win_command: powercfg.exe /hibernate on
changed_when: true
@@ -0,0 +1,63 @@
- name: Update Telegraf configs for consistent InfluxDB settings
hosts: linux_servers
gather_facts: false
vars:
influxdb_url: "http://docker2.tail99133.ts.net:8086"
influxdb_org: "homelab"
influxdb_bucket: "telegraf"
telegraf_conf_path: /etc/telegraf/telegraf.conf
secret_path: /etc/telegraf/secrets/token
nas_token_path: /mnt/nas/public/Hermes_Data/secrets/influxdb/token
tasks:
- name: Ensure secrets directory exists
file:
path: /etc/telegraf/secrets
state: directory
mode: "0700"
owner: root
group: root
ignore_errors: yes
- name: Read NAS token once
local_action:
module: slurp
src: "{{ nas_token_path }}"
register: nas_token
run_once: true
- name: Deploy InfluxDB token to secret path
copy:
content: "{{ nas_token.content | b64decode }}"
dest: "{{ secret_path }}"
mode: "0600"
owner: root
group: root
- name: Update telegraf.conf URL
replace:
path: "{{ telegraf_conf_path }}"
regexp: urls = [.*]
replace: "urls = [\"{{ influxdb_url }}\"]"
- name: Update telegraf.conf token to file reference
replace:
path: "{{ telegraf_conf_path }}"
regexp: token = .*
replace: "token = \"@{{ secret_path }}\""
- name: Update telegraf.conf org and bucket
replace:
path: "{{ telegraf_conf_path }}"
regexp: "{{ item.regexp }}"
replace: "{{ item.replace }}"
loop:
- regexp: "organization = \".*\""
replace: "organization = \"{{ influxdb_org }}\""
- regexp: "bucket = \".*\""
replace: "bucket = \"{{ influxdb_bucket }}\""
- name: Restart Telegraf to apply changes
service:
name: telegraf
state: restarted
+11
View File
@@ -0,0 +1,11 @@
- name: Verify Kiosk Settings
hosts: sams-surface
gather_facts: false
tasks:
- name: Check monitor timeout AC
win_shell: |
powercfg /query SCHEME_CURRENT SUB_VIDEO VIDEOIDLE
register: monitor_ac
- name: Show monitor timeout output
debug:
var: monitor_ac.stdout_lines
@@ -0,0 +1,41 @@
---
- name: Verify Home network SSH key on all hosts
hosts: docker, docker1, docker2, serv1, serv2
gather_facts: false
vars:
home_network_key_pub: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIG2wGZTOpvh0s5KmwOxPVaGHCs5NXmVh2X2djrFY9SXJ Home network"
tasks:
- name: Check if key exists in authorized_keys
shell: grep -q "Home network" /root/.ssh/authorized_keys 2>/dev/null && echo "KEY_PRESENT" || echo "KEY_MISSING"
register: key_check
- name: Display result
debug:
msg: "{{ inventory_hostname }}: {{ key_check.stdout }}"
- name: Verify key on Flint4
hosts: flint4
gather_facts: false
vars:
ansible_python_interpreter: /nonexistent
tasks:
- name: Check key on flint4
raw: sh -c "grep -q 'Home network' ~/.ssh/authorized_keys 2>/dev/null && echo KEY_PRESENT || echo KEY_MISSING"
register: key_check
- name: Display result
debug:
msg: "flint4: {{ key_check.stdout }}"
- name: Verify key on travers-mac-mini
hosts: travers-mac-mini
gather_facts: false
tasks:
- name: Check key on travers-mac-mini
shell: grep -q "Home network" ~/.ssh/authorized_keys 2>/dev/null && echo "KEY_PRESENT" || echo "KEY_MISSING"
register: key_check
- name: Display result
debug:
msg: "travers-mac-mini: {{ key_check.stdout }}"
@@ -0,0 +1,15 @@
---
- name: Verify syslog on flint4
hosts: flint4
gather_facts: false
vars:
ansible_python_interpreter: /nonexistent
tasks:
- name: Check flint4 syslog config
raw: cat /etc/rsyslog.d/50-remote.conf 2>/dev/null || echo "CONFIG_MISSING"
register: config_check
- name: Display result
debug:
msg: "flint4: {{ config_check.stdout }}"
@@ -0,0 +1,25 @@
---
- name: Verify syslog configuration on all Linux hosts
hosts: docker, docker1, docker2, serv1, serv2, flint4
gather_facts: false
vars:
ansible_python_interpreter: auto
tasks:
- name: Check rsyslog config
shell: |
cat /etc/rsyslog.d/50-remote.conf 2>/dev/null || echo "CONFIG_MISSING"
register: syslog_config
- name: Check rsyslog process
shell: pgrep rsyslogd >/dev/null 2>&1 && echo "RUNNING" || echo "NOT_RUNNING"
register: rsyslog_proc
- name: Check cron job
shell: crontab -l 2>/dev/null | grep refresh-syslog || echo "NO_CRON"
register: cron_job
- name: Display results
debug:
msg: "{{ inventory_hostname }} | syslog={{ syslog_config.stdout | trim }} | proc={{ rsyslog_proc.stdout }} | cron={{ cron_job.stdout | trim }}"
ignore_errors: true
+61
View File
@@ -0,0 +1,61 @@
- name: Windows Kiosk
hosts: win-pc
gather_facts: false
vars:
kiosk_power_cfg:
# AC power
ac_timeout_ac: 0 # never sleep on AC
ac_timeout_dc: 0 # never sleep on battery
hibernate_ac: 0 # never hibernate on AC
hibernate_dc: 0 # never hibernate on battery
monitor_ac: 0 # never turn off monitor on AC
monitor_dc: 0 # never turn off monitor on battery
# Always on / disable fast startup
fast_startup: 0
tasks:
- name: Disable sleep on AC
win_shell: powercfg /change standby-timeout-ac {{ kiosk_power_cfg.ac_timeout_ac }}
- name: Disable sleep on battery
win_shell: powercfg /change standby-timeout-dc {{ kiosk_power_cfg.ac_timeout_dc }}
- name: Disable hibernate on AC
win_shell: powercfg /change hibernate-timeout-ac {{ kiosk_power_cfg.hibernate_ac }}
- name: Disable hibernate on battery
win_shell: powercfg /change hibernate-timeout-dc {{ kiosk_power_cfg.hibernate_dc }}
- name: Disable monitor off on AC
win_shell: powercfg /change monitor-timeout-ac {{ kiosk_power_cfg.monitor_ac }}
- name: Disable monitor off on battery
win_shell: powercfg /change monitor-timeout-dc {{ kiosk_power_cfg.monitor_dc }}
- name: Disable fast startup
win_shell: |
$reg = "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Power"
Set-ItemProperty -Path $reg -Name HiberbootEnabled -Value {{ kiosk_power_cfg.fast_startup }} -Type DWord -ErrorAction SilentlyContinue
- name: Set AC battery charge limit to 30% max
win_shell: |
$ac = (powercfg /getactivescheme).Split()[3]
powercfg /setacvalueindex $ac e73a048d-bf27-4f12-9731-8b2076e8891f f5c2ca50-c5f0-4ff2-86dd-252c4e3726b7 30
powercfg /setactive $ac
register: batt_limit
ignore_errors: true
- name: Battery charge limit summary
debug:
msg: >-
{{ 'Battery charge limit set to 30% on AC'
if batt_limit is succeeded and batt_limit is changed
else 'Battery charge limit not applied or unsupported on this device' }}
- name: Summary
debug:
msg:
- "Kiosk mode applied to {{ inventory_hostname }}"
- "Sleep: disabled"
- "Hibernate: disabled"
- "Display: never off"
- "Fast startup: disabled"
+91
View File
@@ -0,0 +1,91 @@
- name: Windows updates and Telegraf maintenance
hosts: win-pc
gather_facts: true
vars:
telegraf_version: "1.39.2"
influxdb_url: "http://docker2.tail99133.ts.net:8086"
influxdb_org: "homelab"
influxdb_bucket: "telegraf"
windows_install_dir: "C:\\Program Files\\Telegraf"
windows_conf: "{{ windows_install_dir }}\\telegraf.conf"
update_categories:
- SecurityUpdates
- CriticalUpdates
- UpdateRollups
- WindowsDefender
secret_search_paths:
- "C:\\Program Files\\Telegraf\\secrets"
- "C:\\secrets\\influxdb"
- "\\\\nas\\public\\Hermes_Data\\telegraf-windows\\secrets"
influxdb_token: ""
tasks:
- name: Configure power settings
block:
- name: Disable sleep
win_shell: powercfg /change standby-timeout-ac 0; powercfg /change monitor-timeout-ac 30; powercfg /change hibernate-timeout-ac 0; powercfg /change standby-timeout-dc 0; powercfg /change monitor-timeout-dc 30; powercfg /change hibernate-timeout-dc 0
- name: Set active power scheme to always on
win_shell: powercfg /setactive 8c5e7fda-e8bf-45a6-a7cc-4e54e757e0d4
ignore_errors: true
- name: Install Windows updates
win_updates:
category_names: "{{ update_categories }}"
state: installed
reboot: no
- name: Ensure temp directory exists
win_file:
path: C:\Temp
state: directory
- name: Download Telegraf {{ telegraf_version }} zip
win_get_url:
url: "https://dl.influxdata.com/telegraf/releases/telegraf-{{ telegraf_version }}_windows_amd64.zip"
dest: C:\Temp\telegraf-{{ telegraf_version }}.zip
- name: Extract Telegraf
win_unzip:
src: C:\Temp\telegraf-{{ telegraf_version }}.zip
dest: C:\Temp\telegraf
creates: C:\Temp\telegraf\telegraf-{{ telegraf_version }}\telegraf.exe
- name: Copy Telegraf to Program Files
win_command: cmd /c xcopy /E /I /Y "C:\Temp\telegraf\telegraf-{{ telegraf_version }}" "{{ windows_install_dir }}"
- name: Deploy Windows Telegraf config
win_copy:
src: ../templates/telegraf-windows.conf.j2
dest: "{{ windows_conf }}"
force: yes
notify: Restart Windows Telegraf
- name: Install Telegraf service if missing
win_shell: |
if (Get-Service -Name telegraf -ErrorAction SilentlyContinue) {
Write-Output "telegraf service already exists"
} else {
& '{{ windows_install_dir }}\telegraf.exe' --service install --config '{{ windows_conf }}' --non-strict-env-handling
}
args:
executable: powershell
- name: Configure Telegraf service auto-restart
win_shell: |
sc.exe failure telegraf reset= 86400 actions= restart/5000
sc.exe start telegraf
args:
executable: cmd
- name: Ensure Telegraf service is running
win_service:
name: telegraf
state: started
start_mode: auto
handlers:
- name: Restart Windows Telegraf
win_service:
name: telegraf
state: restarted
+91
View File
@@ -0,0 +1,91 @@
- name: Windows updates and Telegraf maintenance
hosts: win-pc
gather_facts: true
vars:
telegraf_version: "1.39.2"
influxdb_url: "http://docker2.tail99133.ts.net:8086"
influxdb_org: "homelab"
influxdb_bucket: "telegraf"
windows_install_dir: "C:\\Program Files\\Telegraf"
windows_conf: "{{ windows_install_dir }}\\telegraf.conf"
update_categories:
- SecurityUpdates
- CriticalUpdates
- UpdateRollups
- WindowsDefender
secret_search_paths:
- "C:\\Program Files\\Telegraf\\secrets"
- "C:\\secrets\\influxdb"
- "\\\\nas\\public\\Hermes_Data\\telegraf-windows\\secrets"
influxdb_token: ""
tasks:
- name: Configure power settings
block:
- name: Disable sleep
win_shell: powercfg /change standby-timeout-ac 0; powercfg /change monitor-timeout-ac 30; powercfg /change hibernate-timeout-ac 0; powercfg /change standby-timeout-dc 0; powercfg /change monitor-timeout-dc 30; powercfg /change hibernate-timeout-dc 0
- name: Set active power scheme to always on
win_shell: powercfg /setactive 8c5e7fda-e8bf-45a6-a7cc-4e54e757e0d4
ignore_errors: true
- name: Install Windows updates
win_updates:
category_names: "{{ update_categories }}"
state: installed
reboot: no
- name: Ensure temp directory exists
win_file:
path: C:\Temp
state: directory
- name: Download Telegraf {{ telegraf_version }} zip
win_get_url:
url: "https://dl.influxdata.com/telegraf/releases/telegraf-{{ telegraf_version }}_windows_amd64.zip"
dest: C:\Temp\telegraf-{{ telegraf_version }}.zip
- name: Extract Telegraf
win_unzip:
src: C:\Temp\telegraf-{{ telegraf_version }}.zip
dest: C:\Temp\telegraf
creates: C:\Temp\telegraf\telegraf-{{ telegraf_version }}\telegraf.exe
- name: Copy Telegraf to Program Files
win_command: cmd /c xcopy /E /I /Y "C:\Temp\telegraf\telegraf-{{ telegraf_version }}" "{{ windows_install_dir }}"
- name: Deploy Windows Telegraf config
win_copy:
src: ../templates/telegraf-windows.conf.j2
dest: "{{ windows_conf }}"
force: yes
notify: Restart Windows Telegraf
- name: Install Telegraf service if missing
win_shell: |
if (Get-Service -Name telegraf -ErrorAction SilentlyContinue) {
Write-Output "telegraf service already exists"
} else {
& '{{ windows_install_dir }}\telegraf.exe' --service install --config '{{ windows_conf }}' --non-strict-env-handling
}
args:
executable: powershell
- name: Configure Telegraf service auto-restart
win_shell: |
sc.exe failure telegraf reset= 86400 actions= restart/5000
sc.exe start telegraf
args:
executable: cmd
- name: Ensure Telegraf service is running
win_service:
name: telegraf
state: started
start_mode: auto
handlers:
- name: Restart Windows Telegraf
win_service:
name: telegraf
state: restarted
@@ -0,0 +1,37 @@
---
- name: Configure Microsoft Defender and install Windows updates
hosts: windows
gather_facts: false
tasks:
- name: Configure Defender protections and update signatures
ansible.windows.win_powershell:
script: |
$ErrorActionPreference = 'Stop'
$before = Get-MpPreference
$signatureBefore = (Get-MpComputerStatus).AntivirusSignatureVersion
$settingsChanged = (
$before.DisableRealtimeMonitoring -ne $false -or
$before.DisableBehaviorMonitoring -ne $false -or
$before.PUAProtection.ToString() -ne 'Enabled' -or
$before.EnableControlledFolderAccess.ToString() -ne 'Enabled' -or
$before.EnableNetworkProtection.ToString() -ne 'Enabled'
)
Set-MpPreference -DisableRealtimeMonitoring $false
Set-MpPreference -DisableBehaviorMonitoring $false
Set-MpPreference -PUAProtection Enabled
Set-MpPreference -EnableControlledFolderAccess Enabled
Set-MpPreference -EnableNetworkProtection Enabled
Update-MpSignature
$signatureAfter = (Get-MpComputerStatus).AntivirusSignatureVersion
$Ansible.Changed = $settingsChanged -or ($signatureBefore -ne $signatureAfter)
- name: Install all available Windows updates and reboot if required
ansible.windows.win_updates:
category_names:
- '*'
reboot: true
reboot_timeout: 3600
@@ -0,0 +1,10 @@
$ErrorActionPreference = 'Stop'
foreach ($setting in @('standby-timeout-ac', 'standby-timeout-dc')) {
& powercfg.exe /change $setting 0
if ($LASTEXITCODE -ne 0) {
throw "Failed to set power setting '$setting'."
}
}
Write-Output 'Automatic sleep is disabled for the current power plan on AC and battery.'
@@ -0,0 +1,21 @@
$ErrorActionPreference = 'Stop'
$explorerPolicyKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer'
New-Item -Path $explorerPolicyKey -Force | Out-Null
New-ItemProperty -Path $explorerPolicyKey -Name 'NoClose' -PropertyType DWord -Value 1 -Force | Out-Null
$powerSettings = @(
'standby-timeout-ac',
'standby-timeout-dc',
'hibernate-timeout-ac',
'hibernate-timeout-dc'
)
foreach ($setting in $powerSettings) {
& powercfg.exe /change $setting 0
if ($LASTEXITCODE -ne 0) {
throw "Failed to set power setting '$($setting[0])'."
}
}
Write-Output 'Shutdown-related Start menu commands are hidden, and automatic sleep/hibernate timeouts are disabled for the current power plan.'
@@ -0,0 +1,28 @@
# Unblock-Computer-Shutdown.ps1
# Re-enables normal shutdown behavior on Windows 11
# Run as Administrator, then reboot
# Remove/Reset all policy keys set by BlockShutdown.ps1
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\System' `
-Name 'ShutdownWithoutLogon' -Value 1 -ErrorAction SilentlyContinue
Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\System' `
-Name 'DisableShutdownOption' -ErrorAction SilentlyContinue
Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer' `
-Name 'NoShutdown' -ErrorAction SilentlyContinue
Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer' `
-Name 'CloseSystemNoShutdown' -ErrorAction SilentlyContinue
Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' `
-Name 'DisableCACheck' -ErrorAction SilentlyContinue
Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' `
-Name 'DisableTaskMgr' -ErrorAction SilentlyContinue
# Re-enable sleep and hibernate
powercfg /change standby-timeout-ac 120 | Out-Null
powercfg /change standby-timeout-dc 120 | Out-Null
powercfg /change hibernate-timeout-ac 180 | Out-Null
powercfg /change hibernate-timeout-dc 30 | Out-Null
powercfg /h on
Write-Host "All shutdown restrictions removed. Reboot for changes to take full effect." -ForegroundColor Green
@@ -0,0 +1,11 @@
#Requires -RunAsAdministrator
$ErrorActionPreference = 'Stop'
Update-MpSignature
Set-MpPreference -DisableRealtimeMonitoring $false
Set-MpPreference -DisableBehaviorMonitoring $false
Set-MpPreference -PUAProtection Enabled
Set-MpPreference -EnableControlledFolderAccess Enabled
Set-MpPreference -EnableNetworkProtection Enabled