Skip to content

Commit

Permalink
feat: cleanup and .env loading
Browse files Browse the repository at this point in the history
  • Loading branch information
EntraptaJ committed Feb 13, 2020
1 parent cb603b6 commit 794266c
Show file tree
Hide file tree
Showing 13 changed files with 240 additions and 48 deletions.
14 changes: 14 additions & 0 deletions .devcontainer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "vSphere Networks",
"dockerFile": "Dockerfile.dev",
"shutdownAction": "none",
"settings": {
// This dev container does include /bin/bash if you prefer to use it instead of ash.
"terminal.integrated.shell.linux": "/bin/sh"
},
"remoteEnv": {
"SHELL": "/bin/sh"
},
"extensions": ["esbenp.prettier-vscode"],
"remoteUser": "node"
}
22 changes: 11 additions & 11 deletions .github/workflows/workflow.yml
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
name: Publish Docker
on:
on:
push:
branches:
branches:
- master
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- name: Publish to Registry
uses: elgohr/Publish-Docker-Github-Action@master
with:
dockerfile: Dockerfile
name: docker.pkg.github.com/kristianfjones/vcenter-networks/vcenter-network
username: ${{ secrets.DOCKER_GITHUB_USERNAME }}
password: ${{ secrets.DOCKER_GITHUB_PASSWORD }}
registry: docker.pkg.github.com
- uses: actions/checkout@master
- name: Publish to Registry
uses: elgohr/Publish-Docker-Github-Action@master
with:
dockerfile: Dockerfile
name: docker.pkg.github.com/kristianfjones/vsphere-networks/vcenter-network
username: ${{ secrets.DOCKER_GITHUB_USERNAME }}
password: ${{ secrets.DOCKER_GITHUB_PASSWORD }}
registry: docker.pkg.github.com
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
.LSOverride

# Icon must end with two \r
Icon
Icon

# Thumbnails
._*
Expand Down Expand Up @@ -139,3 +139,5 @@ public/

# Custom rules (everything added below won't be overriden by 'Generate .gitignore File' if you use 'Update' option)

local
.env*
6 changes: 6 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"singleQuote": true,
"trailingComma": "all",
"arrowParens": "always",
"semi": true
}
103 changes: 103 additions & 0 deletions Dockerfile.dev
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
FROM alpine:3.11 AS installer-env

# Define Args for the needed to add the package
ARG PS_VERSION=7.0.0-preview.1
ARG PS_PACKAGE=powershell-${PS_VERSION}-linux-alpine-x64.tar.gz
ARG PS_PACKAGE_URL=https://github.com/PowerShell/PowerShell/releases/download/v${PS_VERSION}/${PS_PACKAGE}
ARG PS_INSTALL_VERSION=7-preview

# Download the Linux tar.gz and save it
ADD ${PS_PACKAGE_URL} /tmp/linux.tar.gz

# define the folder we will be installing PowerShell to
ENV PS_INSTALL_FOLDER=/opt/microsoft/powershell/$PS_INSTALL_VERSION

# Create the install folder
RUN mkdir -p ${PS_INSTALL_FOLDER}

# Unzip the Linux tar.gz
RUN tar zxf /tmp/linux.tar.gz -C ${PS_INSTALL_FOLDER} -v




FROM mhart/alpine-node:13
# This Dockerfile adds a non-root user with sudo access. Use the "remoteUser"
# property in devcontainer.json to use it. On Linux, the container user's GID/UIDs
# will be updated to match your local UID/GID (when using the dockerFile property).
# See https://aka.ms/vscode-remote/containers/non-root-user for details.
ARG USERNAME=node
ARG USER_UID=1000
ARG USER_GID=$USER_UID

# Install Shadow non busybox for better user management & support
RUN apk add --no-cache shadow

# Create a non-root user to use if preferred - see https://aka.ms/vscode-remote/containers/non-root-user.
RUN groupadd -g $USER_GID $USERNAME \
&& useradd -s /bin/sh -K MAIL_DIR=/dev/null -u $USER_UID -g $USER_GID -m $USERNAME

COPY --from=installer-env ["/opt/microsoft/powershell", "/opt/microsoft/powershell"]

# Define Args and Env needed to create links
ARG PS_INSTALL_VERSION=7-preview
ENV PS_INSTALL_FOLDER=/opt/microsoft/powershell/$PS_INSTALL_VERSION \
\
# Define ENVs for Localization/Globalization
DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false \
LC_ALL=en_US.UTF-8 \
LANG=en_US.UTF-8 \
# set a fixed location for the Module analysis cache
PSModuleAnalysisCachePath=/var/cache/microsoft/powershell/PSModuleAnalysisCache/ModuleAnalysisCache \
POWERSHELL_DISTRIBUTION_CHANNEL=PSDocker-Alpine-${fromTag}

# Install dotnet dependencies and ca-certificates
RUN apk add --no-cache \
ca-certificates \
less \
\
# PSReadline/console dependencies
ncurses-terminfo-base \
\
# .NET Core dependencies
krb5-libs \
libgcc \
libintl \
libssl1.1 \
libstdc++ \
tzdata \
userspace-rcu \
zlib \
icu-libs \
&& apk -X https://dl-cdn.alpinelinux.org/alpine/edge/main add --no-cache \
lttng-ust \
\
# Create the pwsh symbolic link that points to powershell
&& ln -s ${PS_INSTALL_FOLDER}/pwsh /usr/bin/pwsh \
\
# Create the pwsh-preview symbolic link that points to powershell
&& ln -s ${PS_INSTALL_FOLDER}/pwsh /usr/bin/pwsh-preview \
# Give all user execute permissions and remove write permissions for others
&& chmod a+x,o-w ${PS_INSTALL_FOLDER}/pwsh \
# intialize powershell module cache
&& pwsh \
-NoLogo \
-NoProfile \
-Command " \
\$ErrorActionPreference = 'Stop' ; \
\$ProgressPreference = 'SilentlyContinue' ; \
while(!(Test-Path -Path \$env:PSModuleAnalysisCachePath)) { \
Write-Host "'Waiting for $env:PSModuleAnalysisCachePath'" ; \
Start-Sleep -Seconds 6 ; \
}" \
&& pwsh -Command Install-Module -Name VMware.PowerCLI -Force

# Copy the Watchman Runtime
# COPY --from=watchmanBuild /usr/local/var/run/watchman /usr/local/var/run/watchman

# Add Sudo to allow occasional usage of root. I wish I could remove this but I can't seem to get the node_modules volume working correctly.
RUN apk add --no-cache sudo \
&& echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME \
&& chmod 0440 /etc/sudoers.d/$USERNAME

CMD [ "tail", "-f", "/dev/null" ]
21 changes: 12 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
# Create Networks Scripts

# vSphere Networks

## Usage

** Environment Variables **

| Variable | Description |
| :--- | --- |
| `URL` | vCenter URL |
| `USER` | vCenter Username |
| `PASS` | vCenter Password |
| Variable | Description |
| :------- | ---------------- |
| `URL` | vCenter URL |
| `USER` | vCenter Username |
| `PASS` | vCenter Password |

## Networks.json

Networks.json is a json file containing the networks to be created on the host
For an example see `networks.json`

## Running

With your `networks.json` file in the directory run the following command with the correct credentials

```bash
docker run -it -e URL=vcsa.example.com -e USER[email protected] -e PASS=password -v $PWD/networks.json:/app/networks.json docker.pkg.github.com/kristianfjones/vcenter-networks/vcenter-network:latest
```
docker run -it -e URL=vcsa.example.com -e USERNAME[email protected] -e PASSWORD=password -v $PWD/networks.json:/app/networks.json docker.pkg.github.com/kristianfjones/vsphere-networks/vcenter-network:latest
```
14 changes: 9 additions & 5 deletions networks.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
{
"host": "vmhost1.srv.example.com",
"vSwitch": "vSwitch1",
"host": "192.168.10.11",
"vSwitch": "Frontend",
"networks": [
{
"name": "HelloWorld",
"vlan": 500
"name": "Server Public 1",
"vlan": 10
},
{
"name": "Server Public 2",
"vlan": 20
}
]
}
}
15 changes: 15 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@
"author": "",
"license": "ISC",
"devDependencies": {
"@types/dotenv": "^6.1.1",
"@types/fs-extra": "^8.0.0",
"@types/node": "^12.7.5",
"@types/node-powershell": "^3.1.0",
"dotenv": "^8.1.0",
"ts-node": "^8.4.1",
"typescript": "^3.6.3"
},
Expand Down
38 changes: 29 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,42 @@ import Shell from 'node-powershell';
import { run } from './lib/run';
import { loadFile, createNetworks } from './lib/networks';

if (process.env.NODE_ENV !== 'production') {
const dotenv = require('dotenv') as typeof import('dotenv');
dotenv.config();
}

const URL = process.env['URL'];
const username = process.env['USER']
const password = process.env['PASS'];
const username = process.env['USERNAME'];
const password = process.env['PASSWORD'];

async function start(): Promise<void> {
// Initialize
const ps = new Shell({
executionPolicy: 'Bypass',
noProfile: true
noProfile: true,
});

await run(ps, 'Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false')
await run(ps, `Connect-VIServer -Server ${URL} -Protocol https -Username ${username} -Password ${password}`);
const file = await loadFile('networks.json')
await createNetworks(ps, file)
await ps.dispose()
// Allow invalid or self signed certificates
await run(
ps,
'Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false',
);

// Connect to the vSphere API
await run(
ps,
`Connect-VIServer -Server ${URL} -Protocol https -Username ${username} -Password ${password}`,
);

// Load JSON Networks.json file
const file = await loadFile('networks.json');

// Create all networks
await createNetworks(ps, file);

// Dispose of created powershell session
await ps.dispose();
}

start()
start();
32 changes: 28 additions & 4 deletions src/lib/networks.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,44 @@
// src/lib/networks.ts
import Shell from 'node-powershell';
import { readJSON } from 'fs-extra';
import { File, Network } from '../types';
import { File } from '../types';
import { run } from './run';

export async function loadFile(path: string): Promise<File> {
return readJSON(path);
}

async function vSwitchExists(
ps: Shell,
host: string,
name: string,
): Promise<boolean> {
// Get all vSwitches with the requested name
const result = await run(
ps,
`Get-VirtualSwitch -VMhost "${host}" -Name "${name}" -ErrorAction Ignore`,
);

// Return if the length of networks in more then zero.
return result.length > 0;
}

export async function createNetworks(
ps: Shell,
{ networks, host, vSwitch }: File
{ networks, host, vSwitch }: File,
): Promise<void> {
for (const { name, vlan } of networks)
const exists = await vSwitchExists(ps, host, vSwitch);

// If vSwitch doesn't already exist then we create it
if (exists === false) {
await run(ps, `New-VirtualSwitch -VMhost "${host}" -Name "${vSwitch}"`);
}

for (const { name, vlan } of networks) {
// Get the vSwitch and create a port group
await run(
ps,
`Get-VirtualSwitch -VMhost ${host} -Name ${vSwitch} | New-VirtualPortGroup -Name ${name} -VlanId ${vlan}`
`Get-VirtualSwitch -VMhost "${host}" -Name "${vSwitch}" | New-VirtualPortGroup -Name "${name}" -VlanId ${vlan}`,
);
}
}
6 changes: 3 additions & 3 deletions src/lib/run.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import Shell from 'node-powershell';
import Shell from "node-powershell";

/**
* Add and exec a PowerShell command
* @param ps node-PowerShell Instance
* @param command Powershell Command to exec
*/
export const run = async (ps: Shell, command: string) => {
export async function run(ps: Shell, command: string) {
// Add command to PowerShell Que
await ps.addCommand(command);

// Return the promise of invoking the command.
return ps.invoke();
};
}
Loading

0 comments on commit 794266c

Please sign in to comment.