Skip to main content

Posts

Showing posts with the label Powershell

ARM templates - iterate & deploy resource

Welcome file Original Post here Background 🧐 I like ARM templates, I use it a lot to deploy Azure cloud resources but as all things it has some pain points associated with it. In this post, let’s see how you can iterate over based on certain logic and deploy multiple resources using linked templates. As it stands out this logic of iterating over and deploying multiple instances of a resource tripped me a lot in the beginning. Walkthrough 🏃 Let’s work through the whole process of writing an ARM template which deploys multiple resources. Github Repository - ArmTemplateLoopExample This is a simple post demonstrating looping logic I often use, feel free to sprinkle your own best practices & modifications on top e.g. storing templates in a private Cloud blob container, adding more parameters, names etc. Scenario Let’s take a scenario of deploying many storage accounts based on the user input. Ideally, if you’re in this situation you should write 2 temp...

AKS PowerShell Tip - Add Authorized Ip

Welcome file Background 🐼 Recently, I found out that there is no sane way to perform adding a public IP address to the authorized IP address ranges using either the Az CLI or Az.Aks PowerShell (no cmdlets available yet) module. From the official docs it says to use something like below format with Az CLI. az aks update \ --resource-group myResourceGroup \ --name myAKSCluster \ --api-server-authorized-ip-ranges 73.140.245.0/24 But it doesn’t tell you how to append the IP to the range, instead you need to supply a comma separated value of public IP addresses. Challenge ☁️ Well, this is can be done by using Az CLI with PowerShell or Bash and parsing output then generating a comma separated string and passing it back to Az CLI 😞 Solution ⚡️ Often, when I am hit with such limitations with cmdlets or Az CLI making life hard. I go back to using simply the 2 cmdlets provided by Az.Resources module. Behold mighty! Get-AzResource - Gets the Az ...

Az.ResourceGraph - Search across all Subscriptions

Azure Resource Graph is an amazing tool in the belt of Az Ops team. It allows to quickly search across all your subscriptions (does it?). Started using Az Resource graph with that pretext that the queries I ran will be run against all the subscriptions I have read access to, Yes it will but there is a catch here! I mostly use Az.ResourceGraph PowerShell module (Why? another post) Found the solution by digging into the source code for the Search-AzGraph cmdlet, if the subscriptions are not specified explicitly then the cmdlet uses a method named GetSubscriptions() Below is a snippet of the method def: The catch is that if no subscriptions are supplied it defaults to subscriptions in the default context. I am not really sure but some of the subscriptions which I can see when running Get-AzSubscription were missing when I ran the below: (Get-AzContext).Account.ExtendedProperties.Subscriptions So, the trick is to set the PSDefaultParameterValues for the Search-AzGraph cmdl...

Python : Exploring Objects similar to PowerShell

To be fair Python's REPL mode allows you to explore objects pretty easy. But since PowerShell has been my first language, I often tend to crib for similar experience. P.S. - I do know that PowerShell language specs picked up quite many things from Python. Also, Python is my goto language on Linux platform as well. So back to cribbing, I tend to miss most the exploring aspects of  PowerShell e.g. Get-Member and Format-* cmdlets until one day I sat down and wrote few functions in Python to give me a similar experience.

Notes on Azure + PowerShell + Account SAS

Well, below are my notes on using account Shared access signatures in Azure using Azure PowerShell modules. Theory Let's get the basics out of the way first. A shared access signature is a way to delegate access to resources in a storage account, without sharing the storage account keys. SAS gives us granular control over the delegated access by : Specifying the start and expiry time. Specifying the permissions granted e.g Read/Write/Delete Specifying the Source IP address where the requests will originate from. Specifying the protocol to be used e.g HTTP/HTTPS.

PowerShell + .psd1 files - decouple environment configuration data from code

What is environment configuration data? Well, you might have heard the term 'configuration data' in usage with PowerShell DSC. The case for using configuration data is wherein all the input arguments are abstracted from the code being written so that this configuration data can be generated on the fly and passed to the underlying scripts or framework like DSC. For some of our solutions being deployed at the customer site, we require a lot of input parameters e.g. different network subnets for management and storage networks, AD/DNS information etc. Adding all these parameters to our input argument collector script was an error prone and tedious task since there were far too many input arguments. So instead of having a file to specify all input arguments was the preferred method. This also helped us while troubleshooting the deployments since a local copy of the input arguments always persisted.

PowerShell + AzureRM : Using Certificate based automated login

This is a long overdue post (previous one here ) on how to use certificates to do an automated login to A zure R esource M anager. Not rocket science but easy to setup, so that you use a cert to authenticate to Azure RM automatically. It seems the Azure docs are already up to date on how to do few bits involved in this, please read the section ' Create service principal with a certificate ' in the docs. The process is almost the same as mentioned in the docs, except the fact that when we do the role assignment, we instead assign the contributor role definition to the service principal, since we want the ability to manage the resources in Azure RM. Also, we will author a function add it to our profile so that PowerShell authenticates automatically to Azure RM each time it opens.  So let's begin with it: Create the self-signed certificate. If you are running this on Windows 8.1, then you have to use the script by MVP Vadims Podans from the gallery. ...

PowerShell : Trust network share to load modules & ps1

Problem Do you have a central network share, where you store all the scripts or PowerShell modules ? What happens if you try to run the script from a network share ? or if you have scripts (local) which invoke scripts or import PowerShell modules stored on this network share ? Well you would see a security warning like below (Note - I have set execution policy as 'Unrestricted' not 'bypass' here): Run a .ps1 from the network share Well this is a similar warning, which you get when you download scripts from Internet. As the message says run Unblock-File cmdlet to unblock the script and then run it, let's try it.

Vagrant using Hyper-V

I have been looking at learning puppet for a while now and to try it out, wanted to quickly deploy a puppet master & node (Ubuntu) on top of my Hyper-V host. Below are the quick & easy steps I followed mostly for my own reference (n00b alert) : Enable Hyper-V on the node, this goes without saying :) (reboot after this step). 001 002 003 004 #region enable Hyper-V                                                                         Add-WindowsFeature   -Name   Hyper-V   -IncludeAllSubFeature   -IncludeManagementTools #endregion Install Vagrant using chocolatey. 001 002 003 004 005 #region install vagrant Import-Module   PackageManagement                      ...

PowerShell + Pester : counter based mocking

