Created
December 31, 2019 04:49
-
-
Save mattycourtney/bf4d43f7a1f7f2c5625094e45dd9a198 to your computer and use it in GitHub Desktop.
Use cURL to create a SNAT rule using the NSX-T Policy API in VMC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Author: Matty Courtney | |
# Description: Use cURL to create a SNAT rule using the NSX-T Policy API in VMC | |
# Ensure jq is installed | |
type jq > /dev/null 2>&1 | |
if [ $? -eq 1 ]; then | |
echo 'Unable to find jq installed. This script requires jq to parse the JSON output' | |
exit 1 | |
fi | |
# Prompt the user for inputs | |
read -p 'CSP Refresh Token: ' REFRESH_TOKEN | |
read -p 'Org ID: ' ORG_ID | |
read -p 'SDDC ID: ' SDDC_ID | |
read -p 'Rule Name: ' RULE_NAME | |
read -p 'Elastic IP: ' EIP | |
read -p 'Internal IPs: ' INTERNAL_IPS | |
# Obtain a CSP Access Token | |
echo "Obtaining a CSP Access Token..." | |
RESULT=$(curl -s -X POST -H "application/x-www-form-urlencoded" "https://console.cloud.vmware.com/csp/gateway/am/api/auth/api-tokens/authorize" -d "refresh_token=$REFRESH_TOKEN") | |
CSP_ACCESS_TOKEN=$(echo $RESULT | jq -r .access_token) | |
# Determine the NSX-T Reverse Proxy URL | |
echo "Determining the NSX-T Reverse Proxy URL..." | |
RESULT=$(curl -s -X GET -H "Content-Type: application/json" -H "csp-auth-token: ${CSP_ACCESS_TOKEN}" "https://vmc.vmware.com/vmc/api/orgs/${ORG_ID}/sddcs/${SDDC_ID}") | |
NSX_PROXY_URL=$(echo $RESULT | jq -r .resource_config.nsx_api_public_endpoint_url) | |
# Construct the JSON payload | |
PAYLOAD=$(jq -n \ | |
--arg rule_name "$RULE_NAME" \ | |
--arg eip "$EIP" \ | |
--arg internal_ips "$INTERNAL_IPS" \ | |
'{display_name: $rule_name, action: "SNAT", service: "", translated_network: $eip, source_network: $internal_ips, scope: ["/infra/labels/cgw-public"], firewall_match: "MATCH_INTERNAL_ADDRESS", logging: false, enabled: true, sequence_number: 0}') | |
# Create the SNAT rule | |
echo "Calling the NSX-T Policy API to create the SNAT rule..." | |
curl -X PUT -H "Content-Type: application/json" -H "csp-auth-token: ${CSP_ACCESS_TOKEN}" "${NSX_PROXY_URL}/policy/api/v1/infra/tier-1s/cgw/nat/USER/nat-rules/${RULE_NAME}" -d "${PAYLOAD}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment