Deleting a group alias fails - google-admin-sdk

I'm trying to remove a group alias in GAS.
The spreadsheet lists the email addresses for which I want to remove aliases.(ex. xxxx#gmai.co.jp)
aliasDomain = #zzz.co.jp
var groupKey = sheet.getRange(i, 2).getValue();
var groupName = groupKey.slice(0,groupKey.indexOf("#"));
var alias = {
alias:`${groupName}${aliasDomain}`
}
var res = AdminDirectory.Groups.Aliases.remove(groupKey, alias);
It fails with the following error message.
message:API call to directory.groups.aliases.delete failed with error: Invalid Input: resource_id
I have successfully got the group alias list with the code below, so I have confirmed that the group key correct.
var res = AdminDirectory.Groups.Aliases.list(groupKey);
I tried the method on the following page with the same group address and alias and it worked fine.
https://developers.google.com/admin-sdk/directory/reference/rest/v1/groups.aliases/delete
Please let me know if you have any idea what's wrong with the code.

Related

How to disable terraform error "Error: Your query returned no results. Please change your search criteria and try again." for data block?

Can someone tell me how to disable the raising of the error if the terraform data block result is empty? I want to handle this situation myself.
My code is below.
data "aws_ami" "specified" {
for_each = toset([
for v in var.ec2_confg_params : v.ami if v.ami != null
])
most_recent = true
include_deprecated = false
filter {
/*
Filter based on the '--filters (list)' keys described here
https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html
*/
name = "image-id"
values = [
each.value,
]
}
filter {
name = "state"
values = ["available"]
}
lifecycle {
postcondition {
condition = try(each.value == self.id)
error_message = "Image '${each.value}' not found!"
}
}
}
If the value var.ec2_confg_params.ami is set but the date block does not find it, I get an error:
Error: Your query returned no results. Please change your search criteria and try again.
│
│ with data.aws_ami.specified["ami-xxxxxxxxxxxxxxxxx"],
│ on main.tf line 293, in data "aws_ami" "specified":
│ 293: data "aws_ami" "specified" {
but I need the lifecycle postcondition block to work.
Thanks in advance for help!
The only solution I found is to select all AMIs with data.aws_ami_ids, and check if the ami in var.ec2_confg_params.ami is in the list data.aws_ami_ids.all.ids. But this option is processed for a long time and it is difficult to set parameters for filtering based on AMI 'owner'.
This particular data source is designed to return exactly one AMI matching the given criteria or return an error if that isn't possible. There is no way to change that behavior.
It is in principle possible for a provider to offer a data resource that doesn't fail when an object doesn't exist, or to return a set of objects that all together match some criteria. The hashicorp/aws provider offers aws_ami_ids as an alternative which returns a set of IDs matching the given criteria, and so you could potentially get the result you wanted using that data source instead:
data "aws_ami_ids" "example" {
for_each = toset([
for v in var.ec2_confg_params : v.ami
if v.ami != null
])
filter {
name = "image-id"
values = [
each.value,
]
}
filter {
name = "state"
values = ["available"]
}
lifecycle {
postcondition {
condition = length(self.ids) == 1
error_message = "Image '${each.value}' not found."
}
}
}
This is an unusual approach though, since it's just replacing an error case that the provider already handles with exactly the same error case implemented in your module. Unless you have a particular reason to return a different error message than normal I would suggest using the built-in behavior for simplicity.

regex to string

I am trying to just use the value before the # symbol as a value for my name during the creation of my ressource. However, I got an error: Inappropriate value for attribute "email": string required. my regex is working on the terraform console so I think it's more an error on where I am applying this regex function.
main.tf
resource "aws_organizations_account" "account" {
for_each = local.all_users
name = "${regex("(.*)#", "john.doe#test.com")}"
email = "admin#test.com"
role_name = "Administrator"
parent_id = var.sandbox_organizational_unit_id
}
I also tried "${tostring(regex("(.*)#", "tom#gmail.com"))}" and I got a different error, Invalid value for "v" parameter: cannot convert tuple to string.
It should be:
name = regex("(.*)#", "john.doe#test.com")[0]

Terraform "primary workGroup could not be created"

I'm trying to execute query on my table In amazone but i cant execute any query i had this error msg :
Before you run your first query, you need to set up a query result location in Amazon S3.
Your query has the following error(s):
No output location provided. An output location is required either through the Workgroup result configuration setting or as an API input. (Service: AmazonAthena; Status Code: 400; Error Code: InvalidRequestException; Request ID: b6b9aa41-20af-4f4d-91f6-db997e226936)
So i'm trying to add Workgroup but i have this problem
'Error: error creating Athena WorkGroup: InvalidRequestException: primary workGroup could not be created
{
RespMetadata: {
StatusCode: 400,
RequestID: "c20801a0-3c13-48ba-b969-4e28aa5cbf86"
},
AthenaErrorCode: "INVALID_INPUT",
Message_: "primary workGroup could not be created"
}
'
Mycode
resource "aws_s3_bucket" "tony" {
bucket = "tfouh"
}
resource "aws_athena_workgroup" "primary" {
name = "primary"
depends_on = [aws_s3_bucket.tony]
configuration {
enforce_workgroup_configuration = false
publish_cloudwatch_metrics_enabled = true
result_configuration {
output_location = "s3://${aws_s3_bucket.tony.bucket}/"
encryption_configuration {
encryption_option = "SSE_S3"
}
}
}
}
please if there are solution
This probably happens because you already have primary work group. Thus, you can't create new one of the same name. Just create a work group with different name if you want:
name = "primary2"
#Marcin suggested a valid approach, but what may be closer to what you are looking for would to to import existing workgroup into the state:
terraform import aws_athena_workgroup.primary primary
Once the state knows about the already existing resource it can do the plan and apply possible changes.

ValidationException error when deploying AWS WorkSpaces via terraform

I've been trying to deploy AWS WorkSpaces infrastructure using Terraform. The code itself passes the verify and plan check, but it fails to apply.
Source:
module "networking" {
source = "../../modules/networking"
region = var.region
main_cidr_block = var.main_cidr_block
cidr_block_1 = var.cidr_block_1
cidr_block_2 = var.cidr_block_2
size = var.size
}
resource "aws_directory_service_directory" "main" {
name = var.aws_ds_name
password = var.aws_ds_passwd
size = var.size
type = "SimpleAD"
vpc_settings {
vpc_id = module.networking.main_vpc
subnet_ids = ["${module.networking.private-0}", "${module.networking.private-1}"]
}
}
resource "aws_workspaces_directory" "main" {
directory_id = aws_directory_service_directory.main.id
subnet_ids = ["${module.networking.private-0}", "${module.networking.private-1}"]
}
resource "aws_workspaces_ip_group" "main" {
name = "Contractors."
description = "Main IP access control group"
rules {
source = "10.0.0.0/16"
description = "Contractors"
}
}
Error code:
ValidationException: 2 validation errors detected: Value at 'password' failed to satisfy constraint: Member must satisfy regular expression pattern: (?=^.{8,64}$)((?=.*\d)(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[^A-Za-z0-9\s])(?=.*[a-z])|(?=.*[^A-Za-z0-9\s])(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9\s]))^.*; Value '' at 'name' failed to satisfy constraint: Member must satisfy regular expression pattern: ^([a-zA-Z0-9]+[\\.-])+([a-zA-Z0-9])+$
status code: 400, request id: 073f6e61-775e-4ff9-a88e-e1eab97f8519
on modules/workspaces/workspaces.tf line 10, in resource "aws_directory_service_directory" "main":
10: resource "aws_directory_service_directory" "main" {
I am aware that it is a regex issue with the username/passwords, but I haven't set any users for now, and I've reset the security policies for testing reasons.
Anyone had this issue before?
The AWS API for the directory service enforces a constraint on the password attribute and matches what you are seeing in that error when you run terraform apply:
Password
The password for the directory administrator. The directory creation
process creates a directory administrator account with the user name
Administrator and this password.
If you need to change the password for the administrator account, you
can use the ResetUserPassword API call.
Type: String
Pattern:
(?=^.{8,64}$)((?=.*\d)(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[^A-Za-z0-9\s])(?=.*[a-z])|(?=.*[^A-Za-z0-9\s])(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9\s]))^.*
Required: Yes
Normally Terraform is able to validate this with the plan or validate commands but unfortunately the AWS provider is currently missing an appropriate ValidateFunc so it will only fail at apply time instead at the minute.
If you want this to be caught at plan or validate time then you should raise a feature request for it on the provider issue tracker.

Unable to generate embed token for accessing dataset due to missing roles in effective identity

I have embedded powerbi report which was working fine until I changed my database.
I observed datasets.IsEffectiveIdentityRequired (in below code) was false earlier, now as it is true, I'm getting an error - {"error":{"code":"InvalidRequest","message":"Creating embed token for accessing dataset 02c90e15-35dd-4036-a525-4f5d158bfade requires roles to be included in provided effective identity"}}
I'm using standard Embed service code.
// Create a Power BI Client object. It will be used to call Power BI APIs.
using (var client = new PowerBIClient(new Uri(ApiUrl), m_tokenCredentials))
{
// Get a list of reports.
var reports = await client.Reports.GetReportsInGroupAsync(WorkspaceId);
Report report = reports.Value.FirstOrDefault(r => r.Id.Equals(ReportId, StringComparison.InvariantCultureIgnoreCase));
var datasets = await client.Datasets.GetDatasetByIdInGroupAsync(WorkspaceId, report.DatasetId);
m_embedConfig.IsEffectiveIdentityRequired = datasets.IsEffectiveIdentityRequired;
m_embedConfig.IsEffectiveIdentityRolesRequired = datasets.IsEffectiveIdentityRolesRequired;
GenerateTokenRequest generateTokenRequestParameters;
// This is how you create embed token with effective identities
// HERE username IS NULL
if (!string.IsNullOrWhiteSpace(username))
{
var rls = new EffectiveIdentity(username, new List<string> { report.DatasetId });
if (!string.IsNullOrWhiteSpace(roles))
{
var rolesList = new List<string>();
rolesList.AddRange(roles.Split(','));
rls.Roles = rolesList;
}
// Generate Embed Token with effective identities.
generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view", identities: new List<EffectiveIdentity> { rls });
}
else
{
// Generate Embed Token for reports without effective identities.
generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
}
var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(WorkspaceId, report.Id, generateTokenRequestParameters);
}
First, I completely understand that this error occurs as I'm not passing any identity. So, is there any option to disable IsEffectiveIdentityRequired?
Second, how to set users and roles in powerbi?
--I'm not a PowerBI expert--
IsEffectiveIdentityRequired is a read only property so you can't control it and there is no option to disable it.
Depending on the data source you are connecting to an effective identity may or may not be required.
If IsEffectiveIdentityRequired is true you need to pass an EffectiveIdentity when calling GenerateTokenRequest to generate an embed token. If the data source requires an effective identity and you do not pass one you will get an error when calling GenerateTokenRequest. You will also get an error if you pass an incomplete EffectiveIdentity, such as one that is missing roles when calling GenerateTokenRequest.
Here is an example of how you can use the IsEffectiveIdentityRequired property to generate an embed token with or without an effective identity depending on if the data source requires it or not.
List<EffectiveIdentity> eil = new List<EffectiveIdentity>();
EffectiveIdentity ef = new EffectiveIdentity();
// UserName
ef.Username = FullADUsername;
// Roles
List<string> Roles = new List<string>();
ef.Roles = Roles;
// Datasets
List<string> _Datasets = new List<string>();
_Datasets.Add(report.DatasetId);
ef.Datasets = _Datasets;
eil.Add(ef);
// Look up the data set of the report and look if we need to pass an Effective Identify
Dataset d = client.Datasets.GetDatasetByIdInGroup(WorkspaceId, report.DatasetId);
if (d.IsEffectiveIdentityRequired == true){
GenerateTokenRequest gtr = new GenerateTokenRequest("View", null, false, eil);
newEmbedToken = client.Reports.GenerateTokenInGroup(WorkspaceId, ReportId, gtr);
}
else
{
GenerateTokenRequest gtr = new GenerateTokenRequest();
newEmbedToken = client.Reports.GenerateTokenInGroup(WorkspaceId, ReportId, gtr);
}