<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Containers Archives - LucD notes</title>
	<atom:link href="https://www.lucd.info/category/cloud-init/containers/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.lucd.info/category/cloud-init/containers/</link>
	<description>My PowerShell ramblings</description>
	<lastBuildDate>Wed, 11 Dec 2019 17:26:50 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9</generator>

<image>
	<url>https://www.lucd.info/wp-content/uploads/2018/12/cropped-120px-Tibetan_Dharmacakra-32x32.png</url>
	<title>Containers Archives - LucD notes</title>
	<link>https://www.lucd.info/category/cloud-init/containers/</link>
	<width>32</width>
	<height>32</height>
</image> 
<atom:link rel="hub" href="https://pubsubhubbub.appspot.com"/><atom:link rel="hub" href="https://pubsubhubbub.superfeedr.com"/><atom:link rel="hub" href="https://websubhub.com/hub"/>	<item>
		<title>Cloud-init &#8211; Part 5 &#8211; Running Containers</title>
		<link>https://www.lucd.info/2019/12/11/cloud-init-part-5-running-containers/</link>
					<comments>https://www.lucd.info/2019/12/11/cloud-init-part-5-running-containers/#comments</comments>
		
		<dc:creator><![CDATA[LucD]]></dc:creator>
		<pubDate>Wed, 11 Dec 2019 14:30:53 +0000</pubDate>
				<category><![CDATA[Cloud-init]]></category>
		<category><![CDATA[Containers]]></category>
		<category><![CDATA[Photon]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Ubuntu]]></category>
		<category><![CDATA[container]]></category>
		<category><![CDATA[docker]]></category>
		<category><![CDATA[ubuntu]]></category>
		<guid isPermaLink="false">http://www.lucd.info/?p=6917</guid>

					<description><![CDATA[In this last part of this series (for now) we will show how [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>In this last part of this series (for now) we will show how to use <strong>containers</strong> to run your PowerShell/PowerCLI scripts on the deployed instances. And although technically not a ‘<em>real</em>‘&nbsp;<a href="https://cloudinit.readthedocs.io/en/latest/" target="_blank" rel="noopener noreferrer">cloud-init</a>&nbsp;post, I consider it related to&nbsp;<a href="https://www.lucd.info/2019/12/06/cloud-init-part-1-the-basics/" target="_blank" rel="noopener noreferrer">Part 1</a>,&nbsp;<a href="https://www.lucd.info/2019/12/07/cloud-init-part-2-advanced-ubuntu/" target="_blank" rel="noopener noreferrer">Part 2</a>&nbsp;and&nbsp;<a href="https://www.lucd.info/2019/12/08/cloud-init-part-3-photon-os/" target="_blank" rel="noopener noreferrer">Part3</a> in this series.&nbsp;</p>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="730" height="349" src="https://www.lucd.info/wp-content/uploads/2019/12/cloud-init-part-5-2.png" alt="" class="wp-image-6923" srcset="https://www.lucd.info/wp-content/uploads/2019/12/cloud-init-part-5-2.png 730w, https://www.lucd.info/wp-content/uploads/2019/12/cloud-init-part-5-2-300x143.png 300w, https://www.lucd.info/wp-content/uploads/2019/12/cloud-init-part-5-2-720x344.png 720w" sizes="(max-width: 730px) 100vw, 730px" /></figure>



<span id="more-6917"></span>



<h2 class="wp-block-heading">Introduction</h2>



<p>In <a rel="noreferrer noopener" aria-label="Post 4 (opens in a new tab)" href="https://www.lucd.info/2019/12/09/cloud-init-part-4-running-scripts/" target="_blank">Post 4</a> of the <a href="https://www.lucd.info/?s=cloud-init" target="_blank" rel="noreferrer noopener" aria-label="cloud-init series (opens in a new tab)">cloud-init series</a>, we ran our PowerShell/PowerCLI scripts natively in the Guest OS of the instance.</p>



<p>That might have an impact in some situations. When the first script installs for example the VMware PowerCLI modules, these modules will stay installed in the Guest OS. Consider this as a kind of <strong>PowerShell tattooing</strong>.</p>



<p>Another task that might be somewhat of a challenge is testing your PowerShell scripts against multiple environments, different module versions, different OS versions&#8230; Again, when we make changes to the Guest OS, these changes might be <strong>hard to remove</strong>.</p>



<p>Besides deploying a new &#8216;cattle&#8217; station for each possible combination, we can also run our scripts in <a rel="noreferrer noopener" aria-label="Docker containers (opens in a new tab)" href="https://www.docker.com/" target="_blank">Docker containers</a>. Once the script is done, we throw away the container instance. And we are back to a pristine OS.</p>



<p>And as it turns out, containers also offer some new features that are harder, or even impossible, to implement when running locally in the Guest OS.</p>



<p>Since we will be using several docker commands in the following sections, it will be useful to have the <a href="https://docs.docker.com/reference/" target="_blank" rel="noreferrer noopener" aria-label="Docker Reference (opens in a new tab)">Docker Reference</a> documentation nearby. </p>



<h2 class="wp-block-heading">Install Docker</h2>



<h3 class="wp-block-heading">Ubuntu</h3>



<p>The Ubuntu OVAs we have been installing in the previous posts in this series, do not contain the docker package. We can easily include that in our YAML file under the <strong>runcmd</strong> section.</p>



<pre class="lang:yaml decode:true ">#cloud-config
hostname: ubuntubioniccontainer
fqdn: ubuntubioniccontainer.local.lab
write_files:
- path: /etc/netplan/50-cloud-init.yaml
  content: |
    network:
     version: 2
     ethernets:
      ens192:
       addresses: [192.168.10.84/24]
       gateway4: 192.168.10.1
       dhcp6: false
       nameservers:
         addresses:
           - 192.168.10.2
           - 192.168.10.3
         search:
           - local.lab
       dhcp4: false
       optional: true
- path: /etc/sysctl.d/60-disable-ipv6.conf
  owner: root
  content: |
    net.ipv6.conf.all.disable_ipv6=1
    net.ipv6.conf.default.disable_ipv6=1
runcmd:
- netplan --debug apply
- sysctl -w net.ipv6.conf.all.disable_ipv6=1
- sysctl -w net.ipv6.conf.default.disable_ipv6=1
- apt -y autoremove
- apt-get update
- apt-get remove docker docker-engine docker.io
- apt install docker.io -y
- systemctl enable docker
- systemctl start docker
timezone: Europe/Brussels
system_info:
  default_user:
    name: default-user
    lock_passwd: false
    sudo: ["ALL=(ALL) NOPASSWD:ALL"]
disable_root: false
ssh_pwauth: yes
users:
  - default
  - name: luc
    gecos: LucD
    lock_passwd: false
    groups: sudo, users, admin
    shell: /bin/bash
    sudo: ['ALL=(ALL) NOPASSWD:ALL']
chpasswd:
  list: |
    default-user:$6$2csGx3AAX0RPRMPB$85sEEZ76z0V93M9pvXGtTFrwlMOaV2VjRHB6IKPRrwc.4qEqcs2EnDzn8oUlcVVb9Biq.Pg7qQchLgNLuetkT0
    luc:$6$.4Kyvju2v5iR$bvZHOntkH9EqgGdMc7fKZKbB132LYHVIFgxN7Ho.mlMGloUayOaKijR6MvLp/ncf4SynTigjaOKGk11EF9gru/
    root:$6$m1TXY60tUAViCYb1$/w.CqV50.M0Nlt6mx2726.bxWZ7/TCqWjOOw4S3h1H8AN.SPWQnKoASXth2E3euBXwebU4Q7dpoGU1SiQontT1
  expire: false
package_upgrade: true
package_reboot_if_required: true</pre>



<h4 class="wp-block-heading">Annotations</h4>



<p><strong>Line 33-36</strong>: Install the docker package, start it and make sure it runs after a reboot.</p>



<p><strong>Line 33</strong>: If there should already be a docker package installed, this line removes that package. If no docker package is installed, the line does nothing.</p>



<h3 class="wp-block-heading">Photon</h3>



<p>The Photon OVA we use comes with docker installed. No need for any additional commands in the YAML file.</p>



<h2 class="wp-block-heading">Image microsoft/powershell</h2>



<p>In the following sections we will run a number of scripts in the microsoft/powershell container on Ubuntu and Photon. Only when there is a difference between both platforms, will the text mention the platforms.</p>



<h3 class="wp-block-heading">A Simple Run</h3>



<p>Let&#8217;s try running a simple PowerShell script in a container on the station.</p>



<pre class="lang:ps decode:true  ">$vmName = 'ubuntubioniccontainer'
$code = @'
sudo docker run --rm microsoft/powershell:latest pwsh -C 'whoami;Get-Process;pwd'
'@

$credItem = Get-VICredentialStoreItem -Host $vmName
$cred = New-Object System.Management.Automation.PSCredential ($credItem.User, (ConvertTo-SecureString $credItem.Password -AsPlainText -Force))

$sInvoke = @{
    VM = $vmName
    GuestCredential = $cred
    ScriptType = 'bash'
    ScriptText = $code
    NoIPinCert = $true
    Verbose = $true
}
Invoke-VMScriptPlus @sInvoke
</pre>



<h4 class="wp-block-heading">Annotations</h4>



<p><strong>Line 3</strong>: The docker command we sent to the station. The details of the different parts in this line are explained in the following table.</p>




<table id="tablepress-2" class="tablepress tablepress-id-2">
<tbody>
<tr class="row-1">
	<td class="column-1">run --rm</td><td class="column-2">Run a command in a container and clean up when the container exits</td>
</tr>
<tr class="row-2">
	<td class="column-1">microsoft/powershell:latest</td><td class="column-2">The name of the Image. In this case, the latest Microsoft provided stable PowerShell image</td>
</tr>
<tr class="row-3">
	<td class="column-1">pwsh -C</td><td class="column-2">The command and argument we send to the container. In this case we start PowerShell and use the Command parameter</td>
</tr>
<tr class="row-4">
	<td class="column-1">whoami;Get-Process;pwd</td><td class="column-2">A series of commands, separated by semi-columns, that will be executed by ‘pwsh’</td>
</tr>
</tbody>
</table>
<!-- #tablepress-2 from cache -->



<p>The output will be something like this.</p>



<figure class="wp-block-image size-large"><img decoding="async" width="855" height="1024" src="https://www.lucd.info/wp-content/uploads/2019/12/crun1-855x1024.png" alt="" class="wp-image-6984" srcset="https://www.lucd.info/wp-content/uploads/2019/12/crun1-855x1024.png 855w, https://www.lucd.info/wp-content/uploads/2019/12/crun1-251x300.png 251w, https://www.lucd.info/wp-content/uploads/2019/12/crun1-768x919.png 768w, https://www.lucd.info/wp-content/uploads/2019/12/crun1-720x862.png 720w, https://www.lucd.info/wp-content/uploads/2019/12/crun1.png 944w" sizes="(max-width: 855px) 100vw, 855px" /></figure>



<p>Notice how docker will search for and install the image (since it isn&#8217;t present). That is the output in the <mark>yellow</mark> box. The actual output of the commands we sent to <em>pwsh</em>, are in the <span style="background-color:#00d084" class="tadv-background-color">green</span> box.</p>



<p>The second time we run the same script, we will only see the actual output of the commands. And that&#8217;s because the image is already present.</p>



<figure class="wp-block-image size-large"><img decoding="async" width="910" height="524" src="https://www.lucd.info/wp-content/uploads/2019/12/crun2.png" alt="" class="wp-image-6985" srcset="https://www.lucd.info/wp-content/uploads/2019/12/crun2.png 910w, https://www.lucd.info/wp-content/uploads/2019/12/crun2-300x173.png 300w, https://www.lucd.info/wp-content/uploads/2019/12/crun2-768x442.png 768w, https://www.lucd.info/wp-content/uploads/2019/12/crun2-720x415.png 720w" sizes="(max-width: 910px) 100vw, 910px" /></figure>



<h3 class="wp-block-heading">Modules</h3>



<p>Time to start diving into PowerCLI. For that we need to install the VMware PowerCLI modules of course.</p>



<pre class="lang:ps decode:true ">$vmName = 'ubuntubioniccontainer'

$script = @'
$ProgressPreference = "SilentlyContinue"
Install-Module -Name VMware.PowerCLI -AllowClobber -Force | Out-Null
Get-Module -Name VMware* -ListAvailable
'@

$docker = @'
sudo docker run --rm microsoft/powershell:latest pwsh -C '$($script.Replace("<code>r",'').Split("</code>n") -join ';')'
'@

$credItem = Get-VICredentialStoreItem -Host $vmName
$cred = New-Object System.Management.Automation.PSCredential ($credItem.User, (ConvertTo-SecureString $credItem.Password -AsPlainText -Force))

$sInvoke = @{
    VM = $vmName
    GuestCredential = $cred
    ScriptType = 'bash'
    ScriptText = $ExecutionContext.InvokeCommand.ExpandString($docker)
    NoIPinCert = $true
    Verbose = $true
}
Invoke-VMScriptPlus @sInvoke
</pre>



<h4 class="wp-block-heading">Annotations</h4>



<p><strong>Line 3-7</strong>: We use a here-string for the script we want to execute under <em>pwsh</em> in the container.</p>



<p><strong>Line 9-11</strong>: And another here-string for the <em>docker</em> command. </p>



<p><strong>Line 10</strong>: The script is running on a Windows box, hence the &lt;CR&gt;&lt;LF&gt; to &lt;LF&gt;. The second manipulation is to convert the array of lines to a single line, where the lines are separated with a semi-column. Note that the actual conversion does not happen here.</p>



<p><strong>Line 20</strong>: The script uses the ExpandString method to perform the text manipulations we described in the comments on <strong>Line 10</strong>. Also note that we don&#8217;t have to escape the dollar-signs in the $script part, since the variable substitution will not go that deep.</p>



<p>The result (don&#8217;t mind the funny characters for now).</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="937" height="794" src="https://www.lucd.info/wp-content/uploads/2019/12/crun3.png" alt="" class="wp-image-6992" srcset="https://www.lucd.info/wp-content/uploads/2019/12/crun3.png 937w, https://www.lucd.info/wp-content/uploads/2019/12/crun3-300x254.png 300w, https://www.lucd.info/wp-content/uploads/2019/12/crun3-768x651.png 768w, https://www.lucd.info/wp-content/uploads/2019/12/crun3-720x610.png 720w" sizes="auto, (max-width: 937px) 100vw, 937px" /></figure>



<h3 class="wp-block-heading">ScreenSpace</h3>



<p>When we use all the defaults in the container, we seem to end up with a simple screen that has the default 80 x 25 dimensions. For better results, we can introduce bigger screens inside the container.</p>


<pre class="urvanov-syntax-highlighter-plain-tag">$vmName = 'ubuntubioniccontainer'

$script = @'
reset -w
$ProgressPreference = "SilentlyContinue"
Install-Module -Name VMware.PowerCLI -AllowClobber -Force | Out-Null
Get-Module -Name VMware* -ListAvailable
'@
$docker = @'
sudo docker run --rm --tty \
    -e TERM=xterm -e LINES=25 -e COLUMNS=135 \
    microsoft/powershell:latest \
    pwsh -C '$($script.Replace("`r",'').Split("`n") -join ';')'
'@

$credVM = Get-VICredentialStoreItem -Host $vmName
$cred = New-Object System.Management.Automation.PSCredential ($credVM.User, (ConvertTo-SecureString $credVM.Password -AsPlainText -Force))

$sInvoke = @{
    VM = $vmName
    GuestCredential = $cred
    ScriptType = 'bash'
    ScriptText = $ExecutionContext.InvokeCommand.ExpandString($docker)
    NoIPinCert = $true
    Verbose = $true
}
Invoke-VMScriptPlus @sInvoke</pre>


<h4 class="wp-block-heading">Annotations</h4>



<p><strong>Line 4</strong>: The <em>reset -w</em> command is a fix for an <a rel="noreferrer noopener" aria-label="issue (opens in a new tab)" href="https://github.com/moby/moby/issues/33794" target="_blank">issue</a> that Docker seems to have when a <strong>pseudo-terminal</strong> (the <strong>&#8211;tty</strong> parameter) is used. With the <em>reset -w</em> command, the terminal will reread the content of <strong>setupterm</strong> and adjust the lines and columns accordingly.</p>



<p><strong>Line 10</strong>: The <strong>&#8211;tty</strong> parameter allocates a pseudo-terminal to the container.</p>



<p><strong>Line 11</strong>: The -e parameter is used to set a number of environment variables for the container. In this case, specify that the container shall use an <strong>xterm</strong> with <strong>dimensions 25 x 135</strong>.</p>



<p>The changed screen is visible in the output (compare it with the width of the previous output).</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="521" src="https://www.lucd.info/wp-content/uploads/2019/12/crun4-1024x521.png" alt="" class="wp-image-7006" srcset="https://www.lucd.info/wp-content/uploads/2019/12/crun4-1024x521.png 1024w, https://www.lucd.info/wp-content/uploads/2019/12/crun4-300x153.png 300w, https://www.lucd.info/wp-content/uploads/2019/12/crun4-768x391.png 768w, https://www.lucd.info/wp-content/uploads/2019/12/crun4-1536x782.png 1536w, https://www.lucd.info/wp-content/uploads/2019/12/crun4-720x367.png 720w, https://www.lucd.info/wp-content/uploads/2019/12/crun4.png 1756w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<h3 class="wp-block-heading">Volumes</h3>



<p>With the method we just showed, we will have to incur the overhead of installing the VMware PowerCLI modules on each run, because we throw away the container after we used it.</p>



<p>But there is a solution for this, by using <a href="https://docs.docker.com/engine/reference/commandline/volume_create/" target="_blank" rel="noreferrer noopener" aria-label="docker volumes (opens in a new tab)">docker volumes</a>. They are kept inside the guest OS of the instance and can be attached to each container we run.</p>





<pre class="lang:ps decode:true  ">$vmName = 'ubuntubioniccontainer'

$script = @'
reset -w
\`$ProgressPreference = "SilentlyContinue"
if(-not (Get-Module -Name VMware.PowerCLI -ListAvailable)){
    Install-Module -Name VMware.PowerCLI -AllowClobber -Force | Out-Null
}
\`$WarningPreference = 'SilentlyContinue'
\`$sConf = @{
    InvalidCertificateAction = 'Ignore'
    ParticipateInCeip = \`$false
    DisplayDeprecationWarnings = \`$false
    Scope = 'User'
    Confirm = \`$false
}
Set-PowerCLIConfiguration @sConf | Out-Null
Connect-VIServer -Server $vcsaName -User $vcsaUser -Password $vcsaPswd | Out-Null
Get-VMHost
Disconnect-VIServer -Server $vcsaName -Confirm:\`$false
'@

$docker = @'
sudo docker volume create PCLIModules &gt; /dev/null
cat &gt; ~/script.ps1 &lt;&lt; EOF
$($script.Split("<code>r"))
EOF
sudo docker run --rm \
    --tty \
    -v /PCLIModules:/root/.local/share/powershell/Modules \
    -v ~:/Scripts \
    -e TERM=xterm -e LINES=25 -e COLUMNS=135 \
    microsoft/powershell:latest \
    pwsh -F /Scripts/script.ps1
rm ~/script.ps1
'@

$vcsaName = 'vcsa.local.lab'
$credVCSA = Get-VICredentialStoreItem -Host $vcsaName
$vcsaUser = $credVCSA.User
$vcsaPswd = $credVCSA.Password

$credVM = Get-VICredentialStoreItem -Host $vmName
$cred = New-Object System.Management.Automation.PSCredential ($credVM.User, (ConvertTo-SecureString $credVM.Password -AsPlainText -Force))

#$credItem = Get-VICredentialStoreItem -Host $vmName
#$cred = New-Object System.Management.Automation.PSCredential ($credItem.User, (ConvertTo-SecureString $credItem.Password -AsPlainText -Force))
$cred = New-Object System.Management.Automation.PSCredential ($vmUser, (ConvertTo-SecureString $vmPswd -AsPlainText -Force))

$dockerExpanded = $ExecutionContext.InvokeCommand.ExpandString($docker)
$sInvoke = @{
    VM = $vmName
    GuestCredential = $cred
    ScriptType = 'bash'
    ScriptText = $ExecutionContext.InvokeCommand.ExpandString($dockerExpanded)
    NoIPinCert = $true
}
Invoke-VMScriptPlus @sInvoke</pre>



<h4 class="wp-block-heading">Annotations</h4>



<p><strong>Line 5</strong>: We have some 'Inception' going on here, hence the '</code>' sequence before the dollar sign. In <strong>line 50</strong> we substitute the variables in the bash script itself. That way we can provide the script as an inline file in the bash script. But since bash also interprets that back-tick, we have to escape it. The back-tick itself is to avoid variable substitution that is done in line 55.</p>



<p><strong>Line 24</strong>: We create a docker volume named <strong>PCLIModules</strong>. If that volume already exists, the bash script will just continue.</p>



<p><strong>Line 25-27</strong>: Instead of having the PowerShell/PowerCLI script in the <strong>Command</strong> parameter of the <em>pwsh</em> command, we use an inline file. This effectively creates a .ps1 file in the home directory of the user in the guest OS.</p>



<p><strong>Line 30</strong>: The Volume parameter on the docker run command maps the docker volume <strong>PCLIModules</strong> to the folder  <strong>/root/.local/share/powershell/Modules</strong> in the container. With an Install-Module, the modules will be installed in this  <strong>/root/.local/share/powershell/Modules</strong> , and thus be stored on the docker volume <strong>PCLIModules</strong>. This volume can be reused on subsequent runs of the container, eliminating the need to install the VMware PowerCLI modules on each run.</p>



<p><strong>Line 31</strong>: On the docker run command we map the <strong>user's home directory</strong> (~) in the guest OS to a folder, named <strong>Scripts</strong> in the container. </p>



<p><strong>Line 34</strong>: The <em>pwsh</em> command that runs in the container uses the <strong>File</strong> parameter to run the .ps1 file created in lines 25-27.</p>



<p><strong>Line 35</strong>: The .ps1 file that was created before calling the <em>docker run</em> command, is now <strong>removed</strong>.</p>



<p><strong>Line 55</strong>: The second substitution round. In this case we substitute primarily all non-escaped (back-tick) dollar sign in the PowerShell script (at this point in the script present as an inline file in the bash script).</p>



<p>The result when we run the script.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="790" src="https://www.lucd.info/wp-content/uploads/2019/12/crun5-1024x790.png" alt="" class="wp-image-7028" srcset="https://www.lucd.info/wp-content/uploads/2019/12/crun5-1024x790.png 1024w, https://www.lucd.info/wp-content/uploads/2019/12/crun5-300x231.png 300w, https://www.lucd.info/wp-content/uploads/2019/12/crun5-768x593.png 768w, https://www.lucd.info/wp-content/uploads/2019/12/crun5-720x556.png 720w, https://www.lucd.info/wp-content/uploads/2019/12/crun5.png 1274w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>Notice how the <strong>ScriptText</strong> property contains the bash script as it is presented to the Guest OS of the instance. In there the dollar signs are escaped (with a back-slash) to <strong>avoid substitution</strong> by bash.</p>



<h3 class="wp-block-heading">ANSI codes and Existing Scripts</h3>



<p>In this section, we will tackle two subjects.</p>



<ul class="wp-block-list"><li>Eliminate those 'funny' characters in the output</li><li>How to run my existing script, similar to what we did in <a rel="noreferrer noopener" aria-label="Part 4 - Running Script (opens in a new tab)" href="https://www.lucd.info/2019/12/09/cloud-init-part-4-running-scripts/" target="_blank">Part 4 - Running Script</a>s.</li></ul>



<p>As it turns out, these 'funny characters' are <a rel="noreferrer noopener" aria-label="ANSI escape codes (opens in a new tab)" href="https://en.wikipedia.org/wiki/ANSI_escape_code" target="_blank">ANSI escape codes</a>. In the container, we are using a pseudo-terminal, and as a result, the OS in the container sends those ANSI escape codes to position the cursor, change the text colour, but also those '...' (three dots) when PowerShell has to cut short the value of a property.</p>



<p>For now, the only way if found to eliminate those ANSI escape codes, is to find and replace them.</p>



<p>For using your existing scripts in this setup, we adopt the same strategy as we did in <a href="https://www.lucd.info/2019/12/09/cloud-init-part-4-running-scripts/" target="_blank" rel="noreferrer noopener" aria-label="Part 4 - Running Scripts (opens in a new tab)">Part 4 - Running Scripts</a>.</p>



<p>Our existing script, in <strong>Sample-PCLI-Script3.ps1</strong>, looks like this.</p>



<pre class="lang:ps decode:true  ">Get-VMHost |
    Select Name, NumCpu, Version |
    ConvertTo-Html
</pre>



<p>And the script to run all this looks like this</p>



<pre class="lang:ps decode:true ">$vmName = 'ubuntubioniccontainer'

$prefix = @'
reset -w
<code>$ProgressPreference = "SilentlyContinue"
if(-not (Get-Module -Name VMware.PowerCLI -ListAvailable)){
    Install-Module -Name VMware.PowerCLI -AllowClobber -Force | Out-Null
}
</code>$WarningPreference = 'SilentlyContinue'
<code>$sConf = @{
    InvalidCertificateAction = 'Ignore'
    ParticipateInCeip = </code>$false
    DisplayDeprecationWarnings = <code>$false
    Scope = 'User'
    Confirm = </code>$false
}
Set-PowerCLIConfiguration @sConf | Out-Null
Connect-VIServer -Server $vcsaName -User $vcsaUser -Password $vcsaPswd | Out-Null
'@
$script = Get-Content -Path .\Sample-PCLI-Script3.ps1
$suffix = @'
Disconnect-VIServer -Server $vcsaName -Confirm:<code>$false
'@

$docker = @'
sudo docker volume create PCLIModules &gt; /dev/null
cat &gt; ~/script.ps1 &lt;&lt; 'EOF'
$($prefix.Split("</code>r"))
$($script -join "<code>n")
$($suffix.Split("</code>r"))
EOF
sudo docker run --rm \
    --tty \
    -v /PCLIModules:/root/.local/share/powershell/Modules \
    -v ~:/Scripts \
    -e TERM=xterm -e LINES=25 -e COLUMNS=135 \
    microsoft/powershell:latest \
    pwsh -F /Scripts/script.ps1 &gt; ~/result.txt
cat ~/result.txt
rm ~/result.txt
rm ~/script.ps1
'@

$vcsaName = 'vcsa.local.lab'
$credVCSA = Get-VICredentialStoreItem -Host $vcsaName
$vcsaUser = $credVCSA.User
$vcsaPswd = $credVCSA.Password

$credVM = Get-VICredentialStoreItem -Host $vmName
$cred = New-Object System.Management.Automation.PSCredential ($credVM.User, (ConvertTo-SecureString $credVM.Password -AsPlainText -Force))

$dockerExpanded = $ExecutionContext.InvokeCommand.ExpandString($docker)
$sInvoke = @{
    VM = $vmName
    GuestCredential = $cred
    ScriptType = 'bash'
    ScriptText = $ExecutionContext.InvokeCommand.ExpandString($dockerExpanded)
    NoIPinCert = $true
    Verbose = $true
}
$result = Invoke-VMScriptPlus @sInvoke

# Remove ANSI Escape Sequences
($result.ScriptOutput.Split("<code>n") |
    Foreach-Object -Process {
        ($_ -replace "\xe2\x80\xa6","…") -replace "\x1b\[\?[1-9]h|\x1b\[[1-9]n|\x1b=|\x1b\]0;|\x07|\x1b\]0;", ''
    }) -join "</code>n"
</pre>



<h4 class="wp-block-heading">Annotations</h4>



<p><strong>Line 3, 20, 21</strong>: We split the code into three parts. A fixed prefix, the code of our existing script and a suffix.</p>



<p><strong>Line 27-31</strong>: We use the same concept of an inline file as we did in the previous section. The only difference is that we now have three parts instead of one.</p>



<p><strong>Line 64-67</strong>: The ANSI escape sequences are <strong>removed</strong> from the output. The <strong>RegEx expression</strong> does not cover all possible ANSI escape sequences, but it did the job for all the ones I encountered. On the other hand, the RegEx expression can easily be expanded.</p>



<p>The result, which is an HTML file, looks like this.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="357" height="209" src="https://www.lucd.info/wp-content/uploads/2019/12/crun6.png" alt="" class="wp-image-7043" srcset="https://www.lucd.info/wp-content/uploads/2019/12/crun6.png 357w, https://www.lucd.info/wp-content/uploads/2019/12/crun6-300x176.png 300w" sizes="auto, (max-width: 357px) 100vw, 357px" /></figure>



<p>The part where we filter away the ANSI code sequence is also used to translate some well-known characters. Remember the funny characters in the module list?</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="785" height="544" src="https://www.lucd.info/wp-content/uploads/2019/12/mod1.png" alt="" class="wp-image-7050" srcset="https://www.lucd.info/wp-content/uploads/2019/12/mod1.png 785w, https://www.lucd.info/wp-content/uploads/2019/12/mod1-300x208.png 300w, https://www.lucd.info/wp-content/uploads/2019/12/mod1-768x532.png 768w, https://www.lucd.info/wp-content/uploads/2019/12/mod1-720x499.png 720w" sizes="auto, (max-width: 785px) 100vw, 785px" /></figure>



<p>With the first -replace operator in the previous code, we can change this back to the character we are used to. The hex sequence 0xE2, 0x80, 0xA6 that get back is, in fact, the code for the horizontal ellipsis, the 3 horizontal dots PowerShell uses to indicate a cut off value.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="763" height="540" src="https://www.lucd.info/wp-content/uploads/2019/12/mod2.png" alt="" class="wp-image-7051" srcset="https://www.lucd.info/wp-content/uploads/2019/12/mod2.png 763w, https://www.lucd.info/wp-content/uploads/2019/12/mod2-300x212.png 300w, https://www.lucd.info/wp-content/uploads/2019/12/mod2-720x510.png 720w" sizes="auto, (max-width: 763px) 100vw, 763px" /></figure>



<p>There are most probably many other characters or character combinations that do not translate well, but at least we have a method to correct this.</p>



<h3 class="wp-block-heading">InFile &amp; OutFile</h3>



<p>Using inline files and the stdout stream for input and results works in most cases, but it might make things needlessly complex in others. To avoid that, we can make use of the <strong>InFile</strong> and <strong>OutFile</strong> parameters on the <a rel="noreferrer noopener" aria-label="Invoke-VMScriptPlus (opens in a new tab)" href="https://www.lucd.info/2019/11/17/invoke-vmscriptplus-v3/" target="_blank">Invoke-VMScriptPlus</a> function. The parameters allows us to pass one or more files along with the script, and retrieve one or more files back from the environment where the script runs.</p>



<p>If we use <strong>InFile</strong> and <strong>OutFile</strong> together with containers, there is some <a rel="noreferrer noopener" aria-label="Inception (opens in a new tab)" href="https://en.wikipedia.org/wiki/Inception" target="_blank">Inception</a> going on. The following schematic might make this a bit more visible.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="995" height="455" src="https://www.lucd.info/wp-content/uploads/2019/12/inception.png" alt="" class="wp-image-7055" srcset="https://www.lucd.info/wp-content/uploads/2019/12/inception.png 995w, https://www.lucd.info/wp-content/uploads/2019/12/inception-300x137.png 300w, https://www.lucd.info/wp-content/uploads/2019/12/inception-768x351.png 768w, https://www.lucd.info/wp-content/uploads/2019/12/inception-720x329.png 720w" sizes="auto, (max-width: 995px) 100vw, 995px" /></figure>



<p>As you can see, the <strong>InFile</strong> files are stored in the guest OS of the instance. And then through the Volume parameter on the docker command, passed along into the container.</p>



<p>The same goes for the <strong>OutFile</strong> files but in the reverse sense.</p>



<p>We are going to execute an existing script. Note how to make a <strong>small change</strong> in the path of the resulting file. We have to use the path to the <strong>Scripts</strong> folder, which will be mapped through the <strong>Volume</strong> parameter.</p>



<pre class="lang:ps decode:true ">Get-VMHost |
Select Name, NumCpu, Version |
ConvertTo-Html | Out-File -FilePath \Scripts\report.html

Write-Host "Script completed"
</pre>



<p>And this is the script that will run that script in a container. </p>



<pre class="lang:ps decode:true ">$vmName = 'ubuntubioniccontainer'
$oldScript = '.\Sample-PCLI-Script.ps1'
$tempScript = 'script.ps1'

$script = @'
reset -w
<code>$ProgressPreference = "SilentlyContinue"
if(-not (Get-Module -Name VMware.PowerCLI -ListAvailable)){
    Install-Module -Name VMware.PowerCLI -AllowClobber -Force | Out-Null
}
</code>$WarningPreference = 'SilentlyContinue'
<code>$sConf = @{
    InvalidCertificateAction = 'Ignore'
    ParticipateInCeip = </code>$false
    DisplayDeprecationWarnings = <code>$false
    Scope = 'User'
    Confirm = </code>$false
}
Set-PowerCLIConfiguration @sConf | Out-Null
Connect-VIServer -Server $vcsaName -User $vcsaUser -Password $vcsaPswd | Out-Null

####### My Script ######
$(Get-Content -Path $oldScript -Raw)
########################

Disconnect-VIServer -Server $vcsaName -Confirm:<code>$false
'@

$docker = @'
sudo docker volume create PCLIModules &gt; /dev/null
sudo docker run --rm \
    --tty \
    -v /PCLIModules:/root/.local/share/powershell/Modules \
    -v </code>$(pwd):/Scripts \
    -e TERM=xterm -e LINES=25 -e COLUMNS=135 \
    microsoft/powershell:latest \
    pwsh -F /Scripts/$($tempScript)
'@

$vcsaName = 'vcsa.local.lab'
$credVCSA = Get-VICredentialStoreItem -Host $vcsaName
$vcsaUser = $credVCSA.User
$vcsaPswd = $credVCSA.Password

$credVM = Get-VICredentialStoreItem -Host $vmName
$cred = New-Object System.Management.Automation.PSCredential ($credVM.User, (ConvertTo-SecureString $credVM.Password -AsPlainText -Force))

$tempScript = 'script.ps1'
$ExecutionContext.InvokeCommand.ExpandString($script) | Out-File -LiteralPath $tempScript
$sInvoke = @{
    VM = $vmName
    GuestCredential = $cred
    ScriptType = 'bash'
    ScriptText = $ExecutionContext.InvokeCommand.ExpandString($docker)
    NoIPinCert = $true
    InFile = $tempScript
    OutFile = 'report.html'
}
Invoke-VMScriptPlus @sInvoke

Remove-Item -LiteralPath $tempScript -Confirm:$false

Invoke-Item -Path .\report.html
</pre>



<h4 class="wp-block-heading">Annotations</h4>



<p><strong>Line 2</strong>: The name of our script we want to execute. Note that we had to change the <strong>Path</strong> of the resulting file. This to allow the mapping through the <strong>volume</strong> parameter on the <em>docker run</em> command.</p>



<p><strong>Line 3</strong>: A filename for the script we are going to run in the container. Ultimately this could be replaced by a randomly generated filename.</p>



<p><strong>Line 5-27</strong>: The full script we are sending to the container. It is comprised of the Prefix, our original script and the Suffix. The Prefix and Suffix are the same as we have shown in previous sections. The only difference is that all three parts now come together in one here-string.</p>



<p><strong>Line 23</strong>: We substitute this line with our original script later on with the call to <strong>ExpandString</strong>.</p>



<p><strong>Line 29-38</strong>: The actual bash script, with the docker commands, that we are running inside the Guest OS of the instance.</p>



<p><strong>Line 49</strong>: We expand the $script variable and save the resulting text to a file.</p>



<p><strong>Line 54</strong>: Another call to <strong>ExpandString</strong>. This time to substitute the variables in the <strong>$docker</strong> variable. </p>



<p><strong>Line 56</strong>: The script file we send along to the Guest OS.</p>



<p><strong>Line 57</strong>: The output file we retrieve from the Guest OS.</p>



<p>The script's output looks like this. Notice that it only contains the result from the Write-Host line in our original script.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="719" height="468" src="https://www.lucd.info/wp-content/uploads/2019/12/out5.png" alt="" class="wp-image-7057" srcset="https://www.lucd.info/wp-content/uploads/2019/12/out5.png 719w, https://www.lucd.info/wp-content/uploads/2019/12/out5-300x195.png 300w" sizes="auto, (max-width: 719px) 100vw, 719px" /></figure>



<p>And the result, report.html, is displayed in a web browser through the Invoke-Item cmdlet.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="338" height="203" src="https://www.lucd.info/wp-content/uploads/2019/12/out6.png" alt="" class="wp-image-7058" srcset="https://www.lucd.info/wp-content/uploads/2019/12/out6.png 338w, https://www.lucd.info/wp-content/uploads/2019/12/out6-300x180.png 300w" sizes="auto, (max-width: 338px) 100vw, 338px" /></figure>



<h2 class="wp-block-heading">Image vmware/powerclicore </h2>



<p>Shortly after the new <strong>tdnf</strong> package for <strong>PowerShell</strong> was made available, a new version of the <a href="https://hub.docker.com/r/vmware/powerclicore/" target="_blank" rel="noreferrer noopener" aria-label="vmware/powerclicore (opens in a new tab)">vmware/powerclicore</a> docker image was created.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="595" height="274" src="https://www.lucd.info/wp-content/uploads/2019/12/image.png" alt="" class="wp-image-7076" srcset="https://www.lucd.info/wp-content/uploads/2019/12/image.png 595w, https://www.lucd.info/wp-content/uploads/2019/12/image-300x138.png 300w" sizes="auto, (max-width: 595px) 100vw, 595px" /></figure>



<p>The difference with the <a rel="noreferrer noopener" aria-label="microsoft/powershell (opens in a new tab)" href="https://hub.docker.com/_/microsoft-powershell" target="_blank">microsoft/powershell</a> image is the underlying OS, Photon v3R2 instead of Ubuntu 18.04.</p>



<p>Let's start with a simple script, similar to the one we used earlier.</p>



<pre class="lang:ps decode:true  ">$code = @'
docker run --rm microsoft/powershell:latest pwsh -C 'whoami;Get-Process;pwd'
'@

$credItem = Get-VICredentialStoreItem -Host $vmName
$cred = New-Object System.Management.Automation.PSCredential ($credItem.User, (ConvertTo-SecureString $credItem.Password -AsPlainText -Force))

$sInvoke = @{
    VM = $vmName
    GuestCredential = $cred
    ScriptType = 'bash'
    ScriptText = $code
    NoIPinCert = $true
    GuestOSType = 'linux'
}
Invoke-VMScriptPlus @sInvoke | select -ExpandProperty ScriptOutput
</pre>



<p>With the <strong>microsoft/powershell image</strong> this produces the following. We see the result of all three commands.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="662" height="254" src="https://www.lucd.info/wp-content/uploads/2019/12/cmp1.png" alt="" class="wp-image-7080" srcset="https://www.lucd.info/wp-content/uploads/2019/12/cmp1.png 662w, https://www.lucd.info/wp-content/uploads/2019/12/cmp1-300x115.png 300w" sizes="auto, (max-width: 662px) 100vw, 662px" /></figure>



<p>On the <strong>vmware/powerclicore</strong> image, the result is a bit different. The <em>whoami</em> output is there, but the output from the other two commands is missing. </p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="530" height="122" src="https://www.lucd.info/wp-content/uploads/2019/12/cmp2-2.png" alt="" class="wp-image-7087" srcset="https://www.lucd.info/wp-content/uploads/2019/12/cmp2-2.png 530w, https://www.lucd.info/wp-content/uploads/2019/12/cmp2-2-300x69.png 300w" sizes="auto, (max-width: 530px) 100vw, 530px" /></figure>



<p>As it turns out, there is an issue when passing commands to pwsh via the Command parameter. When using the File parameter everything seems to work well.</p>



<p>One difference to note, compared with the micorosft/powershell image, the vmware/powerclicore:latest image, and the Photon OS in that image, have minimal terminal types present. As a result, you will need to set the TERM environment variable to <strong>linux</strong> instead of <strong>xterm</strong>.</p>



<p>A typical call would look something like this.</p>



<pre class="lang:sh decode:true  ">docker volume create PCLIModules &gt; /dev/null
docker run --rm \
    --tty \
    -v /PCLIModules:/root/.local/share/powershell/Modules \
    -v `$(pwd):/Scripts \
    -e TERM=linux -e LINES=25 -e COLUMNS=135 \
    vmware/powerclicore:latest \
    pwsh -F /Scripts/script.ps1</pre>



<h2 class="wp-block-heading">Image  mcr.microsoft.com/powershell:preview </h2>



<p>Note that there is also an image for the latest PS v7 Preview available. If you want to test/develop your scripts in this PS v7 Preview, this is a simple and easy method to do it.</p>



<p>All previous methods discussed in this post work against this Preview.</p>



<p>Enjoy!</p>



<p>p</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.lucd.info/2019/12/11/cloud-init-part-5-running-containers/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