Recently, I have been writing/ reading a lot of Pester tests (both Unit and Integration) for infrastructure validation. One of the classic limitation hit during mocking with Pester is that you can have different mocks based on different arguments to a parameter (e.g using parameterFilter with Mock ) but not based on a counter. For Example - See below, I have two mocks for Get-Process cmdlet based on the name passed to it. Mock   -CommandName   Get-Service  -ParameterFilter   { $Name   -eq   'winrm' }   -mockwith   {[PSCustomObjet]@{Status='Running'} } Mock   -CommandName   Get-Service   -ParameterFilter   { $Name   -eq   'bits' }   -mockwith   { [PSCustomObjet]@{Status='Stopped' } This is really helpful, but there is a case where we want different mocks to occur based on a an incremental counter (number of times) a function/Cmdlet etc. are called in our script.

PowerShell : check script running on nano

If you are authoring scripts targeting Nano server specifically then there are two checks which you can bake into (maybe add them to the default nano authoring snippet in ISE) them.

PowerShell + AzureRM : Automated login using Service Principal

Do you remember ? In the older Azure Service Management model, we had an option to import the publish settings file and use the certificate for authenticating. It saved a lot of hassle. That method is deprecating now but we have something better which we can use in the newer ARM model. BTW for record I find it really annoying to enter credentials each time when I want to quickly try something out on Azure. So I have been using two techniques for automated login to the AzureRM portal. Storing Service principal creds locally (encrypted at rest using Windows Data Protection API) and using that to login. Using Certificate based automated login .

Test connectivity via a specific network interface

Recently while working on a Private cloud implementation, I came across a scenario where I needed to test connectivity of a node to the AD/DNS via multiple network adapters.  Many of us would know that having multiple network routes is usually done to take care of redundancy. So that if a network adapter goes down, one can use the other network interface to reach out to the node. In order to make it easy for everyone to follow along, below is an analogy for the above scenario: My laptop has multiple network adapters (say Wi-Fi and Ethernet) connected to the same network. Now how do I test connectivity to a Server on the network only over say Wi-Fi network adapter?

PowerShell : Nested Remoting (PSRemoting + PSDirect)

Well the title is interesting enough, right ? I saw some interesting comments when I posted the below pic around the release of Server 2016 TP3 in our PowerShell FB group: In this post, I try to tell how I use this simple trick in my everyday use.

PowerShell : Getting started with MutEx

After setting up the context for the use case of the MutEx in previous post, it is time to do our homework on the topic. Theory MutEx as per the MSDN documentation is: " A synchronization primitive that grants exclusive access to the shared resource to only one thread. If a thread acquires a mutex, the second thread that wants to acquire that mutex is suspended until the first thread releases the mutex. "

PowerShell : Use Case for MutEx

This post is to give you context on a practical use case of using MutEx in PowerShell. From the  MSDN documentation  for the MutEx class , MutEx is : " A synchronization primitive that can also be used for  interprocess  synchronization." Mut - Mutually  Ex - Exclusive Recently while deploying AzureStack, I saw multiple failed deployments, partly because of me not paying attention.  But since it failed, I had to go and look at the code in an effort to see what went wrong. AzureStack runs all the deployment tasks for creating a POC by using scheduled tasks (runs in System context) heavily. Also the status of the deployment  is tracked by using XML files (these are placed under C:\ProgramData\Microsoft\AzureStack\), so they have to avoid conflicts in reading and writing of these XML files from these tasks which are separate PowerShell processes.

PowerShell : Retry logic in Scripts

One of my projects required me to copy a CSV file (important step) to a VM running on Server 2012 R2. I’ve found this excellent tip by Ravi on using Copy-VMfile cmdlets in Server 2012 R2 Hyper-V . To use this cmdlet, I had to enable " Guest Service Interface " component in the Integration Services (below is what documentation says about the service). This new component in the Integration Services allows copying files to a running VM without any network connection (How cool is that?). The tip mentioned earlier talks about how to enable the component using Enable-VMIntegrationService, but there is a delay between enabling the component and successfully using the Copy-VMfile cmdlet.  So how do I go about making sure that the service is running before the cmdlet is issued, or keep retrying the cmdlet until it succeeds ?

PowerShell + SCCM : Run CM cmdlets remotely

Today I saw a tweet about using implicit remoting to load the Configuration Manager on my machine by Justin Mathews . It caught my eye as I have never really tried it, but theoretically it can be done. Note - The second tweet says "Cannot find a provider with the name CMSite", resolution to which is in the Troubleshooting section at the end.

PowerShell + SCCM : WMI Scripting

Why should I use WMI, when there is a PowerShell module available for Configuration Manager (CM Module) already? Well the cmdlets behind the scene interact with the WMI layer and if you know which WMI classes the corresponding cmdlet work with , it can be of help in future by : Switching to native WMI calls when the CM cmdlets fail for some reason (probably bug in the CM Module). Making your scripts more efficient by optimizing the WMI (WQL query) calls, the cmdlet will query all the properties for an Object (select *) you can select only ones you need.  Lastly no dependency on the CM Module, you can run these automation scripts from a machine not having the CM console installed (needed for CM module). Moreover ConfigMgr uses WMI extensively, you already have this knowledge leveraging it with PowerShell shouldn't surprise you. This post assumes you have been working with CM cmdlets (you already are versed with PowerShell), know where the WMI namespace for ConfigMgr resides ...

PSConfAsia : My experience

Since it has been few weeks after PowerShell conference Asia, I have finally kicked of the laziness and made up my mind to blog about my experience around it. PowerShell Conference Asia