Extract AWS Cost Reports by Tags – Part 1

Hello everyone,

On today’s tip, I would like to share on how you can activate or disable tags in the AWS Billing page in the AWS console.

The scenario here is pretty simple.

As an user responsible for AWS Billing, I would like to view my AWS costs based on certain tags that are being used when people are deploying resources into the account.

So, to execute the above request, perform the following steps in your AWS account.

  1. Using the AWS Console
    • On the AWS console search for Billing.
    • On the Billing dashboard, click on the Cost allocation tags located in the left-hand side of the page.
    • Once the page opens, use the search bar to find the tag you wish to enable.
    • Select the tag you wish to enable, and click on Activate.
    • A prompt will appear to confirm your choices. Just click on Activate once again.
    • Notice that it may take up to 24 hours for the new tag to reflect in the AWS Cost Explorer page.
  2. Using the AWS CLI
    • Using either AWS Cloud Shell or your local AWS CLI, execute the below command.
      aws ce update-cost-allocation-tags-status --cost-allocation-tags-status TagKey=StackName,Status=Active
    • If the action has been executed successfully, you should see similar output in your terminal.

I hope the information is valuable, and if you have any questions, leave me a message in the comments.

How to connect Amazon SNS to Lambda with Terraform

Hello everyone,

Today I wanted to share a quick code snippet of how you can connect Amazon SNS to AWS Lambda using Terraform. What I have seen on the web sometimes is never a complete solution, rather parts of code, which at the end, it doesn’t help you that much.

Hopefully, the below script should give you a complete overview of the same.

######## TERRAFORM PARAMETERS ########
variable "app_name" {
  description = "The name of the application being built"
  default     = "data-archiving"

}

# Customer needs to change for account specifics
variable "region_primary" {
  default = "eu-west-1"
}

# Customer needs to change for account specifics
variable "sns_topic_properties" {
  type        = object({ kms_master_key_id = string })
  description = "SNS Topic"
  default = {

    kms_master_key_id = "alias/aws/sns"

  }
}

# Customer needs to change for account specifics
variable "delete_data_lambda_function_properties" {
  type        = object({ filename = string, runtime = string, handler = string, timeout = number, cloudwatch_log_group_retention_in_days = number })
  description = "Lambda Function"
  default = {
    filename                               = "nametest.zip"
    runtime                                = "python3.8"
    handler                                = "delete_data_lambda_function.lambda_handler"
    timeout                                = 120
    cloudwatch_log_group_retention_in_days = 14
  }
}

### Tags
variable "tags" {
  description = "A map of tags to add to all resources"
  type        = map(any)
  default = {
    deployed_by = "terraform"
  }
}

######## TERRAFORM RESOURCE CREATION ########

data "aws_iam_policy_document" "lambda_assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = ["lambda.amazonaws.com"]
    }
  }
}

####### Lambda Role #######
resource "aws_iam_role" "lambda_role" {
  name               = format("%s-lambda-role", var.app_name)
  assume_role_policy = data.aws_iam_policy_document.lambda_assume_role_policy.json
  tags               = var.tags
}



resource "aws_sns_topic" "sns_archive_topic" {
  name              = format("%s-topic", var.app_name)
  kms_master_key_id = var.sns_topic_properties.kms_master_key_id
  tags              = var.tags
}

data "archive_file" "python_lambda_package" {
  type        = "zip"
  source_file = "${path.module}/code/lambda_code.py"
  output_path = var.delete_data_lambda_function_properties.filename
}

resource "aws_lambda_function" "delete_data_lambda_function" {
 function_name       = format("%s-delete-data-lambda-function", var.app_name)
 filename                 = var.delete_data_lambda_function_properties.filename
 source_code_hash  = data.archive_file.python_lambda_package.output_base64sha256
 role                         = aws_iam_role.lambda_role.arn
 runtime                  = var.delete_data_lambda_function_properties.runtime
 handler                  = var.delete_data_lambda_function_properties.handler
 timeout                  = var.delete_data_lambda_function_properties.timeout
 tags                        = var.tags

  environment {
    variables = {
      AWS_REGION_PRIMARY  = var.region_primary
    }
  }
}

resource "aws_sns_topic_subscription" "lambda_topic_subscription" {
  topic_arn = aws_sns_topic.sns_archive_topic.arn
  protocol  = "lambda"
  endpoint  = aws_lambda_function.delete_data_lambda_function.arn
}

resource "aws_lambda_permission" "lambda_sns_permission" {
  statement_id  = "AllowExecutionFromSNS"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.delete_data_lambda_function.arn
  principal     = "sns.amazonaws.com"
  source_arn    = aws_sns_topic.sns_archive_topic.arn
}

