chef-provisioning-azurerm 0.2.12

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 1ca902d522c0c57a8fab136e174bbfddf1fb24bb
4
+ data.tar.gz: e62e95ed8543c0450b243a63617ac025a97a6d0e
5
+ SHA512:
6
+ metadata.gz: 3159f450ccb244279150ee91b8477da7b531a6ad3ea579f2420184e7927abec91fe18aeb5d1cd948e35dcf6e4d99d32aba860255f5f1d710c276bb483c701581
7
+ data.tar.gz: d88c5a153ef330da7a2f7a7100366166fa23630e4d847a3deaaa92a7810b1761e1e314cda78f7a32f9e5a523197c6499dfb1190d54d26611a42b8c98f3aa7064
data/LICENSE.txt ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,133 @@
1
+ # chef-provisioning-azurerm
2
+
3
+ ```chef-provisioning-azurerm``` is a driver for [chef-provisioning](https://github.com/chef/chef-provisioning) that allows Microsoft Azure resources to be provisioned by Chef. This driver uses the new Microsoft Azure Resource Management REST API.
4
+
5
+ At the moment, the primary use case is to provide a way to deploy Azure Resource Manager templates using Chef as well as provide an automatic means to install and register the Chef client on these machine via the use of the Chef VM Extensions for Azure.
6
+
7
+ ![build status](https://travis-ci.org/pendrica/chef-provisioning-azurerm.svg?branch=master)
8
+
9
+ **Note:** If you are looking for a driver that works with the existing Microsoft Azure Service Management API please visit [chef-provisioning-azure](https://github.com/chef/chef-provisioning-azure)
10
+
11
+ ## Quick-start
12
+
13
+ ### Prerequisites
14
+
15
+ The plugin requires Chef Client 12.2.1 or higher.
16
+
17
+ ### Installation
18
+
19
+ This plugin is distributed as a Ruby Gem. To install it, run:
20
+
21
+ ```$ chef gem install chef-provisioning-azurerm```
22
+
23
+ ### Configuration
24
+
25
+ For the driver to interact with the Microsoft Azure Resource management REST API, a username and password needs to be configured that refer to an account with the role 'Service Administrator'.
26
+
27
+ *Unlike the Microsoft Azure Service Management API which performs authentication via X.509 v3 certificates, the Resource Management API requires an OAUTH2 authentication token to be passed with each request. To obtain the token, a username and password is used.*
28
+
29
+ Using a text editor, open or create the file ```~/.azure/credentials``` and add the following section:
30
+
31
+ ```ruby
32
+ [abcd1234-YOUR-GUID-HERE-abcdef123456]
33
+ username = "username@tenant.onmicrosoft.com"
34
+ password = "your-password-here"
35
+ ```
36
+
37
+ The GUID required is that of your Azure subscription. This can be found after logging into the portal at https://portal.azure.com
38
+
39
+ **Note:** Storage of the password is required due to the generated access token only being valid for 3600 seconds each time it is generated [1].
40
+
41
+ [1] https://twitter.com/vibronet/status/461260062204239872
42
+
43
+ ## Features
44
+
45
+ Unlike a fully-featured **chef-provisioning** driver that fully utilises the **machine**, **machine_batch**, **machine_image** and **load_balancer** resources, the **chef-provisioning-azurerm** driver offers a lightweight way to interact with resources and providers in the Azure Resource Manager framework directly.
46
+
47
+ To work around the issue of storing chef-provisioning driver info in the Chef server:
48
+ - Any Azure Resource Manager (ARM) templates sent for deployment that contain a resource of type 'Microsoft.Compute/virtualMachine' or 'Microsoft.ClassicCompute/virtualMachine' will automatically have the Chef VM extension added (unless overridden with **install_vm_extension: false**)
49
+ - The Chef VM extension will automatically be configured to point at the same Chef server as the provisioning node. This can be overridden in a recipe by using the following line: ```with_chef_server 'http://your.chef.server.url/yourorg'```
50
+
51
+ The following resources are provided:
52
+
53
+ - azure_resource_group
54
+ - azure_storage_account
55
+ - azure_resource_template
56
+
57
+ The following resources are planned (note: these resources may be renamed as they are implemented):
58
+
59
+ - azure_virtual_network
60
+ - azure_availability_set
61
+ - azure_load_balancer
62
+ - azure_network_interface
63
+ - azure_network_security_group
64
+ - azure_public_ip_address
65
+ - azure_virtual_machine
66
+ - PaaS resources such as TrafficManager, SQL Server etc.
67
+
68
+ ## Limitations
69
+ - As the nodes self-register, there are no "managed entries" created on the Chef server other than for resources of type Microsoft.Compute.
70
+ - Bootstrap over SSH or WinRM is not implemented
71
+ - Connect to machine over SSH or WinRM is not implemented
72
+ - machine, machine_batch, machine_image and load_balancer resources are not implemented
73
+ - Azure resources that can only be created through the Service Management (ASM) API are not implemented
74
+ - The path to the validation keys must be provided within the recipe (i.e. they must be in the chef-repo you are working with)
75
+ - **Local mode** is not currently supported - the Chef VM extensions can only register themselves with a 'real' Chef server.
76
+
77
+ ## Example Recipe 1 - deployment of Resource Manager template
78
+ The following recipe creates a new Resource Group within your subscription (identified by the GUID on line 2). It will then execute a resource template by merging the content at the given uri with the parameters specified.
79
+
80
+ A ```deployment_template.json``` is required to be copied to ```cookbooks/provision/templates/default/recipes``` - many examples of a Resource Manager deployment template can be found at the [Azure QuickStart Templates Gallery on GitHub](https://github.com/Azure/azure-quickstart-templates).
81
+
82
+ For our example, we'll need the azure_deploy.json from [here](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-simple-windows-vm/azuredeploy.json) and copy it to a path in our repo. Make sure you amend the path appropriately.
83
+
84
+ ### example1.rb
85
+
86
+ ```ruby
87
+ require 'chef/provisioning/azurerm'
88
+ with_driver 'AzureRM:abcd1234-YOUR-GUID-HERE-abcdef123456'
89
+
90
+ azure_resource_group 'pendrica-demo-resources' do
91
+ location 'West US' # optional, default: 'West US'
92
+ tags businessUnit: 'IT' # optional
93
+ end
94
+
95
+ azure_resource_template 'my-deployment' do
96
+ resource_group 'pendrica-demo-resources'
97
+ template_source 'cookbooks/provision/templates/default/recipes/azure_deploy.json'
98
+ parameters newStorageAccountName: 'penstorage01',
99
+ adminUsername: 'ubuntu',
100
+ adminPassword: 'P2ssw0rd',
101
+ dnsNameForPublicIP: 'pendricatest01',
102
+ ubuntuOSVersion: '14.04.2-LTS'
103
+ end
104
+ ```
105
+
106
+ ## Example Recipe 2 - deployment of locally replicated Storage Account
107
+ ### example2.rb
108
+
109
+ ```ruby
110
+ require 'chef/provisioning/azurerm'
111
+ with_driver 'AzureRM:abcd1234-YOUR-GUID-HERE-abcdef123456'
112
+
113
+ azure_resource_group 'pendrica-demo-resources' do
114
+ location 'West US'
115
+ end
116
+
117
+ azure_storage_account 'pendevstore01' do
118
+ resource_group 'pendrica-demo-resources'
119
+ location 'West US'
120
+ account_type 'Standard_LRS'
121
+ end
122
+ ```
123
+
124
+ ## Contributing
125
+
126
+ Contributions to the project are welcome via submitting Pull Requests.
127
+
128
+ 1. Fork it ( https://github.com/pendrica/chef-provisioning-azurerm/fork )
129
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
130
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
131
+ 4. Push to the branch (`git push origin my-new-feature`)
132
+ 5. Create a new Pull Request
133
+
@@ -0,0 +1,36 @@
1
+ require 'chef/provisioning/azurerm/azure_provider'
2
+
3
+ class Chef
4
+ class Provider
5
+ class AzureResourceGroup < Chef::Provisioning::AzureRM::AzureProvider
6
+ provides :azure_resource_group
7
+
8
+ def whyrun_supported?
9
+ true
10
+ end
11
+
12
+ def api_url
13
+ "https://management.azure.com/subscriptions/#{new_resource.subscription_id}/resourcegroups/" \
14
+ "#{new_resource.name}?api-version=2015-01-01"
15
+ end
16
+
17
+ # API ref: https://msdn.microsoft.com/en-us/library/azure/dn790525.aspx
18
+ action :create do
19
+ converge_by("create or update Resource Group #{new_resource.name}") do
20
+ doc = {
21
+ location: new_resource.location,
22
+ tags: new_resource.tags
23
+ }
24
+ azure_call_until_expected_response(:put, api_url, doc.to_json, '201,200', 60)
25
+ end
26
+ end
27
+
28
+ # API ref: https://msdn.microsoft.com/en-us/library/azure/dn790539.aspx
29
+ action :destroy do
30
+ converge_by("destroy Resource Group #{new_resource.name}") do
31
+ azure_call_until_expected_response(:delete, api_url, nil, '404', 60)
32
+ end
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,138 @@
1
+ require 'chef/provisioning/azurerm/azure_provider'
2
+
3
+ class Chef
4
+ class Provider
5
+ class AzureResourceTemplate < Chef::Provisioning::AzureRM::AzureProvider
6
+ provides :azure_resource_template
7
+
8
+ def whyrun_supported?
9
+ true
10
+ end
11
+
12
+ # Applies a Resource Manager template to Azure.
13
+ # If resources of type Microsoft.Compute/virtualMachines are found, a Chef VM Extension is added
14
+ # Chef VM Extension parameters may be supplied in the recipe.
15
+ action :deploy do
16
+ converge_by("deploy or re-deploy Resource Manager template '#{new_resource.name}'") do
17
+ template_src_file = ::File.join(Chef::Config[:chef_repo_path], new_resource.template_source)
18
+ fail "Cannot find file: #{template_src_file}" unless ::File.file?(template_src_file)
19
+ template_src = ::IO.read(template_src_file)
20
+ template = JSON.parse(template_src)
21
+
22
+ machines = template['resources'].select { |h| h['type'] == 'Microsoft.Compute/virtualMachines' }
23
+ machines.each do |machine|
24
+ Chef::Log.info("[Azure] Found a compute resource with name value: #{machine['name']} and location #{machine['location']}, adding a Chef VM Extension to it.")
25
+ extension = chef_vm_extension(machine['name'], machine['location'])
26
+ template['resources'] << JSON.parse(extension)
27
+ end
28
+ Chef::Log.debug("[Azure] Generated template for deployment: #{template}")
29
+ doc = generate_wrapper_document(template)
30
+ apply_template_deployment(doc)
31
+ follow_deployment_until_ended
32
+ end
33
+ end
34
+
35
+ def generate_wrapper_document(template)
36
+ parameters = new_resource.parameters.map do |key, value|
37
+ { key.to_sym => { 'value' => value } }
38
+ end
39
+ new_template = {
40
+ properties: {
41
+ template: template,
42
+ mode: 'Incremental',
43
+ parameters: parameters.reduce(:merge!)
44
+ }
45
+ }
46
+ new_template
47
+ end
48
+
49
+ def chef_vm_extension(machine_name, location)
50
+ Chef::Log.debug("[Azure] Config: #{Chef::Config.inspect}")
51
+ chef_server_url = Chef::Config[:chef_server_url]
52
+ validation_client_name = Chef::Config[:validation_client_name]
53
+ validation_key_content = ::File.read(Chef::Config[:validation_key])
54
+ <<-EOH
55
+ {
56
+ "type": "Microsoft.Compute/virtualMachines/extensions",
57
+ "name": "[concat(#{machine_name.delete('[]')},'/', 'chefExtension')]",
58
+ "apiVersion": "2015-05-01-preview",
59
+ "location": "#{location}",
60
+ "dependsOn": [
61
+ "[concat('Microsoft.Compute/virtualMachines/', #{machine_name.delete('[]')})]"
62
+ ],
63
+ "properties": {
64
+ "publisher": "Chef.Bootstrap.WindowsAzure",
65
+ "type": "#{new_resource.chef_extension[:client_type]}",
66
+ "typeHandlerVersion": "#{new_resource.chef_extension[:version]}",
67
+ "settings": {
68
+ "bootstrap_options": {
69
+ "chef_node_name" : "[concat(#{machine_name.delete('[]')},'.','#{new_resource.resource_group}')]",
70
+ "chef_server_url" : "#{chef_server_url}",
71
+ "validation_client_name" : "#{validation_client_name}"
72
+ },
73
+ "runlist": "#{new_resource.chef_extension[:runlist]}"
74
+ },
75
+ "protectedSettings": {
76
+ "validation_key": "#{validation_key_content.gsub("\n", "\\n")}"
77
+ }
78
+ }
79
+ }
80
+ EOH
81
+ end
82
+
83
+ def apply_template_deployment(doc)
84
+ url = "https://management.azure.com/subscriptions/#{new_resource.subscription_id}/resourcegroups/" \
85
+ "#{new_resource.resource_group}/providers/microsoft.resources/deployments/#{new_resource.name}" \
86
+ '?api-version=2015-01-01'
87
+ azure_call(:put, url, doc.to_json)
88
+ end
89
+
90
+ def validate_template_deployment(doc)
91
+ url = "https://management.azure.com/subscriptions/#{new_resource.subscription_id}/resourcegroups/" \
92
+ "#{new_resource.resource_group}/providers/microsoft.resources/deployments/#{new_resource.name}" \
93
+ '/validate?api-version=2015-01-01'
94
+ response = azure_call(:post, url, doc.to_json)
95
+ Chef::Log.info("[Azure] #{response.body.inspect}")
96
+ end
97
+
98
+ # API ref: https://msdn.microsoft.com/en-us/library/azure/dn790565.aspx (Deployment)
99
+ # API ref: https://msdn.microsoft.com/en-us/library/azure/dn790519.aspx (Operations)
100
+ def follow_deployment_until_ended
101
+ url = "https://management.azure.com/subscriptions/#{new_resource.subscription_id}/resourcegroups/" \
102
+ "#{new_resource.resource_group}/providers/microsoft.resources/deployments/#{new_resource.name}" \
103
+ '/operations?api-version=2015-01-01'
104
+
105
+ end_provisioning_states = 'Canceled,Failed,Deleted,Succeeded'
106
+ end_operation_states = 'Failed,Succeeded'
107
+ end_provisioning_state_reached = false
108
+
109
+ until end_provisioning_state_reached
110
+ response = azure_call(:get, url, '')
111
+ deployment_operations = JSON.parse(response.body)
112
+ deployment_operations['value'].each do |val|
113
+ resource_provisioning_state = val['properties']['provisioningState']
114
+ resource_name = val['properties']['targetResource']['resourceName']
115
+ resource_type = val['properties']['targetResource']['resourceType']
116
+ end_operation_state_reached = end_operation_states.split(',').include?(resource_provisioning_state)
117
+ unless end_operation_state_reached
118
+ Chef::Log.info("[Azure] Resource #{resource_type} '#{resource_name}' provisioning status is #{resource_provisioning_state}")
119
+ end
120
+ end
121
+ sleep 5
122
+ provisioning_state = retrieve_provisioning_state
123
+ Chef::Log.debug("[Azure] Resource Template deployment is in a state of '#{provisioning_state}'")
124
+ end_provisioning_state_reached = end_provisioning_states.split(',').include?(provisioning_state)
125
+ end
126
+ Chef::Log.info("[Azure] Resource Template deployment reached end state of '#{provisioning_state}'")
127
+ end
128
+
129
+ def retrieve_provisioning_state
130
+ url = "https://management.azure.com/subscriptions/#{new_resource.subscription_id}/resourcegroups/" \
131
+ "#{new_resource.resource_group}/providers/microsoft.resources/deployments/#{new_resource.name}" \
132
+ '?api-version=2015-01-01'
133
+ response = azure_call(:get, url, '')
134
+ JSON.parse(response.body)['properties']['provisioningState']
135
+ end
136
+ end
137
+ end
138
+ end
@@ -0,0 +1,40 @@
1
+ require 'chef/provisioning/azurerm/azure_provider'
2
+
3
+ # MSDN: https://msdn.microsoft.com/en-us/library/azure/mt163564.aspx
4
+
5
+ class Chef
6
+ class Provider
7
+ class AzureStorageAccount < Chef::Provisioning::AzureRM::AzureProvider
8
+ provides :azure_storage_account
9
+
10
+ def whyrun_supported?
11
+ true
12
+ end
13
+
14
+ action :create do
15
+ url = "https://management.azure.com/subscriptions/#{new_resource.subscription_id}/resourcegroups/" \
16
+ "#{new_resource.resource_group}/providers/Microsoft.Storage/storageAccounts/#{new_resource.name}" \
17
+ '?api-version=2015-05-01-preview'
18
+ doc = {
19
+ location: new_resource.location,
20
+ tags: new_resource.tags,
21
+ properties: {
22
+ accountType: "#{new_resource.account_type}"
23
+ }
24
+ }
25
+ converge_by("create or update Storage Account: #{new_resource.name}") do
26
+ azure_call_until_expected_response(:put, url, doc.to_json, '201,200', 600)
27
+ end
28
+ end
29
+
30
+ action :destroy do
31
+ url = "https://management.azure.com/subscriptions/#{new_resource.subscription_id}/resourcegroups/" \
32
+ "#{new_resource.resource_group}/providers/Microsoft.Storage/storageAccounts/#{new_resource.name}" \
33
+ '?api-version=2015-05-01-preview'
34
+ converge_by("destroy Storage Account: #{new_resource.name}") do
35
+ azure_call_until_expected_response(:delete, url, nil, '404', 600)
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,14 @@
1
+ require 'chef/provisioning'
2
+ require 'chef/provisioning/version'
3
+ require 'chef/provisioning/azurerm/driver'
4
+ require 'chef/provisioning/azurerm/version'
5
+ Chef::Log.info(' __ _ _____ _ _ __ ___ ')
6
+ Chef::Log.info(" / _` |_ / | | | '__/ _ \\ chef-client #{Chef::VERSION}")
7
+ Chef::Log.info("| (_| |/ /| |_| | | | __/ chef-provisioning-azurerm #{Chef::Provisioning::AzureRM::VERSION}")
8
+ Chef::Log.info(" \\__,_/___|\\__,_|_| \\___| chef-provisioning #{Chef::Provisioning::VERSION}")
9
+
10
+ resources = %w(resource_group resource_template storage_account)
11
+ resources.each do |r|
12
+ require "chef/resource/azure_#{r}"
13
+ require "chef/provider/azure_#{r}"
14
+ end
@@ -0,0 +1,62 @@
1
+ require 'chef/provider/lwrp_base'
2
+ require 'chef/provisioning/azurerm/azure_resource'
3
+ require 'chef/provisioning/chef_provider_action_handler'
4
+
5
+ class Chef
6
+ module Provisioning
7
+ module AzureRM
8
+ class AzureProvider < Chef::Provider::LWRPBase
9
+ use_inline_resources
10
+
11
+ def action_handler
12
+ @action_handler ||= Chef::Provisioning::ChefProviderActionHandler.new(self)
13
+ end
14
+
15
+ # Makes a call to the specified REST API, adding the Azure bearer token.
16
+ def azure_call(method, url, data)
17
+ Chef::Log.debug("HTTP request: #{method} #{url} #{data.to_json}")
18
+ uri = URI(url)
19
+ response = nil
20
+ Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
21
+ case method
22
+ when :put
23
+ request = Net::HTTP::Put.new uri
24
+ when :delete
25
+ request = Net::HTTP::Delete.new uri
26
+ when :get
27
+ request = Net::HTTP::Get.new uri
28
+ when :post
29
+ request = Net::HTTP::Post.new uri
30
+ when :patch
31
+ request = Net::HTTP::Patch.new uri
32
+ end
33
+ request.body = data
34
+ request['Authorization'] = "Bearer #{new_resource.access_token}"
35
+ request['Content-Type'] = 'application/json'
36
+ response = http.request request
37
+ end
38
+ response
39
+ end
40
+
41
+ # Wraps a call to the Azure REST API with retry and timeout capability.
42
+ def azure_call_until_expected_response(method, url, data, success_codes, wait_time)
43
+ time_elapsed = 0
44
+ sleep_time = 2
45
+ max_wait_time = wait_time
46
+ success_code_found = false
47
+ while time_elapsed < max_wait_time && !success_code_found
48
+ response = azure_call(method, url, data)
49
+ break if response.code.to_i >= 400
50
+ success_code_found = success_codes.split(',').include?(response.code)
51
+ break if success_code_found
52
+ Chef::Log.debug("awaiting success code (#{success_codes}) (got: #{response.code}) - timeout in #{(max_wait_time - time_elapsed)} seconds.")
53
+ sleep(sleep_time)
54
+ time_elapsed += sleep_time
55
+ end
56
+ Chef::Log.debug("response code: #{response.code} body: #{response.body}")
57
+ response
58
+ end
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,26 @@
1
+ require 'chef/resource/lwrp_base'
2
+ require 'chef/provisioning/azurerm/credentials'
3
+
4
+ class Chef
5
+ module Provisioning
6
+ module AzureRM
7
+ class AzureResource < Chef::Resource::LWRPBase
8
+ def initialize(*args)
9
+ super
10
+ return unless run_context
11
+ @chef_environment = run_context.cheffish.current_environment
12
+ @chef_server = run_context.cheffish.current_chef_server
13
+ @driver = run_context.chef_provisioning.current_driver
14
+ fail 'No driver set. (has it been set in your recipe using with_driver?)' unless driver
15
+ @driver_name, @subscription_id = driver.split(':', 2)
16
+ @access_token = Credentials.new.access_token_for_subscription(@subscription_id)
17
+ end
18
+
19
+ attr_accessor :driver
20
+ attr_accessor :driver_name
21
+ attr_accessor :access_token
22
+ attr_accessor :subscription_id
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,52 @@
1
+ require 'inifile'
2
+
3
+ class Chef
4
+ module Provisioning
5
+ module AzureRM
6
+ class Credentials
7
+ AZURE_SERVICE_PRINCIPAL = '1950a258-227b-4e31-a9cf-717495945fc2'
8
+ CONFIG_PATH = "#{ENV['HOME']}/.azure/credentials"
9
+
10
+ def initialize
11
+ config_file = ENV['AZURE_CONFIG_FILE'] || File.expand_path(CONFIG_PATH)
12
+ fail "#{CONFIG_PATH} was not found or not accessible." unless File.file?(config_file)
13
+ @credentials = IniFile.load(File.expand_path(config_file))
14
+ end
15
+
16
+ def access_token_for_subscription(subscription_id)
17
+ fail "No credentials loaded! Do you have a #{CONFIG_PATH} and a section [#{subscription_id}] within it?" \
18
+ unless @credentials[subscription_id]
19
+ fail "No username was found for subscription #{subscription_id}, please verify #{CONFIG_PATH}" \
20
+ unless @credentials[subscription_id]['username']
21
+ azure_authenticate(@credentials[subscription_id]['username'], @credentials[subscription_id]['password'])
22
+ end
23
+
24
+ # Do a user_impersonation to get an OAUTH2 access_token for further requests
25
+ # - Right now this means that the entire recipe must complete with 1 hour
26
+ # - of the token being issued (NB: the same token can be issued with that hour)
27
+ def azure_authenticate(username, password)
28
+ url = 'https://login.windows.net/Common/oauth2/token'
29
+ data = "resource=https%3A%2F%2Fmanagement.core.windows.net%2F&client_id=#{AZURE_SERVICE_PRINCIPAL}" \
30
+ "&grant_type=password&username=#{username}&scope=openid&password=#{password}"
31
+ response = http_post(url, data)
32
+ JSON.parse(response.body)['access_token']
33
+ end
34
+
35
+ def http_post(url, data)
36
+ uri = URI(url)
37
+ response = nil
38
+ Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
39
+ request = Net::HTTP::Post.new uri
40
+ request.body = data
41
+ response = http.request request
42
+ end
43
+ response
44
+ end
45
+
46
+ def self.singleton
47
+ @credentials ||= Credentials.new
48
+ end
49
+ end
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,31 @@
1
+ require 'chef/provisioning/driver'
2
+
3
+ class Chef
4
+ module Provisioning
5
+ module AzureRM
6
+ class Driver < Chef::Provisioning::Driver
7
+ def self.from_url(driver_url, config)
8
+ Driver.new(driver_url, config)
9
+ end
10
+
11
+ def initialize(driver_url, config)
12
+ super
13
+ end
14
+
15
+ def self.canonicalize_url(driver_url, config)
16
+ [driver_url, config]
17
+ end
18
+
19
+ def allocate_machine(_action_handler, _machine_spec, _machine_options)
20
+ fail "The Azure Resource Manager does not implement the 'machine' resource. Please refer to documentation."
21
+ end
22
+
23
+ def ready_machine(_action_handler, _machine_spec, _machine_options)
24
+ end
25
+
26
+ def destroy_machine(_action_handler, _machine_spec, _machine_options)
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,7 @@
1
+ class Chef
2
+ module Provisioning
3
+ module AzureRM
4
+ VERSION = '0.2.12'
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,2 @@
1
+ require 'chef/provisioning/azurerm/driver'
2
+ Chef::Provisioning.register_driver_class('AzureRM', Chef::Provisioning::AzureRM::Driver)
@@ -0,0 +1,14 @@
1
+ require 'chef/provisioning/azurerm/azure_resource'
2
+
3
+ class Chef
4
+ class Resource
5
+ class AzureResourceGroup < Chef::Provisioning::AzureRM::AzureResource
6
+ resource_name :azure_resource_group
7
+ actions :create, :destroy, :nothing
8
+ default_action :create
9
+ attribute :name, kind_of: String, name_attribute: true, regex: /^[\w\-\(\)\.]{0,80}$+(?<!\.)$/i
10
+ attribute :location, kind_of: String, default: 'westus'
11
+ attribute :tags, kind_of: Hash
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,17 @@
1
+ require 'chef/provisioning/azurerm/azure_resource'
2
+
3
+ class Chef
4
+ class Resource
5
+ class AzureResourceTemplate < Chef::Provisioning::AzureRM::AzureResource
6
+ resource_name :azure_resource_template
7
+ actions :deploy, :validate, :nothing
8
+ default_action :deploy
9
+ attribute :name, kind_of: String, name_attribute: true
10
+ attribute :resource_group, kind_of: String
11
+ attribute :template_source, kind_of: String
12
+ attribute :parameters, kind_of: Hash
13
+ attribute :chef_extension, kind_of: Hash
14
+ attribute :outputs, kind_of: Hash
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,18 @@
1
+ require 'chef/provisioning/azurerm/azure_resource'
2
+
3
+ # MSDN Ref: https://msdn.microsoft.com/en-us/library/azure/mt163564.aspx
4
+
5
+ class Chef
6
+ class Resource
7
+ class AzureStorageAccount < Chef::Provisioning::AzureRM::AzureResource
8
+ resource_name :azure_storage_account
9
+ actions :create, :destroy, :nothing
10
+ default_action :create
11
+ attribute :name, kind_of: String, name_attribute: true, regex: /^[\w]{3,24}$/i
12
+ attribute :resource_group, kind_of: String
13
+ attribute :location, kind_of: String, default: 'westus'
14
+ attribute :tags, kind_of: Hash
15
+ attribute :account_type, kind_of: String, equal_to: %w(Standard_LRS Standard_ZRS Standard_GRS Standard_RAGRS Premium_LRS), default: 'Standard_LRS'
16
+ end
17
+ end
18
+ end
metadata ADDED
@@ -0,0 +1,150 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: chef-provisioning-azurerm
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.12
5
+ platform: ruby
6
+ authors:
7
+ - Stuart Preston
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2015-08-13 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: chef
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '12.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '12.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: chef-provisioning
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: json
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.8'
48
+ - - ">="
49
+ - !ruby/object:Gem::Version
50
+ version: 1.8.2
51
+ type: :runtime
52
+ prerelease: false
53
+ version_requirements: !ruby/object:Gem::Requirement
54
+ requirements:
55
+ - - "~>"
56
+ - !ruby/object:Gem::Version
57
+ version: '1.8'
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: 1.8.2
61
+ - !ruby/object:Gem::Dependency
62
+ name: inifile
63
+ requirement: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - "~>"
66
+ - !ruby/object:Gem::Version
67
+ version: '2.0'
68
+ type: :runtime
69
+ prerelease: false
70
+ version_requirements: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - "~>"
73
+ - !ruby/object:Gem::Version
74
+ version: '2.0'
75
+ - !ruby/object:Gem::Dependency
76
+ name: bundler
77
+ requirement: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - "~>"
80
+ - !ruby/object:Gem::Version
81
+ version: '1.7'
82
+ type: :development
83
+ prerelease: false
84
+ version_requirements: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - "~>"
87
+ - !ruby/object:Gem::Version
88
+ version: '1.7'
89
+ - !ruby/object:Gem::Dependency
90
+ name: rake
91
+ requirement: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - "~>"
94
+ - !ruby/object:Gem::Version
95
+ version: '10.0'
96
+ type: :development
97
+ prerelease: false
98
+ version_requirements: !ruby/object:Gem::Requirement
99
+ requirements:
100
+ - - "~>"
101
+ - !ruby/object:Gem::Version
102
+ version: '10.0'
103
+ description: Chef Provisioner for the Microsoft Azure Resource Management API.
104
+ email:
105
+ - stuart@pendrica.com
106
+ executables: []
107
+ extensions: []
108
+ extra_rdoc_files: []
109
+ files:
110
+ - LICENSE.txt
111
+ - README.md
112
+ - lib/chef/provider/azure_resource_group.rb
113
+ - lib/chef/provider/azure_resource_template.rb
114
+ - lib/chef/provider/azure_storage_account.rb
115
+ - lib/chef/provisioning/azurerm.rb
116
+ - lib/chef/provisioning/azurerm/azure_provider.rb
117
+ - lib/chef/provisioning/azurerm/azure_resource.rb
118
+ - lib/chef/provisioning/azurerm/credentials.rb
119
+ - lib/chef/provisioning/azurerm/driver.rb
120
+ - lib/chef/provisioning/azurerm/version.rb
121
+ - lib/chef/provisioning/driver_init/azurerm.rb
122
+ - lib/chef/resource/azure_resource_group.rb
123
+ - lib/chef/resource/azure_resource_template.rb
124
+ - lib/chef/resource/azure_storage_account.rb
125
+ homepage: https://github.com/pendrica/chef-provisioning-azurerm
126
+ licenses:
127
+ - Apache-2.0
128
+ metadata: {}
129
+ post_install_message:
130
+ rdoc_options: []
131
+ require_paths:
132
+ - lib
133
+ required_ruby_version: !ruby/object:Gem::Requirement
134
+ requirements:
135
+ - - ">="
136
+ - !ruby/object:Gem::Version
137
+ version: '0'
138
+ required_rubygems_version: !ruby/object:Gem::Requirement
139
+ requirements:
140
+ - - ">="
141
+ - !ruby/object:Gem::Version
142
+ version: '0'
143
+ requirements: []
144
+ rubyforge_project:
145
+ rubygems_version: 2.4.4
146
+ signing_key:
147
+ specification_version: 4
148
+ summary: Chef Provisioner for the Azure Resource Management (ARM) REST API.
149
+ test_files: []
150
+ has_rdoc: