tech.guitarrapc.cóm

Technical updates

PowerShell Desired State Configuration for DevOps and ALM practitioners の公開とConfig as Code

先日、Visual Studio ALM Rangers から、表題のガイダンスが公開されました。

https://vsardevops.codeplex.com/releases/view/132181

Microsoft を含む ALM Rangers が公開したこの資料は、Windows において PowerShell DSC を利用した Config as Code がDevOps に果たす役割を具体的に、シナリオをもって細かに説明しています。

その内容は多岐に渡っており、これまで公開されてきた資料の中でも格別の質とボリュームを誇っています。

  • Config as Code がなぜ求められるのか
  • Pushとは
  • Pullとは
  • 具体的なDSCリソースの開発フローとチェックリスト*1
  • 中小規模環境でのDSC
  • 守るべきこと
  • よくある質問 ー File Serverと共有カスタムリソースをゼロから完成させる流れ詳細
  • DSC を使った TFS 2013 のデプロイ
  • PowerShell Scripting の Good Practice*2
  • リソースのコードサンプル

無料で読めることが信じられないぐらいに密度の濃い内容となっています。

@ITに以前寄稿した、PowerShell DSC の基礎記事から、発展、実践的な内容となっています。

今回はこの資料の内容をさくっと見るとともに紹介したいと思います。今のうちに言っておきます「長い」です。

目次

v1.0 - PowerShell DSC for DevOps Guidance のダウンロード

リンクからダウンロードが可能です。

https://vsardevops.codeplex.com/releases/view/132181

PDF サンプルコードとポスター
https://vsardevops.codeplex.com/downloads/get/904896 https://vsardevops.codeplex.com/downloads/get/904897

ライセンス (Page 2 of 77)

本資料は、 Creative Commons Attribution 3.0 License. としてラインセンスされています。

以下の通り、Microsoft はこの資料の内容はインフォメーション目的のみであり、なんの保証もしていないことには留意してください。

今回の記事も、資料からの引用はしますが、簡単な要約程度でその改変はしませんし引用箇所を明示します。

The information contained in this document represents the current view of Microsoft Corporation on the issues discussed as of the date of publication. Because Microsoft must respond to changing market conditions, you should not be interpret this to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information presented after the date of publication.

This document is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED, OR STATUTORY, AS TO THE INFORMATION IN THIS DOCUMENT.

Microsoft grants you a license to this document under the terms of the Creative Commons Attribution 3.0 License. All other rights are reserved.

2014 Microsoft Corporation.

序文 (4 of 77)

序文において、DevOps に関して改めて述べています。

The DevOps concept focuses on how to build deep integration between Development and Operations, organizations who have historically been at odds. This has been brought about, in part, by the need to increase the velocity of delivery from development into production, while ensuring that the Production environments are always running.

その上で DsvOps を達成する上で発生する問題点に触れています。

One of the big problems to solve is ensuring that everyone is working with the same processes, systems, and tools, throughout the product development and delivery cycle.

Dev視点で見たときに、本番への変更前に同じ構成の開発環境でのテスト、同じ自動化が適用されること。

The Development team needs to know that changes they deliver to Operations will work in Production, so they need to develop and test their changes in environments that match Production systems. The same automation scripts Operations use in Production should be used in the early test VMs and pre-Production test labs. Any changes to the system that were required by the Developers would be made in the automation scripts directly, and included with their updates. Those scripts then document the modified environment, improving the ability to review changes with the Operations team before they would be applied.

Ops視点で見たときに、本番にデプロイされたものが正常に動いているのかを知る必要性、システムの自動構成から、本番での適用の自動化とシンプルにすることによるエラーの低減、さらにはロールバックまで。

The Operations team needs to know that what they are deploying has already been proven to work in Production, or spend critical time re-validating changes during “outage windows”. Automating system setup and configuration is not new, but historically the scripts were monolithic, requiring the Operations team to modify the core code when moving from test labs into Production. Separating the actions in the automation code from the environmental data (such as server names & accounts) simplifies the updates, and reduces the risk of error.

