File System - Add entry to hosts file

Octopus.Script exported 2018-07-16 by anatolie-darii belongs to ‘File System’ category.

Adds an entry to etc/hosts file with the specified host name and optional ip address

Parameters

When steps based on the template are included in a project’s deployment process, the parameters below can be set.

Host name

AD_AddHostsEntry_HostName

The host name

IP address

AD_AddHostsEntry_IpAddress = 127.0.0.1

The optional IP address

Nr of attempts

AD_AddHostsEntry_Attempts = 5

Optional number of attempts before failing

Script body

Steps based on this template will execute the following PowerShell script.

# Running outside octopus
Param(
    [string] $AD_AddHostsEntry_HostName,
    [string] $AD_AddHostsEntry_IpAddress = "127.0.0.1",
    [Int16] $AD_AddHostsEntry_Attempts = 5,
    [switch] $WhatIf
)

$ErrorActionPreference = "Stop"

function Get-Param($Name, [switch]$Required, $Default) {
    $result = $null

    if ($null -ne $OctopusParameters) {
        $result = $OctopusParameters[$Name]
    }

    if ($null -eq $result) {
        $variable = Get-Variable $Name -EA SilentlyContinue
        if ($null -ne $variable) {
            $result = $variable.Value
        }
    }

    if ($null -eq $result) {
        if ($Required) {
            throw "Missing parameter value $Name"
        }
        else {
            $result = $Default
        }
    }

    return $result
}

function Execute(
    [Parameter(Mandatory = $true)][string] $HostName,
    [Parameter(Mandatory = $false)][string] $IpAddress = "127.0.0.1",
    [Parameter(Mandatory = $false)][Int16] $Attempts = 5
) {
    $attemptCount = 0
    $operationIncomplete = $true
    $maxFailures = $Attempts
    $sleepBetweenFailures = 1

    $hostsFile = "$($env:windir)\system32\Drivers\etc\hosts"
    $entry = "$IpAddress $HostName"
    $regexMatch = "^\s*$IpAddress\s+$HostName"
    while ($operationIncomplete -and $attemptCount -lt $maxFailures) {
        $attemptCount = ($attemptCount + 1)
        if ($attemptCount -ge 2) {
            Write-Output "Waiting for $sleepBetweenFailures seconds before retrying..."
            Start-Sleep -s $sleepBetweenFailures
            Write-Output "Retrying..."
            $sleepBetweenFailures = ($sleepBetweenFailures * 2)
        }
        try {
            $matchingEntries = @(Get-Content $hostsFile) -match ($regexMatch)
            if (-Not $matchingEntries) {
                Write-Output "Entry '$entry' doesn't exist - ADDING..."
                if (-Not ($WhatIf)) {
                    $formattedEntry = [environment]::newline + $entry
                    [System.IO.File]::AppendAllText($hostsFile, $formattedEntry)
                }
                Write-Output "Entry '$entry' - ADDED"
            }
            else {
                Write-Output "Entry '$entry' already exists - SKIPPING"
            }
            $operationIncomplete = $false
        }
        catch [System.Exception] {
            if ($attemptCount -lt ($maxFailures)) {
                Write-Host ("Attempt $attemptCount of $maxFailures failed: " + $_.Exception.Message)
            }
            else {
                throw
            }
        }
    }
}
& Execute `
(Get-Param 'AD_AddHostsEntry_HostName' -Required)`
(Get-Param 'AD_AddHostsEntry_IpAddress')`
(Get-Param 'AD_AddHostsEntry_Attempts')

Provided under the Apache License version 2.0.

Report an issue

To use this template in Octopus Deploy, copy the JSON below and paste it into the Library → Step templates → Import dialog.

{
  "Id": "0ad0ad00-adad-adad-adad-000000000001",
  "Name": "File System - Add entry to hosts file",
  "Description": "Adds an entry to etc/hosts file with the specified host name and optional ip address",
  "Version": 1,
  "ExportedAt": "2018-07-16T12:37:14.428Z",
  "ActionType": "Octopus.Script",
  "Author": "anatolie-darii",
  "Parameters": [
    {
      "Name": "AD_AddHostsEntry_HostName",
      "Label": "Host name",
      "HelpText": "The host name",
      "DefaultValue": null,
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Name": "AD_AddHostsEntry_IpAddress",
      "Label": "IP address",
      "HelpText": "The optional IP address",
      "DefaultValue": "127.0.0.1",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Name": "AD_AddHostsEntry_Attempts",
      "Label": "Nr of attempts",
      "HelpText": "Optional number of attempts before failing",
      "DefaultValue": "5",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    }
  ],
  "Properties": {
    "Octopus.Action.Script.ScriptSource": "Inline",
    "Octopus.Action.Script.Syntax": "PowerShell",
    "Octopus.Action.Script.ScriptBody": "# Running outside octopus\nParam(\n    [string] $AD_AddHostsEntry_HostName,\n    [string] $AD_AddHostsEntry_IpAddress = \"127.0.0.1\",\n    [Int16] $AD_AddHostsEntry_Attempts = 5,\n    [switch] $WhatIf\n)\n\n$ErrorActionPreference = \"Stop\"\n\nfunction Get-Param($Name, [switch]$Required, $Default) {\n    $result = $null\n\n    if ($null -ne $OctopusParameters) {\n        $result = $OctopusParameters[$Name]\n    }\n\n    if ($null -eq $result) {\n        $variable = Get-Variable $Name -EA SilentlyContinue\n        if ($null -ne $variable) {\n            $result = $variable.Value\n        }\n    }\n\n    if ($null -eq $result) {\n        if ($Required) {\n            throw \"Missing parameter value $Name\"\n        }\n        else {\n            $result = $Default\n        }\n    }\n\n    return $result\n}\n\nfunction Execute(\n    [Parameter(Mandatory = $true)][string] $HostName,\n    [Parameter(Mandatory = $false)][string] $IpAddress = \"127.0.0.1\",\n    [Parameter(Mandatory = $false)][Int16] $Attempts = 5\n) {\n    $attemptCount = 0\n    $operationIncomplete = $true\n    $maxFailures = $Attempts\n    $sleepBetweenFailures = 1\n\n    $hostsFile = \"$($env:windir)\\system32\\Drivers\\etc\\hosts\"\n    $entry = \"$IpAddress $HostName\"\n    $regexMatch = \"^\\s*$IpAddress\\s+$HostName\"\n    while ($operationIncomplete -and $attemptCount -lt $maxFailures) {\n        $attemptCount = ($attemptCount + 1)\n        if ($attemptCount -ge 2) {\n            Write-Output \"Waiting for $sleepBetweenFailures seconds before retrying...\"\n            Start-Sleep -s $sleepBetweenFailures\n            Write-Output \"Retrying...\"\n            $sleepBetweenFailures = ($sleepBetweenFailures * 2)\n        }\n        try {\n            $matchingEntries = @(Get-Content $hostsFile) -match ($regexMatch)\n            if (-Not $matchingEntries) {\n                Write-Output \"Entry '$entry' doesn't exist - ADDING...\"\n                if (-Not ($WhatIf)) {\n                    $formattedEntry = [environment]::newline + $entry\n                    [System.IO.File]::AppendAllText($hostsFile, $formattedEntry)\n                }\n                Write-Output \"Entry '$entry' - ADDED\"\n            }\n            else {\n                Write-Output \"Entry '$entry' already exists - SKIPPING\"\n            }\n            $operationIncomplete = $false\n        }\n        catch [System.Exception] {\n            if ($attemptCount -lt ($maxFailures)) {\n                Write-Host (\"Attempt $attemptCount of $maxFailures failed: \" + $_.Exception.Message)\n            }\n            else {\n                throw\n            }\n        }\n    }\n}\n& Execute `\n(Get-Param 'AD_AddHostsEntry_HostName' -Required)`\n(Get-Param 'AD_AddHostsEntry_IpAddress')`\n(Get-Param 'AD_AddHostsEntry_Attempts')\n"
  },
  "Category": "File System",
  "HistoryUrl": "https://github.com/OctopusDeploy/Library/commits/master/step-templates//opt/buildagent/work/75443764cd38076d/step-templates/file-system-add-hosts-entry.json",
  "Website": "/step-templates/0ad0ad00-adad-adad-adad-000000000001",
  "Logo": "iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAMAAACahl6sAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAKhQTFRF/////78A/6oAVVVV/++//+q/gICA1dXV/79A/9R///ff/8MQ/9dg/8cg//vv/68A/+ef//PP//rv/7Ug/68Q/+Sv/8sw/9tw/9NQ/89w/+uv/+OP/8pg/89A/8VQ/9+f/9+A/9qP/+/P/99//7cA/7IA/7wA/6sA/+/A39/f/64A2tjX//Tfn5+f/7MA/7sA/74A/60A/9Zw/7gA/74Q/7oA/7UA/7EAi6g4fwAAAuRJREFUeNrs21tT2mAUheEvaaCQQCSczyi29WzP7f//Z6UdZBIIM44us9hf13vbC+eRbLo3qnNKKaWUUkoppZRSSimllFJKKaWUwlVrLhsvbrLqnoai2+yFr2x+fwKOwasZm/oXdEczxDQnOyYhqgn3uQpxDZhz3gdCesQ3r3mIjDfwXagj7NEgKywkXLMgSzCE9mz1wBDaOzDYETYEEUSQ/wPSaz6rQa174pDnt1x5Atm8emtPIGG48gUClJAh/XtPILi36+L3Zz6oVdBF4w32/sIbYmWH6qAPX5fzjio/14Q/W7nnqtIPDnYfFfThkGpPovXu68IhNdKSVyXkoQ7qgQ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