Jun 12, 2014

mini post - Chef (Opscode) - Simplifying Unit Testing

Saw something cool today in regards to unit testing.

Chefspec runs the first portion of your Chef run, the complication phase, but not the execution phase.

Next, it tests the resulting objects against the set of objects you defined in your unit tests. If they match, you pass. The key here is that you have all of the recipe stuff accessible to you from inside your unit tests, so you can use it to simplify your life. (where applicable, last thing you want is a set of tests that never fails)

For example, in situations where I build a string and some of the attributes are from upstream cookbooks - DNS server, Bill Gates favorite color, population of Ukraine...

So, with an attribute driven cookbook, a traditional unit test looks something like this:

Attribute:
default['download_dir'] = '/var/windows/rocks'

Recipe:
directory node['download_dir'] do
  owner "root"
  group "root"
  mode 0755
  action :create
  recursive true
end
Unit test (traditional):
it 'create directory' do
    expect(chef_run).to create_directory('/var/windows/rocks')
      .with_owner('root')
      .with_group('root')
      .with_mode(0755)
end
Unit test (simplified):
it 'create directory' do
    expect(chef_run).to create_directory(chef_run.node['download_dir'])
      .with_owner('root')
      .with_group('root')
      .with_mode(0755)
end

Now if you modify the attribute your unit test will still pass. Whether you want it or not is a whole different story, but so far it's been working much better than placing an exact string in the unit test.




mini post - Chef (Opscode) best practices series - Unit testing and TDD

The argument of TDD is great and all, but I do not think it's directly applicable to Chef.

Here is the idea - Chef offers a lot of resources, and a lot of ways to skin the cat/dog/lizard/etc.. So you simply can't write unit tests first, because you don't actually know which resources you're going to use to skin said animal.

What you CAN do, is write integration tests first. Because you DO know the ultimate outcome of your cookbook. And you can write Stubs for your unit tests ahead of time, if that makes you feel good.

Lets say you want to write a WSUS cookbook. The goal of the cookbook is to install WSUS role on your server. So your TDD (test driven development) for installing WSUS server would look something like this:
/> knife kitchen create wsus (or knife cookbook create wsus)
Your unit test would look very generic:

it 'installs some prerequisite that came with windows' do
end 
it 'downloads some prereq that didnt come with windows' do
end 
it 'installs the downloaded prereq' do
end 
etc...
Your integration tests on the other hand, would look very specific - Because you know ahead of time what constitutes a functional WSUS server.

 describe package('wsus') do
   it { should be_installed }
 end 
describe service('wsus') do
  it { should be_enabled   }
  it { should be_running   }
end 
describe port(3859) do
  it { should be_listening }
end
etc... 
IMHO, that's the best you can do when it comes to TDD with Chef. If you start with unit tests you're forcing yourself down the path of constantly re-writing your tests... over and over and over...

Here is an image of DNA relication.



May 20, 2014

Net user hidden switch

Holy moly... if only all of the internet problems were this easy to solve.

After creating and nuking 3 AWS boxes I finally broke down and regenerated the private cert. (I lost .pem file to interactively login a long time ago. Knife EC2 server create ftw!!)

Login and run my user_data script manually and get greeted with this 14 year old annoyance. Who in their right mind still runs win2k? Is it even supported?? Well, sadly we all know the answer to that question.

The password entered is longer than 14 characters.  Computers with Windows prior to Windows 2000 will not be able to use his account. Do you want to continue this operation? (Y/N) [Y]:
I nuked three boxes to find out my password was too long...

Combining last few drops of coffee with curiosity I ran the below command which to my complete and utter amazement succeeded. Half a google search later I find that this is a hidden switch in NET command... and now you know too

net user /add $user $password /yes
fyi: both /y and /yes work, and no matter how many times you type net help you wont get the answer you're looking for.

btw, here is the user data scrip:
<powershell>  #https://gist.github.com/vinyar/6735863;
  "[System Access]" | out-file c:\delete.cfg;  "PasswordComplexity = 0" | out-file c:\delete.cfg -append;  "[Version]"  | out-file c:\delete.cfg -append;  'signature="$CHICAGO$"'  | out-file c:\delete.cfg -append;    secedit /configure /db C:\Windows\security\new.sdb /cfg c:\delete.cfg /areas SECURITYPOLICY;    $user="UsernameGoesHere";  $password = "UserPasswordGoestHere";  net user /add $user $password;  net localgroup Administrators /add $user;    winrm quickconfig -q;  Enable-PSRemoting -force;  winrm set winrm/config/winrs '@{MaxMemoryPerShellMB="300"}';  winrm set winrm/config '@{MaxTimeoutms="1800000"}';  winrm set winrm/config/service '@{AllowUnencrypted="true"}';  winrm set winrm/config/service/auth '@{Basic="true"}';  winrm set winrm/config/service/auth '@{CredSSP="true"}';    netsh advfirewall firewall set rule name="Windows Remote Management (HTTP-In)" profile=public protocol=tcp localport=5985 new remoteip=any;</powershell>

Here is a random bit of awesomeness

May 9, 2014

Finding illegal characters somewhere in your chef cookbook / code

Use case:
I cant upload a cookbook / run powershell script / render web.config because something somewhere throws up on an illegal character.

One route to fix it, is to look at most critical files - web.config, json.config, README.MD and hope that the error is somewhere in there.

Well, that's one approach. About a year ago I would fire up notepad++ or BeyondCompare and look for iffy characters. It works, but it's stupid slow.

In case of Chef, the whole cookbook is processed, so theoretically the error could be anywhere. So, going through it one file at a time is just not practical. On top of that, I advocate automation, so... automation it is:

I've been learning OSX so I actually dont know the equivalent for windows, but since you dont have grep anyway, install the version that comes with -P and all is good.

brew install pcre
CD to the folder where you're breaking
pcregrep --color='auto'  -r -n "[^\x00-\x7F]" .
pcregrep --color='auto'  -r -n "[\x80-\xFF]" .

-r                              is for recursive
--exclude-dir .git      is to exclude .git from your search. You'll get a ton of hits here otherwise (not used in example above)
-n                             is to specify ascii range. Both work.

Source:
http://stackoverflow.com/questions/3001177/how-do-i-grep-for-all-non-ascii-characters-in-unix?s=4513f650-b50e-4611-8497-83fe400a3cc1

