summaryrefslogtreecommitdiff
path: root/cloud/lxc/lxc_container.py
blob: d3b6804ce5038ec57a05a8d9fc1b739a652c75e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
#!/usr/bin/python
# -*- coding: utf-8 -*-

# (c) 2014, Kevin Carter <kevin.carter@rackspace.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.


ANSIBLE_METADATA = {'status': ['preview'],
                    'supported_by': 'community',
                    'version': '1.0'}

DOCUMENTATION = """
---
module: lxc_container
short_description: Manage LXC Containers
version_added: 1.8.0
description:
  - Management of LXC containers
author: "Kevin Carter (@cloudnull)"
options:
    name:
        description:
          - Name of a container.
        required: true
    backing_store:
        choices:
          - dir
          - lvm
          - loop
          - btrfs
          - overlayfs
          - zfs
        description:
          - Backend storage type for the container.
        required: false
        default: dir
    template:
        description:
          - Name of the template to use within an LXC create.
        required: false
        default: ubuntu
    template_options:
        description:
          - Template options when building the container.
        required: false
    config:
        description:
          - Path to the LXC configuration file.
        required: false
        default: null
    lv_name:
        description:
          - Name of the logical volume, defaults to the container name.
        default: $CONTAINER_NAME
        required: false
    vg_name:
        description:
          - If Backend store is lvm, specify the name of the volume group.
        default: lxc
        required: false
    thinpool:
        description:
          - Use LVM thin pool called TP.
        required: false
    fs_type:
        description:
          - Create fstype TYPE.
        default: ext4
        required: false
    fs_size:
        description:
          - File system Size.
        default: 5G
        required: false
    directory:
        description:
          - Place rootfs directory under DIR.
        required: false
    zfs_root:
        description:
          - Create zfs under given zfsroot.
        required: false
    container_command:
        description:
          - Run a command within a container.
        required: false
    lxc_path:
        description:
          - Place container under PATH
        required: false
    container_log:
        choices:
          - true
          - false
        description:
          - Enable a container log for host actions to the container.
        default: false
    container_log_level:
        choices:
          - INFO
          - ERROR
          - DEBUG
        description:
          - Set the log level for a container where *container_log* was set.
        required: false
        default: INFO
    clone_name:
        version_added: "2.0"
        description:
          - Name of the new cloned server. This is only used when state is
            clone.
        required: false
        default: false
    clone_snapshot:
        version_added: "2.0"
        required: false
        choices:
          - true
          - false
        description:
          - Create a snapshot a container when cloning. This is not supported
            by all container storage backends. Enabling this may fail if the
            backing store does not support snapshots.
        default: false
    archive:
        choices:
          - true
          - false
        description:
          - Create an archive of a container. This will create a tarball of the
            running container.
        default: false
    archive_path:
        description:
          - Path the save the archived container. If the path does not exist
            the archive method will attempt to create it.
        default: null
    archive_compression:
        choices:
          - gzip
          - bzip2
          - none
        description:
          - Type of compression to use when creating an archive of a running
            container.
        default: gzip
    state:
        choices:
          - started
          - stopped
          - restarted
          - absent
          - frozen
        description:
          - Define the state of a container. If you clone a container using
            `clone_name` the newly cloned container created in a stopped state.
            The running container will be stopped while the clone operation is
            happening and upon completion of the clone the original container
            state will be restored.
        required: false
        default: started
    container_config:
        description:
          - list of 'key=value' options to use when configuring a container.
        required: false
requirements:
  - 'lxc >= 1.0 # OS package'
  - 'python >= 2.6 # OS Package'
  - 'lxc-python2 >= 0.1 # PIP Package from https://github.com/lxc/python2-lxc'
notes:
  - Containers must have a unique name. If you attempt to create a container
    with a name that already exists in the users namespace the module will
    simply return as "unchanged".
  - The "container_command" can be used with any state except "absent". If
    used with state "stopped" the container will be "started", the command
    executed, and then the container "stopped" again. Likewise if the state
    is "stopped" and the container does not exist it will be first created,
    "started", the command executed, and then "stopped". If you use a "|"
    in the variable you can use common script formatting within the variable
    iteself The "container_command" option will always execute as BASH.
    When using "container_command" a log file is created in the /tmp/ directory
    which contains both stdout and stderr of any command executed.
  - If "archive" is **true** the system will attempt to create a compressed
    tarball of the running container. The "archive" option supports LVM backed
    containers and will create a snapshot of the running container when
    creating the archive.
  - If your distro does not have a package for "python2-lxc", which is a
    requirement for this module, it can be installed from source at
    "https://github.com/lxc/python2-lxc" or installed via pip using the package
    name lxc-python2.
"""

EXAMPLES = """
- name: Create a started container
  lxc_container:
    name: test-container-started
    container_log: true
    template: ubuntu
    state: started
    template_options: --release trusty

- name: Create a stopped container
  lxc_container:
    name: test-container-stopped
    container_log: true
    template: ubuntu
    state: stopped
    template_options: --release trusty

- name: Create a frozen container
  lxc_container:
    name: test-container-frozen
    container_log: true
    template: ubuntu
    state: frozen
    template_options: --release trusty
    container_command: |
      echo 'hello world.' | tee /opt/started-frozen

# Create filesystem container, configure it, and archive it, and start it.
- name: Create filesystem container
  lxc_container:
    name: test-container-config
    backing_store: dir
    container_log: true
    template: ubuntu
    state: started
    archive: true
    archive_compression: none
    container_config:
      - "lxc.aa_profile=unconfined"
      - "lxc.cgroup.devices.allow=a *:* rmw"
    template_options: --release trusty

# Create an lvm container, run a complex command in it, add additional
# configuration to it, create an archive of it, and finally leave the container
# in a frozen state. The container archive will be compressed using bzip2
- name: Create a frozen lvm container
  lxc_container:
    name: test-container-lvm
    container_log: true
    template: ubuntu
    state: frozen
    backing_store: lvm
    template_options: --release trusty
    container_command: |
      apt-get update
      apt-get install -y vim lxc-dev
      echo 'hello world.' | tee /opt/started
      if [[ -f "/opt/started" ]]; then
          echo 'hello world.' | tee /opt/found-started
      fi
    container_config:
      - "lxc.aa_profile=unconfined"
      - "lxc.cgroup.devices.allow=a *:* rmw"
    archive: true
    archive_compression: bzip2
  register: lvm_container_info

- name: Debug info on container "test-container-lvm"
  debug:
    var: lvm_container_info

- name: Run a command in a container and ensure its in a "stopped" state.
  lxc_container:
    name: test-container-started
    state: stopped
    container_command: |
      echo 'hello world.' | tee /opt/stopped

- name: Run a command in a container and ensure its it in a "frozen" state.
  lxc_container:
    name: test-container-stopped
    state: frozen
    container_command: |
      echo 'hello world.' | tee /opt/frozen

- name: Start a container
  lxc_container:
    name: test-container-stopped
    state: started

- name: Run a command in a container and then restart it
  lxc_container:
    name: test-container-started
    state: restarted
    container_command: |
      echo 'hello world.' | tee /opt/restarted

- name: Run a complex command within a "running" container
  lxc_container:
    name: test-container-started
    container_command: |
      apt-get update
      apt-get install -y curl wget vim apache2
      echo 'hello world.' | tee /opt/started
      if [[ -f "/opt/started" ]]; then
          echo 'hello world.' | tee /opt/found-started
      fi

# Create an archive of an existing container, save the archive to a defined
# path and then destroy it.
- name: Archive container
  lxc_container:
    name: test-container-started
    state: absent
    archive: true
    archive_path: /opt/archives

# Create a container using overlayfs, create an archive of it, create a
# snapshot clone of the container and and finally leave the container
# in a frozen state. The container archive will be compressed using gzip.
- name: Create an overlayfs container archive and clone it
  lxc_container:
    name: test-container-overlayfs
    container_log: true
    template: ubuntu
    state: started
    backing_store: overlayfs
    template_options: --release trusty
    clone_snapshot: true
    clone_name: test-container-overlayfs-clone-snapshot
    archive: true
    archive_compression: gzip
  register: clone_container_info

- name: debug info on container "test-container"
  debug:
    var: clone_container_info

- name: Clone a container using snapshot
  lxc_container:
    name: test-container-overlayfs-clone-snapshot
    backing_store: overlayfs
    clone_name: test-container-overlayfs-clone-snapshot2
    clone_snapshot: true

- name: Create a new container and clone it
  lxc_container:
    name: test-container-new-archive
    backing_store: dir
    clone_name: test-container-new-archive-clone

- name: Archive and clone a container then destroy it
  lxc_container:
    name: test-container-new-archive
    state: absent
    clone_name: test-container-new-archive-destroyed-clone
    archive: true
    archive_compression: gzip

- name: Start a cloned container.
  lxc_container:
    name: test-container-new-archive-destroyed-clone
    state: started

- name: Destroy a container
  lxc_container:
    name: '{{ item }}'
    state: absent
  with_items:
    - test-container-stopped
    - test-container-started
    - test-container-frozen
    - test-container-lvm
    - test-container-config
    - test-container-overlayfs
    - test-container-overlayfs-clone
    - test-container-overlayfs-clone-snapshot
    - test-container-overlayfs-clone-snapshot2
    - test-container-new-archive
    - test-container-new-archive-clone
    - test-container-new-archive-destroyed-clone
"""

RETURN="""
lxc_container:
    description: container information
    returned: success
    type: list
    contains:
        name:
            description: name of the lxc container
            returned: success
            type: string
            sample: test_host
        init_pid:
            description: pid of the lxc init process
            returned: success
            type: int
            sample: 19786
        interfaces:
            description: list of the container's network interfaces
            returned: success
            type: list
            sample: [ "eth0", "lo" ]
        ips:
            description: list of ips
            returned: success
            type: list
            sample: [ "10.0.3.3" ]
        state:
            description: resulting state of the container
            returned: success
            type: string
            sample: "running"
        archive:
            description: resulting state of the container
            returned: success, when archive is true
            type: string
            sample: "/tmp/test-container-config.tar"
        clone:
            description: if the container was cloned
            returned: success, when clone_name is specified
            type: boolean
            sample: True
"""

import re

try:
    import lxc
except ImportError:
    HAS_LXC = False
else:
    HAS_LXC = True


# LXC_COMPRESSION_MAP is a map of available compression types when creating
# an archive of a container.
LXC_COMPRESSION_MAP = {
    'gzip': {
        'extension': 'tar.tgz',
        'argument': '-czf'
    },
    'bzip2': {
        'extension': 'tar.bz2',
        'argument': '-cjf'
    },
    'none': {
        'extension': 'tar',
        'argument': '-cf'
    }
}


# LXC_COMMAND_MAP is a map of variables that are available to a method based
# on the state the container is in.
LXC_COMMAND_MAP = {
    'create': {
        'variables': {
            'config': '--config',
            'template': '--template',
            'backing_store': '--bdev',
            'lxc_path': '--lxcpath',
            'lv_name': '--lvname',
            'vg_name': '--vgname',
            'thinpool': '--thinpool',
            'fs_type': '--fstype',
            'fs_size': '--fssize',
            'directory': '--dir',
            'zfs_root': '--zfsroot'
        }
    },
    'clone': {
        'variables': {
            'backing_store': '--backingstore',
            'lxc_path': '--lxcpath',
            'fs_size': '--fssize',
            'name': '--orig',
            'clone_name': '--new'
        }
    }
}


# LXC_BACKING_STORE is a map of available storage backends and options that
# are incompatible with the given storage backend.
LXC_BACKING_STORE = {
    'dir': [
        'lv_name', 'vg_name', 'fs_type', 'fs_size', 'thinpool'
    ],
    'lvm': [
        'zfs_root'
    ],
    'btrfs': [
        'lv_name', 'vg_name', 'thinpool', 'zfs_root', 'fs_type', 'fs_size'
    ],
    'loop': [
        'lv_name', 'vg_name', 'thinpool', 'zfs_root'
    ],
    'overlayfs': [
        'lv_name', 'vg_name', 'fs_type', 'fs_size', 'thinpool', 'zfs_root'
    ],
    'zfs': [
        'lv_name', 'vg_name', 'fs_type', 'fs_size', 'thinpool'
    ]
}


# LXC_LOGGING_LEVELS is a map of available log levels
LXC_LOGGING_LEVELS = {
    'INFO': ['info', 'INFO', 'Info'],
    'ERROR': ['error', 'ERROR', 'Error'],
    'DEBUG': ['debug', 'DEBUG', 'Debug']
}


# LXC_ANSIBLE_STATES is a map of states that contain values of methods used
# when a particular state is evoked.
LXC_ANSIBLE_STATES = {
    'started': '_started',
    'stopped': '_stopped',
    'restarted': '_restarted',
    'absent': '_destroyed',
    'frozen': '_frozen',
    'clone': '_clone'
}


# This is used to attach to a running container and execute commands from
# within the container on the host.  This will provide local access to a
# container without using SSH.  The template will attempt to work within the
# home directory of the user that was attached to the container and source
# that users environment variables by default.
ATTACH_TEMPLATE = """#!/usr/bin/env bash
pushd "$(getent passwd $(whoami)|cut -f6 -d':')"
    if [[ -f ".bashrc" ]];then
        source .bashrc
    fi
popd

# User defined command
%(container_command)s
"""


def create_script(command):
    """Write out a script onto a target.

    This method should be backward compatible with Python 2.4+ when executing
    from within the container.

    :param command: command to run, this can be a script and can use spacing
                    with newlines as separation.
    :type command: ``str``
    """

    import os
    import os.path as path
    import subprocess
    import tempfile

    (fd, script_file) = tempfile.mkstemp(prefix='lxc-attach-script')
    f = os.fdopen(fd, 'wb')
    try:
        f.write(ATTACH_TEMPLATE % {'container_command': command})
        f.flush()
    finally:
        f.close()

    # Ensure the script is executable.
    os.chmod(script_file, int('0700',8))

    # Output log file.
    stdout_file = os.fdopen(tempfile.mkstemp(prefix='lxc-attach-script-log')[0], 'ab')

    # Error log file.
    stderr_file = os.fdopen(tempfile.mkstemp(prefix='lxc-attach-script-err')[0], 'ab')

    # Execute the script command.
    try:
        subprocess.Popen(
            [script_file],
            stdout=stdout_file,
            stderr=stderr_file
        ).communicate()
    finally:
        # Close the log files.
        stderr_file.close()
        stdout_file.close()

        # Remove the script file upon completion of execution.
        os.remove(script_file)


class LxcContainerManagement(object):
    def __init__(self, module):
        """Management of LXC containers via Ansible.

        :param module: Processed Ansible Module.
        :type module: ``object``
        """
        self.module = module
        self.state = self.module.params.get('state', None)
        self.state_change = False
        self.lxc_vg = None
        self.lxc_path = self.module.params.get('lxc_path', None)
        self.container_name = self.module.params['name']
        self.container = self.get_container_bind()
        self.archive_info = None
        self.clone_info = None

    def get_container_bind(self):
        return lxc.Container(name=self.container_name)

    @staticmethod
    def _roundup(num):
        """Return a rounded floating point number.

        :param num: Number to round up.
        :type: ``float``
        :returns: Rounded up number.
        :rtype: ``int``
        """
        num, part = str(num).split('.')
        num = int(num)
        if int(part) != 0:
            num += 1
        return num

    @staticmethod
    def _container_exists(container_name, lxc_path=None):
        """Check if a container exists.

        :param container_name: Name of the container.
        :type: ``str``
        :returns: True or False if the container is found.
        :rtype: ``bol``
        """
        if [i for i in lxc.list_containers(config_path=lxc_path) if i == container_name]:
            return True
        else:
            return False

    @staticmethod
    def _add_variables(variables_dict, build_command):
        """Return a command list with all found options.

        :param variables_dict: Pre-parsed optional variables used from a
                               seed command.
        :type variables_dict: ``dict``
        :param build_command: Command to run.
        :type build_command: ``list``
        :returns: list of command options.
        :rtype: ``list``
        """

        for key, value in variables_dict.items():
            build_command.append(
                '%s %s' % (key, value)
            )
        else:
            return build_command

    def _get_vars(self, variables):
        """Return a dict of all variables as found within the module.

        :param variables: Hash of all variables to find.
        :type variables: ``dict``
        """

        # Remove incompatible storage backend options.
        variables = variables.copy()
        for v in LXC_BACKING_STORE[self.module.params['backing_store']]:
            variables.pop(v, None)

        return_dict = dict()
        false_values = [None, ''] + BOOLEANS_FALSE
        for k, v in variables.items():
            _var = self.module.params.get(k)
            if _var not in false_values:
                return_dict[v] = _var
        else:
            return return_dict

    def _run_command(self, build_command, unsafe_shell=False):
        """Return information from running an Ansible Command.

        This will squash the build command list into a string and then
        execute the command via Ansible. The output is returned to the method.
        This output is returned as `return_code`, `stdout`, `stderr`.

        :param build_command: Used for the command and all options.
        :type build_command: ``list``
        :param unsafe_shell: Enable or Disable unsafe sell commands.
        :type unsafe_shell: ``bol``
        """

        return self.module.run_command(
            ' '.join(build_command),
            use_unsafe_shell=unsafe_shell
        )

    def _config(self):
        """Configure an LXC container.

        Write new configuration values to the lxc config file. This will
        stop the container if it's running write the new options and then
        restart the container upon completion.
        """

        _container_config = self.module.params.get('container_config')
        if not _container_config:
            return False

        container_config_file = self.container.config_file_name
        with open(container_config_file, 'rb') as f:
            container_config = f.readlines()

        # Note used ast literal_eval because AnsibleModule does not provide for
        # adequate dictionary parsing.
        # Issue: https://github.com/ansible/ansible/issues/7679
        # TODO(cloudnull) adjust import when issue has been resolved.
        import ast
        options_dict = ast.literal_eval(_container_config)
        parsed_options = [i.split('=', 1) for i in options_dict]

        config_change = False
        for key, value in parsed_options:
            key = key.strip()
            value = value.strip()
            new_entry = '%s = %s\n' % (key, value)
            keyre = re.compile(r'%s(\s+)?=' % key)
            for option_line in container_config:
                # Look for key in config
                if keyre.match(option_line):
                    _, _value = option_line.split('=', 1)
                    config_value = ' '.join(_value.split())
                    line_index = container_config.index(option_line)
                    # If the sanitized values don't match replace them
                    if value != config_value:
                        line_index += 1
                        if new_entry not in container_config:
                            config_change = True
                            container_config.insert(line_index, new_entry)
                    # Break the flow as values are written or not at this point
                    break
            else:
                config_change = True
                container_config.append(new_entry)

        # If the config changed restart the container.
        if config_change:
            container_state = self._get_state()
            if container_state != 'stopped':
                self.container.stop()

            with open(container_config_file, 'wb') as f:
                f.writelines(container_config)

            self.state_change = True
            if container_state == 'running':
                self._container_startup()
            elif container_state == 'frozen':
                self._container_startup()
                self.container.freeze()

    def _container_create_clone(self):
        """Clone a new LXC container from an existing container.

        This method will clone an existing container to a new container using
        the `clone_name` variable as the new container name. The method will
        create a container if the container `name` does not exist.

        Note that cloning a container will ensure that the original container
        is "stopped" before the clone can be done. Because this operation can
        require a state change the method will return the original container
        to its prior state upon completion of the clone.

        Once the clone is complete the new container will be left in a stopped
        state.
        """

        # Ensure that the state of the original container is stopped
        container_state = self._get_state()
        if container_state != 'stopped':
            self.state_change = True
            self.container.stop()

        build_command = [
            self.module.get_bin_path('lxc-clone', True),
        ]

        build_command = self._add_variables(
            variables_dict=self._get_vars(
                variables=LXC_COMMAND_MAP['clone']['variables']
            ),
            build_command=build_command
        )

        # Load logging for the instance when creating it.
        if self.module.params.get('clone_snapshot') in BOOLEANS_TRUE:
            build_command.append('--snapshot')
        # Check for backing_store == overlayfs if so force the use of snapshot
        # If overlay fs is used and snapshot is unset the clone command will
        # fail with an unsupported type.
        elif self.module.params.get('backing_store') == 'overlayfs':
            build_command.append('--snapshot')

        rc, return_data, err = self._run_command(build_command)
        if rc != 0:
            message = "Failed executing lxc-clone."
            self.failure(
                err=err, rc=rc, msg=message, command=' '.join(
                    build_command
                )
            )
        else:
            self.state_change = True
            # Restore the original state of the origin container if it was
            # not in a stopped state.
            if container_state == 'running':
                self.container.start()
            elif container_state == 'frozen':
                self.container.start()
                self.container.freeze()

        return True

    def _create(self):
        """Create a new LXC container.

        This method will build and execute a shell command to build the
        container. It would have been nice to simply use the lxc python library
        however at the time this was written the python library, in both py2
        and py3 didn't support some of the more advanced container create
        processes. These missing processes mainly revolve around backing
        LXC containers with block devices.
        """

        build_command = [
            self.module.get_bin_path('lxc-create', True),
            '--name %s' % self.container_name,
            '--quiet'
        ]

        build_command = self._add_variables(
            variables_dict=self._get_vars(
                variables=LXC_COMMAND_MAP['create']['variables']
            ),
            build_command=build_command
        )

        # Load logging for the instance when creating it.
        if self.module.params.get('container_log') in BOOLEANS_TRUE:
            # Set the logging path to the /var/log/lxc if uid is root. else
            # set it to the home folder of the user executing.
            try:
                if os.getuid() != 0:
                    log_path = os.getenv('HOME')
                else:
                    if not os.path.isdir('/var/log/lxc/'):
                        os.makedirs('/var/log/lxc/')
                    log_path = '/var/log/lxc/'
            except OSError:
                log_path = os.getenv('HOME')

            build_command.extend([
                '--logfile %s' % os.path.join(
                    log_path, 'lxc-%s.log' % self.container_name
                ),
                '--logpriority %s' % self.module.params.get(
                    'container_log_level'
                ).upper()
            ])

        # Add the template commands to the end of the command if there are any
        template_options = self.module.params.get('template_options', None)
        if template_options:
            build_command.append('-- %s' % template_options)

        rc, return_data, err = self._run_command(build_command)
        if rc != 0:
            message = "Failed executing lxc-create."
            self.failure(
                err=err, rc=rc, msg=message, command=' '.join(build_command)
            )
        else:
            self.state_change = True

    def _container_data(self):
        """Returns a dict of container information.

        :returns: container data
        :rtype: ``dict``
        """

        return {
            'interfaces': self.container.get_interfaces(),
            'ips': self.container.get_ips(),
            'state': self._get_state(),
            'init_pid': int(self.container.init_pid),
            'name' : self.container_name,
        }

    def _unfreeze(self):
        """Unfreeze a container.

        :returns: True or False based on if the container was unfrozen.
        :rtype: ``bol``
        """

        unfreeze = self.container.unfreeze()
        if unfreeze:
            self.state_change = True
        return unfreeze

    def _get_state(self):
        """Return the state of a container.

        If the container is not found the state returned is "absent"

        :returns: state of a container as a lower case string.
        :rtype: ``str``
        """

        if self._container_exists(container_name=self.container_name, lxc_path=self.lxc_path):
            return str(self.container.state).lower()
        else:
            return str('absent')

    def _execute_command(self):
        """Execute a shell command."""

        container_command = self.module.params.get('container_command')
        if container_command:
            container_state = self._get_state()
            if container_state == 'frozen':
                self._unfreeze()
            elif container_state == 'stopped':
                self._container_startup()

            self.container.attach_wait(create_script, container_command)
            self.state_change = True

    def _container_startup(self, timeout=60):
        """Ensure a container is started.

        :param timeout: Time before the destroy operation is abandoned.
        :type timeout: ``int``
        """

        self.container = self.get_container_bind()
        for _ in xrange(timeout):
            if self._get_state() != 'running':
                self.container.start()
                self.state_change = True
                # post startup sleep for 1 second.
                time.sleep(1)
            else:
                return True
        else:
            self.failure(
                lxc_container=self._container_data(),
                error='Failed to start container'
                      ' [ %s ]' % self.container_name,
                rc=1,
                msg='The container [ %s ] failed to start. Check to lxc is'
                    ' available and that the container is in a functional'
                    ' state.' % self.container_name
            )

    def _check_archive(self):
        """Create a compressed archive of a container.

        This will store archive_info in as self.archive_info
        """

        if self.module.params.get('archive') in BOOLEANS_TRUE:
            self.archive_info = {
                'archive': self._container_create_tar()
            }

    def _check_clone(self):
        """Create a compressed archive of a container.

        This will store archive_info in as self.archive_info
        """

        clone_name = self.module.params.get('clone_name')
        if clone_name:
            if not self._container_exists(container_name=clone_name, lxc_path=self.lxc_path):
                self.clone_info = {
                    'cloned': self._container_create_clone()
                }
            else:
                self.clone_info = {
                    'cloned': False
                }

    def _destroyed(self, timeout=60):
        """Ensure a container is destroyed.

        :param timeout: Time before the destroy operation is abandoned.
        :type timeout: ``int``
        """

        for _ in xrange(timeout):
            if not self._container_exists(container_name=self.container_name, lxc_path=self.lxc_path):
                break

            # Check if the container needs to have an archive created.
            self._check_archive()

            # Check if the container is to be cloned
            self._check_clone()

            if self._get_state() != 'stopped':
                self.state_change = True
                self.container.stop()

            if self.container.destroy():
                self.state_change = True

            # post destroy attempt sleep for 1 second.
            time.sleep(1)
        else:
            self.failure(
                lxc_container=self._container_data(),
                error='Failed to destroy container'
                      ' [ %s ]' % self.container_name,
                rc=1,
                msg='The container [ %s ] failed to be destroyed. Check'
                    ' that lxc is available and that the container is in a'
                    ' functional state.' % self.container_name
            )

    def _frozen(self, count=0):
        """Ensure a container is frozen.

        If the container does not exist the container will be created.

        :param count: number of times this command has been called by itself.
        :type count: ``int``
        """

        self.check_count(count=count, method='frozen')
        if self._container_exists(container_name=self.container_name, lxc_path=self.lxc_path):
            self._execute_command()

            # Perform any configuration updates
            self._config()

            container_state = self._get_state()
            if container_state == 'frozen':
                pass
            elif container_state == 'running':
                self.container.freeze()
                self.state_change = True
            else:
                self._container_startup()
                self.container.freeze()
                self.state_change = True

            # Check if the container needs to have an archive created.
            self._check_archive()

            # Check if the container is to be cloned
            self._check_clone()
        else:
            self._create()
            count += 1
            self._frozen(count)

    def _restarted(self, count=0):
        """Ensure a container is restarted.

        If the container does not exist the container will be created.

        :param count: number of times this command has been called by itself.
        :type count: ``int``
        """

        self.check_count(count=count, method='restart')
        if self._container_exists(container_name=self.container_name, lxc_path=self.lxc_path):
            self._execute_command()

            # Perform any configuration updates
            self._config()

            if self._get_state() != 'stopped':
                self.container.stop()
                self.state_change = True

            # Run container startup
            self._container_startup()

            # Check if the container needs to have an archive created.
            self._check_archive()

            # Check if the container is to be cloned
            self._check_clone()
        else:
            self._create()
            count += 1
            self._restarted(count)

    def _stopped(self, count=0):
        """Ensure a container is stopped.

        If the container does not exist the container will be created.

        :param count: number of times this command has been called by itself.
        :type count: ``int``
        """

        self.check_count(count=count, method='stop')
        if self._container_exists(container_name=self.container_name, lxc_path=self.lxc_path):
            self._execute_command()

            # Perform any configuration updates
            self._config()

            if self._get_state() != 'stopped':
                self.container.stop()
                self.state_change = True

            # Check if the container needs to have an archive created.
            self._check_archive()

            # Check if the container is to be cloned
            self._check_clone()
        else:
            self._create()
            count += 1
            self._stopped(count)

    def _started(self, count=0):
        """Ensure a container is started.

        If the container does not exist the container will be created.

        :param count: number of times this command has been called by itself.
        :type count: ``int``
        """

        self.check_count(count=count, method='start')
        if self._container_exists(container_name=self.container_name, lxc_path=self.lxc_path):
            container_state = self._get_state()
            if container_state == 'running':
                pass
            elif container_state == 'frozen':
                self._unfreeze()
            elif not self._container_startup():
                self.failure(
                    lxc_container=self._container_data(),
                    error='Failed to start container'
                          ' [ %s ]' % self.container_name,
                    rc=1,
                    msg='The container [ %s ] failed to start. Check to lxc is'
                        ' available and that the container is in a functional'
                        ' state.' % self.container_name
                )

            # Return data
            self._execute_command()

            # Perform any configuration updates
            self._config()

            # Check if the container needs to have an archive created.
            self._check_archive()

            # Check if the container is to be cloned
            self._check_clone()
        else:
            self._create()
            count += 1
            self._started(count)

    def _get_lxc_vg(self):
        """Return the name of the Volume Group used in LXC."""

        build_command = [
            self.module.get_bin_path('lxc-config', True),
            "lxc.bdev.lvm.vg"
        ]
        rc, vg, err = self._run_command(build_command)
        if rc != 0:
            self.failure(
                err=err,
                rc=rc,
                msg='Failed to read LVM VG from LXC config',
                command=' '.join(build_command)
            )
        else:
            return str(vg.strip())

    def _lvm_lv_list(self):
        """Return a list of all lv in a current vg."""

        vg = self._get_lxc_vg()
        build_command = [
            self.module.get_bin_path('lvs', True)
        ]
        rc, stdout, err = self._run_command(build_command)
        if rc != 0:
            self.failure(
                err=err,
                rc=rc,
                msg='Failed to get list of LVs',
                command=' '.join(build_command)
            )

        all_lvms = [i.split() for i in stdout.splitlines()][1:]
        return [lv_entry[0] for lv_entry in all_lvms if lv_entry[1] == vg]

    def _get_vg_free_pe(self, vg_name):
        """Return the available size of a given VG.

        :param vg_name: Name of volume.
        :type vg_name: ``str``
        :returns: size and measurement of an LV
        :type: ``tuple``
        """

        build_command = [
            'vgdisplay',
            vg_name,
            '--units',
            'g'
        ]
        rc, stdout, err = self._run_command(build_command)
        if rc != 0:
            self.failure(
                err=err,
                rc=rc,
                msg='failed to read vg %s' % vg_name,
                command=' '.join(build_command)
            )

        vg_info = [i.strip() for i in stdout.splitlines()][1:]
        free_pe = [i for i in vg_info if i.startswith('Free')]
        _free_pe = free_pe[0].split()
        return float(_free_pe[-2]), _free_pe[-1]

    def _get_lv_size(self, lv_name):
        """Return the available size of a given LV.

        :param lv_name: Name of volume.
        :type lv_name: ``str``
        :returns: size and measurement of an LV
        :type: ``tuple``
        """

        vg = self._get_lxc_vg()
        lv = os.path.join(vg, lv_name)
        build_command = [
            'lvdisplay',
            lv,
            '--units',
            'g'
        ]
        rc, stdout, err = self._run_command(build_command)
        if rc != 0:
            self.failure(
                err=err,
                rc=rc,
                msg='failed to read lv %s' % lv,
                command=' '.join(build_command)
            )

        lv_info = [i.strip() for i in stdout.splitlines()][1:]
        _free_pe = [i for i in lv_info if i.startswith('LV Size')]
        free_pe = _free_pe[0].split()
        return self._roundup(float(free_pe[-2])), free_pe[-1]

    def _lvm_snapshot_create(self, source_lv, snapshot_name,
                             snapshot_size_gb=5):
        """Create an LVM snapshot.

        :param source_lv: Name of lv to snapshot
        :type source_lv: ``str``
        :param snapshot_name: Name of lv snapshot
        :type snapshot_name: ``str``
        :param snapshot_size_gb: Size of snapshot to create
        :type snapshot_size_gb: ``int``
        """

        vg = self._get_lxc_vg()
        free_space, messurement = self._get_vg_free_pe(vg_name=vg)

        if free_space < float(snapshot_size_gb):
            message = (
                'Snapshot size [ %s ] is > greater than [ %s ] on volume group'
                ' [ %s ]' % (snapshot_size_gb, free_space, vg)
            )
            self.failure(
                error='Not enough space to create snapshot',
                rc=2,
                msg=message
            )

        # Create LVM Snapshot
        build_command = [
            self.module.get_bin_path('lvcreate', True),
            "-n",
            snapshot_name,
            "-s",
            os.path.join(vg, source_lv),
            "-L%sg" % snapshot_size_gb
        ]
        rc, stdout, err = self._run_command(build_command)
        if rc != 0:
            self.failure(
                err=err,
                rc=rc,
                msg='Failed to Create LVM snapshot %s/%s --> %s'
                    % (vg, source_lv, snapshot_name)
            )

    def _lvm_lv_mount(self, lv_name, mount_point):
        """mount an lv.

        :param lv_name: name of the logical volume to mount
        :type lv_name: ``str``
        :param mount_point: path on the file system that is mounted.
        :type mount_point: ``str``
        """

        vg = self._get_lxc_vg()

        build_command = [
            self.module.get_bin_path('mount', True),
            "/dev/%s/%s" % (vg, lv_name),
            mount_point,
        ]
        rc, stdout, err = self._run_command(build_command)
        if rc != 0:
            self.failure(
                err=err,
                rc=rc,
                msg='failed to mountlvm lv %s/%s to %s'
                    % (vg, lv_name, mount_point)
            )

    def _create_tar(self, source_dir):
        """Create an archive of a given ``source_dir`` to ``output_path``.

        :param source_dir:  Path to the directory to be archived.
        :type source_dir: ``str``
        """

        old_umask = os.umask(int('0077',8))

        archive_path = self.module.params.get('archive_path')
        if not os.path.isdir(archive_path):
            os.makedirs(archive_path)

        archive_compression = self.module.params.get('archive_compression')
        compression_type = LXC_COMPRESSION_MAP[archive_compression]

        # remove trailing / if present.
        archive_name = '%s.%s' % (
            os.path.join(
                archive_path,
                self.container_name
            ),
            compression_type['extension']
        )

        build_command = [
            self.module.get_bin_path('tar', True),
            '--directory=%s' % os.path.realpath(
                os.path.expanduser(source_dir)
            ),
            compression_type['argument'],
            archive_name,
            '.'
        ]

        rc, stdout, err = self._run_command(
            build_command=build_command,
            unsafe_shell=True
        )

        os.umask(old_umask)

        if rc != 0:
            self.failure(
                err=err,
                rc=rc,
                msg='failed to create tar archive',
                command=' '.join(build_command)
            )

        return archive_name

    def _lvm_lv_remove(self, lv_name):
        """Remove an LV.

        :param lv_name: The name of the logical volume
        :type lv_name: ``str``
        """

        vg = self._get_lxc_vg()
        build_command = [
            self.module.get_bin_path('lvremove', True),
            "-f",
            "%s/%s" % (vg, lv_name),
        ]
        rc, stdout, err = self._run_command(build_command)
        if rc != 0:
            self.failure(
                err=err,
                rc=rc,
                msg='Failed to remove LVM LV %s/%s' % (vg, lv_name),
                command=' '.join(build_command)
            )

    def _rsync_data(self, container_path, temp_dir):
        """Sync the container directory to the temp directory.

        :param container_path: path to the container container
        :type container_path: ``str``
        :param temp_dir: path to the temporary local working directory
        :type temp_dir: ``str``
        """
        # This loop is created to support overlayfs archives. This should
        # squash all of the layers into a single archive.
        fs_paths = container_path.split(':')
        if 'overlayfs' in fs_paths:
            fs_paths.pop(fs_paths.index('overlayfs'))

        for fs_path in fs_paths:
            # Set the path to the container data
            fs_path = os.path.dirname(fs_path)

            # Run the sync command
            build_command = [
                self.module.get_bin_path('rsync', True),
                '-aHAX',
                fs_path,
                temp_dir
            ]
            rc, stdout, err = self._run_command(
                build_command,
                unsafe_shell=True
            )
            if rc != 0:
                self.failure(
                    err=err,
                    rc=rc,
                    msg='failed to perform archive',
                    command=' '.join(build_command)
                )

    def _unmount(self, mount_point):
        """Unmount a file system.

        :param mount_point: path on the file system that is mounted.
        :type mount_point: ``str``
        """

        build_command = [
            self.module.get_bin_path('umount', True),
            mount_point,
        ]
        rc, stdout, err = self._run_command(build_command)
        if rc != 0:
            self.failure(
                err=err,
                rc=rc,
                msg='failed to unmount [ %s ]' % mount_point,
                command=' '.join(build_command)
            )

    def _overlayfs_mount(self, lowerdir, upperdir, mount_point):
        """mount an lv.

        :param lowerdir: name/path of the lower directory
        :type lowerdir: ``str``
        :param upperdir: name/path of the upper directory
        :type upperdir: ``str``
        :param mount_point: path on the file system that is mounted.
        :type mount_point: ``str``
        """

        build_command = [
            self.module.get_bin_path('mount', True),
            '-t overlayfs',
            '-o lowerdir=%s,upperdir=%s' % (lowerdir, upperdir),
            'overlayfs',
            mount_point,
        ]
        rc, stdout, err = self._run_command(build_command)
        if rc != 0:
            self.failure(
                err=err,
                rc=rc,
                msg='failed to mount overlayfs:%s:%s to %s -- Command: %s'
                    % (lowerdir, upperdir, mount_point, build_command)
            )

    def _container_create_tar(self):
        """Create a tar archive from an LXC container.

        The process is as follows:
            * Stop or Freeze the container
            * Create temporary dir
            * Copy container and config to temporary directory
            * If LVM backed:
                * Create LVM snapshot of LV backing the container
                * Mount the snapshot to tmpdir/rootfs
            * Restore the state of the container
            * Create tar of tmpdir
            * Clean up
        """

        # Create a temp dir
        temp_dir = tempfile.mkdtemp()

        # Set the name of the working dir, temp + container_name
        work_dir = os.path.join(temp_dir, self.container_name)

        # LXC container rootfs
        lxc_rootfs = self.container.get_config_item('lxc.rootfs')

        # Test if the containers rootfs is a block device
        block_backed = lxc_rootfs.startswith(os.path.join(os.sep, 'dev'))

        # Test if the container is using overlayfs
        overlayfs_backed = lxc_rootfs.startswith('overlayfs')

        mount_point = os.path.join(work_dir, 'rootfs')

        # Set the snapshot name if needed
        snapshot_name = '%s_lxc_snapshot' % self.container_name

        container_state = self._get_state()
        try:
            # Ensure the original container is stopped or frozen
            if container_state not in ['stopped', 'frozen']:
                if container_state == 'running':
                    self.container.freeze()
                else:
                    self.container.stop()

            # Sync the container data from the container_path to work_dir
            self._rsync_data(lxc_rootfs, temp_dir)

            if block_backed:
                if snapshot_name not in self._lvm_lv_list():
                    if not os.path.exists(mount_point):
                        os.makedirs(mount_point)

                    # Take snapshot
                    size, measurement = self._get_lv_size(
                        lv_name=self.container_name
                    )
                    self._lvm_snapshot_create(
                        source_lv=self.container_name,
                        snapshot_name=snapshot_name,
                        snapshot_size_gb=size
                    )

                    # Mount snapshot
                    self._lvm_lv_mount(
                        lv_name=snapshot_name,
                        mount_point=mount_point
                    )
                else:
                    self.failure(
                        err='snapshot [ %s ] already exists' % snapshot_name,
                        rc=1,
                        msg='The snapshot [ %s ] already exists. Please clean'
                            ' up old snapshot of containers before continuing.'
                            % snapshot_name
                    )
            elif overlayfs_backed:
                lowerdir, upperdir = lxc_rootfs.split(':')[1:]
                self._overlayfs_mount(
                    lowerdir=lowerdir,
                    upperdir=upperdir,
                    mount_point=mount_point
                )

            # Set the state as changed and set a new fact
            self.state_change = True
            return self._create_tar(source_dir=work_dir)
        finally:
            if block_backed or overlayfs_backed:
                # unmount snapshot
                self._unmount(mount_point)

            if block_backed:
                # Remove snapshot
                self._lvm_lv_remove(snapshot_name)

            # Restore original state of container
            if container_state == 'running':
                if self._get_state() == 'frozen':
                    self.container.unfreeze()
                else:
                    self.container.start()

            # Remove tmpdir
            shutil.rmtree(temp_dir)

    def check_count(self, count, method):
        if count > 1:
            self.failure(
                error='Failed to %s container' % method,
                rc=1,
                msg='The container [ %s ] failed to %s. Check to lxc is'
                    ' available and that the container is in a functional'
                    ' state.' % (self.container_name, method)
            )

    def failure(self, **kwargs):
        """Return a Failure when running an Ansible command.

        :param error: ``str``  Error that occurred.
        :param rc: ``int``     Return code while executing an Ansible command.
        :param msg: ``str``    Message to report.
        """

        self.module.fail_json(**kwargs)

    def run(self):
        """Run the main method."""

        action = getattr(self, LXC_ANSIBLE_STATES[self.state])
        action()

        outcome = self._container_data()
        if self.archive_info:
            outcome.update(self.archive_info)

        if self.clone_info:
            outcome.update(self.clone_info)

        self.module.exit_json(
            changed=self.state_change,
            lxc_container=outcome
        )


