Powershell group export

I needed to get a list of people in som AD group for an audit so I wrote a quick script to export each group matching my filter to a CSV-file and populate it with name and samaccountname. Setting semi colon as an delimiter ensures that you can open the CSV-file in Excel with no additional work to get columns correct.

$groups = Get-ADGroup -filter { name -like "Company-Fileserver-ACL*" }

foreach ($group in $groups)
	Write-Output $group.name
	$file=$group.name + ".csv"
	Get-ADGroupMember $group.name | Select-Object name, samaccountname | Export-Csv -path $file -NoTypeInformation -delimiter ";"

Setup AWX Vcenter inventory with tags part 2

This is the second part in how you can setup Vmware inventory in AWX based on VM tags. Link to first part.

Create a file that ends with vmware.yml or vmware.yaml. For example invent. I called my file invent.vmware.yml

plugin: vmware_vm_inventory
strict: False
hostname: vc.homelab.domain.com
validate_certs: False
with_tags: True
  - 'config.name'
  ansible_host: 'guest.hostName'
  - key: 'tags'
    separator: ''

Make sure to set you hostname and check in your file in a Git repository.

Create a project, my is called Inventory an select Git as SCCM Type. Add you Git repository URL as SCM URL. Don´t forget to create SCM credentials if you haven’t done that already. Set /opt/my-envs/vm-tags as Ansible environment.

Next step is to create a custom credential type. I called my Vmware_Inventory

#Input configuration
  - id: username
    type: string
    label: Username
  - id: password
    type: string
    label: Password
    secret: true
  - username
  - password

#Injector configuration
  VMWARE_PASSWORD: '{{password}}'
  VMWARE_USERNAME: '{{username}}'

Create a new credential with your new credential type. You will need a user with read permissions in your Vcenter server.

Go to Inventory and create a new Inventory and give a name and hit Save.

Click sources and create a new source. Give it a name and select Sourced from a project as a sources. Set /opt/my-ens/vm-tags/ as ansible environment. Search for and select for your credential with read permission in Vcenter.

Now you should be able to sync your new inventory.

After the sync has finished you should see your hosts and groups.

For example I have connection details as a group variable on my group win. All my windows server are in the group win. I needed you cand have second group like SQL servers and then add that group to win group to allow it to inherit all win group variables.

ansible_winrm_server_cert_validation: ignore
ansible_port: 5986
ansible_connection: winrm
ansible_winrm_transport: kerberos

That’s it, hopefully this can be helpful to any one seeking information about AWX and Vmware tags as inventory groups.

Setup AWX Vcenter inventory with tags part 1

New to AWX and I had a goal to setup Vcenter as an inventory source with groups based on vmware tags. I got that setup working with ansible and started to investigate how to achieve same result in AWX. After a couple of days testing I got some hints on Reddit and was able to get it working as expected. Hopefully this guide can help someone (and me next time) setup inventory with tags.

First step if not already done is to install AWX. I will not cover the setup. It is already covered here https://github.com/ansible/awx/blob/devel/INSTALL.md. I have chosen to install on a standalone Docker host in my Home lab running CentOS.

Open the inventory file install/inventory in your favorite editor.
Look for and uncomment custom_venv_dir=/opt/my-envs/

Create dir: mkdir /opt/my-envs

Run the playbook: ansible-playbook install.yml -i inventory

Create folder and Python env and install all prerequisites

mkdir /opt/my-envs/vm-tags
python3 -m venv /opt/my-envs/vm-tags/
source /opt/my-envs/vm-tags/bin/activate
yum install gcc
yum install python36-devel
pip3 install psutil
pip3 install ansible
pip3 install pyaml
pip3 install requests
pip3 install PyVmomi
pip3 install --upgrade pip setuptools
pip3 install --upgrade git+https://github.com/vmware/vsphere-automation-sdk-python.git

Log on to AWX and navigate to Settings -> System.
Add /opt/my-envs/vm-tags to CUSTOM VIRTUAL ENVIRONMENT PATHS

Last step in this part is to verify our new custom env. Go to ORGANIZATIONS and push then pencil to edit default organization.

Verify that you can see your new Ansible Environment.

Ansible dynamic inventory with Vcenter

In order to create your Ansible groups based on vmware tags you need to create a inventory file and name it to something.vmware.yaml.

Also make sure to enable vmware inventory plugin in ansible.cfg

enable_plugins = vmware_vm_inventory


plugin: vmware_vm_inventory
strict: False
hostname: vc.homelab.jonasdahlgen.se
username: administrator@vsphere.local
password: secretpassword
validate_certs: false
with_tags: true
    - 'name'
    - 'config.uuid'
    - 'config.name'
    - 'guest.toolsStatus'
    - 'guest.toolsRunningStatus'
    - 'guest.ipAddress'
    - 'configIssue'
    - 'config.bootOptions'
    - 'config.annotation'
    - 'config.alternateGuestName'
      ansible_host: 'guest.ipAddress'
        - key: 'tags'
          separator: ''

Test new inventory with ansible-inventory –graph -i vcenter.vmware.yaml Groups named Linux, ansible_managed,win are created from Vmware tags.

[root@d4e7b19ae23b playbooks]# ansible-inventory --graph -i vcenter.vmware.yaml
| |--Ansible01_564d4590-0ab7-8192-33c4-8690b6394208
| |--Ansible01_564d4590-0ab7-8192-33c4-8690b6394208
| |--SQL2016_421e22dd-ecbd-83f2-6010-b679a3840a70
| |--2019Template_42237f2e-f317-3fbd-2688-023de31ffcdf
| |--AD_564d896d-f1cb-3837-4c15-6355e1b78b1d
| |--Docker01_4223eb67-2e2b-519c-0f90-959234307b44
| |--Esxi1_4223f791-c6b1-294b-b8be-00441105f73b
| |--Ubuntu_template_4223cce6-d618-6994-1550-db4d872cdf98
| |--Vcenter7_564d3c9f-07a3-90fa-60df-bfb39b3f697b
| |--Win10_01_564da1fa-1da0-7b6b-d386-8b173a48fbc6
| |--centos_template_42232f6e-96bb-f385-7ea4-aedaec2dedea
| |--esxi-01_422366be-06b3-eb4e-b837-cb472cce4208
| |--esxi-02_4223d129-24c4-98fe-205f-af445f578a03
| |--esxi-03_4223e353-2be9-a388-5203-60f887bfb14a
| |--SQL2016_421e22dd-ecbd-83f2-6010-b679a3840a70

Add users or groups to local admin group

Sometimes you need to add users or groups in local Administrators group on a windows server. This function helps to accomplish that on one or more servers. Load a text- or csv-file and pipe it to Add-AdminGroup. All servers not responding will be shown at the end for later follow-up.

function Add-AdminGroup
	Param (
		[parameter(Mandatory = $true,
				   ValueFromPipeline = $true,
				   position = 0)]
		[Alias('IPAddress', '__Server', 'CN', 'server')]
		[Alias('groupname', 'adgroup')]
		if (Test-Connection -quiet -Computername $computername)
			Write-Output "Adding $group to local administrators on" $Computername
			Invoke-Command -ComputerName $Computername -ScriptBlock {
			Add-LocalGroupMember -Group Administrators -Member $args[0]
			} -ArgumentList $group
			write-output "No response from" $Computername
			$failed += $computername
			foreach ($obj in $failed)
				Write-Output $obj

List VMs according to memory and CPU usage

For internal billing purpose I needed a way list all Windows VMs for a given subsidiary and their CPU and memory configuration.

Connect-VIServer -Server vcenter.corp.lan

$var = get-vm -location Subsidiary1 | Where{ $_.Guest.OSFullName -like '*windows*' }  | select numcpu, memorygb | Group-Object numcpu,memorygb

function get-numOfVms
		[parameter(Mandatory = $true)]

	$results = foreach ($row in $var)
		$cpu, $mem = $row.Name -split ',', 2
			NumOfVMs = $row.Count
			NumOfCPUs   = $cpu
			MemoryGB = $mem.Trim()
	return $results
$total = get-numOfVms -VMs $var
$total | Export-Csv -Path totalvms.csv -NoTypeInformation


Example of totalvms.csv. It gives you a number of each specific CPU and memory configuration.


Create DHCP scopes from a CSV file

A fast way to import multiple DHCP scopes to a DHCP server. Some settings needs to be added on top level. For example DNS servers.

Required header in CSV:

$dhcpserver = ""
$scopes = Import-Csv -Path dhcp.csv -Delimiter ";"
foreach ($scope in $scopes)
	$name = $scope.name
	$description = $scope.description
Write-Output "Creating scope  $name"
Add-DhcpServerv4Scope -ComputerName $dhcpserver -Name "$name" -Description "$description" -StartRange $scope.startrange -EndRange $scope.endrange -SubnetMask $scope.subnetmask -State Active -LeaseDuration 1.00:00:00
Set-DhcpServerv4OptionValue -Router $scope.router -ScopeId $scope.scopeid -ComputerName $dhcpserver

Docker and macvlan

If you want to use docker containers in your regular LAN subnet you need to setup a new Docker network with macvlan driver.

First create your Docker network. — ip-range specifies all addresses that Docker will manage. Chose a part of your subnet outside your DHCP-scoop if you have one to avoid ip conflicts.
–aux-address=’host=′ docker_net is tied to your host interface to allow your containers to comunicate with your host.

[root@docker01 ~]# docker network create -d macvlan -o parent=ens224 \
--subnet \
--gateway \
--ip-range \
--aux-address='host=' docker_net

As you can see when running docker network ls we have a new network called docker_net with macvlan driver.

Docker network

Next step is to create a macvlan interface, in this example called docker_int.
[root@docker01 ~]# ip addr add docker_int link ens224 type macvlan mode bridge

Configure the interface with your selected host address and bring it up. Last step is to add a IP route to tell your host how to connect to to al Docker containers.

[root@docker01 ~]# ip link add docker_int link ens224 type macvlan mode bridge
[root@docker01 ~]# ip link set docker-shim up
[root@docker01 ~]# ip route add dev docker_int

Run a container and connect it to docker_net
[root@docker01 ~]# docker run nginx -network docker_net

If you want to check container ip run:

[root@docker01 ~]# docker inspect CONTAINER_ID