Module: Chef::Knife::AzurermBase
- Includes:
- Mixin::ShellOut
- Included in:
- AzurermServerCreate, AzurermServerDelete, AzurermServerList, AzurermServerShow, BootstrapAzurerm
- Defined in:
- lib/chef/knife/helpers/azurerm_base.rb
Class Method Summary collapse
Instance Method Summary collapse
- #authentication_details ⇒ Object
- #azure_authentication ⇒ Object
- #check_token_validity(token_details) ⇒ Object
- #find_file(name) ⇒ Object
- #get_azure_cli_version ⇒ Object
- #is_token_valid?(token_details) ⇒ Boolean
- #locate_config_value(key) ⇒ Object
- #msg_server_summary(server) ⇒ Object
- #parse_publish_settings_file(filename) ⇒ Object
- #refresh_token ⇒ Object
- #service ⇒ Object
- #token_details_for_linux ⇒ Object
- #token_details_for_windows ⇒ Object
- #token_details_from_accessToken_file ⇒ Object
-
#validate_arm_keys!(*keys) ⇒ Object
validates ARM mandatory keys.
- #validate_azure_login ⇒ Object
- #validate_params! ⇒ Object
Class Method Details
.included(includer) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/chef/knife/helpers/azurerm_base.rb', line 31 def self.included(includer) includer.class_eval do deps do require "readline" require "chef/json_compat" require_relative "../../azure/resource_management/ARM_interface" require "chef/mixin/shell_out" require "time" require "json" if Chef::Platform.windows? require_relative "../../azure/resource_management/windows_credentials" include Azure::ARM::WindowsCredentials end end option :azure_resource_group_name, short: "-r RESOURCE_GROUP_NAME", long: "--azure-resource-group-name RESOURCE_GROUP_NAME", description: "The Resource Group name." end end |
Instance Method Details
#authentication_details ⇒ Object
95 96 97 98 99 100 101 102 103 104 105 106 |
# File 'lib/chef/knife/helpers/azurerm_base.rb', line 95 def authentication_details if is_azure_cred? return { azure_tenant_id: locate_config_value(:azure_tenant_id), azure_client_id: locate_config_value(:azure_client_id), azure_client_secret: locate_config_value(:azure_client_secret) } elsif Chef::Platform.windows? token_details = token_details_for_windows else token_details = token_details_for_linux end token_details = check_token_validity(token_details) token_details end |
#azure_authentication ⇒ Object
154 155 156 157 158 159 160 |
# File 'lib/chef/knife/helpers/azurerm_base.rb', line 154 def azure_authentication ui.log("Authenticating...") Mixlib::ShellOut.new("#{@azure_prefix} vm show 'knifetest@resourcegroup' testvm", timeout: 30).run_command rescue Mixlib::ShellOut::CommandTimeout rescue Exception raise_azure_status end |
#check_token_validity(token_details) ⇒ Object
162 163 164 165 166 167 168 |
# File 'lib/chef/knife/helpers/azurerm_base.rb', line 162 def check_token_validity(token_details) unless is_token_valid?(token_details) token_details = refresh_token raise_azure_status unless is_token_valid?(token_details) end token_details end |
#find_file(name) ⇒ Object
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 |
# File 'lib/chef/knife/helpers/azurerm_base.rb', line 212 def find_file(name) name = ::File.(name) config_dir = Chef::Knife.chef_config_dir if File.exist? name file = name elsif config_dir && File.exist?(File.join(config_dir, name)) file = File.join(config_dir, name) elsif File.exist?(File.join(ENV["HOME"], ".chef", name)) file = File.join(ENV["HOME"], ".chef", name) else ui.error("Unable to find file - " + name) exit 1 end file end |
#get_azure_cli_version ⇒ Object
108 109 110 111 112 113 114 115 |
# File 'lib/chef/knife/helpers/azurerm_base.rb', line 108 def get_azure_cli_version if @azure_version != "" get_version = shell_out!("azure -v || az -v | grep azure-cli", { returns: [0] }).stdout @azure_version = get_version.gsub(/[^0-9.]/, "") end @azure_prefix = @azure_version.to_i < 2 ? "azure" : "az" @azure_version end |
#is_token_valid?(token_details) ⇒ Boolean
137 138 139 140 141 142 143 144 145 146 147 |
# File 'lib/chef/knife/helpers/azurerm_base.rb', line 137 def is_token_valid?(token_details) time_difference = Time.parse(token_details[:expiry_time]) - Time.now.utc if time_difference <= 0 return false elsif time_difference <= 600 # 600sec = 10min # This is required otherwise a long running command may fail inbetween if the token gets expired. raise "Token will expire within 10 minutes. Please run '#{@azure_prefix} login' command" else return true end end |
#locate_config_value(key) ⇒ Object
64 65 66 67 68 69 70 71 |
# File 'lib/chef/knife/helpers/azurerm_base.rb', line 64 def locate_config_value(key) key = key.to_sym if defined?(config_value) # Inherited by bootstrap config_value(key) || default_config[key] else config[key] || Chef::Config[:knife][key] || default_config[key] end end |
#msg_server_summary(server) ⇒ Object
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 |
# File 'lib/chef/knife/helpers/azurerm_base.rb', line 228 def msg_server_summary(server) puts "\n\n" if server.provisioningstate == "Succeeded" Chef::Log.info("Server creation went successfull.") puts "\nServer Details are:\n" msg_pair("Server ID", server.id) msg_pair("Server Name", server.name) msg_pair("Server Public IP Address", server.publicipaddress) if is_image_windows? msg_pair("Server RDP Port", server.rdpport) else msg_pair("Server SSH Port", server.sshport) end msg_pair("Server Location", server.locationname) msg_pair("Server OS Type", server.ostype) msg_pair("Server Provisioning State", server.provisioningstate) else Chef::Log.info("Server Creation Failed.") end puts "\n\n" if server.resources.provisioning_state == "Succeeded" Chef::Log.info("Server Extension creation went successfull.") puts "\nServer Extension Details are:\n" msg_pair("Server Extension ID", server.resources.id) msg_pair("Server Extension Name", server.resources.name) msg_pair("Server Extension Publisher", server.resources.publisher) msg_pair("Server Extension Type", server.resources.type) msg_pair("Server Extension Type Handler Version", server.resources.type_handler_version) msg_pair("Server Extension Provisioning State", server.resources.provisioning_state) else Chef::Log.info("Server Extension Creation Failed.") end puts "\n" end |
#parse_publish_settings_file(filename) ⇒ Object
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
# File 'lib/chef/knife/helpers/azurerm_base.rb', line 185 def parse_publish_settings_file(filename) require "nokogiri" require "base64" require "openssl" require "uri" begin doc = Nokogiri::XML(File.open(find_file(filename))) profile = doc.at_css("PublishProfile") subscription = profile.at_css("Subscription") # check given PublishSettings XML file format.Currently PublishSettings file have two different XML format if profile.attribute("SchemaVersion").nil? management_cert = OpenSSL::PKCS12.new(Base64.decode64(profile.attribute("ManagementCertificate").value)) Chef::Config[:knife][:azure_api_host_name] = URI(profile.attribute("Url").value).host elsif profile.attribute("SchemaVersion").value == "2.0" management_cert = OpenSSL::PKCS12.new(Base64.decode64(subscription.attribute("ManagementCertificate").value)) Chef::Config[:knife][:azure_api_host_name] = URI(subscription.attribute("ServiceManagementUrl").value).host else ui.error("Publish settings file Schema not supported - " + filename) end Chef::Config[:knife][:azure_mgmt_cert] = management_cert.certificate.to_pem + management_cert.key.to_pem Chef::Config[:knife][:azure_subscription_id] = doc.at_css("Subscription").attribute("Id").value rescue => error puts "#{error.class} and #{error.}" exit 1 end end |
#refresh_token ⇒ Object
149 150 151 152 |
# File 'lib/chef/knife/helpers/azurerm_base.rb', line 149 def refresh_token azure_authentication token_details = Chef::Platform.windows? ? token_details_for_windows : token_details_for_linux end |
#service ⇒ Object
54 55 56 57 58 59 60 61 62 |
# File 'lib/chef/knife/helpers/azurerm_base.rb', line 54 def service details = authentication_details details.update(azure_subscription_id: locate_config_value(:azure_subscription_id)) @service ||= begin service = Azure::ResourceManagement::ARMInterface.new(details) end @service.ui = ui @service end |
#token_details_for_linux ⇒ Object
125 126 127 |
# File 'lib/chef/knife/helpers/azurerm_base.rb', line 125 def token_details_for_linux token_details_from_accessToken_file end |
#token_details_for_windows ⇒ Object
117 118 119 120 121 122 123 |
# File 'lib/chef/knife/helpers/azurerm_base.rb', line 117 def token_details_for_windows if is_old_xplat? token_details_from_WCM else is_WCM_env_var_set? ? token_details_from_WCM : token_details_from_accessToken_file end end |
#token_details_from_accessToken_file ⇒ Object
129 130 131 132 133 134 135 |
# File 'lib/chef/knife/helpers/azurerm_base.rb', line 129 def token_details_from_accessToken_file home_dir = File.("~") file = File.read(home_dir + "/.azure/accessTokens.json") file = JSON.parse(file) token_details = { tokentype: file[-1]["tokenType"], user: file[-1]["userId"], token: file[-1]["accessToken"], clientid: file[-1]["_clientId"], expiry_time: file[-1]["expiresOn"], refreshtoken: file[-1]["refreshToken"] } token_details end |
#validate_arm_keys!(*keys) ⇒ Object
validates ARM mandatory keys
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
# File 'lib/chef/knife/helpers/azurerm_base.rb', line 74 def validate_arm_keys!(*keys) parse_publish_settings_file(locate_config_value(:azure_publish_settings_file)) unless locate_config_value(:azure_publish_settings_file).nil? keys.push(:azure_subscription_id) if azure_cred? validate_azure_login else keys.concat(%i{azure_tenant_id azure_client_id azure_client_secret}) end errors = [] keys.each do |k| if locate_config_value(k).nil? errors << "You did not provide a valid '#{pretty_key(k)}' value. Please set knife[:#{k}] in your knife.rb." end end if errors.each { |e| ui.error(e) }.any? exit 1 end end |
#validate_azure_login ⇒ Object
170 171 172 173 174 175 176 177 178 179 180 181 182 183 |
# File 'lib/chef/knife/helpers/azurerm_base.rb', line 170 def validate_azure_login if Chef::Platform.windows? && (is_old_xplat? || is_WCM_env_var_set?) # cmdkey command is used for accessing windows credential manager xplat_creds_cmd = Mixlib::ShellOut.new("cmdkey /list | findstr AzureXplatCli") result = xplat_creds_cmd.run_command raise if result.stdout.nil? || result.stdout.empty? else home_dir = File.("~") puts "File.exist? = #{File.exist?("a")}" if !File.exist?(home_dir + "/.azure/accessTokens.json") || File.size?(home_dir + "/.azure/accessTokens.json") <= 2 raise end end end |
#validate_params! ⇒ Object
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 |
# File 'lib/chef/knife/helpers/azurerm_base.rb', line 267 def validate_params! if locate_config_value(:connection_user).nil? raise ArgumentError, "Please provide --connection-user option for authentication." end unless locate_config_value(:connection_password).nil? ^ locate_config_value(:ssh_public_key).nil? raise ArgumentError, "Please specify either --connection-password or --ssh-public-key option for authentication." end if locate_config_value(:azure_vnet_subnet_name) && !locate_config_value(:azure_vnet_name) raise ArgumentError, "When --azure-vnet-subnet-name is specified, the --azure-vnet-name must also be specified." end if locate_config_value(:azure_vnet_subnet_name) == "GatewaySubnet" raise ArgumentError, "GatewaySubnet cannot be used as the name for --azure-vnet-subnet-name option. GatewaySubnet can only be used for virtual network gateways." end if locate_config_value(:node_ssl_verify_mode) && !%w{none peer}.include?(locate_config_value(:node_ssl_verify_mode)) raise ArgumentError, "Invalid value '#{locate_config_value(:node_ssl_verify_mode)}' for --node-ssl-verify-mode. Use Valid values i.e 'none', 'peer'." end if !is_image_windows? if (locate_config_value(:azure_vm_name).match /^(?=.*[a-zA-Z-])([a-zA-z0-9-]{1,64})$/).nil? raise ArgumentError, "VM name can only contain alphanumeric and hyphen(-) characters and maximun length cannot exceed 64 charachters." end elsif (locate_config_value(:azure_vm_name).match /^(?=.*[a-zA-Z-])([a-zA-z0-9-]{1,15})$/).nil? raise ArgumentError, "VM name can only contain alphanumeric and hyphen(-) characters and maximun length cannot exceed 15 charachters." end if locate_config_value(:server_count).to_i > 5 raise ArgumentError, "Maximum allowed value of --server-count is 5." end if locate_config_value(:daemon) unless is_image_windows? raise ArgumentError, "The daemon option is only support for Windows nodes." end unless %w{none service task}.include?(locate_config_value(:daemon)) raise ArgumentError, "Invalid value for --daemon option. Use valid daemon values i.e 'none', 'service' and 'task'." end end if locate_config_value(:azure_image_os_type) unless %w{ubuntu centos rhel debian windows}.include?(locate_config_value(:azure_image_os_type)) raise ArgumentError, "Invalid value of --azure-image-os-type. Accepted values ubuntu|centos|rhel|debian|windows" end end config[:ohai_hints] = format_ohai_hints(locate_config_value(:ohai_hints)) validate_ohai_hints unless locate_config_value(:ohai_hints).casecmp("default").zero? end |