Skip to content

Instantly share code, notes, and snippets.

@smitmartijn
Created November 8, 2021 12:00
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save smitmartijn/bab19fd056baf57be00c5a0d6585c052 to your computer and use it in GitHub Desktop.
vRealize Automation Action that reconfigures server after deployment
#
# This script can be used as an action inside vRealize Automation to handle
# logging into deployed servers after deployment.
#
# It's provided as-is. If you'd like to use it, there are multiple changes needed.
# I.e. vraUrl to point to your own vRA. The username that's used to SSH. The way it decides
# which servers to log into.
#
# Martijn Smit <martijn@lostdomain.org>
# https://lostdomain.org
#
import requests
import os
import json
import urllib3
import paramiko
#from pprint import pprint
urllib3.disable_warnings()
def vra_get_token(url):
api_url = '{0}csp/gateway/am/api/login?access_token'.format(url)
headers = {'Content-Type': 'application/json'}
data = {
"username": "your-vra-service-account",
"password": "your-password",
"domain": "lab.local"
}
response = requests.post(api_url, headers=headers,
data=json.dumps(data), verify=False)
if response.status_code == 200:
json_data = json.loads(response.content.decode('utf-8'))
key = json_data['refresh_token']
return key
else:
print(response.status_code)
return None
def vra_get_bearer_token(vraUrl, refreshToken):
# Generate Bearer Token
print('Generating Bearer Token...')
body = {
"refreshToken": refreshToken
}
bearer = ""
bearer_url = vraUrl + 'iaas/api/login'
response_bearerToken = requests.post(bearer_url, data=json.dumps(body), verify=False)
if response_bearerToken.status_code == 200:
vraBearerToken = response_bearerToken.json()['token']
bearer = "Bearer "
bearer = bearer + vraBearerToken
return bearer
else:
print('[?] Unexpected Error: [HTTP {0}]: Content: {1}'.format(response_bearerToken.status_code, response_bearerToken.content))
return None
def reconfigureWebserver(server_password, web_server, app_server_ips):
# Form the command to run on the web server VM
command_nginx = "wget -O /etc/nginx/conf.d/proxy.conf http://lab-manager.lab.local/files/vra-3tierapp-nginx-proxy.conf && "
# Form the string to put into the nginx config. This'll contain the list of app servers in an upstream block
nginx_app_server_config = "upstream APPTIER { "
for app_ip in app_server_ips:
nginx_app_server_config += "server " + app_ip +":8080; ";
nginx_app_server_config += "} "
# Replace the template upstream with the new app servers
command_nginx += "sed -i 's/upstream APPTIER { }/" + nginx_app_server_config + "/g' /etc/nginx/conf.d/proxy.conf &&";
# Restart nginx to take effect
command_nginx += "service nginx restart"
# Connect via SSH to web server and run command
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=web_server, username='root', password=server_password)
stdin,stdout,stderr = ssh_client.exec_command(command_nginx)
#print(stdin)
#print(stdout)
#print(stderr)
def handler(context, inputs):
vraUrl = "https://vra.lab.local/"
deploymentId = inputs['deploymentId']
appliance_password = inputs['requestInputs']['password']
vraRefreshToken = vra_get_token(vraUrl)
vraBearerToken = vra_get_bearer_token(vraUrl, vraRefreshToken)
# Discovering Deployment Name and Resources Details
print('Discovering Deployment Name...')
web_server_ips = []
app_server_ips = []
headers = {"Accept": "application/json", "Content-Type": "application/json", "Authorization": vraBearerToken}
response_deploymentName = requests.get(vraUrl + 'deployment/api/deployments/' + deploymentId +'/resources/?expandResources=true', data='', headers=headers, verify=False)
if response_deploymentName.status_code == 200:
response = response_deploymentName.json()
for resource in response['content']:
if resource['type'] == "Cloud.vSphere.Machine":
if "App" in resource['name']:
app_server_ips.append(resource['properties']['address'])
if "Web" in resource['name']:
web_server_ips.append(resource['properties']['address'])
print("Found Web Servers: " + ", ".join(web_server_ips))
print("Found App Servers: " + ", ".join(app_server_ips))
app_ip_list = ",".join(app_server_ips)
for web in web_server_ips:
print("Reconfiguring web server " + web + " to use app servers: " + app_ip_list)
reconfigureWebserver(appliance_password, web, app_server_ips)
outputs = {
"check_log": "no_output_here"
}
return outputs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment