Browse Source

updating readme + pylint recomendations

David Yurkiewicz 8 months ago
parent
commit
1e74b02c4a
5 changed files with 73 additions and 44 deletions
  1. 8 0
      .travis.yaml
  2. 19 2
      README.md
  3. 41 38
      miniConfigApply.py
  4. 3 0
      requirements.txt
  5. 2 4
      roles/example/files/info.php

+ 8 - 0
.travis.yaml

@@ -0,0 +1,8 @@
1
+language: python
2
+python:
3
+  - 3.7
4
+install:
5
+  - pip install -r requirements.txt
6
+  - pip install pylint
7
+script: 
8
+  - pylint miniConfigApply.py

+ 19 - 2
README.md

@@ -13,7 +13,7 @@ pip3 install parallel-ssh
13 13
 
14 14
 ## Usage
15 15
 
16
-miniConfig works of config.json files which are under a "role" directory. The following directory structure should be followed:
16
+miniConfig uses configurations files (`config.json`) under a "role" directory to apply config changes to remote host. The following directory structure should be followed:
17 17
 ```
18 18
 ── roles
19 19
     ├── role-config-1
@@ -27,6 +27,21 @@ ── roles
27 27
             └── index.php
28 28
 ```
29 29
 
30
+## Auth
31
+The user and password for ssh can be configure by setting the following environment variables:
32
+
33
+- miniConfigUser
34
+```
35
+export miniConfigUser='r00t'
36
+```
37
+
38
+- miniConfigPass
39
+```
40
+export miniConfigPass='p@ssw0rd'
41
+```
42
+
43
+
44
+
30 45
 ## config.json
31 46
 
32 47
 Config files tell miniConfig what to do. Each role directory should have a `config.json` file. 
@@ -105,7 +120,9 @@ When using the `service_notify` key make sure to include the actual service name
105 120
 
106 121
 
107 122
 
108
-## Logging 
123
+## Applying configurations
124
+Run `miniConfigApply.py` `$rolename` 
125
+
109 126
 miniConfig writes its log to stdout.
110 127
 ```
111 128
 $ ./miniConfigApply.py webserver

+ 41 - 38
miniConfigApply.py

@@ -1,5 +1,5 @@
1 1
 #!/usr/bin/env python3
2
-# miniConfig 
2
+# miniConfig
3 3
 # A very simple config management system
4 4
 
5 5
 import os
@@ -12,25 +12,28 @@ from gevent import joinall
12 12
 from pssh.utils import enable_host_logger
13 13
 enable_host_logger()
14 14
 
15
-class miniConfig():
15
+class MiniConfig():
16 16
     hosts = []
17 17
     pkgs = []
18 18
     files = {}
19 19
     cmds = []
20
-    ssh_user = 'root'
20
+    try:
21
+        ssh_user = os.environ['miniConfigUser']
22
+    except KeyError:
23
+        raise KeyError("SSH USER VARIABLE [miniConfigUser] NOT SET.")
21 24
     try:
22 25
         ssh_pass = os.environ['miniConfigPass']
23 26
     except KeyError:
24 27
         raise KeyError("SSH PASSWORD VARIABLE [miniConfigPass] NOT SET.")
25
-    
28
+
26 29
     def __init__(self, role, defaultConfigFile='config.json', defaultFiledir='files/'):
27 30
         self.role = role
28
-        self.rolePath = './roles/' + role
29
-        self.configPath = self.rolePath + '/' + defaultConfigFile
30
-        self.filePath = self.rolePath + '/' + defaultFiledir
31
+        self.role_path = './roles/' + role
32
+        self.config_path = self.role_path + '/' + defaultConfigFile
33
+        self.file_path = self.role_path + '/' + defaultFiledir
31 34
 
32
-    def configParser(self):
33
-        with open(self.configPath) as f:
35
+    def config_parser(self):
36
+        with open(self.config_path) as f:
34 37
             data = json.load(f)
35 38
             self.hosts.append(data['hosts'])
36 39
             self.pkgs.append(data['packages'][0])
@@ -38,42 +41,42 @@ class miniConfig():
38 41
             self.cmds.append(data['commands'])
39 42
         return data
40 43
 
41
-    def applyConfig(self):
44
+    def apply_config(self):
42 45
         # Parse config.json
43
-        config = self.configParser()
46
+        config = self.config_parser()
44 47
         # start ssh session
45 48
         self.client = ParallelSSHClient(self.hosts[0], user=self.ssh_user, password=self.ssh_pass)
46 49
         # START OF APPLY
47 50
         # add/rm packages, if listed in config
48 51
         if 'add' in self.pkgs[0]:
49
-            self.addPackage(self.pkgs[0]['add'])
52
+            self.add_package(self.pkgs[0]['add'])
50 53
         if 'remove' in self.pkgs:
51
-            self.rmPackage(self.pkgs[0]['remove'])
54
+            self.rm_package(self.pkgs[0]['remove'])
52 55
         # add/rm files, if listed in config
53 56
         if len(self.files) != 0:
54 57
             for file in self.files:
55 58
                 if file['action'] == 'add':
56
-                    self.addFile(file)
57
-                elif file['action'] == 'remove' :
58
-                    self.rmFile(file)
59
+                    self.add_file(file)
60
+                elif file['action'] == 'remove':
61
+                    self.rm_file(file)
59 62
                 else:
60
-                    raise ValueError('UNKNOWN ACTION. Only "'"add"'" or "'"remove"'" are supported actions')
63
+                    raise ValueError('UNKNOWN ACTION. Only [add] or [remove] are supported actions')
61 64
         # Run commands found in config
62
-        if len(self.cmds) !=0:
63
-            self.runCmd(self.cmds)
64
-        
65
-    def runCmd(self, cmds=[]):
65
+        if len(self.cmds) != 0:
66
+            self.run_cmd(self.cmds)
67
+
68
+    def run_cmd(self, cmds=[]):
66 69
         for cmd in cmds[0]:
67
-            run_cmd = self.client.run_command(cmd, sudo=True)
68
-            self.client.join(run_cmd, consume_output=True)
69
-            for host, host_output in run_cmd.items():
70
+            run_command = self.client.run_command(cmd, sudo=True)
71
+            self.client.join(run_command, consume_output=True)
72
+            for host, host_output in run_command.items():
70 73
                 if host_output.exit_code != 0:
71 74
                     print('[%s] Error running: [ %s ]' % (host, cmd))
72 75
                 else:
73 76
                     print('[%s] Ran [ %s ]' % (host, cmd))
74
-                 
75 77
 
76
-    def addPackage(self, pkgs=[]):
78
+
79
+    def add_package(self, pkgs=[]):
77 80
         for pk in pkgs:
78 81
             verify = self.client.run_command('apt list --installed | grep '+ pk + '/', sudo=True)
79 82
             self.client.join(verify, consume_output=False)
@@ -88,13 +91,13 @@ class miniConfig():
88 91
                         if host_output.exit_code != 0:
89 92
                             print('[%s] Error installing %s' % (host, pk))
90 93
                         else:
91
-                            print('[%s] %s installed' % (host, pk))  
94
+                            print('[%s] %s installed' % (host, pk))
92 95
                 else:
93
-                    print('[%s] %s already installed. Nothing to do!' % (host, pk))            
94
-    
95
-    def rmPackage(self, pkgs=[]):
96
+                    print('[%s] %s already installed. Nothing to do!' % (host, pk))
97
+
98
+    def rm_package(self, pkgs=[]):
96 99
         for pk in pkgs:
97
-            # Check if package is installed 
100
+            # Check if package is installed
98 101
             verify = self.client.run_command('apt list --installed | grep '+ pk + '/', sudo=True)
99 102
             self.client.join(verify, consume_output=False)
100 103
             for host, host_output in verify.items():
@@ -113,8 +116,8 @@ class miniConfig():
113 116
                 else:
114 117
                     print('[%s] %s not installed. Nothing to do' % (host, pk))
115 118
 
116
-    def addFile(self, file={}):
117
-        local_file_path = self.filePath + '/' + file['name']
119
+    def add_file(self, file={}):
120
+        local_file_path = self.file_path + '/' + file['name']
118 121
         remote_file_path = file['path'] + '/' + file['name']
119 122
         # Get local md5hash to compare with remote file
120 123
         hasher = hashlib.md5()
@@ -178,9 +181,9 @@ class miniConfig():
178 181
                 print('[%s] %s already on system/checksum match local file' % (host, remote_file_path))
179 182
 
180 183
 
181
-    def rmFile(self, file={}):
184
+    def rm_file(self, file={}):
182 185
         remote_file_path = file['path'] + '/' + file['name']
183
-        # Stat the file to make sure is there before attempting to remove 
186
+        # Stat the file to make sure is there before attempting to remove
184 187
         verify = self.client.run_command('/usr/bin/stat -t ' + remote_file_path, sudo=True)
185 188
         self.client.join(verify, consume_output=False)
186 189
         for host, host_output in verify.items():
@@ -198,6 +201,6 @@ class miniConfig():
198 201
 
199 202
 if len(sys.argv) == 1:
200 203
     print("Missing role name. Please provide role to apply")
201
-for i in range(1,len(sys.argv)):
202
-    t = miniConfig(sys.argv[i])
203
-    t.applyConfig()
204
+for i in range(1, len(sys.argv)):
205
+    t = MiniConfig(sys.argv[i])
206
+    t.apply_config()

+ 3 - 0
requirements.txt

@@ -0,0 +1,3 @@
1
+parallel-ssh==1.9.1
2
+gevent==1.4.0
3
+

+ 2 - 4
roles/example/files/info.php

@@ -1,5 +1,3 @@
1 1
 <?php
2
-
3
-header("Content-Type: text/plain");
4
-
5
-echo "Hello, world!\n";
2
+phpinfo();
3
+?>