Way to test:  Grab a broken Repo and run the command to make sure you get expected broken file
Fix is here (https://github.com/stackforge/cookbook-openstack-common/commit/f4112fc77385a6044c2418f08da451aa57dfd247), so we're going to grab a pre fix commit

git clone https://github.com/stackforge/cookbook-openstack-common
git checkout 5e1a812a38c19a45b774862345f552c41836606f
pcregrep --color='auto'  -r -n "[\x80-\xFF]" .

Boom
Done

Apr 18, 2014

Post conference Rage blog - ChefConf

Having spent a week hanging out with the most genius people I've ever met, have really changed the way I look at user experience of the technology around us.

The third place goes to: Volvo
This example came from the CEO of the company during his keynote speech:
Volvo has a yearly GPS update package, which consists of 6 DVD disks, which have to be fed into the car over the course of 6 hours. AND!!! the car has to be running the whole time. Holy fucking shit, no way would a $60k+ car make you do that.

Sloppy seconds goes to: Hyatt
Preface: Hyatt has this pretty elevator system with dual factor authentication which doubles as first firewall in their customer defense system: after 7pm, you have to scan your card, AND the elevator takes you to your floor only. Neat, but mildly annoying, because card slots are small and very annoying to a drunk guy. Strike one.

That's minor though. The major flaw is that after the doors close, no new input can be added to the system. So, you're stuck riding in elevator till it stops.

And the first place goes to a Dealership:
Younker Nissan
3401 East Valley Rd
Renton, WA  98057

All of their emails come from: System Administrator ileads_Younker_Nissan@webcrmmail.adpcrm.net



... maybe not so much of user experience on that last one, but it definitely inspired this whole post. ...and now off to find a relevant XKCD post.

How about: What is Heartbleed in pictures


Feb 15, 2014

Automating WSUS 3.0 server with Powershell on Win 2k8r2

It was supposed to be easy... EASY!!!!

...this ended up being the first line that actually did anything relevant... obviously not fucking easy.
[reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration")

So this project started as usual, with a false hopes and unkept promises
PS C:\chef> Add-WindowsFeature OOB-WSUS
WARNING: Installation of 'Windows Server Update Services' is not supported on the command line. Skipping...

Oh Come on!!!!

So Step 1 - Install Pre - Reqs
"web-server", "Web-Asp-Net", "Web-Windows-Auth", "Web-Metabase", "File-Services" | foreach {if (!(Get-WindowsFeature $_)){add-windowsfeature $_}}

Step 2 - download / contribute to my Chef cookbook which will do it all for you
https://github.com/vinyar/wsus

The thing you probably really care about the most is here:
https://github.com/vinyar/wsus/blob/master/recipes/configure_wsus.rb 

Feb 10, 2014

Chef and Ruby and Gems and Windows



One of the many things in Chef ecosystem is Gems. Think of Gems as DLLs. They have versions, dependencies, and while MSFT figured this dependency hell years ago, Gems do not have that luxury.

One of the minuses is that when you install a gem, it pulls down depends, when you uninstall a gem, depends stay behind.

A - clean up unused gems
gem cleanup
B - nuke everything and start for scratch.
gem list | cut -d" " -f1 | xargs gem uninstall -aIx

C - read about bundler and track your depends in a gemfile. Each cookbook has its own gemfile. You always update your gemfile and never install gems manually

D - when your gems start complaining about missing dependencies see B

A good read:
http://shanky.org/2010/09/02/painlessly-remove-all-ruby-gems-on-windows/

Feb 6, 2014

Chef - Packer and generating images from custom ISO

If you want to develop quicker, you cant sit around waiting for your operations team to give you a server. .. and then give you another server when you destroyed it 20 minutes later. That's where you download VirtualBox, get Packer, Vagrant and go nuts.

The point of this post is to talk about packer templates you can get from GitHub. (templates have been moved into another project, but you can still get all of them for basic packer consumption from a dev branch of the same repo. Or just roll back master branch a couple of commits):
https://github.com/misheska/basebox-packer

If you want to use a ISO other than the one in a template, you'll need to specify a couple of parameters for packer, and get the SHA1 of the ISO you're using.

If you have OpenSSL, SHA1 is super easy: 
openssl sha1 c:\Images\raw\7601.17514.101119-1850_x64fre_server_eva
l_en-us-GRMSXEVAL_EN_DVD.iso
Alternatively, you can get this tool from the mothership:
http://www.microsoft.com/en-us/download/details.aspx?id=11533

Command:
packer build -only=virtualbox-iso -var 'iso_url=C:\Images\raw\7601.17514.101119-1850_x64fre_server_eval_en-us-GRMSXEVAL_EN_DVD.iso' -var 'iso_checksum=beed231a34e90e1dd9a04b3afabec31d62ce3889' win2008r2-enterprise.json

That's it. 5 minutes later you will have a brand spanking new virtual box for continuous destruction.

 ______________________________________ 
/ The best way to learn Chef is to use \
\ Chef. --Me                           /
 -------------------------------------- 
   \
    \
     \
       .--,--.          
       `.  ,.'        
        |___|        
        :o o:   O   
       _`~^~'_  |    
     /'   ^   `=)
   .'  _______ '~|
   `(<=|     |= /'
       |     |
       |_____|
 ~~~~~~ ===== ~~~~~~~~


 _________________________________________ 
/ Actually, my goal is to have a sandwich \
\ named after me.                         /
 ----------------------------------------- 
   \
    \
     \
       .--,--.          
       `.  ,.'        
        |___|        
        :o o:   O   
       _`~^~'_  |    
     /'   ^   `=)
   .'  _______ '~|
   `(<=|     |= /'
       |     |
       |_____|
 ~~~~~~ ===== ~~~~~~~~

Jan 27, 2014

Fixing AWS after upgrading to Powershell 4.0

I just got done scratching my head... After all, it's a PC, not an iPhone. I didnt think Amazon had a way to uninstall cmd-lets off my box remotely... or DID THEY!?

Well, no, they didnt. But apparently upgrading to powershell 4.0 does nuke all of the user modules, which sucks.

So. Step 1. Re-Install amazon modules (I just installed everything)
http://aws.amazon.com/powershell/  

Step 2.
Open new Powershell window and run:
Get-Module -ListAvailable
Step 3.
ImportSystemModules

Step 4. - Setup your private keys again. Oddly enough that part actually still works. So, hitting the ec2 commands works right after reinstalling cmdlets.
Set-AWSCredentials
(Get-EC2ImageByName WINDOWS_2008_BASE).imageid 

Step 5. If your creds were not carried over, or you never configured them, take a look at my earlier post
http://releaseengineer.blogspot.com/2013/09/managing-aws-with-powershell.html 

Ta-Da
You done

Jan 15, 2014

How to use same set of cookbooks with multiple Chef Servers

Simple answer is GIT. Well... probably the simple answer is to have multiple folders, each with corresponding .PEM files and configs, but then each knife.rb will have things like ../../cookbooks ../../.. and that's just too ghetto.

I assume by now you have GIT installed. If not, go install it - http://git-scm.com/
As a side benefit now you can do knife cookbook site install (instead of download)

Now you have a set of cookbooks - lets say your working directory is <somedir> and it has a few sub folders:
.chef
.kitchen (maybe, maybe not)
cookbooks
environments
roles
spec (maybe?, maybe not yet)
etc..
And you want to share them between two different Orgs - lets say, getchef.com chef server, and a private Server behind 13 firewalls and 14 VPNs..

Easy. Add your configs under source control, and setup two branches. One for each Chef server you'll be dealing with. Then you'll just check out the branch corresponding to the server config you want to use.

* Test that your current server works (knife cookbook show or knife client list)
* Go to .chef folder, or wherever your knife.rb and various settings live.
git init (initialize bare git repo)
git add . (add all files to repo)
git commit -m 'bla' (commit files to git repo)
You just placed your configs under version control in 'master' branch. YAY (*think of Dallas cheer leaders*)

Now, we will clone the master branch and configure .PEM keys and URL for the other server

git checkout -b local master (you just cloned master into local - good idea to have this as a backup of master)git checkout -b russia master (you just cloned master into russia)git checkout russia (switch to working on a specific branch)Add new .PEM files (your validator/pem may have different names.)Make changes to knife.rb (URL and if needed, file names. The rest should stay the same)Connect to the VPN's and/or whatever else. Test the new connections. (knife cookbook show)git add .git commit -m 'bbbla'

now any time you want to change which server you're working with just do git checkout local or git checkout russia. 

Boom
Done





Oct 25, 2013

Easy way to benchmark ruby code

As I was pounding away at the language I barely understand, I started thinking... which of the two approaches is faster:

A:    Let RegEx do a case insensitive search or
B:    Downcase all of the output, and let the regex run.
`auditpol /get /subcategory:\"#{@category}\"`.match(/#{test}/i)
or
`auditpol /get /subcategory:\"#{@category}\"`.downcase.match(/#{test}/)

Well, apparently there is an incredibly .. retardedly easy way to satisfy that curiosity:


 The simplest way to measure your Ruby code is with Benchmark.measure
require 'benchmark'
require 'bigdecimal/math'

# calculate pi to 10k digits
puts Benchmark.measure { BigMath.PI(10_000) }
More here: http://rubylearning.com/blog/2013/06/19/how-do-i-benchmark-ruby-code/

Just wow.... I don't think I ever had it that easy with measure object in powershell... to be perfectly honest, that object in powershell is borderline useless.

Oct 21, 2013

Managing AWS with powershell - part 3

Pure Magic...

How to get Information for all of the nodes you have with passwords and FQDS... Like this:

(Get-EC2Instance |? {$_.RunningInstance.keyname -like '<YOUR KEY NAME>'}).RunningInstance | select instanceid, PublicDnsName, IpAddress, @{Label="password";Expression={Get-EC2PasswordData $_.instanceid -PemFile '<Path to your .PEM file...C:\Bla\bla.pem>'}}, @{label="test";expression={(Get-EC2Instance $_.instanceid).RunningInstance.Tag.value}} | ft -autosize
 
Enjoy

Idempotence in Chef on Windows via WMI / Powershell - Light at at the end of the tunel

As part of writing Chef recipes, the big thing is to run code once and only once.

Well, Chef is Ruby, running on top of windows. To make things more interesting, the native wmi providers come in the form of a community GEMs.

Example:
only_if { WMI::Win32_Service.find(:first, :conditions => {:name => 'chef-client'}).nil? }

The best way to find / test WMI functionality is with Powershell... Well..Here are a few things that make life just a little easier:


1: This bad boy automatically generates WMI query in powershell. Talk about free.
http://technet.microsoft.com/en-us/library/ff730935.aspx
Download here: http://www.microsoft.com/en-us/download/details.aspx?id=24121

2: Which namespace should you use???
Powershell 3 (Server 2008+) gives you the answer for free!!!!
Example1: Get-CimClass -MethodName *bios*
Example2: Get-CimClass -ClassName *bios*


What do you get?

    NameSpace: ROOT/cimv2

CimClassName                        CimClassMethods      CimClassProperties
------------                                  ---------------               ------------------
Win32_SMBIOSMemory       {SetPowerState, R...   {Caption, Descripti
CIM_BIOSElement                 {}                                {Caption, Descripti
Win32_BIOS                           {}                                {Caption, Descripti
CIM_VideoBIOSElement       {}                                {Caption, Descripti

You get a free Powershell Query:

 

Holy Crap!! That was easy.

Sep 27, 2013

Managing AWS with powershell - part2

Passing in User Data to server create command


Interestingly enough, you have to pass userdata to new instance in a specific format. It has to start with <powershell> and end with </powershell>

..but then in gets more interesting.

You have to pass in your custom script in the Base64 format.


Converting your file to Base64

$string64 = gc .\aws-userdata.ps1 -Encoding byte
$string64_string = [System.Convert]::ToBase64String($string64)
$string64_string

Creating node with user data

New-EC2Instance -ImageId ami-monkey -MinCount 1 -MaxCount 1 -keyname monkey -InstanceType m1.medium -Verbose -UserData $string64_string 
 

Managing AWS with powershell - part 1

So, as ironic as it may be, EC2 is significantly faster and easier to use than Azure. Like.. 2 minutes vs 15 per server faster. Not only that, to get Azure powershell running, you need to download 200 megs of crap, including SQL server lite, hello kitty theme, and aol 2.5. Amazon on the other hand is a 5 meg download which includes a couple of powershell cmdlets for managing all of Amazon... it does have a few caveats.

Get your creds automated

Set-AWSCredentials 
note: http://docs.aws.amazon.com/powershell/latest/userguide/pstools-appendix-signup.html 
note: http://docs.aws.amazon.com/powershell/latest/userguide/specifying-your-aws-credentials.html 

How to get AMI name for creating a server 

(Get-EC2ImageByName windows_2008_base).imageid

How to create a server:

New-EC2Instance -imageid <ami-monkeys> -mincount 1 -maxcount 1 -keyname monkeys -instancetype m1.medium

How to get connection information for the box (or 20 boxes) you've just cooked up 

$a = Get-EC2Instance
$b = $a | ?{$_.reservationid -like "whatever is the reservation you got from new-EC2Instance"}

$b.RunningInstance | select PublicDnsName, ipaddress, privateipaddres

How to get password for the node you just made?

Get-EC2PasswordData -InstanceId $c.RunningInstance.instanceid -PemFile 'C:\Users\monkeys\monkey.pem'
or in case of multiple boxes just make a loop


With all of the above said, and as awesome as AWS is, there is a horrible horrible default which makes absolutely no sense:

help New-EC2Instance -full
-MinCount <System.Decimal?>
Minimum number of instances to launch.  If the value is more than Amazon EC2 can launch,  no instances are launched at all.
         Constraints: Between 1 and the maximum number  allowed for your account (default: 20).

-MaxCount <System.Decimal?>
Maximum number of instances to launch.  If the value is more than Amazon EC2 can launch, the largest possible  number above minCount will be launched instead.
         Constraints:  Between 1 and the maximum number allowed for your account  (default: 20).


Sep 18, 2013

Powershell - converting array output into string (OpenSSL ...)

In my specific example, I was trying to get OpenSSL output to show up as a string in the least amount of typing (this is for a class I'll be teaching), meaning each student would have to read the slide, and type what's on it. Meaning that each extra bracket of code students type, could result in some unpredictable disaster which would stop the whole class from moving forward. So, I wanted to come up with the most elegant way possible.


Example:
PS\> openssl rand -base64 512
vq6liIBbS0vy5XXUQiknc8Mw/Bzm5YwjYJKkv34wns0w7OGXcXpXN4mutLmlcJ7h
N7P8557UtZW2JPwhrh6KbrtqK6SzvQK0uZvAejt074gOS0yWkVvnQC6/y4GWpfkA
l93McZpiHB7dAUxglHWPdA2u3+wYfJMt4VkCYAFTqyDyFyRxhi9KWhRdE55OyZQz
P92tVM8Vjo7rQVroDdW/SvQTPklAzJcwbubuBCfXvENWwhcXFEOyLhjftoxSEojR
qTraYr5J6CfMs9ELedRKjEUgHeXcnarBf0BbjliDwzeVQ7DcFGeq6i4aRed4U+1X
OuH5ewOI2qqrY3sQtWnG52X2BYWhi8Bs0G6h1SVvn7LsCLO3HGjB/cyLcujYQpcv
HMw8EXXndOvSXMif/N66RjRbafn0ZNjlCB1KtdNIy8y7gPJCkf6UbJuypZGWHlnd
wktJV1L4S7kKNKyaDX+9tZoTiZhN50qTYFZ+dQ9E5ItIBxoHc5UuQvK334nm8y70
Czpq1lfj1S9CSEvkcCaMkOnZOx+mb1rPcIm4fg6pA+F10m1t4Eph4m3QLxY7H4RE
yfxsZhWbE+I/epsODOeVi3VzHzz3UuNKuA+RvLD2U8QGDgyl9DRIgKGmMaShN7oa
6+OWoKeX4spSCkFIPwuPlcLAkVSBDEIrwlAIi+9hQr8=

But what you really want is a string... The reason is, in Chef the data_bag object can be encrypted. So user names, password, data base keys are all safe and sound behind OpenSSL (pun retroactively intended). However, decrypt takes a string, and Powershell generates an array. So, I needed to convert array to string in powershell in the most elegant way possible.

I am not* going to bore you with the many failed attempts, so here is the best answer I came up with*:

PS\> -join $(openssl rand -base64 512)

Yup. That's it.

A really neat side effect, is that in every class I have a few people tell me this "join" is awesome and they had no idea it was possible.  This is why I dig what I do now.

* I didn't actually come up with the -join by itself, this dude here did: http://stackoverflow.com/questions/7723584/powershell-how-to-convert-array-object-to-string

I lied about not boring you... here are the various semi-failed attempts:

  •     [string]$(openssl rand -base64 512) -replace " ",""
  •     openssl rand -base64 512 | %{write-host $_ -NoNewline}
  •     Write-Host -Object $(openssl rand -base64 512) -Separator ""
  •     openssl rand -base64 512 | %{[string]$a+=$_}
  •     $result = $result -replace "`t|`n|`r",""
  •     ...this one is cool, but makes changes to $ofs:
              $ofs="";[string]$(openssl rand -base64 512)

Sep 16, 2013

Pushd / Popd / Powershell - let our powers combine

Simple, redefine your CD command as PUSHD

... I honestly cant believe that it just hit me now, after years of using powershell... this is just brilliant. I am a genius*!!!

remove-Item alias:cd
new-alias cd pushd

..and now any just fire off POPD any time you want to go back.
...and now that you're absolutely in love with this, you will never go back, so go ahead and make it a part of your profile

"remove-Item alias:cd;new-alias cd pushd" |out-file $profile -append


MAGIC!!!

unrelated image:

*pending scientific study

Sep 6, 2013

Chef / Ruby... What editor to use?

Well... I've been living in the powershell world for the last few years, and writing Chef recipes (Ruby) has blown the lid off my teapot.. the number of brackets and commas, is borderline absurd.

Sublime to the rescue (it's totally free - minus one annoying occasional popup)
http://www.sublimetext.com/

Single best feature of the tool is bracket / comma / braces / etc.. auto completion.

I've switched to Sublime exclusively for Ruby, but still using Notepad++ for Powershell... however! Today I was referred to two excellent plugins which look VERY promising:

https://github.com/n1k0/SublimeHighlight (Export highlighted code into RTF or HTML - great for Demos)

and https://github.com/SublimeText/PowerShell (Syntax highlighting for powershell in Sublime)

A simple installation doc:


Completely unrelated image of the thing I'm building..Sous Vide Heating Immersion Circulator
DSC_0041

Aug 26, 2013

Three hints for Active Directory

1: How to get distinguished name through powershell from a computer without using Active Directory module


$filter = "(&(objectCategory=computer)(objectClass=computer)(cn=$env:COMPUTERNAME))"
([adsisearcher]$filter).FindOne().Properties.distinguishedname

Compliments to Shay: http://stackoverflow.com/questions/11146264/get-current-computers-distinguished-name-in-powershell-without-using-the-active


2: How to get Domain controller to see Security Policies.

Apparently, as part of the design, AD will not see security properties from it's own GPO unless they are defined at the global scope.

Which mean, if you're trying to lock down AD to some security spec, such as CIS, you'll have to define hardened policies at the global scope. If you dont want your nodes to be as locked down as the AD, you'll have to enforce the GPO with relaxed settings at the node OU to overwrite global.

A bit of a headache if you ask me.... especially since it took me nearly a day and a half to find an answer.
http://support.microsoft.com/kb/259576


3:  Exposing MSS settings (some hardening specs such as CIS calls for it)

Note: You can edit GPO from any server where GPMC is installed, so this tool can be installed on any 2k8 server in the domain (no reason to clutter up the AD).

* Install Security Compliance Management Toolkit.
(http://www.microsoft.com/downloads/details.aspx?FamilyID=5534bee1-3cad-4bf0-b92b-a8e545573a3e&displaylang=en)
-- the installer will probably fail to work...it's probably by design.

* Install SQL express manually. Use any version.
* Re-run Security Compliance Management Toolkit installer.
* Click the Start, click All Programs, Microsoft Security Compliance Manager, Local GPO.
* Install LocalGPO.MSI
* Go to the folder where you installed the MSI (default is C:\Program Files (x86)\LocalGPO) and
* From Administrative command prompt run: cscript LocalGPO.wsf /ConfigSCE and then press ENTER.
* Open GPO editor
* Navigate to Computer Config -> Policies -> Windows settings -> Security Settings -> Local Policies -> Security Options

BOOM MSS is now visible.



Aug 5, 2013

Subduing sublime - moving out of quotes with ease

Yet another entry shamelessly stolen from another blog.

I just started using Sublime and I really dig the bracket and quote auto completion, but it immediately became apparent to me, that it pisses me off as much as it helps me. There is no really good way to move out of the brackets without either typing them out - which defeats the purpose of auto completion in the first place, using arrow keys, using end key, or god forbid using the mouse.

The only built in functionality is control+enter which gets you a new line - not something you want every time.

The answer is to create your own key binding - below example gets you out of all kinds of brackets (the kind I use at least) and gives you a good template for setting it up for your own use.

For practice I setup 2 keys to do same thing: Tab and Enter. Might end up changing it later, or making it Shift+Enter or something


Preferences > Key Bindings -- User



{ "keys": ["enter"], "command": "move", "args": {"by": "characters", "forward": true},
  "context":
  [
      { "key": "following_text", "operator": "regex_contains", "operand": "^[})\\]'\"]", "match_all": true },
      { "key": "preceding_text", "operator": "regex_contains", "operand": "[{(['\"]", "match_all": true },
      { "key": "auto_complete_visible", "operator": "equal", "operand": false }
  ]
},
{ "keys": ["tab"], "command": "move", "args": {"by": "characters", "forward": true},
  "context":
  [
      { "key": "following_text", "operator": "regex_contains", "operand": "^[})\\]'\"]", "match_all": true },
      { "key": "preceding_text", "operator": "regex_contains", "operand": "[{(['\"]", "match_all": true },
      { "key": "auto_complete_visible", "operator": "equal", "operand": false }
  ]
}


Plug goes out to: http://www.codejury.com/fixing-some-of-sublime-texts-annoyances/