In addition, by restricting changes to what is in automation scripts, updates can be validated in advance, rolled back if something bad occurs, and all common systems can be ensured to be consistent.

PowerShell DSC が求められるのは、まさにこの視点で立った時です。PowerShell の言語拡張として、関数をベースにして、繰り返し実行、構造化された構成、そして環境によるデータを扱うことを念頭に置かれています。それぞれが、Resource、Configurations、ConfigurationDataとよばれるもので、これまでとは違う新しいスクリプティングといえます。

The development of PowerShell Desired State Configuration (DSC) was based in part on these requirements. PowerShell DSC is a set of extensions to the PowerShell language that enable creating PowerShell functions that are repeatable, and by design scripts into are separated into components for repeatable actions, structural configuration, and environmental data. In PowerShell DSC, the separate components are called Resources, Configurations, Configuration Data. This separation of action from structure from data is a new way of scripting, and requires changes in thinking.

PowerShell is new to most Developers, and the style of coding is new to experienced PowerShell users.

DevOps と DSCについて

個人的な感想を抜きにすると、客観的にみてそれなりにずれていないと思います。このDevとOps の区別自体に疑問は抱きますがそれは本質ではないので省きます。

実際に、DSC が求められる概念としては上述の通りでしょうが、現場ではそんなことではなくもっと差し迫った問題がありました。それは、1回きりの適用ではなく、ずっとその状態を維持したい時にどうやってあるべき状態を保証するかということです。

例えば、Linux において、サーバーがあるべき状態になるようにしようと思った場合、個別に簡単な Shell Scriptを書いて、cron で回しますか?違いますよね、ふつーにChef を使うでしょう。自分だけであっても、Chef Solo という手段があります。

しかし Windows ではそうも言ってられなかったわけです。DSCの前から Chef がWindows をサポートをしていましたが、仕組みとしてあるのはいいですが存在すら知られず、その内容もテキスト処理をしたもので扱いにくいという印象がぬぐえませんでした。あるいは、Rubyを検討すらできない環境では、バッチファイル(cmd) や PowerShellスクリプト (.ps1) を個別にタスクスケジューラで回していたという方も多いでしょう。*3。valentia なら一台の管理サーバーでスケジューリングして、全台に定期的に実行することで DSC PUSH に似た環境を作ることができましたが、構成を維持する仕組みを提供することはなく、ただ利用して似たようなことができるだけでした。

いずれも、その程度が Windowsにおける現実だったのです。さいてーさいあくですね。

これがDSC の登場で変わります。DSC PULL を使うことで、ノードの作成時に指定した特定の構成を見るように構成したいノードに指示するだけで、DSCサーバーで記述、生成したあるべき状態にしなさいよという指示をノードが自動的に取得しにきます。あるべき構成の指示書を取得したら、ノードは自分自身を指示書通りに自動的に構成し、勝手にスケジューリングしてサーバーの指示通りに構成を維持します。

スケジュールも定期実行も考えなくてよく、あるべき状態も宣言的に記述が可能になりました。環境に依存することも小さくなり、バッチファイルをばらまいたりする必要もありません。リソースを書いたり利用することで、自由に構成も可能になりました。

Windows に、Chef と同等に、あるいはChefからも使える Platform として Configuration Managementができたのです。だから DSC を使うべきなのです。

DSC は今、WindowsだけでなくLinuxなどクロスプラットフォームでの動作 を目指しています。当初から CIMをベースにすることで Windows だけでない実行を想定していたように思えます。PowerShell 自体が CIMに移行しており、クロスプラットフォームを想定されています。

現実にWindows に求められてきた Configuration Management。ツールレベルではなく、プラットフォームレベルで、OS標準としてサポートすることに、DSCの真の価値があります。*4

Introduction (6 of 77)

ここで Visual Studio ALM Ranfers について説明がありますので引用しておきます。

Visual Studio ALM Rangers

The Visual Studio ALM Rangers are a special group with members from the Visual Studio Product group, Microsoft Services, Microsoft Most Valuable Professionals (MVP), and Visual Studio Community Leads. Their mission is to provide out-of-band solutions to missing features and guidance. A growing Rangers Index is available online.

Setting the context for PowerShell DSC (7 of 77)

Context を合わせるため、DSC が何かを知るにはここを読むといいでしょう。

What is DSC

ここで、DSC とはについて語られています。

DSC is short for Desired state Configuration, and is a new way to manage deployments, that is fundamental different from traditional, instruction-based deployment. Instead of providing instructions for how to deploy your environment, you simply describe the Desired State you want to achieve in a PowerShell script file. You can then deploy or rather apply a Desired State Configuration to a server using the PowerShell engine.

ここにある通り、DSC はよく言われる通り「どうやって構成するか(手順書)」ではなく「どういう構成にあるべきか(宣言)」です。どういう手順で構成するかをResourceにロジックを組み立て、利用者には 宣言的に利用できるようにすることで、煩雑なスクリプティングからの脱却を目指しているといえます。

DSC について、PowerShell MVP の著名な3名からの言葉が掲載されています。

“Desired State Configuration is Microsoft’s technology, introduced in Windows Management Framework 4.0, for declarative configuration of systems. At the risk of oversimplifying a bit, DSC lets you create specially formatted text files that describe how you should configure your system. > You then deploy those files to the actual systems, and they magically configure themselves as directed. At the top level, DSC isn’t programming – it’s just listing how you want a system to look.” (Steve Murawski, Don Jones, Stephen Owen)

DSC リソースは、モジュールです。そのモジュールの中にマニフェストを持っており、1つ以上のリソースを含みます。各リソースはスクリプトスキーマを持っており、PowerShell DSC の仕組みでは自動的にリソース探索し利用できるようにします。

f:id:guitarrapc_tech:20141021074526j:plain

Configuration サンプルがのっているので見てみてください。Windowsの機能を Server001 というホストで構成するためのシンプルな内容です。

Configuration ContosoWeb 
{ 
   # A Configuration block can have zero or more Node blocks 
   Node "Server001" 
   { 
      # Next, specify one or more resource blocks 
      # WindowsFeature is one of the built-in resources you can use in a Node block 
      # This example ensures the Web Server (IIS) role is installed 
      WindowsFeature IIS 
      { 
          Ensure = "Present" # To uninstall the role, set Ensure to "Absent" 
          Name = "Web-Server"   
      } 
      WindowsFeature ASP 
      { 
          Ensure = "Present" # To uninstall the role, set Ensure to "Absent" 
          Name = "Web-Asp-Net45"   
      } 
      # File is a built-in resource you can use to manage files and directories 
      # This example ensures files from the source directory are present in the destination directory 
      File SiteCatalog 
      { 
         Ensure = "Present"  # You can also set Ensure to "Absent" 
         Type = "Directory“ # Default is “File” 
         Recurse = $true 
         SourcePath = $WebsiteFilePath # This is a path that has web files 
         DestinationPath = "C:\inetpub\wwwroot"  
         # The path where we want to ensure the web files are present 
         DependsOn = "[WindowsFeature]MyRoleExample" 
         # This ensures that MyRoleExample completes successfully before this block runs 
      } 
   } 
} 
Push と Pull モード (10 of 77)

PowerShell DSC は、Push と Pull の両方をサポートしています。本セクションで、それを説明していますが、@IT で詳細を書いているのでそっちでもいいでしょう。

抜粋だけ引用しておきます。

The Push model is the simplest one and gives you control over the events and configurations, since they start manually.

f:id:guitarrapc_tech:20141021074940p:plain

In the pull model, the target servers automatically pull the current configuration from a DSC Pull Server.

