2f94d1ad0658a0069a065471c3cebe5f5ca021c0
[appc/deployment.git] / docs / Ansible Adapter / Ansible Adapter.rst
1 .. ============LICENSE_START==========================================
2 .. ===================================================================
3 .. Copyright © 2017 AT&T Intellectual Property. All rights reserved.
4 .. ===================================================================
5 .. Licensed under the Creative Commons License, Attribution 4.0 Intl.  (the "License");
6 .. you may not use this documentation except in compliance with the License.
7 .. You may obtain a copy of the License at
8 .. 
9 ..  https://creativecommons.org/licenses/by/4.0/
10 .. 
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.
16 .. ============LICENSE_END============================================
17 .. ECOMP is a trademark and service mark of AT&T Intellectual Property.
18
19 ==================================
20 APPC Ansible Adapter Documentation
21 ==================================
22
23 This wiki provides documentation regarding the design, capabilities and
24 usage of the Ansible Extension for APP-C. Ansible_ is a an open-source
25 VNF management framework that allows provide an almost cli like set of
26 tools in a structured form. It is agentless in that the target VNF need
27 not have any additional software other than:
28
29 a) SSH server
30 b) Python >= 2.7 
31 c) Any necessary software that is specific to the VNF to run its functions. 
32
33 Any action (e.g configure, restart, health check etc) can be
34 executed on the VNF by constructing a **playbook (or set of playbooks)**
35 that is executed by an Ansible agent on the VNF via SSH.
36
37 The Ansible Extension for APP-C allows management of VNFs that support Ansible
38 through the following three additions :
39
40  - **An APP-C/Ansible Server interface:** Ansible libraries are written in python and hence cannot be executed natively from within the APP-C Karaf container. Instead, the design calls for an **Ansible Server** that can execute the Ansible playbooks and exposes a **REST** interface that is compliant with requirements of APP-C. These requirements are documented as the Server API Interface that any compliant Ansible Server must support. Exact implementation of the Ansible Server is left open and does not affect APP-C operations as long as the server follows the interface. For purposes of evaluation, a reference web server that implements this APP-C/Ansible Server interface has been developed and the code is available from the App-C ONAP repository under *appc-adapters/appc-ansible-adapter/appc-ansible-example-server*.
41
42  - **An APP-C Ansible adapter:** The ansible adapter is an OSGI bundle in the APP-C Karaf container that interacts with the Ansible Server . It is essentially a set of REST calls that performs two actions, submit request for a playbook to be executed, and if required get the results of the playbook after execution (if in synchronous mode).
43
44  - **Ansible Directed Graph (DG):** The Ansible Directed graph is generic DG that can be used to invoke any playbook via Ansible (and hence any APP-C action, since in Ansible, VNF actions map to playbooks) corresponding to an LCM action.
45
46 The architecture design for supporting Ansible is outlined in the diagram below :
47
48 |image0|
49
50 The workflow envisioned when Application Controller receives an event is
51 as follows :
52
53 1) Application Controller receives event from the Event Bus for an LCM action.
54 2) The appropriate LCM API invokes the Dispatcher which performs the relevant lookups for A&AI and Workflow (DG information).
55 3) The dispatcher calls the DG relevant to the LCM action (for the VNF).
56 4) The DG conducts any processing of data (e.g retrieving additional information, filling templates etc) , prepares the necessary DG context variables outlined in Table 1 and then invokes the Ansible DG.
57 5) Ansible DG leverages the Ansible Adapter to interact with the Ansible Server.
58 6) Ansible Server invokes the appropriate playbook which in turn interacts with the VNF and then returns the playbook results.
59 7) Ansible Server returns results.
60 8) Ansible DG provides these results back to calling DG.
61
62 A ladder diagram of the work flow is pasted below :
63
64 |image1|
65
66 Details of each of these three (DG, Adapter and Ansible Server) are listed below :
67
68 1.  **Ansible Directed Graph (DG):** The Ansible Directed graph is the most common way an App-C developer is expected to leverage Ansible functionality. The Ansible DG is a general purpose graph that can be used to invoke and retrieve results from any playbook on an ONAP-compliant Ansible Server. The Ansible Graph,when called, expects a certain set of inputs to be provided as input and when upon completion provides results from the execution of the Ansible playbook. The Ansible
69 DG can be invoked using the following (current) naming:
70
71 +------------+----------------------+
72 | Field      | Value                |
73 +============+======================+ 
74 | module     | APPC                 |
75 +------------+----------------------+
76 | rpc        | ansible-adapter-1.0  | 
77 +------------+----------------------+
78 | version    | 2.0.1                | 
79 +------------+----------------------+
80
81 The inputs that the Ansible DG expects in DG context memory are listed below:
82
83 Table 1: Input Parameters to the Ansible Directed Graph
84
85 +----------------+-----------------------------------------------------------------+-----------------------+--------------------------------------------------------------------------+
86 | Variable Name  | Description                                                     | Type                  | Comments                                                                 |
87 +================+=================================================================+=======================+==========================================================================+
88 | User           | Username to logon to Ansible Server                             |  Mandatory            | Should be provided by APPC.                                              |
89 +----------------+-----------------------------------------------------------------+-----------------------+--------------------------------------------------------------------------+
90 | Password       | Password to logon to Ansible Server                             |  Mandatory            | Should be provided by APPC.                                              |
91 +----------------+-----------------------------------------------------------------+-----------------------+--------------------------------------------------------------------------+
92 | AgentUrl       | The complete URL of the Ansible Server to post the request for  |  Mandatory            | Should be provided by APPC.                                              |
93 |                | execution and retrieve results (if in synchronous mode)         |                       |                                                                          |
94 +----------------+-----------------------------------------------------------------+-----------------------+--------------------------------------------------------------------------+
95 | PlaybookName   | Name/identifier of playbook to run                              |  Mandatory            | To be provided in the template.                                          |
96 +----------------+-----------------------------------------------------------------+-----------------------+--------------------------------------------------------------------------+
97 | Action         | The type of VNF action being requested                          |  Optional             | Provided either by APPC or Template.                                     |
98 +----------------+-----------------------------------------------------------------+-----------------------+--------------------------------------------------------------------------+
99 | EnvParameters  | A JSON dictionary (stringified) listing the parameters to be    |  Optional             | Structure of the EnvParameters dictionary to be supplied in template.    |
100 |                | passed to the Ansible playbook                                  |                       | Values to be filled in by App-C based on values from payload in run-time |
101 +----------------+-----------------------------------------------------------------+-----------------------+--------------------------------------------------------------------------+
102 | FileParameters | A JSON dictionary (stringified) listing file names and files to |  Optional             | Structure of the FileParameters dictionary to be supplied in template.   |
103 |                | be created for Ansible playbook                                 |                       | Values to be filled in by App-C based on values from payload in run-time |
104 +----------------+-----------------------------------------------------------------+-----------------------+--------------------------------------------------------------------------+
105 | Timeout        | Time Ansible Server should wait before terminating playbook     |  Optional             | To be provided in the template.                                          |
106 +----------------+-----------------------------------------------------------------+-----------------------+--------------------------------------------------------------------------+
107 | NodeList       | List of FQDNs/IP Addresses of VNF that the Ansible playbook     |  Optional             | To be provided to App-C during Runtime.                                  |
108 |                | should be executed on.                                          |  (if not supplied,    |                                                                          |
109 |                |                                                                 |  will run on server)  |                                                                          |
110 +----------------+-----------------------------------------------------------------+-----------------------+--------------------------------------------------------------------------+
111
112   The 'template' referred in the above table must be a JSON file as documented in the VNF vendor requirements and must contain the key-value pairs listed above (that are expected to be in the template). An LCM API Directed graph should fill in necessary parameters in the template, and then put the key-value pairs from the template as listed above in DG context memory before calling the Ansible DG.
113
114 Upon completion the Ansible DG sets the following variables in DG context memory
115
116 Table 2: Output Variables set by Ansible DG Variable
117
118 +-----------------------+--------------------------------------------------------------------------+
119 | Type                  | Comments                                                                 |
120 +=======================+==========================================================================+
121 | output.status.code    | Result of the request: 400 if SUCCESS , 200 if FAILURE.                  |
122 |                       |                                                                          |
123 |                       | The ansible playbook may have multiple sub-tasks, playbooks etc and may  |
124 |                       | run on multiple VMs of a host. The request is considered to fail if even |
125 |                       | one of the tasks is incomplete.                                          |
126 +-----------------------+--------------------------------------------------------------------------+
127 | output.status.message | If playbook finished, set to FINISH, if playbook terminated, set to      |
128 |                       | TERMINATED. If abnormal error, reported in message                       |
129 +-----------------------+--------------------------------------------------------------------------+
130 | output.status.results | A JSON dictionary with results corresponding to output provided by the   |
131 |                       | Ansible playbook request. This is optional (may not be present if        |
132 |                       | playbook was terminated). The results, if present, will be in the form   |
133 |                       | of a dictionary that follows the format presented in the Ansible Server  |
134 |                       | API Documentation. The document also contains examples of output.        |
135 +-----------------------+--------------------------------------------------------------------------+
136
137   *Note : The Ansible Server supports a Callback Url functionality, but it is currently not invoked by App-C Ansible Adapter or Directed Graph. If added, it is easy to change the Adapter and Ansible DG to support this.*
138
139 2.  **APP-C Ansible Adapter:** The App-C Ansible Adapter is an OSGI bundle which essentially makes REST calls to the Ansible Server. It exposes three methods that can be invoked by the Service Logic Interpreter (SLI).
140
141   a. *void reqExec(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException*: A method to invoke the test.
142
143   b. *void reqExecResult(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException*:  A method to request results of a test.
144
145   c. *void reqExecLog(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException* : A method to retreive the logs from a request (not used in the Ansible DG currently).
146
147     Currently, the Ansible DG uses only the first two (reqExec and reqExecResult) since only these two are needed to request execution of a playbook and retrieval of results. The reqExecLog is for diagnostic purposes.
148
149     In order to communicate with the Ansible Server, it is currently assumed that:
150
151     a. Credentials comprise of a username and password.
152
153     b. Communication is over https
154
155     The Ansible Adapter has three configurable parameters related to SSL certificate of the Ansible Server, which can be set from the properties file:
156
157     a. org.openecomp.appc.adapter.ansible.clientType. If set to "TRUST\_ALL", will accept all SSL certificates from any Ansible Server. If set to "TRUST\_CERT", will accept SSL from only those Ansible Servers whose certificate is in the trustStore keystore file. These two options can be used for development environment. Default option is to trust only well known server certificates (use in Production).
158
159     b. org.openecomp.appc.adapter.ansible.trustStore used to point to the keystore file
160
161     c. org.openecomp.appc.adapter.ansible.trustStorePasswd used to set password for keystore file
162
163 3.  **Reference Ansible Server Implementation of APPC / Ansible Interface (for testing purposes only)**
164
165     a. Overview
166
167     |image2|
168
169     b. Inventory file
170
171       The Prototype Ansible Server requires that all credentials and IP Addresses for the VNF being tested either already be present in the Server’s Database or be loaded before any playbooks are invoked. Supported credentials are user-name/password and public-key authentication. 
172
173       All VNF credentials stored in a unique file (or in a SQL database depending on the ansible server runtime configuration):
174
175       [host]
176       localhost ansible\_connection=local
177
178       [hostgroup1] hostname11 ansible\_connection=ssh
179       ansible\_ssh\_user=loginid11 ansible\_ssh\_pass=passwd11 hostname12
180       ansible\_connection=ssh ansible\_ssh\_user=loginid12
181       ansible\_ssh\_private\_key\_file=kefile12 … [hostgroup2] hostname21
182       ansible\_connection=ssh ansible\_ssh\_user=loginid21
183       ansible\_ssh\_private\_key\_file=keyfile21 …. [hostgroup3] …
184
185     c. Playbooks
186
187       Playbooks can either be provided as stand alone text files or gzipped tar file (playbooks with roles sub-directories) either stored in a local file or in an SQL database.
188
189       Naming convention: anything\_LCM@M.mn.{yml,tar.gz} where version number M is a digit and mn are subversion number digits.
190
191       Playbooks should be written such that they can run from the command line: "ansible-playbook -i inventoryfile –extra-vars optionalvariables playbookname" That means the playbook should not contain any VM credentials information, they are expected to be provided through the inventory file passed at run time.
192
193         a.  Stand-alone playbooks
194
195         |image3|
196
197         b.  Playbooks in gzipped tarfiles
198
199         |image4|
200
201     d. Installation
202
203       a. Python
204
205         sudo apt-get install python2.7
206         sudo apt-get install python-pip
207         pip install PyMySQL
208         pip install requests
209
210       b. Ansible
211
212         sudo apt-get install software-properties-common
213         sudo apt-add-repository ppa:ansible/ansible
214         sudo apt-get update 
215         sudo apt-get install ansible 
216
217       c. SQL database
218
219         a. Installing MySQL
220
221           sudo apt-get install mysql-server
222
223           Set root passwd during installation (i.e. password\_4\_mysql\_user\_id)
224
225           sudo service mysql restart
226
227         b. Setting up mysql
228
229           mysql -u [username]-p
230
231           mysql -uroot -p
232
233           Create user (i.e. id=mysql\_user\_id psswd=password\_4\_mysql\_user\_id)
234
235           CREATE USER 'appc'@'%' IDENTIFIED BY 'password\_4\_mysql\_user\_id';
236
237           GRANT ALL PRIVILEGES ON *.* TO 'mysql\_user\_id'@'%';
238
239           SET PASSWORD FOR 'mysql\_user\_id'@'%'=PASSWORD('password\_4\_mysql\_user\_id');
240
241         c. Creating schema
242
243           CREATE SCHEMA ansible;
244
245           SHOW DATABASES;
246
247           USE ansible;
248
249           CREATE TABLE playbook (name VARCHAR(45) NOT NULL, value BLOB, type VARCHAR(60), version VARCHAR(60), PRIMARY KEY (name));
250
251           SHOW TABLES;
252
253           CREATE TABLE inventory (hostname VARCHAR(45) NOT NULL, hostgroup VARCHAR(45), credentials VARCHAR(500), PRIMARY KEY (hostname));
254
255           SHOW COLUMNS FROM playbook;
256
257           SHOW COLUMNS FROM inventory;
258
259           GRANT ALL PRIVILEGES ON *.* TO 'mysql\_user\_id'@'%' IDENTIFIED BY 'password\_4\_mysql\_user\_id' WITH GRANT OPTION;
260
261           GRANT ALL PRIVILEGES ON *.* TO 'ansible'@'%' IDENTIFIED BY 'ansible\_agent' WITH GRANT OPTION;
262
263           FLUSH PRIVILEGES;
264
265
266
267         d. Loading playbooks and inventory data in SQL database
268
269           Place inventory file and playbooks to be loaded in one directory, set LoadAnsibleMySql variables:
270
271           SQL credentials:
272
273           host="localhost" # your host, usually localhost
274           user="mysql\_user\_id" # your username
275           passwd="password\_4\_mysql\_user\_id" # your password
276           db="ansible" # name of the database
277
278
279           Path of playbook location:
280
281           playbook\_path = "something/something/"
282
283
284           Full name of inventory file:
285
286           inventory = "something/something/Ansible\_inventory"
287
288           These variables are located right after main:
289
290           |image5|
291
292           Run loader: python LoadAnsibleMySql.py
293
294     e. Execution
295
296       Ansible server is executed through RestServer.py. Its configuration file consists of the following:
297
298       # Host definition
299       ip: 0.0.0.0
300       port: 8000
301       # Security (controls use of TLS encrypton and RestServer authentication)
302       tls: no
303       auth: no
304       # TLS certificates (must be built on application host)
305       priv: provide\_privated\_key.pem
306       pub: provide\_public\_key.pem 
307       # RestServer authentication
308       id: provide\_RestServer\_id
309       psswd: provide\_password\_4\_RestServer\_id
310       # Mysql
311       host: localhost
312       user: mysql\_user\_id
313       passwd: password\_4\_mysql\_user\_id
314       db: ansible 
315       #Playbooks
316       from\_files: yes
317       ansible\_path: /home/ubuntu/RestServerOpenSource
318       ansible\_inv: Ansible\_inventory
319       ansible\_temp: PlaybooksTemp
320       timeout\_seconds: 60
321       # Blocking on GetResults
322       getresults\_block: yes
323
324 Execution and testing steps:
325
326  1.  **Start RestServer**: *python RestServer.py*
327
328    Note: RSA key fingerprint needs to be loaded manually in server for each VM defined in inventory file that requires ssh authentication. This can be done by testing ssh credentials to each target VM and accepting RSA key fingerprint:
329
330    .. code:: bash
331
332      ssh -i key \|VMaddress\|
333      RSA key fingerprint is \|something.\|
334      Are you sure you want to continue connecting (yes/no)? yes
335
336
337  2.  **Try curl commands** (case no secured REST: HTTP & no authentication)
338
339    Request to execute playbook:
340
341    .. code:: bash
342
343      curl -H "Content-type: application/json" -X POST -d '{"Id": "10", "PlaybookName": "ansible\_sleep", "NodeList": ["host"], "Timeout": "60", "EnvParameters": {"Sleep": "10"}}'http://0.0.0.0:8000/Dispatch
344
345    Response:
346
347    .. code:: bash
348
349      {"ExpectedDuration": "60sec", "StatusMessage": "PENDING", "StatusCode": 100}
350
351    Get results (blocked until test finished):
352
353    .. code:: bash
354
355      curl -H "Content-type: application/json" -X GET "http://0.0.0.0:8000/Dispatch/?Id=10&Type=GetResult"
356
357    Response:
358
359    .. code:: bash
360
361      {"Results": {"localhost": {"GroupName": "host", "StatusMessage": "SUCCESS", "StatusCode": 200}}, "PlaybookName":"ansible\_sleep", "Version": "0.00", "Duration": "11.261794", "StatusMessage": "FINISHED", "StatusCode": 200}
362
363    Delete playbook execution information
364
365    .. code:: bash
366
367      curl -H "Content-type: application/json" -X DELETE http://0.0.0.0:8000/Dispatch/?Id=10
368
369    Response:
370
371    .. code:: bash
372
373      {"StatusMessage": "PLAYBOOK EXECUTION RECORDS DELETED", "StatusCode": 200}
374
375 Playbook execution done through system call
376
377    .. code:: bash
378
379      ansible-playbook --v -extra-vars ‘playbookvars’ -i inventoryfile playbook.yml
380
381    - Inventory file created at run time, playbook loaded from mysql, both placed in the temporary directory destroyed at end of test (Playbook archive is unpacked in the temporary directory)
382
383 All tested playbooks written such that the ansible ‘play recap’ log indicates whether or not the playbook tasks succeeded (multiple tasks in a standalone playbook or playbooks with roles directory structure)
384
385 Sample ansible ‘play recap’:
386
387 |image6|
388
389
390
391 .. _Ansible: https://www.ansible.com/
392
393 .. |image0| image:: images/image0.png
394 .. |image1| image:: images/image1.png
395 .. |image2| image:: images/image2.png
396 .. |image3| image:: images/image3.png
397 .. |image4| image:: images/image4.png
398 .. |image5| image:: images/image5.png
399 .. |image6| image:: images/image6.png