Oracle - Add Database User To Role

Octopus.Script exported 2020-08-21 by twerthi belongs to ‘Oracle’ category.

Adds database user to a role

Parameters

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

Server name

oracleServerName =

Name of the Oracle server.

Port

oracleServerPort = 1521

Port that the Oracle server listens on.

Service Name

oracleServiceName =

Service name for Oracle database.

Login name

oracleLoginWithAddRoleRights =

Login name of a user that can add roles to other users.

Login password

oracleLoginPasswordWithAddRoleRights =

Password for the login account.

User name

oracleUsername =

Name of the user to add the role to.

Role name

oracleRoleName =

Name of the role to add to the user.

Script body

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

# Define functions
function Get-ModuleInstalled
{
    # Define parameters
    param(
        $PowerShellModuleName
    )

    # Check to see if the module is installed
    if ($null -ne (Get-Module -ListAvailable -Name $PowerShellModuleName))
    {
        # It is installed
        return $true
    }
    else
    {
        # Module not installed
        return $false
    }
}

function Install-PowerShellModule
{
    # Define parameters
    param(
        $PowerShellModuleName,
        $LocalModulesPath
    )

	# Check to see if the package provider has been installed
    if ((Get-NugetPackageProviderNotInstalled) -ne $false)
    {
    	# Display that we need the nuget package provider
        Write-Host "Nuget package provider not found, installing ..."
        
        # Install Nuget package provider
        Install-PackageProvider -Name Nuget -Force
    }

	# Save the module in the temporary location
    Save-Module -Name $PowerShellModuleName -Path $LocalModulesPath -Force
}

function Get-NugetPackageProviderNotInstalled
{
	# See if the nuget package provider has been installed
    return ($null -eq (Get-PackageProvider -ListAvailable -Name Nuget -ErrorAction SilentlyContinue))
}

function Get-UserInRole
{
	# Define parameters
    param (
    $Username,
    $RoleName)
    
	# Execute query
    $userRole = Invoke-SqlQuery "SELECT * FROM DBA_ROLE_PRIVS WHERE GRANTEE = '$Username' AND GRANTED_ROLE = '$RoleName'"

    # Check to see if anything was returned
    if ($userRole.ItemArray.Count -gt 0)
    {
        # Found
        return $true
    }
    

    # Not found
    return $false
}

# Define PowerShell Modules path
$LocalModules = (New-Item "$PSScriptRoot\Modules" -ItemType Directory -Force).FullName
$env:PSModulePath = "$LocalModules$([System.IO.Path]::PathSeparator)$env:PSModulePath"
$PowerShellModuleName = "SimplySql"

# Set secure protocols
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls11 -bor [System.Net.SecurityProtocolType]::Tls12

# Check to see if SimplySql module is installed
if ((Get-ModuleInstalled -PowerShellModuleName $PowerShellModuleName) -ne $true)
{
    # Tell user what we're doing
    Write-Output "PowerShell module $PowerShellModuleName is not installed, downloading temporary copy ..."

    # Install temporary copy
    Install-PowerShellModule -PowerShellModuleName $PowerShellModuleName -LocalModulesPath $LocalModules
}

# Display
Write-Output "Importing module $PowerShellModuleName ..."

# Check to see if it was downloaded
if ((Test-Path -Path "$LocalModules\$PowerShellModuleName") -eq $true)
{
	# Use specific location
    $PowerShellModuleName = "$LocalModules\$PowerShellModuleName"
}

# Import the module
Import-Module -Name $PowerShellModuleName

# Create credential object for the connection
$SecurePassword = ConvertTo-SecureString $oracleLoginPasswordWithAddRoleRights -AsPlainText -Force
$ServerCredential = New-Object System.Management.Automation.PSCredential ($oracleLoginWithAddRoleRights, $SecurePassword)