def main():
    """Ansible Main module."""

    module = AnsibleModule(
        argument_spec=dict(
            name=dict(
                type='str',
                required=True
            ),
            template=dict(
                type='str',
                default='ubuntu'
            ),
            backing_store=dict(
                type='str',
                choices=LXC_BACKING_STORE.keys(),
                default='dir'
            ),
            template_options=dict(
                type='str'
            ),
            config=dict(
                type='path',
            ),
            vg_name=dict(
                type='str',
                default='lxc'
            ),
            thinpool=dict(
                type='str'
            ),
            fs_type=dict(
                type='str',
                default='ext4'
            ),
            fs_size=dict(
                type='str',
                default='5G'
            ),
            directory=dict(
                type='path'
            ),
            zfs_root=dict(
                type='str'
            ),
            lv_name=dict(
                type='str'
            ),
            lxc_path=dict(
                type='path'
            ),
            state=dict(
                choices=LXC_ANSIBLE_STATES.keys(),
                default='started'
            ),
            container_command=dict(
                type='str'
            ),
            container_config=dict(
                type='str'
            ),
            container_log=dict(
                type='bool',
                default='false'
            ),
            container_log_level=dict(
                choices=[n for i in LXC_LOGGING_LEVELS.values() for n in i],
                default='INFO'
            ),
            clone_name=dict(
                type='str',
                required=False
            ),
            clone_snapshot=dict(
                type='bool',
                default='false'
            ),
            archive=dict(
                type='bool',
                default='false'
            ),
            archive_path=dict(
                type='path',
            ),
            archive_compression=dict(
                choices=LXC_COMPRESSION_MAP.keys(),
                default='gzip'
            )
        ),
        supports_check_mode=False,
        required_if = ([
            ('archive', True, ['archive_path'])
        ]),
    )

    if not HAS_LXC:
        module.fail_json(
            msg='The `lxc` module is not importable. Check the requirements.'
        )

    lv_name = module.params.get('lv_name')
    if not lv_name:
        module.params['lv_name'] = module.params.get('name')

    lxc_manage = LxcContainerManagement(module=module)
    lxc_manage.run()


# import module bits
from ansible.module_utils.basic import *
if __name__ == '__main__':
    main()