resource "aws_cloudwatch_log_group" "lambda_cloudwatch_group" {
name              = format("/aws/lambda/%s", aws_lambda_function.delete_data_lambda_function.function_name)
retention_in_days = var.delete_data_lambda_function_properties.cloudwatch_log_group_retention_in_days
  tags              = var.tags
}

I know it is lengthy code, but this gives an end to end demonstration of SNS to Lambda Trigger. The most important bit in the above code are the two resources being used: aws_sns_topic_subscription and aws_lambda_permission. Those are two that gives you the link between the services, and should allow you use them.

Be aware that I am skipping also the configuration of the AWS terraform provider of this post, as it is irrelevant for what I am trying to show. Perhaps, I will demonstrate in a later blog how to do so.

Once the solution is deployed, you should see similar thing in your account.

If you have any questions or comments, leave it in the comments section of this post.

Happy coding!

Marcos Freccia

Instalando o Visual Studio Code

Olá pessoal, tudo bom com vocês?

Como vocês podem ver, estou ha um longo tempo sem postar nada aqui em meu blog, principalmente na língua portuguesa. Com a minha mudança para a Alemanha no início de 2017, e por focar mais aqui no mercado da Europa, acabei por focar um pouco mais na língua inglesa para postagens.

Aproveitando o gancho da postagem. Vocês tem curiosidade em saber mais como foi o meu processo de mudança aqui para a Alemanha (mais especificamente Berlim)?

Caso vocês queiram saber mais, posso também fazer um vídeo explicando todo o processo para vocês. Deixa um comentário aqui nesse post caso vocês queiram.

missed

 

Mas porque estou voltando com posts em Português?

A resposta para essa pergunta é bastante simples. Um dos conteúdos que gosto muito de falar é sobre PowerShell e nesse ultimo ano tenho especialmente trabalhado com dbatools. Não sei o porquê, mas enquanto trabalhava no Brasil, não via muitas pessoas utilizando esse módulo e notei que existem poucos materiais sobre o mesmo em minha língua materna. Esse é o motivo que vou voltar a escrever um pouco mais.

Todas as segundas-feiras, vou lançar um vídeo novo em meu canal do Youtube sobre alguma função do dbatools que utilizo no meu dia-a-dia como administrador de banco de dados. Afinal, esse é um excelente módulo que merece ser amplamente dessiminado em nossa língua.

Para esse primeiro vídeo, decidi começar do mais simples possível! Como instalar o Visual Studio Code e instalar a extensão do PowerShell para a mesma.

Espero que vocês gostem do conteúdo que estou preparando e fico ansiosamente aguardando por sugestões, críticas ou elogios de vocês! 

Ah, se inscrevam também no meu canal no Youtube, assim quando qualquer novo vídeo sair, vocês irão receber uma notificação.

Abraços e até o próximo vídeo!

Marcos Freccia
Data Platform MVP

 

Creating Database Link from AWS RDS to OnPremises

Hi Folks,

It has been a very long time that I don’t write anything in here, but I just wanted to share with you something that you might find useful for doing Oracle migrations. I wanted to create a Database Link from my AWS Oracle RDS Instance to an Oracle sitting on an On-premises environment.

Of course the very first thing you need to have is internal network connectivity between the instances. Take a look on this part of the documentation for more specification. Assuming that you have the connectivity between then, this is the script you need to execute on your Oracle RDS Instance.

create database link <NameOfDBLink>
connect to UserName
identified by “UserNamePassword”
using ‘(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=TheHostAddressOrIp)(PORT=TCPPortHere))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=TheOracleServiceName)))’;

To test that your database link has been successfully created, you can do a simple test by executing the following query.

select sysdate from dual@NameOfDBLink;

Best,
Marcos Freccia

Como restaurar bancos de dados no SQL Server

Olá pessoal, tudo bom com vocês?

Nos artigos anteriores demos inicio a nossa sequencia de vídeos sobre o dbatools, onde realizamos a instalação do Visual Studio Code e consequentemente instalamos o módulo do dbatools. Abordamos também nossos primeiros comandos: Get-DbaLogin e Export-DbaLogin.

Pois bem, aprofundando um pouco mais em todas as áreas do dbatools, vamos agora abordar um tópico bastante importante: A restauração de um banco de dados.

Uma das tarefas do administrador de banco de dados recorrentes é realizar a restauração, ou na linguagem técnica “restore” de um banco, seja a mesma sobrescrever um banco já existente, ou até mesmo restaurar um único banco para várias instancias em servidores diferentes.

Como sempre o módulo do dbatools possui comandos que nos ajudam e muito nessa tarefa. Aconselho vocês a assistirem o vídeo abaixo e aprender um pouco mais sobre esse poderoso módulo para administração de SQL Server.


