cDockerDSC.psm1

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
enum Ensure
{ 
    Absent
    Present
}

[DscResource()]
class DockerDSC
{
    [DscProperty(Key)]
    [String]$DockerVersion

    [DscProperty(NotConfigurable)]
    [String]$InstallState

    [DscProperty(Mandatory = $false)]
    [String]$Ensure = 'Present'

    [DscProperty(NotConfigurable)]
    [String]$DockerName

    # Gets the resource's current state.
    [DockerDSC] Get()
    {
        try
        {
            $docker = docker version -f '{{json .}}' | ConvertFrom-Json

            if ($docker)
            {
                $this.InstallState = 'Present'
                $this.DockerVersion = $docker.Server.Version
                $this.DockerName = $docker.Server.Platform.Name
            }
        }
        catch [System.Management.Automation.CommandNotFoundException]
        {
            $this.InstallState = 'Absent'
        }
        return $this
    }
    
    # Sets the desired state of the resource.
    [void] Set()
    {
        Write-Verbose "Desired State is: $($this.Ensure)"
        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

        switch ($this.Ensure)
        {
            "Absent"
            {
                Uninstall-Package -Name docker -ProviderName DockerMsftProvider -Force -ForceBootstrap

            }
            "Present"
            {
                Install-Package -Name docker -ProviderName DockerMsftProvider -Force -RequiredVersion $this.DockerVersion -ForceBootstrap
            }
        }
    }
    
    # Tests if the resource is in the desired state.
    [bool] Test()
    {
        foreach ($level in "Machine", "User")
        {
            [Environment]::GetEnvironmentVariables($level)
        }
        $dockerInfo = $this.Get()
        if ($dockerInfo.InstallState -eq $this.Ensure)
        {
            return $true
        }
        else
        {
            return $false
        }
    }
}