Generating Azure Storage Tokens On the Fly With PowerShell

As I talked about in last week’s blog post, it’s important to ensure that files that you store in blob are secure from public eyes. But how do you allow your automation to access them when needed? That’s where a Shared Access Signature (SAS) token comes into play.

A SAS token is essentially an authorized URI that grants the person or object using it rights to access the object that you are otherwise concealing from the world. You can specify the amount of time that the URI is valid for; the protocol that is allowed; and the specific permissions to the object (read, write, delete). Once the time has elapsed, the URI is no longer valid and the object is not accessible.

Let me show you how this works!

After we’ve logged into Azure and set the appropriate subscription context, We need to get the resource group and storage account that our blob object lives in:

PS BlogScripts:> $StorageAccount = Get-AzureRmStorageAccount -ResourceGroupName 'nrdcfgstore' -Name 'nrdcfgstoreacct'

Once you’ve got your storage account, we can then acquire the storage account key, like we did in our last blog.


$StorageKey = (Get-AzureRmStorageAccountKey -ResourceGroupName $StorageAccount.ResourceGroupName -Name $StorageAccount.StorageAccountName)[0]

And then once we have our key, we can get the storage context and access our container:


$StorContext = New-AzureStorageContext -StorageAccountName $StorageAccount.StorageAccountName -StorageAccountKey $StorageKey.Value$Containers = Get-AzureStorageContainer -Context $StorContext -Name 'json'

And now we can get our object inside of the container:

 $TargetObject = (Get-AzureStorageBlob -Container $Containers.Name -Context $StorContext).where({$PSItem.Name -eq 'AzureDSCDeploy.json'})

And finally, we can get our SAS Token URI. Note, that I’m using HTTPSOnly for the protocol, r (Read-Only) for the permission, setting an immediate start time, and then limiting the time allowed for one hour with the ExpiryTime parameter. This ensures that the object will only be accessible for an hour after the command is run via HTTPS.


$SASToken = New-AzureStorageBlobSASToken -Container $Containers.Name -Blob $TargetObject.Name -Context $StorContext -Protocol 'HttpsOnly' -Permission r -StartTime (Get-Date) -ExpiryTime (Get-Date).AddHours(1) -FullUri

So by comparison, if I tried to access the direct URL of the object, this is what I’ll get:

However, with my SAS Token URL, I can successfully read the file:

And we’re done!

“So where is this useful in automation?” you may ask. Well I’ll be showing you exactly how next week when we take the code that we’ve built for the last couple of weeks and use it to deploy an Azure template via Azure automation.

See you then!

Managing Azure Blob Containers and Content with PowerShell

I do a lot of work in Azure with writing and testing ARM templates.  Oftentimes I deal with a lot of parameters that need to access resources existing in Azure.  Things such as Azure Automation Credentials, KeyVault objects, etc.  To streamline my testing process, I’ll often create an Azure runbook to run the deployment template, pulling in the necessary objects as they’re needed.

Of course, this requires putting the template in a place that’s secure, and that Azure Automation can easily get to it.  This means uploading my templates to a location, and then creating a secure method of access.  This week, I’ll show you how to do the former process – with the latter coming next week.  Then later on, I’ll be walking you through how to create a runbook to access these resources and do your own test deployments!

First, let’s log in to our AzureRM instance in PowerShell and select our target subscription.  Once we’re done, we’re going to get our target resource group to play with and the storage account.:

$Subscription = 'LastWordInNerd'
Add-AzureRmAccount
$SubscrObject = Get-AzureRmSubscription -SubscriptionName $Subscription
Set-AzureRmContext -SubscriptionObject $SubscrObject

$ResourceGroupName = 'nrdcfgstore'
$StorageAccountName = 'nrdcfgstoreacct'

$StorAcct = Get-AzureRmStorageAccount -ResourceGroupName $ResourceGroupName -Name $StorageAccountName
 Now that we have our storage account object, we’re going to retrieve the storage account key for use with the classic Azure storage commands.
$StorKey = (Get-AzureRmStorageAccountKey -ResourceGroupName $ModuleStor.ResourceGroupName -Name $ModuleStor.StorageAccountName).where({$PSItem.KeyName -eq 'key1'})

I know it’s not the most intuitive thing to think of, but if you take a look, there are currently no AzureRM cmdlets for accessing blob stores.  What we can do, however, is use the storage key that we’ve retrieved and pass it in to the appropriate Azure commands to get the storage context.  Here’s how:

Let’s go ahead and log in to our Azure classic instance and select the same target subscription.    Once you’re logged in, you can use the New-AzureStorageContext cmdlet and pass the storage key we just retrieved from AzureRM.  This allows us to use the AzureRM storage account in the ASM context.

Add-AzureAccount

$AzureSubscription = ((Get-AzureSubscription).where({$PSItem.SubscriptionName -eq $SubscrObject.Name}))
Select-AzureSubscription -SubscriptionName $AzureSubscription.SubscriptionName -Current

$StorContext = New-AzureStorageContext -StorageAccountName $StorAcct.StorageAccountName -StorageAccountKey $StorKey.Value
Now that we have a usable storage context, let’s create our blob store by using the New-AzureStorageContainer cmdlet with the -Context parameter to get at our storage account:
$ContainerName = 'json'
Try{

$Container=Get-AzureStorageContainer-Name $ContainerName-Context $StorContext-ErrorAction Stop

}

Catch [System.Exception]{

Write-Output ("The requested container doesn't exist. Creating container "+$ContainerName)

$Container=New-AzureStorageContainer-Name $ContainerName-Context $StorContext -Permission Off

}

I decided to write this as a Try/Catch statement so that if the container doesn’t exist, it will go ahead and create one for me.  It works great for implementations where I might be working with a new customer and I forget to configure the storage account to where I need it.  Also, if you notice, I’ve set the Public Access to Private by setting the Permission parameter to Off.  Once again, a little counter-intuitive.

Now, if our script created the blob, we’ll be able to look at the storage account in the portal we’ll see that our container is available:

But we’ve also captured the object on creation, which you can see here:

So now that we have our container, all we have to do is select our target and upload the file:

$FilesToUpload = Get-ChildItem -Path .\ -Filter *.json
ForEach ($File in $FilesToUpload){

Set-AzureStorageBlobContent-Context $StorContext-Container $Container.Name-File $File.FullName-Force -Verbose

}

And we get the following return:

Now that we’ve uploaded our JSON template to a blob store, we can use it in automation.  But first, we’ll need to be able to generate Shared Access Signature (SAS) Tokens on the fly for our automation to securely access the file.  Which is what we’ll be talking about next week!

You can find the script for this discussion on my GitHub.

New Year’s Resolutions and Why They’re Horrible

I was chatting with my personal trainer a couple of days ago and noted how I was surprised that the gym was so empty the day after the biggest resolution making day of the year. He noted to me that a lot of people take this week off, but the next week was going to be overloaded. Fortunately, I’m booked in my time slot for a couple of months out, but it got me thinking about New Year’s resolutions and why they’re such a bad idea.

Everybody does it. At some point in your life you’re going to make some kind of resolution to quit smoking or lose weight or something that feels like a lofty goal. You might go to the gym, or pick up a pack of nicotine gum, do it for a few days. Most often, you have a bad day and pick up a pack of cigarettes, or come home super tired and decide you’ll skip the gym for a day, and then settle into your bad routines again.

I’m not chastising anyone for doing this because I’ve been there. I’ve done it. But if you’ll humour me for a few thousand words, I can share with you what I’ve done, and maybe it’ll help you stick to a program. Programming being the key word.

Routines Are Hard, Horrible, and Necessary

Humans are creatures of routine, not habit. Interrupt our routines and we might as well be wearing a blue screen of death on our foreheads. We can have a small panic attack if our routine has been interrupted. Habits are things that we do in our established routine. Habits can be exceptionally easy for usto pick up, but are also easy to change.

Why do we eat too much food, or things that are bad for us? Habit. When are you eating the food? That’s routine. Why do we have to have that coffee at exactly 9AM with a particular co-worker? Routine. Why do we need to have a cigarette at a certain time of day? Routine.

Are you seeing my point here?

How do we change this? Change the habit, but keep the routine. How? Well this is a longer answer.

Smoking

I used to smoke about three packs of cigarettes a day back in my aircraft mechanic days. Back then, of course, smoking laws were a little bit more lax, and so were our managers. As long as we weren’t having a smoke while we were leaning on a bottle of oxygen, or while refueling a plane, our supervisors didn’t really care. If we could work and smoke at the same time and not blow anything up, we were golden.

Times changed and I started working in the office, but I still had the habit. I’d sneak out between meetings for a quick smoke. Feed the beast, and get right back to work. I quit when I got married, a thing by necessity, but I still quietly yearned for a cigarette, having one occasionally during a night of drinking. When I separated, the first thing I did was head to the local store and pick up a pack of smokes. The habit restarted.

When I started dating again, this of course became problematic. The musky smell of burnt tobacco apparently has the same appeal to someone in their late 30’s as Axe Body Spray. I knew from my previous experience that I couldn’t just quit cold turkey. I needed an alternative. So I took up vaping.

There’s a lot of conflicting information out there about it, and I highly encourage you to read on what you can. I’m not here to push my opinion on what study is valid and what the news is saying. What we can all agree on is this – if you’re smoking, you are doing irreparable harm to your body. My take is essentially this: If you’re going to kill yourself slowly, you might as well at least smell better doing it.

If you decide that it’s time to put away the cigarettes, then vaping is a good way to go about doing it. Why? Because you’re replacing the habit while keeping the same routine. I went to a vape shop and consulted with a sales rep. Told them what my daily habits were and they recommended a nicotine strength. That was about four years ago.

Now? I still vape, but I don’t use nicotine in my liquids. It was a long road of whittling it down, but I was able to get to zero. I still vape out of habit and have my routine set accordingly, but at least I’ve managed to knock at least one (and probably a ton more) toxins out of my body and smell a lot more appealing to my partner.

Truth be told, I feel a lot better doing it too. I don’t cough up a lung full of greenish, brownish stuff first thing in the morning while I shower. I can take a brisk jog up a flight of stairs without wishing I was dead at the top. Overall, I would call that a win. I actually find myself vaping less now that I work almost exclusively from home too, but that’s a blog for another time.

Weight Loss

Listen, I know what it’s like to gain massive amounts of weight. Let me share with you a little graphic of my journey.

Drastic, eh? In high school I was about 165, and while I wore a lot of loose fitting clothing, I was pretty well built. At my worst, I had ballooned up to 280 lbs. And that picture of me on the far right is right about where I’m at now. Probably about 15lbs heavier actually than my current weight. I’m at about 197 right now, and I fully intend on getting to 165 with the final goal of settling on about 185.

I can make excuses all day long about why I got so heavy, but none of it matters. What does matter is that I was that size, and I hate it. Hate is actually a very powerful motivator in fact. So what did I do about it? I changed the habit, but kept my routine. I added some things, like tools to the mix to help track and fix what I was doing. But more importantly I fixed what I was putting in my body. So what did I do?

  • Before you diet, get an app.
    • I use an app called Lose It! (#NoSponsor #NotAnAd). At first, I just used it to track what I was eating and more importantly, how many calories I was taking in. There are a lot of apps that will have assigned calories for foods, including dishes you get at major restaurants. The app I use can actually read barcodes and let you set the serving size you consumed.
  • Get the 2500 calorie “recommendation” out of your mind.
    • Everyone is different. Every body is different. Even if you’re taking in 2500 calories a day, can still gain weight, or maintain an overweight state. If you’re in an office job, more than likely you aren’t moving around very much and therefore aren’t burning the calories. After you’ve tracked your diet in the app for a couple of weeks,
    • Talk to your doctor about what an appropriate amount of weight loss per week looks like. They might direct you to a dietitian. That’s fine, go with it. With your data in hand and a plan, you can appropriately set the amount of calories per week a healthy weight loss will be.
    • Example – I used to sit on my butt all day at a desk and not moving around. Furthermore, my caloric intake was closer to 3000 calories a day. My doctor and I were able to plot out my caloric intake needed to maintain a weight of 185 lbs. And then figure out what would be needed to lose a pound a week from that point. Have doubts on the process? Refer to picture above.
  • Don’t set a weekly loss goal – set an overall goal. Make it a year or two out.
    • You are going to lose a ton of weight fast – in the beginning. As you lose the fat, and your caloric intake starts to line up closer to what you should be getting at your target weight, you’ll taper off. That’s fine as long as you’re losing it. If you set too aggressive you won’t follow it.
  • If you have a spouse/family, get their support and participation.
    • This is going to be crucial. If you have family members that insist on keeping things like cookies, candy, or ice cream in the kitchen, it’s going to be that much harder on you.
  • Go to the fridge and throw everything out.
    • Seriously. Having food available to eat means you’re going to eat it. Consider going grocery shopping twice or three times a week. I realize this is an addition to the routine, but having a large mass of food at the beginning of the week means you’ll have more temptations to snack on when you do. Maintaining a lower amount of food in the fridge with fewer snacking options goes a long way to keeping your hands off.
    • I’m single, so this makes things exceptionally easy. I only have a few meals worth of food at a given time. I actually caught myself just last night getting up and rummaging through the cupboards looking for something to munch on. I was a little unhappy last night that I didn’t, but much happier this morning when I weighed in.
    • You can also replace certain foods with other lower calorie options. There are ice creams out there now where you can eat the entire pint and it’s only about 340 calories. I myself enjoy a nice Cherry Coke Zero on occasion. We can talk about aspartame later. If something sweet is in your routine, replace it with that.
  • Get a scale. Weigh in twice a week.
    • Weighing in daily is also going to frustrate you. Some days you might lose a pound, others you’ll gain a half a pound. Let the averages take over. Also, weigh in first thing in the morning before you take a shower or consume anything.

Going to the Gym

Everybody talks about going to the gym. Truth be told, I’m one of those people. Why doesn’t it work? It’s because it introduces a major impact to our daily routines. Taking an hour or two a day to go someplace new and do more work can create a lot of stress in our lives. Moreover, humans work better in daily routines, and who has time for that noise?

If you’re going to make the commitment, you need to put a carrot on it. I did with a personal trainer. Paying to have someone yell at you if you don’t show up for your scheduled workout might sound dumb, but it works – and a good personal trainer will do exactly that. They’re being paid not just to show you how the machines work and what routines you should be doing; but they are also there to encourage you, and help you establish your routine.

So how did I get started? Here goes.

  • Find the right time.
    • I am not a nice person at 4AM. So getting up that early to workout doesn’t work for me. Likewise, at the end of the day, I sometimes just want to be a vegetable. Since I’ve started working from home exclusively, I’ve scheduled a time in the middle of the day to head to my local gym and workout with a personal trainer. It provides a good break between tasks in my day, helps me clear my head, and prepares me for my afternoon work. If you have the flexibility to do this, I highly recommend it.
  • Pay the money for a personal trainer.
    • Yes, there’s a cost to that. But having someone to call you up and yell at you can be beneficial. If you can’t afford to have a trainer long term, at least get a short term package deal. They can at least get you started on the right path to do what you need to.
  • Go every day.
    • You don’t have to lift every day. As a matter of fact, a lot of trainers will tell you to do your training two or three times a week. On the off days, go to the gym and get on a bike or an elliptical or something to solidify the gym as a daily routine. If you’re skipping days, it’s way too easy to just stop going.

Again, these are things that worked for me. Your body is different. You have different needs. The important thing is that you recognize that habits can be changed far easier when you maintain your established routine. Experiment!

New Year’s resolutions aren’t important, and most oftentimes are made with quite a bit of cynicism. If you really want to change, you need to plan, and that’s probably best done without consuming mass quantities of alcohol first.

Trust, Expectations, and Working From Home

More and more these days, I’ve been seeing some interesting conversations on social media outlets such as LinkedIn regarding work from home policies. Oftentimes these conversations are in reaction to shared articles such as this one from Forbes, or this article from Inc.

I’m a very big proponent of the work from home model for a myriad of reasons, many of which are covered in the aforementioned articles, so feel free to read through them. But right now, I’m much more interested in talking about a particular reaction to these posts that I see quite frequently regarding trust. Most of the comments I’ve seen can be boiled down to this:

“How can I trust that my employee is doing their job if I can’t see them?”

Trust vs. Expectations

Trust is almost analogous to faith. I trust that my best friend won’t get a pile of speeding tickets or in an accident if they borrow my car. I trust that my partner won’t go blabbering about my private comments to our friends.

Why do I trust them in this? Because we’ve built a rapport over time and built a relationship that establishes this trust. I have no real evidence that they won’t do those bad things, but because I’ve known them for a period of time, I can have faith that they won’t do them.

It’s understandable, as creatures who rely on positive interpersonal relationships, that we want to trust the people that we work with or for. Trust is part of what makes a good team. And a trust that is broken between co-workers can have serious effects on providing a good product to customers – both internally and externally. But when we hire someone to a position, it isn’t because we trust that they’re a good worker – we hire them because we expect that they can do a particular job.

I expect a co-worker will perform the tasks that are assigned to them, regardless if they work above, below, or alongside me in the reporting structure. Likewise, I have tasks that I need to perform, and my co-workers expect that I will accomplish what is necessary to achieve the end goal.

So the question you should ask yourself is simply, “does the person in question meet the required demands within the deadline assigned?” If the answer is yes, then the question of whether or not you ‘trust’ an employee becomes moot. They do the job.

Another comment that I frequently see is, “I’m worried that my employee is going to spend the majority of their day playing Xbox or PlayStation and not actually working!” This one actually makes me giggle a little bit inside for a few reasons.

First, if you’re employee is meeting your expectations of delivering quality work in the time allotted, then why is this a question? Second, if it takes them two hours out of the day to accomplish the work, and they’re playing their preferred gaming console for the other six, then you are failing to leverage your assets effectively. The only difference is that if you are doing so with them in the office, they’ll replace video games with Facebook or something else they can do from their computer.

The Solution Is Easy and Manageable

Any good manager should understand, at least fundamentally, what their employee’s job is and what they need to do to get the job done. With this information in hand, you can not only set those expectations, you can measure the results.

Those expectations should include how much time the employee expects that the work will take to accomplish. If those tasks aren’t filling out their 40 hours, then you can assign additional tasks. If you don’t have any tasks to assign, there should be no problem in allowing the employee some idle time – in or out of the office – to allow them to blow off some steam. If something comes up and that employee has the idle time, then you have flexibility in your team to accomplish those unforeseen tasks and avoid overtime.

Pure, plain, and simple. You don’t trust an employee to do a job; you expect them to. If your employee isn’t meeting those expectations, then that’s a problem that can be solved by coaching, education, or dismissal. Where they work from isn’t important – it’s whether or not they get the job done that does.