try
{
	# Connect to MySQL
    Open-OracleConnection -Datasource $oracleServerName -Credential $ServerCredential -Port $oracleServerPort -ServiceName $oracleServiceName

    # See if database exists
    $userInRole = Get-UserInRole -Username $oracleUsername -RoleName $oracleRoleName

    if ($userInRole -eq $false)
    {
        # Create database
        Write-Output "Adding user $oracleUsername to role $oracleRoleName ..."
        $executionResults = Invoke-SqlUpdate "GRANT `"$oracleRoleName`" TO `"$oracleUsername`""

        # See if it was created
        $userInRole = Get-UserInRole -Username $oracleUsername -RoleName $oracleRoleName
            
        # Check array
        if ($userInRole -eq $true)
        {
            # Success
            Write-Output "$oracleUserName added to $oracleRoleName successfully!"
        }
        else
        {
            # Failed
            Write-Error "Failure adding $oracleUserName to $oracleRoleName!"
        }
    }
    else
    {
    	# Display message
        Write-Output "User $oracleUsername is already in role $oracleRoleName"
    }
}
finally
{
    Close-SqlConnection
}



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": "6a0db144-3ad5-46bb-bd7d-02b22b98a559",
  "Name": "Oracle - Add Database User To Role",
  "Description": "Adds database user to a role",
  "Version": 2,
  "ExportedAt": "2020-08-21T21:54:08.753Z",
  "ActionType": "Octopus.Script",
  "Author": "twerthi",
  "Packages": [],
  "Parameters": [
    {
      "Id": "66790019-ca40-41cc-8849-5995557e34c1",
      "Name": "oracleServerName",
      "Label": "Server name",
      "HelpText": "Name of the Oracle server.",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "d29f262e-74d2-4c7b-acb3-67b642b614c4",
      "Name": "oracleServerPort",
      "Label": "Port",
      "HelpText": "Port that the Oracle server listens on.",
      "DefaultValue": "1521",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "330f737b-dc2b-4ceb-9d27-168c1b5f6e18",
      "Name": "oracleServiceName",
      "Label": "Service Name",
      "HelpText": "Service name for Oracle database.",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "0531e03b-c152-46e4-ab2d-7cb8093aa641",
      "Name": "oracleLoginWithAddRoleRights",
      "Label": "Login name",
      "HelpText": "Login name of a user that can add roles to other users.",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "5bddbafe-0ca0-4037-9dd1-d522abc5838e",
      "Name": "oracleLoginPasswordWithAddRoleRights",
      "Label": "Login password",
      "HelpText": "Password for the login account.",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "Sensitive"
      }
    },
    {
      "Id": "2c6ee772-96f6-4803-b6a1-5d57a58b28f0",
      "Name": "oracleUsername",
      "Label": "User name",
      "HelpText": "Name of the user to add the role to.",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "7f806b37-e0d5-4560-873e-de6c73f80161",
      "Name": "oracleRoleName",
      "Label": "Role name",
      "HelpText": "Name of the role to add to the user.",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    }
  ],
  "Properties": {
    "Octopus.Action.Script.ScriptSource": "Inline",
    "Octopus.Action.Script.Syntax": "PowerShell",
    "Octopus.Action.Script.ScriptBody": "# Define functions\nfunction Get-ModuleInstalled\n{\n    # Define parameters\n    param(\n        $PowerShellModuleName\n    )\n\n    # Check to see if the module is installed\n    if ($null -ne (Get-Module -ListAvailable -Name $PowerShellModuleName))\n    {\n        # It is installed\n        return $true\n    }\n    else\n    {\n        # Module not installed\n        return $false\n    }\n}\n\nfunction Install-PowerShellModule\n{\n    # Define parameters\n    param(\n        $PowerShellModuleName,\n        $LocalModulesPath\n    )\n\n\t# Check to see if the package provider has been installed\n    if ((Get-NugetPackageProviderNotInstalled) -ne $false)\n    {\n    \t# Display that we need the nuget package provider\n        Write-Host \"Nuget package provider not found, installing ...\"\n        \n        # Install Nuget package provider\n        Install-PackageProvider -Name Nuget -Force\n    }\n\n\t# Save the module in the temporary location\n    Save-Module -Name $PowerShellModuleName -Path $LocalModulesPath -Force\n}\n\nfunction Get-NugetPackageProviderNotInstalled\n{\n\t# See if the nuget package provider has been installed\n    return ($null -eq (Get-PackageProvider -ListAvailable -Name Nuget -ErrorAction SilentlyContinue))\n}\n\nfunction Get-UserInRole\n{\n\t# Define parameters\n    param (\n    $Username,\n    $RoleName)\n    \n\t# Execute query\n    $userRole = Invoke-SqlQuery \"SELECT * FROM DBA_ROLE_PRIVS WHERE GRANTEE = '$Username' AND GRANTED_ROLE = '$RoleName'\"\n\n    # Check to see if anything was returned\n    if ($userRole.ItemArray.Count -gt 0)\n    {\n        # Found\n        return $true\n    }\n    \n\n    # Not found\n    return $false\n}\n\n# Define PowerShell Modules path\n$LocalModules = (New-Item \"$PSScriptRoot\\Modules\" -ItemType Directory -Force).FullName\n$env:PSModulePath = \"$LocalModules$([System.IO.Path]::PathSeparator)$env:PSModulePath\"\n$PowerShellModuleName = \"SimplySql\"\n\n# Set secure protocols\n[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls11 -bor [System.Net.SecurityProtocolType]::Tls12\n\n# Check to see if SimplySql module is installed\nif ((Get-ModuleInstalled -PowerShellModuleName $PowerShellModuleName) -ne $true)\n{\n    # Tell user what we're doing\n    Write-Output \"PowerShell module $PowerShellModuleName is not installed, downloading temporary copy ...\"\n\n    # Install temporary copy\n    Install-PowerShellModule -PowerShellModuleName $PowerShellModuleName -LocalModulesPath $LocalModules\n}\n\n# Display\nWrite-Output \"Importing module $PowerShellModuleName ...\"\n\n# Check to see if it was downloaded\nif ((Test-Path -Path \"$LocalModules\\$PowerShellModuleName\") -eq $true)\n{\n\t# Use specific location\n    $PowerShellModuleName = \"$LocalModules\\$PowerShellModuleName\"\n}\n\n# Import the module\nImport-Module -Name $PowerShellModuleName\n\n# Create credential object for the connection\n$SecurePassword = ConvertTo-SecureString $oracleLoginPasswordWithAddRoleRights -AsPlainText -Force\n$ServerCredential = New-Object System.Management.Automation.PSCredential ($oracleLoginWithAddRoleRights, $SecurePassword)\n\ntry\n{\n\t# Connect to MySQL\n    Open-OracleConnection -Datasource $oracleServerName -Credential $ServerCredential -Port $oracleServerPort -ServiceName $oracleServiceName\n\n    # See if database exists\n    $userInRole = Get-UserInRole -Username $oracleUsername -RoleName $oracleRoleName\n\n    if ($userInRole -eq $false)\n    {\n        # Create database\n        Write-Output \"Adding user $oracleUsername to role $oracleRoleName ...\"\n        $executionResults = Invoke-SqlUpdate \"GRANT `\"$oracleRoleName`\" TO `\"$oracleUsername`\"\"\n\n        # See if it was created\n        $userInRole = Get-UserInRole -Username $oracleUsername -RoleName $oracleRoleName\n            \n        # Check array\n        if ($userInRole -eq $true)\n        {\n            # Success\n            Write-Output \"$oracleUserName added to $oracleRoleName successfully!\"\n        }\n        else\n        {\n            # Failed\n            Write-Error \"Failure adding $oracleUserName to $oracleRoleName!\"\n        }\n    }\n    else\n    {\n    \t# Display message\n        Write-Output \"User $oracleUsername is already in role $oracleRoleName\"\n    }\n}\nfinally\n{\n    Close-SqlConnection\n}\n\n\n",
    "Octopus.Action.EnabledFeatures": ""
  },
  "Category": "Oracle",
  "HistoryUrl": "https://github.com/OctopusDeploy/Library/commits/master/step-templates//opt/buildagent/work/75443764cd38076d/step-templates/oracle-add-user-to-role.json",
  "Website": "/step-templates/6a0db144-3ad5-46bb-bd7d-02b22b98a559",
  "Logo": "iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjEuMWMqnEsAAAX6SURBVHhe7df5jxRVEAdw/gwEhOVYLjkElEMEFBYUMIJHJIpR0Qge6y1RFAkgXlFRCKsoERSVYFAg4Kq/qCiiCGhgEQEjaqJiOLanZ2dm5+iZKauqZ9md6YKdEIbqH4rkk2W/8/q9N6/6ve7tAAAmRMTQ6BFDo0cMjR4xNHrE0OgRQ6NHDI0eMTR6xNDoEUOjRwyNHjE0esTQ6BFDo0cMjR4xNHrE0OgRQ6NHDI0eMTR6xNDoEUOjRwyNHjE0esTQ6BFDo0cMjR4xNHrE0OgRQ6NHDI0eMTR6AoFbMxnM+VO6/kW/kMauvcCcP8k17+GyW0FCwwoSMlaQkLGChIwVJGSsICFjBQkZK0jIWEFCxgoSMpUtSJce/s8efYO6o07di9t37yO3JdS+c6E/yYU9wek3mH+KnxOaT9XpxuiHbarB6dnfbyNdX6pTlT8vqT/KaU59Bp55TiUqVhBanObldZA7fhwgmw1Kp8Fr2A+x2ff7E8bipDZ8Irct8H45ANHJ04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