The Pull model requires software installation and configuration, but provides scalability and conformability. The pull server allows a single repository of configurations. You can apply these to any number of VMs delivering a given role, hence giving scalability. Because this is a VM, we recheck its state against this pull server on a regular schedule to avoid configuration drift if you manually update a machine’s state.

f:id:guitarrapc_tech:20141021075054p:plain

Developing PowerShell DSC resources (11 of 77)

本資料のもっとも素晴らしい箇所は、リソースの開発について具体的に記述していることです。私が日頃やっているやり方がかなりそのままのっているので、参考になると思います。

ポイントは、以下の3つをリソースは含む必要があるということです。

Get-TargetResource – This method should receive the keys of the resource and return a hash table with all the resource properties as configured on the system.

Test-TargetResource – This method receives the keys and properties (as defined in the schema) and checks if the current configuration for the resource exists in the system. If any of the property values do not match the resource instance, $false should be returned and $true otherwise.

Set-TargetResource - This method will called to guarantee the resource instance matches the property values. This method must be idempotent so that after it DSC runs the method, DSC must ensure the resource instance is exactly as defined. It needs to be able to create a resource from scratch or to make some changes to an existing resource to make sure its state matches the state defined in the configuration.

Flow – Resource Development (12 of 77)

リソースの開発フローも載せています。だいじだいじ。

The following flow diagram summarizes the setup, development and deployment steps you should consider when you start building your custom DSC resources.

f:id:guitarrapc_tech:20141021075420p:plain

Checklist – Resource Development (13 of 77)

はいぱーチェックリストです。やったね。守ると幸せになれます。4文字の短縮名むりぽ。

f:id:guitarrapc_tech:20141021080037p:plain

Bug report and resolution process (14 of 77)

バグはつきものなのです。だからこそフィードバックを!ということで。

If a bug is found in a Microsoft provided resource

Microsoft リソースなら、 Connect へ!

Go to Microsoft Connect for PowerShell 14

 Select Report a Bug and then the type of bug you want to report (code, documentation etc.).

 In the Bug report form, be sure to add the module and/or resource name to the title where applicable and then describe the problem with as much context as possible.

If a bug is found in community supplied resource (15 of 77)

コミュニティのリソースなら?このサンプルのは ふぇぇ、しょーがにゃい。

@SORRY FOR THE INCONVENIENCE! THIS SECTION WILL BE COMPLETED IN V1 UPDATES OR THE V2 RELEASE@

In the interim please post bugs to the resource kit location where you found the resource or contact us.

Forum (15 of 77)

フォーラムですよー!そーだんしちゃえ!

Microsoft のフォーラムです。

PowerShell.Org というコミュニティのフォーラムです。

Resource library (15 of 77)

Microsoft から、DSC Resource Kit がTechNet Script Centerで公開されています。

ででん!と公開されてるのでぜひぜひ!

Practical implementations (15 of 77)

具体的に守ること!が書いてあるのですよ。

PowerShell DSC within a small to medium team environment

中小規模ということなので、某謎社をサンプルにしてを例にすると 100台を超える サーバー群をまとめて1台のDSCで管理できますよ?これぐらいが中規模かな?

原則は、Configuration As Code を Windows でも行うことです。ここにありますが、現実のものとして、Configuration As Code がメリットというより、 Configuration As Codeをしないと話にならないのです。自動化をするその第一歩は、繰り返し処理を含む、あらゆるインフラ処理のコード化からです。

PowerShell DSC provides a mechanism for achieving configuration as code on windows platform. You are determining infrastructure with code when you define a script that describes in an objective and practical manner the desired configuration for any given infrastructure.

Configuration as code leverages many possibilities, especially when it comes down to automation, among other benefits. However, it is crucial to keep in mind some inherent aspects that may potentially lead to problems and difficulties. The main idea here is to show those aspects, how they may affect you, and what can be you can do about them.

Treat configuration files as first-class citizens

First Class citizen とはこういうことです。

 They must to be standard of use

 They must be kept up-to-date

 They must always represent the current and proper state of configuration

