--- # Not ansible.posix.sysctl, which always manages a file too. The absolute path is for a PATH without the sbin directories. # A key that cannot be read (unknown or write-only) counts as different, so the write below decides. - name: Read the live sysctl values ansible.builtin.command: argv: [/usr/sbin/sysctl, -e, -n, "{{ item.key }}"] loop: "{{ __system_baseline_sysctl | dict2items }}" register: __system_baseline_sysctl_live changed_when: false failed_when: false check_mode: false become: true # `removes` names a path that always exists: with it, check mode reports the pending write as changed instead of skipping the command. # sysctl exits 0 for a read-only key and only warns (`setting key ...`), so stderr counts too. - name: Apply the sysctl hardening settings ansible.builtin.command: argv: [/usr/sbin/sysctl, -w, "{{ item.item.key }}={{ item.item.value }}"] removes: /proc/sys environment: LC_ALL: C loop: "{{ __system_baseline_sysctl_live.results }}" loop_control: label: "{{ item.item.key }}={{ item.item.value }}" when: item.stdout | default('') | split != item.item.value | split register: __system_baseline_sysctl_apply failed_when: >- __system_baseline_sysctl_apply.rc | default(0) != 0 or __system_baseline_sysctl_apply.stderr | default('') is search('setting key') become: true