How can I pass a value from a TeamCity failure Condition to an e-mail notification? - kotlin

I want to show the status of the build in an e-mail with just a simple FAIL or PASS text appear in the body. There does not seem to be any kind of predefined "buildStatus" variable that I can access or setup in TeamCity. I guess I need to access the "failureConditions" function at bottom but not sure how, tried lots of things but nothing worked, this is my script:
package _Self.buildTypes
import jetbrains.buildServer.configs.kotlin.v2019_2.failureConditions.BuildFailureOnText
import jetbrains.buildServer.configs.kotlin.v2019_2.failureConditions.failOnText
import jetbrains.buildServer.configs.kotlin.v2019_2.triggers.schedule
allowExternalStatus = true
params {
param("MinorVersion", "0")
param("RevisionVersion", "0")
}
powerShell {
name = "Email"
scriptMode = script {
content = """
function Send-ToEmail([string]${'$'}email, [string]${'$'}attachmentpath){
${'$'}message = new-object Net.Mail.MailMessage;
${'$'}message.From = "teamcity#blog.com";
${'$'}message.To.Add(${'$'}email);
${'$'}message.Subject = "%env.TEAMCITY_PROJECT_NAME% | %VersionNumber% ";
${'$'}message.Body = "The build: PASS or FAIL text here";
${'$'}smtp = new-object Net.Mail.SmtpClient("blog.local", "25");
${'$'}smtp.EnableSSL = ${'$'}true;
${'$'}smtp.send(${'$'}message);
write-host "Mail Sent" ;
}
Send-ToEmail -email "me#blog.com" -attachmentpath ${'$'}path;
""".trimIndent()
}
}
}
failureConditions {
failOnText {
conditionType = BuildFailureOnText.ConditionType.CONTAINS
pattern = "FAIL"
reverse = false
}
}

To solve this in T/C:
Create new custom env. var. e.g. MyBuildStatus
Create new build step e.g. Set build status (only executes if build successful)
Create a new Parameter name='env.MyBuildStatus.Status' value='SUCCESS'
Add variable to email subject: $message.Subject = "%env.MyBuildStatus.Status%
Why T/C has no build in "buildstatus" env. variable is interesting.

Related

LrDialogs.runOpenDialog not working inside LrExportServiceProvider

I am trying to create a Lightroom Classic Export Service Provider plugin that has a Browse... button in the sectionsForTopOfDialog to allow the user to choose a Folder related to the plugin. The open dialog is attached to the action of the viewFactory:push_button, and the dialog opens successfully, but it seems like the rest of the push button's action is never executed, as if the runOpenPanel function never returned.
How can I create a Browse button to allow the user to select a folder and get the result? (I want to store the result in the propertyTable, this part is omitted from the code.)
Complete plugin code to reproduce the issue below. (Create a folder named runOpenDialogMCVE.lrdevplugin folder, add these files, load it as a Lightroom plugin.)
-- Info.lua
return {
LrSdkVersion = 3.0,
LrSdkMinimumVersion = 1.3, -- minimum SDK version required by this plugin
LrPluginName = "RunOpenPanel MCVE",
LrToolkitIdentifier = 'com.example.lightroom.runopenpanelmcve',
LrExportServiceProvider = {
title = "LrDialogs.runOpenPanel MCVE",
file = 'ExportServiceProvider.lua',
},
VERSION = { major=0, minor=1, revision=0 },
}
-- ExportServiceProvider.lua
local LrDialogs = import 'LrDialogs'
local LrLogger = import 'LrLogger'
local LrView = import 'LrView'
local logger = LrLogger("LrDialogs.runOpenDialogMCVE")
local viewFactory = LrView.osFactory()
logger:enable("print")
local ExportServiceProvider = {}
function ExportServiceProvider.sectionsForTopOfDialog( propertyTable )
return {
{
title = "LrDialogs.runOpenDialog MCVE",
viewFactory:row {
viewFactory:push_button {
title = "Browse...",
action = function ()
logger:trace("Opening dialog...")
LrDialogs.message("Will open dialog after this.")
local result = LrDialogs.runOpenPanel( {
title = "Location",
prompt = "Choose",
canChooseDirectories = true,
canChooseFiles = false,
allowsMultipleSelection = false,
} )
-- I would expect the code below to execute, but it never does.
-- No trace is printed and none of the dialogs below are shown.
logger.trace("Closing dialog. "..tostring(result))
if result ~= nil then
logger:trace("Chosen folder: "..result[1])
LrDialogs.message("Choseen folder: "..result[1])
else
logger:trace("Cancelled")
LrDialogs.message("Cancelled")
end
end,
},
},
},
}
end
return ExportServiceProvider
I'm using Lightroom version 12.0 on MacOS.

Invalid character error while running terraform init, terraform plan or apply

I'm running Terraform using VScode editor which uses PowerShell as the default shell and getting the same error when I try to validate it or to run terraform init/plan/apply through VScode, external PowerShell or CMD.
The code was running without any issues until I added Virtual Machine creation code. I have clubbed the variables.tf, terraform.tfvars and the main Terraform code below.
terraform.tfvars
web_server_location = "West US 2"
resource_prefix = "web-server"
web_server_address_space = "1.0.0.0/22"
web_server_address_prefix = "1.0.1.0/24"
Environment = "Test"
variables.tf
variable "web_server_location" {
type = string
}
variable "resource_prefix" {
type = string
}
variable "web_server_address_space" {
type = string
}
#variable for network range
variable "web_server_address_prefix" {
type = string
}
#variable for Environment
variable "Environment" {
type = string
}
terraform_example.tf
# Configure the Azure Provider
provider "azurerm" {
# whilst the `version` attribute is optional, we recommend pinning to a given version of the Provider
version = "=2.0.0"
features {}
}
# Create a resource group
resource "azurerm_resource_group" "example_rg" {
name = "${var.resource_prefix}-RG"
location = var.web_server_location
}
# Create a virtual network within the resource group
resource "azurerm_virtual_network" "example_vnet" {
name = "${var.resource_prefix}-vnet"
resource_group_name = azurerm_resource_group.example_rg.name
location = var.web_server_location
address_space = [var.web_server_address_space]
}
# Create a subnet within the virtual network
resource "azurerm_subnet" "example_subnet" {
name = "${var.resource_prefix}-subnet"
resource_group_name = azurerm_resource_group.example_rg.name
virtual_network_name = azurerm_virtual_network.example_vnet.name
address_prefix = var.web_server_address_prefix
}
# Create a Network Interface
resource "azurerm_network_interface" "example_nic" {
name = "${var.resource_prefix}-NIC"
location = azurerm_resource_group.example_rg.location
resource_group_name = azurerm_resource_group.example_rg.name
ip_configuration {
name = "internal"
subnet_id = azurerm_subnet.example_subnet.id
private_ip_address_allocation = "Dynamic"
public_ip_address_id = azurerm_public_ip.example_public_ip.id
}
}
# Create a Public IP
resource "azurerm_public_ip" "example_public_ip" {
name = "${var.resource_prefix}-PublicIP"
location = azurerm_resource_group.example_rg.location
resource_group_name = azurerm_resource_group.example_rg.name
allocation_method = var.Environment == "Test" ? "Static" : "Dynamic"
tags = {
environment = "Test"
}
}
# Creating resource NSG
resource "azurerm_network_security_group" "example_nsg" {
name = "${var.resource_prefix}-NSG"
location = azurerm_resource_group.example_rg.location
resource_group_name = azurerm_resource_group.example_rg.name
# Security rule can also be defined with resource azurerm_network_security_rule, here just defining it inline.
security_rule {
name = "RDPInbound"
priority = 100
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "3389"
source_address_prefix = "*"
destination_address_prefix = "*"
}
tags = {
environment = "Test"
}
}
# NIC and NSG association
resource "azurerm_network_interface_security_group_association" "example_nsg_association" {
network_interface_id = azurerm_network_interface.example_nic.id
network_security_group_id = azurerm_network_security_group.example_nsg.id
}
# Creating Windows Virtual Machine
resource "azurerm_virtual_machine" "example_windows_vm" {
name = "${var.resource_prefix}-VM"
location = azurerm_resource_group.example_rg.location
resource_group_name = azurerm_resource_group.example_rg.name
network_interface_ids = [azurerm_network_interface.example_nic.id]
vm_size = "Standard_B1s"
delete_os_disk_on_termination = true
storage_image_reference {
publisher = "MicrosoftWindowsServer"
offer = "WindowsServerSemiAnnual"
sku  = "Datacenter-Core-1709-smalldisk"
version = "latest"
}
storage_os_disk  {
name = "myosdisk1"
caching  = "ReadWrite"
create_option = "FromImage"
storage_account_type = "Standard_LRS"
}
os_profile {
computer_name = "hostname"
admin_username = "adminuser"
admin_password = "Password1234!"
}
os_profile_windows_config {
disable_password_authentication = false
}
tags = {
environment = "Test"
}
}
Error:
PS C:\Users\e5605266\Documents\MyFiles\Devops\Terraform> terraform init
There are some problems with the configuration, described below.
The Terraform configuration must be valid before initialization so that
Terraform can determine which modules and providers need to be installed.
Error: Invalid character
on terraform_example.tf line 89, in resource "azurerm_virtual_machine" "example_windows_vm":
89: location = azurerm_resource_group.example_rg.location
This character is not used within the language.
Error: Invalid expression
on terraform_example.tf line 89, in resource "azurerm_virtual_machine" "example_windows_vm":
89: location = azurerm_resource_group.example_rg.location
Expected the start of an expression, but found an invalid expression token.
Error: Argument or block definition required
on terraform_example.tf line 90, in resource "azurerm_virtual_machine" "example_windows_vm":
90: resource_group_name = azurerm_resource_group.example_rg.name
An argument or block definition is required here. To set an argument, use the
equals sign "=" to introduce the argument value.
Error: Invalid character
on terraform_example.tf line 90, in resource "azurerm_virtual_machine" "example_windows_vm":
90: resource_group_name = azurerm_resource_group.example_rg.name
This character is not used within the language.
*
I've encountered this problem myself in several different contexts, and it does have a common solution which is no fun at all: manually typing the code back in...
This resource block seems to be where it runs into problems:
resource "azurerm_virtual_machine" "example_windows_vm" {
name = "${var.resource_prefix}-VM"
location = azurerm_resource_group.example_rg.location
resource_group_name = azurerm_resource_group.example_rg.name
network_interface_ids = [azurerm_network_interface.example_nic.id]
vm_size = "Standard_B1s"
delete_os_disk_on_termination = true
storage_image_reference {
publisher = "MicrosoftWindowsServer"
offer = "WindowsServerSemiAnnual"
sku  = "Datacenter-Core-1709-smalldisk"
version = "latest"
}
storage_os_disk  {
name = "myosdisk1"
caching  = "ReadWrite"
create_option = "FromImage"
storage_account_type = "Standard_LRS"
}
os_profile {
computer_name = "hostname"
admin_username = "adminuser"
admin_password = "Password1234!"
}
os_profile_windows_config {
disable_password_authentication = false
}
tags = {
environment = "Test"
}
}
Try copying that back into your editor as is. I cannot see any problematic characters in it, and ironically StackOverflow may have done you a solid and filtered them out. Literally copy/pasting it over the existing block may remedy the situation.
I have seen Terraform examples online with stylish double quotes (which aren't ASCII double quotes and won't work) many times. That may be what you are seeing.
Beyond that, you'd need to push your code to GitHub or similar so I can see the raw bytes for myself.
In the off-chance this helps someone who runs into this error and comes across it on Google, I just thought I would post my situation and how I fixed it.
I have an old demo Terraform infrastructure that I revisited after months and, long story short, I issued this command two days ago and forgot about it:
terraform plan -out=plan.tf
This creates a zip archive of the plan. Upon coming back two days later and running a terraform init, my terminal scrolled garbage and "This character is not used within the language." for about 7 seconds. Due to the .tf extension, terraform was looking at the zip data and promptly pooping its pants.
Through moving individual tf files to a temp directory and checking their validity with terraform init, I found the culprit, deleted it, and functionality was restored.
Be careful when exporting your plan files, folks!
I ran into the same problem and found this page.
I solved the issue and decided to post here.
I opened my plan file in Notepad++ and selected View-Show all symbols.
I removed all the TAB characters and replaced them with spaces.
In my case, the problem was fully resolved by this.
In my case, when I ran into the same problem ("This character is not used within the language"), I found the encoding of the files was UTF-16 (it was a generated file from PS). Changing the file encoding to UTF-8 (as mentioned in this question) solved the issue.
I found I got this most often when I go from Windows to linux. The *.tf file does not like the windows TABs and Line Breaks.
I tried to some of the same tools I use when I have this problem with *.sh, but so far I've resorted to manually cleaning up the lines I've seen in there error.
In my case, the .tf file was generated by the following command terraform show -no-color > my_problematic.tf, and this file's encoding is in "UTF-16 LE BOM", converting it to UTF-8 fixed my issue.

Datadog monitor API/terraform process monitor check

I'm trying to integrate a Datadog monitor check on sshd process in my terraform codebase, but I'm getting datadog_monitor.host_is_up2: error updating monitor: API error 400 Bad Request: {"errors":["The value provided for parameter 'query' is invalid"]}
What I did was to copy the monitor's query I created on the Datadog panel and pasted it into the tf file:
resource "datadog_monitor" "host_is_up2" {
name = "host is up"
type = "metric alert"
message = "Monitor triggered"
escalation_message = "Escalation message"
query = "process.up.over('process:ssh').last(4).count_by_status()"
thresholds {
ok = 0
warning = 1
critical = 2
}
notify_no_data = false
renotify_interval = 60
notify_audit = false
timeout_h = 60
include_tags = true
silenced {
"*" = 0
}
}
ofc the query example "avg(last_1h):avg:aws.ec2.cpu{environment:foo,host:foo} by {host} > 2" works
What's the right way to check via Datadog API or terraform if a specific service, like sshd, is up or not?
There are two error in your code:
The type used is wrong. It should be service check instead of metric alert.
You need to enclose process.up in a pair of ''.
Once done, your code will run flawlessly.

Sense/net using content query in console application

I try to use content query in console application but it throw an exception "Object reference not set to an instance of an object".
Please give help me resolve that problem.
var startSettings = new RepositoryStartSettings
{
Console = Console.Out,
StartLuceneManager = false,
IsWebContext = false,
PluginsPath = AppDomain.CurrentDomain.BaseDirectory,
};
using (Repository.Start(startSettings))
{
try
{
string path = "/Root/Sites/Default_Site/workspaces/Document/HACCP/Document_Library/SanXuat/ChonLocChuanBiDiaDiemSXRau";
string fieldName1 = "Name";
var content = Content.Load(path);
int count = ContentQuery.Query(".AUTOFILTERS:OFF .COUNTONLY Infolder:" + path).Count;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
if you want to execute a content query, you have to enable LuceneManager when you start the repository, because that component is responsible for querying.
new RepositoryStartSettings
{
Console = Console.Out,
StartLuceneManager = true, // <-- this is necessary
IsWebContext = false,
PluginsPath = AppDomain.CurrentDomain.BaseDirectory,
}
Please make sure that all the config values are in place (e.g. index directory path, enable outer search engine). You can copy them from the Export or Import tool's config file.
A few more notes:
in a content query please always enclose path expressions in quotes, because if there is a space in the path, it causes a query error that is hard to find (because it would return a different result set). For example:
InTree:'/Root/My Folder'
Or you can use the built-in parameter feature that makes sure the same:
// note the #0 parameter, which is a 0-based index
ContentQuery.Query("+TypeIs:Article +InTree:#0", null, containerPath);

Jenkins - Email notifications

I'm trying to customize email using Groovy with the email-ext plugin. As I add new features to these emails, I may introduce errors in the scripts and so receive bad mails containing the StackTrace. So, I'd like to be able to send notifications on finished jobs as my jobs may take many hours (more than 4 currently).
Is there a way to ask jenkins to send notifications on finished jobs (using Groovy or any other scripting language)?
find a solution :
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import groovy.text.Template
import groovy.text.SimpleTemplateEngine
import javax.mail.*
import javax.mail.internet.*
//-------------- Job params --------------
projectName="YourProjectName";
buildNum = 10;
templateName="groovy-html-cobertura.template";
recipients="someone#somewhere.com";
sender="jenkins#somewhere.com";
smtpHost="mysmtphost";
//------------End Job params -------------
for (hudson.model.AbstractProject p : hudson.model.Hudson.instance.projects) {
if(p.name.equals(projectName)){
for (hudson.model.AbstractBuild b : p.getBuilds() ) {
if(b.getNumber() == buildNum){
println b;
b.reload();
def binding = [ "build" : b,
"project" : b.getProject(),
"rooturl" : hudson.model.Hudson.getInstance().getRootUrl(),
"it" : new hudson.plugins.emailext.plugins.content.ScriptContentBuildWrapper(b),
"spc" : " " ]
def engine = new SimpleTemplateEngine()
java.io.File file = new java.io.File(hudson.model.Hudson.getInstance ().getRootPath().getBaseName()+"/email-templates/"+templateName);
mailBody = engine.createTemplate(file.getText()).make(binding).toString();
port = 25
props = new Properties()
props.put('mail.smtp.host', smtpHost)
props.put('mail.smtp.port', port.toString())
session = Session.getDefaultInstance(props, null)
// Construct the message
msg = new MimeMessage(session)
msg.from = new InternetAddress(sender)
msg.sentDate = new Date()
msg.subject = 'Template Test'
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients))
msg.setHeader('Organization', 'i-BP')
msg.setContent(mailBody,
'text/html')
// Send the message
Transport.send(msg)
}
}
}
}