Put your configuration files under source control

GitHub なり、BitBucket でもいいです。インフラをコード化したら、ソース管理してください。インフラがソースとして、アプリと同様に扱えるメリットは多大なものがあります。その一例が示されています。

Putting your configuration files under source control will allow you to maintain a history of all the changes done to them. In addition, having them under source control facilitates backup processes, avoiding situations where scripts may be lost. With the proper branching strategies, we can make changes in parallel as well optimize productivity.

Use configuration files to describe end states

Configuration ファイルは、あるべき状態を記述しさいということです。単純ですね。

Always keep in mind that the configuration described will be tested and ensured against a machine. Using partial and/or sequential configurations burdens the whole deployment process by adding unnecessary orchestration steps. A configuration file has to be sufficient, unique, and self-contained. Configurations may be nested, see this article: Reusing Existing Configuration Scripts in PowerShell Desired State Configuration。

Configuration は、Component といわれます。そして、コンポーネントは、固有のものではなく、共通した処理でもあるでしょう。Configuration では、変数を渡すことができるので、固有のパラメータを変数で渡すことで、Configuration を様々なシーンで使いまわせるようになります。さらに、Configuration は、Resource として使うこともできます。そのサンプルがここにのっています。

Test your configurations

テスト大事です。はい。現在は Pester を用いた方式が主流ですね。RSpec からの ServerSpec と同じ流れを感じます。

Like any other code, testing is crucial for delivering reliable solutions. The same applied to configuration files: thoroughly test them in test environments before deploying them to production environments. Make sure that everything works as expected; otherwise, any problems brought by malfunctioning configurations may be hard to track down.

Use a pull server as a single point-of-truth

当然ですが、PULL サーバーはただ一つの正しい構成を保持しているサーバーです。個別のサーバーが正しい状態を持っているわけではなく、PULLサーバーの構成こそが正しい。 Compliant という意味でも基準になるため覚えておいてください。

A pull server will keep all the production configurations in one place, with the machines configured by it constantly pull the configurations they use. This leverages updating configurations, since you would just have to update a configuration file at the pull server and the machines that use it will pull it and update their configuration themselves. Imagine that you need to update 100 servers using the same configuration - a pull server allows you to do it easily, instead of updating one by one.

Don't make manual changes to machines

Configuration As Code をする原則です。個別に手動でサーバー構成はしないでください。何が正しい状態かわからなくなりますよ?

When machines are manually changed, this means you are not tracking these changes into the configuration script – you would have to do this manually, which might be unreliable. Manually changing a machine will present some challenging situations when applying the same configuration to another machine, since there will be no way to ensure that the configurations are the same.

Consider rollback scenarios

ロールバックを常に考慮してください。当然です。

Sometimes, you may need to roll back the configuration changes for various reasons. For those situations, most of the time you just have to pick up a previous version from the configuration script and apply it“, which means you must save versions of your PowerShell DSC configurations to support rollback. However, reality tends to be more complex, and you will need to re-run the previous configuration scripts.

References and tooling - where to find which gems

最後にリファレンスを。

Video

https://channel9.msdn.com/Events/TechEd/NorthAmerica/2014/DCIM-B417

Blogs

Tutorials
  • DSC の概要です
  • より高度なDSCの概要です

  • PULL サーバーの構成です
ToolKit
  • Microsoft PowerShell Team の出している DSC Resourceです

まとめ

資料はまだ続きますが、記事はここまでとします。

DSC のコンテキストだけ抜き出しましたが、これは Configuration As Code のコンテキストとほぼ変わりません。

18page 以降に、よくある質問や具体的なリソースの開発まで続きます。

ぜひぜひ読んでみてください。私が考える Windows における Configuration Management も、これと大きくずれていないです。

*1:書き方からテスト、リソースの配置と実行まで

*2:Bestとは書いていない

*3:見たことあります

*4:まだ未完成でしょぼーんも多いけど置いておきましょう