Como sempre peço por aqui e nos vídeos, fico sempre aguardando os comentários, sugestões, e até mesmo dicas de vídeos que gostariam de ver por aqui.

Se inscrevam também no meu canal do Youtube para sempre receberem as notificações de vídeos novos.

Um grande abraço para vocês e até o próximo vídeo!

Marcos Freccia
Data Platform MVP

Retornando e Exportando Logins no SQL Server

Olá pessoal, tudo bom com vocês?

Nos artigos anteriores demos inicio a nossa sequencia de vídeos sobre o dbatools, onde realizamos a instalação do Visual Studio Code e consequentemente instalamos o módulo do dbatools.

Nesse vídeo é onde de fato vamos abortar os primeiros comandos que compoem esse maravilhoso módulo que são: Get-DbaLogin e Export-DbaLogin. Vocês verão que através de scripts simples podem automatizar algumas rotinas que farão a vida de um administrador de banco de dados mais simples.

Nada do que vou mostrar no vídeo é complexo de ser feito, você precisa apenas pensar no problema a ser resolvido, e é isso mesmo a minha abordagem.

Espero que vocês gostem do conteúdo que estão prestes a assistir.

Como sempre enfatizo, fico aguardando os comentários de vocês, sejam com sugestões de vídeos ou até mesmo críticas.

 Abraços e até o próximo vídeo.

Marcos Freccia
Data Platform MVP

 

Instalação do dbatools

Olá pessoal, tudo com vocês?

Sejam bem vindos a mais um post nesse blog que dá início a minha serie de vídeos sobre os mais variados temas. Por enquanto estou abordando o dbatools, mas a ideia é que no futuro eu também aborde aqui outros assuntos como por exemplo Python, desenvolvimento web com Django e por ai vai.

Antes mesmo de começarmos a falar sobre o dbatools, temos que instalar o módulo seja em nossa estação de trabalho, ou no servidor onde os scripts serão executados.

Então o vídeo de hoje aborda esse tema, onde primeiramente eu mostro a navegação no site, como encontrar mais informações sobre o módulo. Feito isso, partimos então para a tela do Visual Studio Code, onde demonstro como realizar a instalação do módulo.

Por fim, validamos se a instalação foi feita com sucesso quando executamos alguns comandos no Visual Studio Code.

Espero que vocês gostem do conteúdo que estou preparando e fico ansiosamente aguardando por sugestões, críticas ou elogios de vocês!

Ah, se inscrevam também no meu canal no Youtube, assim quando qualquer novo vídeo sair, vocês irão receber uma notificação.

Abraços e até o próximo vídeo!

Marcos Freccia
Data Platform MVP

 

 

I’m speaking at Microsoft Ignite The Tour – Stockholm

image

Howdy!

I just wanted to share that I will have the pleasure of speaking at Microsoft Ignite The Tour in Stockholm/Sweden.

The event is taking place on the days 24th and 25th of April at Stockolmsmassan.

I will be speaking about Azure SQL Database and all the cool features around the platform that you can take advantage off. If you are planning to attend the event and have any curiosities around Azure SQL DB, I really recommend you to be there.

Below you can see more details of the session.

Working smarter, not harder with Azure SQL Database

Azure SQL DB brings a lot of benefits for new and existing workloads. In this session we are going to explore the various aspects of an Azure SQL DB. How we can have a self managed, high available and high performing Database. Properly monitoring is also an important part of the job and we will cover several aspects of monitoring an Azure SQL DB. After this session you will feel comfortable in moving your workload to the cloud.

I hope to see some of you there!

Marcos Freccia

 

 

Python scripts for Secret Server

Hey everyone!

I just wanted to share with you some cool scripts in Python that I have been working on. I don’t think they are perfect, but as I am not seeing anything similar to that on the internet I decided to share with you.

Secret Server

Secret Server as the company states in their website.

Secret Server is a clear pick for Privileged Account Management. Competitive pricing, rapid deployment, and short time to value. supporting a variety of complex and specialized enterprise use cases

Secret Server is really helpfull for sharing credentials among teams, checking-in and out from secrets, automatic rotation of passwords, etc.. 


Read the rest of this entry

Customizing Remove-DbaBackup from dbatools

Howdy!

As a matter fact, it is not new that dbatools is a great PowerShell module for the SQL Server DBA, and from time to time they come up with new functions that for me I just think: Why I never thought about it before?

Today I want to talk about the function Remove-DbaBackup and more specifically my customized version of it. No, I didn’t rewrite Remove-DbaBackup but rather improved to my environment. The function by itself is just great and it addresses the goal of removing the backups nicely, but at the end, the function was not doing something that I wanted. Read the rest of this entry