How can I write this code into ansible(yaml) format?
grep -i "^\s*PermitRootLogin\s* no\s*" /etc/ssh/sshd_config
if [ $? -eq "0" ]
then
echo "[ PASSED ] - Ensure SSH root login is disabled"
else
echo "[ FAILED ] - Ensure SSH root login is disabled"
fi
This is what I have, I don't know what to write in the when
- name: Check permitRootLogin
hosts: web
tasks:
- lineinfile:
path: /etc/ssh/sshd_config
state: absent
regexp: '^\s*PermitRootLogin\s* yes\s*'
check_mode: yes
register: permit
- name: Ensure SSH root
debug:
msg:
- "[ PASSED ] - Ensure SSH root login is disabled"
when: $regexp == 'PermitRootLogin yes'
CodePudding user response:
Ansible is commonly used to create a desired state. But you can do the trick and use check_mode: yes
as you already tried, not to actually write back the change, but only to simulate it. For this, however, you must write a fully functional task.
- lineinfile:
path: /etc/ssh/sshd_config
state: present
line: "\\g<1>yes"
regexp: '^#?(PermitRootLogin\s )'
backrefs: yes
check_mode: yes
register: permit_root_login_result
- debug:
msg: "[ PASSED ] - Ensure SSH root login is disabled"
when: permit_root_login_result is not changed
In this case you simulate the change of the line PermitRootLogin
to the value yes
. If this change has taken place, the option was not set to yes
before.
If you want to switch the output between PASSED
and FAILED
, your debug
task could look like this:
- debug:
msg: "[ {{ permit_root_login_result is changed | ternary('FAILED', 'PASSED') }} ] - Ensure SSH root login is disabled"
CodePudding user response:
You can always debug by printing out the output of the register:
- name: Print result
debug:
msg: "{{ permit }}"
Every module in Ansible has a different output.
When you get the output/depending on your use case, you can then choose which attribute to use in your condition:
TASK [Print pass/fail result] *************************************************************
ok: [localhost] => {
"msg": {
"backup": "",
"changed": false,
"diff": [
{
"after": "",
"after_header": "/etc/ssh/sshd_config (content)",
"before": "",
"before_header": "/etc/ssh/sshd_config (content)"
},
{
"after_header": "/etc/ssh/sshd_config (file attributes)",
"before_header": "/etc/ssh/sshd_config (file attributes)"
}
],
"failed": false,
"found": 0,
"msg": ""
}
}
In your case, you want to know if the line PermitRootLogin yes
is found.
So you can use the attribute found
from the output:
- name: Ensure SSH root login is disabled
debug:
msg:
- "[ PASSED ] - Ensure SSH root login is disabled"
when: permit.found == 0
- name: Ensure SSH root login is enabled
debug:
msg:
- "[ PASSED ] - Ensure SSH root login is enabled"
when: permit.found != 0