5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
19 from ansible.module_utils.basic import AnsibleModule
21 class SshdConf(object):
24 self.module = AnsibleModule(argument_spec=dict(regexp=dict(required=True),
25 values=dict(required=True)))
26 self.used_regexp = self.module.params["regexp"]
27 self.set_values = self.module.params["values"]
28 self.sshd_contents = None
30 self.target = "/etc/ssh/sshd_config"
32 def _read_sshd_conf(self):
34 with open(self.target, "r") as sshd_file:
35 self.sshd_contents = sshd_file.readlines()
37 def _write_sshd_conf(self):
39 os.remove(self.target)
41 for line in self.sshd_contents:
42 with open(self.target, "a") as out:
46 os.system("chmod 600 "+ self.target)
48 os.system("chown root:root "+ self.target)
51 def _start_finder(self):
55 for line in self.sshd_contents:
56 if start is None and re.compile("^[A-Za-z].*").search(line):
58 if re.compile("^[#\s]*Match ").search(line):
71 def ssh_checker_and_setter(self, line):
73 self.sshd_contents[line] = ''
75 self.sshd_contents[line] = self.module.params["values"]
78 def _configuration(self, start, end):
79 for line in range(0, end):
80 if re.compile("^"+self.module.params["regexp"]).search(self.sshd_contents[line]):
81 self.ssh_checker_and_setter(line)
83 for line in range(0, end):
84 if re.compile("^#"+self.module.params["regexp"]).search(self.sshd_contents[line]) and not self.changed:
85 self.sshd_contents[line] = self.sshd_contents[line]+self.module.params["values"]
88 self.sshd_contents.insert(start, self.module.params["values"])
92 self._read_sshd_conf()
94 indexes = self._start_finder()
95 start_index = indexes[0]
96 end_index = indexes[1]
98 self._configuration(start_index, end_index)
100 self._write_sshd_conf()
102 self.module.exit_json(changed=self.changed, msg=self.module.params["values"]+" configured")
108 if __name__ == '__main__':