Wednesday, August 9, 2023

NSX-T (local log in) with VIDM integration

We will explain how to log in with a local account to your NSX-T which integrated with VIDM.

We integrated our NSX-T into the VIDM. We had an issue in the VIDM and no one could log in to the NSX.


We had to use the below URL and log in with the admin account.


https://<NSX-T_FQDN/IP>/login.jsp?local=true

Monday, February 6, 2023

Provision ESXi host with Ansible

once you can reach your ESXi host on it management IP address. you will be able to use the below playbook to configure everything automatically with Ansible


Note: you will need to update the VLANs in this playbook

If you don't have NSX-T in your environment, you will ned to remove the tasks which create the vDS to the NSX.


Playbook on Github

Wednesday, January 18, 2023

Full backup to NSX-T with Ansible tower

Hereunder is a playbook to backup all your NSX-T components through simple API calls and then it will make another GET API call ?filter=Type- to backup everything in the NSX-T.

The Ansible playbook will save the output to a remote SFTP server

What you will need to update in the below playbook?

1. The SFTP server.

2. The components paths.


The Playbook on Github



- hosts: remotesftpserver
  vars:
    date: "{{ lookup('pipe', 'date +%Y%m%d') }}"
    whichnsx: "dev_nsx"
    host: "https://nsxturl/policy/api/v1/infra"
    nsxpassword: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          6632653863dfsdfsdufghjkfdsjfhsdifhsdjndsjkchusihcsdciyugsdlchjo
  tasks:
  - name: NSX-T Components Backup
    uri:
      url: "{{ host }}{{ item }}"
      force_basic_auth: yes
      validate_certs: no
      headers:
        Accept: "application/json"
        Content-Type: "application/json"
      user: admin
      password: "{{ nsxpassword }}"
      method: GET
      status_code: "200"
      body_format: json
    with_items:
      - /segments
      - /domains/default/groups
      - /domains/security-policies
      - /tier-0s/Test-T0
      - /tier-0s/Test-T0/locale-services/default/bgp
      - /tier-0s/Test-T0/locale-services/default/bgp/neighbors
      - /tier-0s/Test-T0/locale-services/default/interfaces
      - /tier-1s/T1
    register: components
  - debug: var=components

  - local_action:
      module: copy
      content: "{{ components }}"
      dest: "/tmp/components.json"


  - name: NSX-T All components Backup
    uri:
      url: "{{ host }}{{ item }}"
      force_basic_auth: yes
      validate_certs: no
      headers:
        Accept: "application/json"
        Content-Type: "application/json"
      user: admin
      password: "{{ nsxpassword }}"
      method: GET
      status_code: "200"
      body_format: json
    with_items:
      - ?filter=Type-
    register: all
  - debug: var=all

  - local_action:
      module: copy
      content: "{{ all }}"
      dest: "/tmp/all.json"


  - name: Create the backup directory
    file:
     path: /backup/nsx_backup/api/{{ whichnsx }}_{{ date }}
     state: directory
     owner: root
     group: root
     mode: 0750


  - name: Copy the first file to a remote FTP remotesftpserver
    copy:
      src='/tmp/components.json'
      dest='/backup/nsx_backup/api/{{ whichnsx }}_{{ date }}/components.json'


  - name: Copy the second file to a remote FTP remotesftpserver
    copy:
      src='/tmp/all.json'
      dest='/backup/nsx_backup/api/{{ whichnsx }}_{{ date }}/all.json'













































































































Thursday, January 5, 2023

Ansible Playbook to backup all NSX-T components

Herebelow you will find an ansible playbook to backup all your NSX-T components. You can add more tasks for your different NSX-Ts. In my playbook I use 2 tasks for my DEV NSX-T. but I have another URL variable and I can use it in another 2 tasks.

The first task will get the output of the listed items (Segmets, Groups, FW Policies,...etc). and the second task will get everything. but it will not be easy to work on teh second task during crisies. because it contains a lot of data and you will get lost 😂.

Note: you can use the second task response to restore your NSX-T environment. 

- hosts: localhost
  connection: local
  gather_facts: no
  vars:
    host:
      dev:
        - https://URL1/policy/api/v1/infra
      prod:
        - https://URL2/policy/api/v1/infra/
    nsxpassword: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          6632653863373166623766653666666666666666661393965633934386536363463386463
          
  tasks:
  - name: DEV NSX-T Backup
    uri:
      url: "{{ host.dev[0] }}{{ item }}"
      force_basic_auth: yes
      validate_certs: no
      headers:
        Accept: "application/json"
        Content-Type: "application/json"
      user: admin
      password: "{{ nsxpassword }}"
      method: GET
      status_code: "200"
      body_format: json
    with_items:
      - /segments
      - /domains/default/groups
      - /domains/security-policies
      - /tier-0s/Test-T0
      - /tier-0s/Test-T0/locale-services/default/bgp
      - /tier-0s/Test-T0/locale-services/default/bgp/neighbors
      - /tier-0s/Test-T0/locale-services/default/interfaces
      - /tier-1s/T1
    register: response
  - debug: var=response

  - name: DEV NSX-T All components Backup
    uri:
      url: "{{ host.dev[0] }}{{ item }}"
      force_basic_auth: yes
      validate_certs: no
      headers:
        Accept: "application/json"
        Content-Type: "application/json"
      user: admin
      password: "{{ nsxpassword }}"
      method: GET
      status_code: "200"
      body_format: json
    with_items:
      - ?filter=Type-
    register: response
  - debug: var=response
















































































































































Thursday, December 22, 2022

Ansible Playbook to backup NSX-T Segments

Ansible Playbook to backup NSX-T Segments


I thought a lot before I write this blog here. but as it is about the NSX , I will put it here. 

I will not go into how to setup Ansible Tower. I assume that you have Ansible Tower and Versioning Control System in your environment.

Hereunder is the playbook that you can use. but I need to show you how you can encrypt your password. 

- hosts: all
  connection: local
  gather_facts: false
  vars:
    host:
      devNsx:
        - https://FirstNSX.xyz.com/policy/api/v1/infra
      prodNsx:
        - https://SecondNSX.xyz.com/policy/api/v1/infra/
    urls:
      - /segments
  tasks:
  - name: DEV NSX-T Test Calls
    uri:
      url: "{{ host.devNsx[0] }}{{ urls[0] }}"
      force_basic_auth: yes
      validate_certs: no
      headers:
        Accept: "application/json"
        Content-Type: "application/json"
      user: admin
      password: !vault |
          $ANSIBLE_VAULT;1.1;AES256
      66326538633731666237666536306338656131616564376261393965633934386536363463386463

      method: GET
      status_code: "200"
      body_format: json
    register: response
  - debug: var=response.json


Here how I encrypted the password 

root@AnsibleServerCli:~/ansible#  ansible-vault encrypt_string 'MyPassword'  --name 'password'
New Vault password:
Confirm New Vault password:

password: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          66326538633731666237666536306338656131616564376261393965633934386536363463386463
          
Encryption successful


This website can do it for you https://ansible-vault-tool.com/ . but I don't recommend to do so.


 I created a credential with type vault and I used it in the AWX template

 









in case you don't have AWX and you use ansible through CLI , you can use the below command:


ansible-playbook YOURPLAYBOOKNAME  --vault-id @prompt



























































Monday, October 31, 2022

How to automate the deletion of NSX components with Ansible (2)

 Hereunder I delete several LSWs in one playbook


root@dcex1510ctrl001:~# cat ansible/playbooks/nsx-delete-bridges.yaml
- hosts: nsxtdev
  connection: local
  gather_facts: false
  vars:
    host:
      dev:
        - https://dcea-ptdnsxmgrvip/policy/api/v1/infra/segments/
  tasks:
  - name: DEV NSX-T delete all the LSWs for the bridged LSWs
    uri:
      url: "{{ host.dev[0] }}LSW-DCE-{{ item }}b-01"
      force_basic_auth: yes
      validate_certs: no
      headers:
        Accept: "application/json"
        Content-Type: "application/json"
      user: USERNAME
      password: PASSWORD
      method: DELETE
      status_code: "200"
      body_format: json
    with_items:
      - 121
      - 141
      - 142
   loop_control:
        pause: 2



root@dcex1510ctrl001:~# cat /root/ansible/hosts/hostsNsx.ini
[nsxtdev]
dcea-ptdnsxmgrvip

then we will execute it 

ansible-playbook -i /root/ansible/hosts/hostsNsx.ini /root/ansible/playbooks/nsx-delete-bridges.yaml

























































Friday, October 28, 2022

How to automate the deletion of NSX components with Ansible

 Hereunder I delete the LSW, SG and a Firewall policy with Ansible Playbook.

Note: the LSW is a member in the SG , and the SG is a member in the FWP , so it has to be done in this order: delete the FW policy then the SG then the LSW


root@dcex1510ctrl001:~# cat ansible/hosts/hostsNsx.ini
[nsxtdev]
dcea-ptdnsxmgrvip.test.local


root@dcex1510ctrl001:~# cat ansible/playbooks/nsx-delete-bridges.yaml
- hosts: nsxtdev
  connection: local
  gather_facts: false
  vars:
    host:
      dev:
        - https://dcea-ptdnsxmgrvip/policy/api/v1/infra/
  tasks:
  - name: DEV NSX-T Delete the unneeded components 
    uri:
      url: "{{ host.dev[0] }}{{ item  }}"
      force_basic_auth: yes
      validate_certs: no
      headers:
        Accept: "application/json"
        Content-Type: "application/json"
      user: USERNAME
      password: PASSWORD
      method: DELETE
      status_code: "200"
      body_format: json
    with_items:
      - domains/default/security-policies/FWP-VPC-122v
      - domains/default/groups/SG-LSW-DCE-122v
      - segments/LSW-DCE-122v-01
    loop_control:
        pause: 5



root@dcex1510ctrl001:~# ansible-playbook -i /root/ansible/hosts/hostsNsx.ini /root/ansible/playbooks/nsx-delete-bridges.yaml































































Wednesday, September 28, 2022

Migration from Classic env. to NSX-T env.

 The best way to migrate from a traditional VMware env. "doesn't contain NSX" to a new modern env. "contains NSX-T" id to change the IPs of the VMs and attache them to VxLAN LSWs . but in some situations, we will need to migrate the VMs with their current IPs. so we will need to do one of the following:

1. Bridge the VxLAN to VLAN.

2. Use VLAN LSW and rely on the physical network, but you will be still able to create FW, LB,...etc


In the below example we will use the VRO WF to do for us the second question:

The VRO Workflow in Github



var token = "Basic " + nsxBasicAuth
var nsxt
var vlanNumber
var lswName = "LSW-DCE-"+vlanNumber+"v"+"-01";



// Determine which NSX will be our endpoint
if(nsxt === "vxRailDR")
{
  var transport_zone_path = "/infra/sites/default/enforcement-points/default/transport-zones/1111ed4a-97f8-46b8-a6b1-d0a8f9591111";
  var vlan_transport_zone_path = "/infra/sites/default/enforcement-points/default/transport-zones/1111ac59-5195-4301-b4f5-f9e199811111";
  
}else if(nsxt === "vxRailnonDR")
{
  var transport_zone_path = "/infra/sites/default/enforcement-points/default/transport-zones/11115ddb-a726-4755-aa27-350fe29d1111";
  var vlan_transport_zone_path = "/infra/sites/default/enforcement-points/default/transport-zones/11118cca-aeb8-4ba8-8fe3-5324ed821111";
}


//LSW Creation
var url = "/policy/api/v1/infra/segments/" + lswName

var payload = {
    "type": "DISCONNECTED",
    "vlan_ids": [
        ""+vlanNumber+""
    ],
    "transport_zone_path": ""+vlan_transport_zone_path+"",
    "advanced_config": {
        "connectivity": "ON"
    },
    "admin_state": "UP",


       "tags": [
        {
            "scope": "LSW",
            "tag": ""+lswName+""
        }
    ]
}

//System.log(JSON.stringify(payload))


if(nsxt === "vxRailDR")
{
var response = restContent("PATCH",drNsxtHost,url,payload,token);
if (response.statusCode != 200) throw "HTTP status code :" + response.statusCode + "(" + response.serverMessage + ")";
}else if(nsxt === "vxRailnonDR")
{
var response = restContent("PATCH",nonDrNsxtHost,url,payload,token);
if (response.statusCode != 200) throw "HTTP status code :" + response.statusCode + "(" + response.serverMessage + ")";
}




//Security Group Creation 
var url = "/policy/api/v1/infra/domains/default/groups/" + "SG-LSW-DCE-"+vlanNumber+"v";

var payload = {
    "expression": [
        {
            "member_type": "Segment",
            "key": "Tag",
            "operator": "EQUALS",
            "value": "LSW|"+lswName+"",
            "resource_type": "Condition"

        }
    ],
    "extended_expression": [],
    "reference": false,
    "resource_type": "Group",

        "tags": [
        {
            "scope": "SG",
            "tag": "SG-"+lswName+""
        }
    ]

}


if(nsxt === "vxRailDR")
{
var response = restContent("PATCH",drNsxtHost,url,payload,token);
if (response.statusCode != 200) throw "HTTP status code :" + response.statusCode + "(" + response.serverMessage + ")";
}else if(nsxt === "vxRailnonDR")
{
var response = restContent("PATCH",nonDrNsxtHost,url,payload,token);
if (response.statusCode != 200) throw "HTTP status code :" + response.statusCode + "(" + response.serverMessage + ")";
}




var url = "/policy/api/v1/infra/domains/default/security-policies/" + "FWP-VPC-" + ""+vlanNumber+"" + "v"
var payload = {
    "rules": [
        {
            "action": "ALLOW",
            "resource_type": "Rule",
            "id": "FWR-"+vlanNumber+"v-Out",
            "display_name": "FWR-"+vlanNumber+"v-Out",
            "source_groups": [
                "/infra/domains/default/groups/SG-LSW-DCE-"+vlanNumber+"v"
            ],
            "destination_groups": [
                "ANY"
            ],
            "services": [
                "ANY"
            ],
            "profiles": [
                "ANY"
            ],
            "logged": false,
            "scope": [
                 "/infra/domains/default/groups/SG-LSW-DCE-"+vlanNumber+"v"
            ]
       
        },
        {
            "action": "ALLOW",
            "resource_type": "Rule",
            "id": "FWR-"+vlanNumber+"v-IN",
            "display_name": "FWR-"+vlanNumber+"v-IN",
            "source_groups": [
                "ANY"
            ],
            "destination_groups": [
                "/infra/domains/default/groups/SG-LSW-DCE-"+vlanNumber+"v"
            ],
            "services": [
                "ANY"
            ],
            "profiles": [
                "ANY"
            ],
            "logged": false,
            "scope": [
                "/infra/domains/default/groups/SG-LSW-DCE-"+vlanNumber+"v"
            ]
        }
    ],
    "logging_enabled": false,
    "resource_type": "SecurityPolicy",
    "scope": [
        "ANY"
    ]
}



if(nsxt === "vxRailDR")
{
var response = restContent("PATCH",drNsxtHost,url,payload,token);
if (response.statusCode != 200) throw "HTTP status code :" + response.statusCode + "(" + response.serverMessage + ")";
}else if(nsxt === "vxRailnonDR")
{
var response = restContent("PATCH",nonDrNsxtHost,url,payload,token);
if (response.statusCode != 200) throw "HTTP status code :" + response.statusCode + "(" + response.serverMessage + ")";
}




function restContent(method, host, url, payload, token) {
    //System.debug("**** Requesting endpoint data...");
    req = host.createRequest(method, url, payload ? JSON.stringify(payload) : null);
    req.setHeader("Accept", "application/json");
    req.setHeader("Content-Type", "application/json");
    if (token) { req.setHeader("Authorization", token); }
    return req.execute();
}

















































































































Wednesday, September 14, 2022

Increase NSX-T API requests per second

 By default there are some limitations on how many API requests you can do per second on the NSX. and when you exceed this number, you will start to get this error message Client 'admin' exceeded request rate of 100 per second


Now we will increase these numbers 

  • SSH to your NSX-T manager
  • check your current limitations  get service http
  • by default you will find these numbers 
Service name: http
Service state: running
Logging level: info
Session timeout: 0
Connection timeout: 30
Client API rate limit: 100 requests/sec
Client API concurrency limit: 40 connections
Global API concurrency limit: 199 connections

Redirect host: (not configured)
Basic authentication: enabled
Cookie-based authentication: enabled


  • use the below three commands and choose your preferred limitations
set service http client-api-rate-limit 500
set service http client-api-concurrency-limit 200
set service http global-api-concurrency-limit 200

  • check your new limitations with this command  get service http
Service name:  http
Service state:   stopped
Logging level:  info
Session timeout:  0
Connection timeout: 30
Client API rate limit: 500 requests/sec
Client API concurrency limit:     200 connections
Global API concurrency limit:     200 connections
Redirect host: (not configured)
Basic authentication: enabled
Cookie-based authentication: enabled

























































Monday, July 25, 2022

PowerCli to get all the needed data for a VM

 We are going to migrate one of our classical environments which doesn't have NSX to a new env. which has NSX.

To start doing some analysis, we will need to collect these data :

1. all the VMs in the env.
2. The OS
3. The power status
4. VLAN number 
5. The CPU and memory of the VMs
6. The size of the VM in GB without decimals 
7. Cluster
8. IP address
9. Number of NICs


here in this GUT repo you will find the powercli script The PowerCli Script



























Wednesday, July 13, 2022

GET VRA Tokens

We will get the refresh and access tokens for VRA , I am following the below page but with a small adjustment

https://vdc-download.vmware.com/vmwb-repository/dcr-public/97d1d46c-8846-4c12-85a8-5655d1189825/3873335e-1ec6-4bac-a9c2-2f62636ce19f/GUID-AC1E4407-6139-412A-B4AA-1F102942EA94.html  


Step number zero :-) . you will need to have a linux VM that can reach to VRA on port 443

1. Define your variables

identity_service_url='https://<vRA-HOSTNAME>'
username='<your_username>'
password='<your_password>'

2. Execute the below command
api_token=`curl -k -X POST \
  "$identity_service_url/csp/gateway/am/api/login?access_token" \
  -H 'Content-Type: application/json' \
  -d '{
  "username": "'"$username"'",
  "password": "'"$password"'"
}' | jq -r .refresh_token`

3. Get the refresh token
echo $api_token

to get the access token:

1. Define your variables
identity_service_url='https://<vRA-HOSTNAME>'
username='<your_username>'
password='<your_password>'

2. Execute the below command
access_token=`curl -k -X POST \
  "$identity_service_url/iaas/api/login" \
  -H 'Content-Type: application/json' \
  -s \
  -d '{
  "refreshToken": "'"$api_token"'"
}' | jq -r .token`

3. Get the access token
echo $access_token

Create bulk of VRA deployments with VRA

 How can you deploy bulk of VRA deployments with the minimum effort , the answer will be Terraform 


terraform {
  required_providers {
    vra = {
      source  = "vmware/vra"
      version = "0.5.1"
    }
  }
}

provider "vra" {
  url           = "https://YourVraURL"
# I will explain to you how to get the refresh token in another page
  refresh_token = ""
  insecure      = "false"
}



resource "vra_deployment" "Test_deployment" {
  count = 10
  name  = "Terraform - MAIB.${count.index}"
  #name        = "Terraform - MAIB100"
  description = "Deployment description"

# You can get this information from the service broker page 
# The catalog_item_id you can get it from the URL  
#https://ABC.COM/catalog/#/library/55dc45e8-ba3f-378b-b900-c16a556f7a55
#The project ID can be gotten from the infrastructure and choose the projects and get teh project ID from the URL
#https://ABC.COM/automation-ui/#/provisioning-ui;ash=%2Fprojects%2Fedit%2Fd6437f49-ebf6-41eb-821c-13cabb509fc0

  catalog_item_id      = "55dc45e8-ba3f-378b-b900-c16a556f7a55"
  catalog_item_version = "2021.08.25-01"
  project_id           = "d6437f49-ebf6-41eb-821c-13cabb509fc0"
  

# This inputs will be changable from one customer to another 
  inputs = {
    t_shirt_size    = "small",
    deployment_name = "Terraform - MAIB.${count.index}"
    image              = "Windows 2019"
    Backup             = "No Backup"
    #Patching_Method    = "Automated monthly patching"
    #Patching_Week      = "Fourth"
    #Patching_Day       = "Sunday"
    #Patching_Timeframe = "13:00 - 15:00"

  }

  timeouts {
    create = "30m"
    delete = "30m"
    update = "30m"
  }

# I am using this part because we are migrating from NSX-V to NSX-T and the cloud zone is changed after the migration.

    lifecycle {
    ignore_changes = [
      catalog_item_id,
      catalog_item_version,
      inputs
    ]

  }


}

Tuesday, July 12, 2022

How to make API call on NSX-T with ansible

 We will make execute an ansible playbook to get all the NSX-T segments for us



cat /root/ansible/hosts/hostsNsx.ini
[nsxtdev]
NSX-T.abc.com


cat /root/ansible/playbooks/nsx.yaml
- hosts: nsxtdev
  connection: local
  gather_facts: false
  tasks:
  - name: Get all the NSX-T Segments
    uri:
      url: https://NSX-T/policy/api/v1/infra/segments
      force_basic_auth: yes
      validate_certs: no
      headers:
        Accept: "application/json"
        Content-Type: "application/json"
      user: USERNAME
      password: PASSWORD
      method: GET
      status_code: "200"
      body_format: json


ansible-playbook -i /root/ansible/hosts/hostsNsx.ini /root/ansible/playbooks/nsx.yaml -vvvv


to avoid using  -vvvv and to get the only API call result , you can use the following playbook

 
- hosts: nsxtdev
  connection: local
  gather_facts: false
  tasks:
  - name: Get all the NSX-T Segments
    uri:
      url: https://NSX-T/policy/api/v1/infra/segments
      force_basic_auth: yes
      validate_certs: no
      headers:
        Accept: "application/json"
        Content-Type: "application/json"
      user: USERNAME
      password: PASSWORD
      method: GET
      status_code: "200"
      body_format: json
    register: response
  - debug: var=response.json


ansible-playbook -i /root/ansible/hosts/hostsNsx.ini /root/ansible/playbooks/nsx.yaml

Wednesday, June 1, 2022

How to filter NSX-T GET API call

 I faced a small issue today. I am creating all the NSX-T segments by Terraform and one of my customers asked me to enable DHCP relay on his segment, and he told me that we will need to do that in the future for other NSX-T segments.


As I am lazy, I started to think how can I automate this kind of requests. and I found 2 possibilities:

1. Providing him a way to edit in his Terraform config. file , and by this way he will have a high priv. on the NSX-T which is not a good idea at all.

2. Create for him a VRO workflow to write in it the segment name and the workflow will add the DHCP relay configuration to his segment.


I decided to proceed with the second option. and I found 2 issues:

1. I have to add a life cycle in the NSX-T segment resource in the Terraform. to avoid rolling back during the next apply :-)

2. I have to get the LSW by its name via API , to be able to edit in it and make post API with the DHCP relay config.


The second point was really tough point. because the segments have been created via terraform and they have random ID in their API path. so I have to find a way to get the segment with its name not with its API path


making GET API call to the below URL after editing it with your data, will get for you the segment 


https://YOUR_NSX_T_FQDN/policy/api/v1/search/query?query=display_name:YOUR_SEGMENT_NAME

Monday, May 30, 2022

Backup VDS and DRS rules and groups

 We are going today to do a backup for the vDS of the vCenter and backup the DRS rules and groups


1. The first step is to encrypt your administrator@vsphere.local password, you will find the script on the Github How to encrypt the password

2. The second step is to use your encrypted password in this script How to backup vDS and DRS rules

3. Schedule this script in the task scheduler of your jump box.




Note: I highly recommend to use a service account to execute the backup scripts. 

Thursday, May 19, 2022

vSphere Tags after Cross vCenter vMotion

We will explain here how you can reapply the vSphere Tags after you migrate a VM from one vCenter to another or even when you use VEEAM or any other replication tool to replicate a VM from one vCenter to another vCenter


Before executing this script you will need to create 2 folders in the 2 vCenters with the same name. and put the machines under these folders. because the main Idea of the script is getting the VMs under a certain folder and collect their TAGs , and then login to the other vCenter and search for the collected VMs and start to apply the TAGs on them. you also will need to make sure that the TAGs exist on the destination VC (The script will not create the TAGs , it will apply them only)


Import-Module VMware.VimAutomation.Core
 
$vCenterIP = "First vCenter"
$FOLDERNAME = 'XXXX'          ##Change XXXX with folder Namer###
Connect-VIServer $vCenterIP

$tagsall = @()

foreach($machine in $machines = Get-Folder -Name $FOLDERNAME | Get-VM){
$tagsall+=@(Get-TagAssignment -Entity $machine.name)
}
$tagsall

sleep 10

Disconnect-VIServer $vCenterIP -confirm:$false


1. Don't close your Powershell window. 

2. Start to do the cross vCenter vmotion.

3. After you finish from all the VMs.

4. Execute the below script.


$vCenterIP = "Second vCenter"
Connect-VIServer $vCenterIP -User $vCenterUser -Password $vCenterPass 

$tagsallnew = $tagsall | select Tag,Entity

for($i = 0; $i -lt $tagsallnew.length; $i++){

 $tag = Get-Tag -name $tagsallnew[$i].tag.name -Category $tagsallnew[$i].tag.Category.name   -Server "Second vCenter"
 $vm = get-vm -name $tagsallnew[$i].Entity.Name   -Server "Second vCenter"

 New-TagAssignment -Tag $tag  -Entity $vm -Server "Second vCenter"
 }



Sunday, May 15, 2022

Set Env. variable for Terraform on Windows

 We will explain how you can put your Terraform variable in your windows environment variables.

Note: you can for example put your VMC Token in your windows variables. This will avoid you from 2 things:

1. Put the token in the code itself, which is not recommended at all for security reasons.

2. Write the token every time when you plan or apply the code.


Note: The below variable is changeable based on the variable name in your code.


Set-Item -Path env:TF_VAR_token -Value “token_value“


To set the backend access key and secret key:


Set-Item -Path env:AWS_ACCESS_KEY_ID -Value "xyxyxyxyxyx12345"

Set-Item -Path env:AWS_SECRET_ACCESS_KEY -Value "abcabcabcabcabcabcabc12345"


Source: https://www.terraform.io/language/settings/backends/s3 

Monday, March 28, 2022

NSX-T resources in VMC

 

We will create some NSX components on VMC via Terraform


1.1. Segments

You have to use this resource nsxt_policy_fixed_segment , if you try to use the normal resource of the on premises NSX-T , that will not work and you will get an error.


# you can replace the variables with names or numbers as you like

resource "nsxt_policy_fixed_segment" "projectLSW" {
  display_name      = "LSW-VMC-${var.lswNumber}-01"
  connectivity_path =  var.connectivity_path  

   subnet {
    cidr = var.subnet
  }
   tag {
    scope = "LSW"
    tag   = "LSW-VMC-${var.lswNumber}-01"
  }
  advanced_config {
    connectivity = "ON"
  }
}


1.2. SEC Groups


Whenever you create a group in VMC, you have to specify the domain of this group. The domain will be either cgw or mgw

cgw: used for compute groups that will be used in the compute FW rules

mgw: used for the management groups that will be used in the management FW rules


# the below SEC Group will have the LSW as a member {it will match the TAG which we are applying on the Segment}

resource "nsxt_policy_group" "projectSG" {
  display_name = "SG-VMC-VPC-${var.lswNumber}"
  domain       = "cgw"
  criteria {
    condition {
      key         = "Tag"
      member_type = "Segment"
      operator    = "EQUALS"
      value       = "LSW-VMC-${var.lswNumber}-01"
    }
  }
}


1.3. IP SET

# NSX-T is unlike NSX-V , you have to create SEC group and put your subnet as a member in this SEC group, because there is no option to create IPSET directly

 

resource "nsxt_policy_group" "SG-IPSET-5_5_5_5_32-To-VPC-7e" {
  display_name = "SG-IPSET-5_5_5_5_32-To-VPC-7e"
  domain       = "cgw"
  criteria {
    ipaddress_expression {
      ip_addresses = ["5.5.5.5"]
    }
  }
}



1.4. Service


resource "nsxt_policy_service" "SRV-TCP-P-4444" {
  display_name = "SRV-TCP-P-4444"


 l4_port_set_entry {
    display_name = "SRV-TCP-P-4444"
    protocol     = "TCP"
    destination_ports = ["4444"]
  }
}




1.5. SEC TAG


# I am using here a dummy VM to apply all the NSX-T Tags on it , because if the TAG is not applied on any resource, the NSX will delete it automatically 


resource "nsxt_policy_vm_tags" "projectTAGs" {
  instance_id = var.vmBIOS  tag {
    scope = "FWP"
    tag   = "FWP-${var.lswNumber}-Dummy"
  }
}



1.6. FW Policy


Whenever you create a FW policy, you have to specify the domain of the policy. The domain will be either cgw or mgw


  resource "nsxt_policy_security_policy" "projectFWP" {
  display_name = "FWP-VPC-${var.lswNumber}"
  category   = "Application"
  scope      = [nsxt_policy_group.projectSG.path]
  domain       = "cgw"
  locked     = false
  stateful   = true
  tcp_strict = false



Terraform on VMC series

 It will be a small series to show you how you can use Terraform on your VMware cloud env. on AWS.


  1. Collecting the needed information: Part-1
  2. Generate your Token: Part-2
  3. Create your first resource on VMC: Part-3
  4. Create some NSX-T resources on VMC via Terraform: Part-4
  5. Full example with LSW, SG, FW Policy and FW rule: Part-5
  6. Create env. variable for your Terraform variable: Part-6

Monday, March 14, 2022

Using Terraform on NSX-T on VMC/AWS - Part 3

 Create your first resource on VMC via Terraform


The HCL code on githup


terraform {

  required_providers {

    nsxt = {

      source = "vmware/nsxt"

      version = "3.2.5"

    }

  }

}

# The below Token and NSX host are just for explanation :-) , they are not real data

provider "nsxt" {

  host                 = "https://nsx-1-38-60-79.rp.vmwarevmc.com/vmc/reverse-proxy/api/orgs/53045f5a-59f7-4921-8bcb-0b09e8c3ac16/sddcs/24163dc6-2b22-475b-b197-167932ef5124/sks-nsxt-manager"

  vmc_token            = "12345IZf8Elb9VFTorfvnoyk6CsDXi15678utfdsFHfdsdafsadfasfIUTdghuy7815"

  allow_unverified_ssl = true

  enforcement_point    = "vmc-enforcementpoint"

}


resource "nsxt_policy_fixed_segment" "Terraform-segment1" {

  display_name      = "Terraform-segment1"

  description       = "Terraform provisioned Segment"

  connectivity_path = "/infra/tier-1s/cgw"


  subnet {

    cidr        = "12.12.2.1/24"

    dhcp_ranges = ["12.12.2.100-12.12.2.160"]


    dhcp_v4_config {

      server_address = "12.12.2.2/24"

      lease_time     = 36000

    

    }

  }

}

Using Terraform on NSX-T on VMC/AWS - Part 2

 How can you generate access token for your account on VMC?

  • Open your VMC portal https://console.cloud.vmware
  • Write your username and password
  • On the top right corner press on your account and choose my account

  • Press on API Tokens 
  • Press on generate Token.
  • Write your Token name.
  • Choose your Token TTL "As per your company policy, I choose it never expire because this is just a demo"

  • Copy your Token and keep it in a secure place.

Using Terraform on NSX-T on VMC/AWS - Part 1

 How to use Terraform on NSX-T on VMC/AWS ?


The first step is to collect the needed information like your NSX-T host on your VMC environment.

The second step is to create access token for your account to be able to connect to the NSX-T.


1. How to get your NSX-T host on your VMC env.:

  1.  Login to your VMC env.
  2.  Choose VMware Cloud on AWS
  3.  Choose Inventory
  4.  Choose your SDDC 
  5.  Choose developer Center
  6.  Press on VMware Cloud on AWS
  7.  Press on Notifications 2
  8.  Press on NSX VMC Policy API
  9.  Choose your SDDC one more time, in case you have more than 1 SDDC
  10.  Copy your NSX-T host proxy from the service information part 

 it should be something like that

https://nsx-1-38-60-79.rp.vmwarevmc.com/vmc/reverse-proxy/api/orgs/53045f5a-59f7-4921-8bcb-0b09e8c3ac16/sddcs/24163dc6-2b22-475b-b197-167932ef5124





you will need to add at the end of the URL of your host /sks-nsxt-manager


so in Terraform your host will be like that 

host = "https://nsx-1-38-60-79.rp.vmwarevmc.com/vmc/reverse-proxy/api/orgs/53045f5a-59f7-4921-8bcb-0b09e8c3ac16/sddcs/24163dc6-2b22-475b-b197-167932ef5124/sks-nsxt-manager"

in the second article I will show you can create access token for yourself to be able to authenticate with it and to create some resources with Terraform

Wednesday, March 2, 2022

Create NSX-T TAG and Security Group match on this TAG with Terraform

 How to create NSX-T TAG and Security Group match on this TAG with Terraform?


resource "nsxt_policy_vm_tags" "VM123TAG" {

  instance_id = var.vmBIOS

# you can get the vmBIOS from the NSX-T GUI , go to inventory and then Virtual machines

  tag {

    scope = "FWP"

    tag   = "FWP-VPC-1000e-on-P15172"

  }

}



resource "nsxt_policy_group" "SG-FWP-VPC-1000e-on-P15172"{

  display_name = "SG-FWP-VPC-1000e-on-P15172"

  criteria {

    condition {

      key         = "Tag"

      member_type = "VirtualMachine"

      operator    = "EQUALS"

      value       = "FWP|FWP-VPC-1000e-on-P15172"

    }

  }

}

Create NSX-T Service with Terraform

 How to create  NSX-T Service with Terraform?


resource "nsxt_policy_service" "SRV-TCP-P-22-SSH" {

  display_name = "SRV-TCP-P-22-SSH"

  l4_port_set_entry {
    display_name = "SRV-TCP-P-22-SSH"
    protocol     = "TCP"
    destination_ports = ["22"]
  }

}

Create Service Group on NSX-T with Terraform

 How to create Service Group on NSX-T with Terraform?


resource "nsxt_policy_service" "SRV-GRP-TCP-P-1024-To-1064-443-22" {

  display_name = "SRV-GRP-TCP-P-1024-To-1064-443-22"


 l4_port_set_entry {

    display_name = "SRV-TCP-P-1024-To-1064"

    protocol     = "TCP"

    destination_ports = ["1024-1064"]

  }


   l4_port_set_entry {

    display_name = "SRV-TCP-P-443"

    protocol     = "TCP"

    destination_ports = ["443"]

  }


  l4_port_set_entry {

    display_name = "SRV-TCP-P-22-ssh"

    protocol     = "TCP"

    destination_ports = ["22"]

  }


}

Tuesday, March 1, 2022

Create NSX-T IPSET with Terraform

 How to create  NSX-T IPSET with Terraform


resource "nsxt_policy_group" "SG-IPSET-172_25_11_104_32" {

  display_name = "SG-IPSET-172_25_11_104_32"

  criteria {

    ipaddress_expression {

      ip_addresses = ["172.25.11.104"]

    }

  }

}


Note: you are free to put any preferred resource name and display name, but from my point of view, this is the best way of naming because once you see it in the GUI, you will know directly what is the IP or the subnet included in this IP-SET

Monday, February 14, 2022

Install VMtools without reboot

Today we are going to upgrade VMtools for virtual machine without reboot.

at the beginning we will do it for one machine and after that we will make a simple loop to upgrade VMtools of bulk of virtual machines


PS C:\> Get-VM VMname


Name                     PowerState     Num CPUs  MemoryGB

----                             ----------      --------           --------

VMname                  PoweredOn   2                   4.000



PS C:\> Get-VM VMname   |  Update-Tools -NoReboot








and now we will do upgrade for VMtools for bulk of VMs


PS C:\> Get-Folder FolderName | Get-VM | Update-Tools -NoReboot

Upgrade Terraform Provider


I am trying now to upgrade the Terraform provider which I am using for my NSX-T

First you have to put the new provider version in your main.tf file 


terraform {

  required_providers {

    nsxt = {

    source  = "vmware/nsxt"

      version = "3.2.5"

    }

  }

}


Second is to execute the below command

 .\terraform init -upgrade


once you execute the above command you will find output like the below output. That means that you upgraded your Terraform provider successfully







 

NSX-T (local log in) with VIDM integration

We will explain how to log in with a local account to your NSX-T which integrated with VIDM. We integrated our NSX-T into the VIDM. We had a...