question stringlengths 11 28.2k | answer stringlengths 26 27.7k | tag stringclasses 130
values | question_id int64 935 78.4M | score int64 10 5.49k |
|---|---|---|---|---|
The following code snippet is my terraform configuration to create an Azure SignalR Service:
output "signalrserviceconnstring" {
value = azurerm_signalr_service.mysignalrservice.primary_connection_string
description = "signalR service's primary connection string"
sensitive = true
}
I got an error when sensitive ... | The entire point of sensitive = true is to prevent the values from being displayed on the console every time you run terraform apply. You have to output the sensitive value explicitly, like this:
terraform output signalrserviceconnstring
I highly suggest reading the documentation.
| Terraform | 67,650,019 | 58 |
Does Terraform support conditional attributes? I only want to use an attribute depending on a variable's value.
Example:
resource "aws_ebs_volume" "my_volume" {
availability_zone = "xyz"
size = 30
if ${var.staging_mode} == true:
snapshot_id = "a_specific_snapshot_id"
endif
}
The above if stat... | Terraform 0.12 (yet to be released) will also bring support for HCL2 which allows you to use nullable arguments with something like this:
resource "aws_ebs_volume" "my_volume" {
availability_zone = "xyz"
size = 30
snapshot_id = var.staging_mode ? local.a_specific_snapshot_id : null
}
Nullable ... | Terraform | 51,496,445 | 56 |
I have a Terraform 0.11 project with 30-40 different resources. I would like to delete all of them except a few - and those few are logically related to each other.
I was looking for something close to terraform destroy --except=resource-id but that of course doesn't exist.
Is there a way to achieve that without too mu... | There is no --except feature in terraform destroy command currently. If you really want to do that, and you know what you are doing, here is the workaround.
# list all resources
terraform state list
# remove that resource you don't want to destroy
# you can add more to be excluded if required
terraform state rm <resou... | Terraform | 55,265,203 | 55 |
I defined a aws_cloudwatch_event_target in terraform to fire an event to lambda from cloudwatch. The input field is the event parameter for example:
resource "aws_cloudwatch_event_target" "data" {
rule = "${aws_cloudwatch_event_rule.scheduler.name}"
target_id = "finance_producer_cloudwatch"
arn = "${aw... | The answer here depends on a few different questions:
Is this file a static part of your configuration, checked in to version control alongside your .tf files, or is it dynamically generated as part of the apply process?
Do you want to use the file contents literally, or do you need to substitute values into it from e... | Terraform | 57,454,591 | 53 |
I have problem with terraform on my macOS Ventura 13.3.1. When I try to initialize terragrunt:
terragrunt init
I have information that
Terraform will damage your computer
My colleague is using M1 and terraform version 1.0.11 and he don't have problem. I tried latest version and also 1.0.11, but I still have this er... | Looks like the rotated signing key was the issue for me too (and probably every mac user of terraform)
Reinstall with brew solved this for me.
I keep previous versions in case I need them so I have a symlink to the current version.
Remove that first
which terraform
#remove my symlink so brew can replace it
#rm '/usr/lo... | Terraform | 76,129,509 | 53 |
I have two environment variables. One is TF_VAR_UN and another is TF_VAR_PW. Then I have a terraform file that looks like this.
resource "google_container_cluster" "primary" {
name = "marcellus-wallace"
zone = "us-central1-a"
initial_node_count = 3
master_auth {
username = ${env.TF_VAR_UN}
... | I would try something more like this, which seems closer to the documentation.
variable "UN" {
type = string
}
variable "PW" {
type = string
}
resource "google_container_cluster" "primary" {
name = "marcellus-wallace"
zone = "us-central1-a"
initial_node_count = 3
master_auth {
username = var.UN
p... | Terraform | 36,629,367 | 52 |
In Terraform, I'm trying to create a module with that includes a map with variable keys. I'm not sure if this is possible but I've tried the following without success.
resource "aws_instance" "web" {
ami = "${var.base_ami}"
availability_zone = "${var.region_a}"
instance_type = "${var.ec2_instance_size}"
... | There's (now) a lookup function supported in the terraform interpolation syntax, that allows you to lookup dynamic keys in a map.
Using this, I can now do stuff like:
output "image_bucket_name" {
value = "${lookup(var.image_bucket_names, var.environment, "No way this should happen")}"
}
where:
variable "image_bucket... | Terraform | 35,491,987 | 51 |
Is there a way to use something like this in Terraform?
count = "${var.I_am_true}"&&"${var.I_am_false}"
| This is more appropriate in the actual version (0.12.X)
The supported operators are:
Equality: == and !=
Numerical comparison: >, <, >=, <=
Boolean logic: &&, ||, unary !
https://www.terraform.io/docs/configuration/interpolation.html#conditionals
condition_one and condition two:
count = var.condition_one && var.condi... | Terraform | 39,479,849 | 51 |
Using Terraform modules with a git branch as a source,
I am referring to:
git::ssh://private_server:myport/kbf/my_repository.git//ecs-cluster?ref=v0.0.1
In my module source parameter, this works great and provides me with my module at tag v0.0.1 on master.
However I'd like to specify a branch, not a tag, but am not su... | As mentioned in the Terraform documentation here:
git::ssh://private_server:myport/kbf/my_repository.git//ecs-cluster?ref=myBranch
| Terraform | 52,538,920 | 50 |
I'm trying to do a rather simple task in Terraform and it's not working:
tfvars:
hosted_zone = "example.com"
domain = "my.${var.hosted_zone}"
route_53_record:
resource "aws_route53_record" "regional" {
zone_id = "${data.aws_route53_zone.selected.zone_id}"
name = "${var.domain}"
type = "A"
... | You can't use interpolation in a tfvars file.
Instead you could either join it directly in your Terraform like this:
terraform.tfvars
hosted_zone = "example.com"
domain = "my"
main.tf
resource "aws_route53_record" "regional" {
zone_id = data.aws_route53_zone.selected.zone_id
name = "${var.domain}.${var.hos... | Terraform | 54,752,049 | 50 |
Is there a way to write a conditional statement with multiple branches in terraform?
I'm setting up a terraform module to create an Amazon Aurora cluster. I need to have an option for cross region replication so I need to decide the region of the replica in relation to the source region.
| This is one way using the coalesce() function:
locals{
prod = "${var.environment == "PROD" ? "east" : ""}"
prod2 = "${var.environment == "PROD2" ? "west2" : ""}"
nonprod = "${var.environment != "PROD" && var.environment != "PROD2" ? "west" : ""}"
region = "${coalesce(local.prod,local.prod2, local.nonprod)}"
}
| Terraform | 55,555,963 | 50 |
I'm just getting to grips with Terraform (so apologies if this is a stupid question).
I'm setting up an azure vnet with a set of subnets, each subnet has a routing table that sends traffic via a firewall.
It looks like the subnet and route table combination would make a good re-useable module.
By convention, I'd like ... | This is possible with terraform > 0.12. You can use the object type, but you have to explicitly list fields that you use within your module.
# module's variables.tf
variable "parent_vnet" {
# List each field in `azurerm_route_table` that your module will access
type = object({
name = string
location = strin... | Terraform | 50,740,412 | 48 |
I have the following list of objects variable:
variable "objects" {
type = "list"
description = "list of objects
default = [
{
id = "name1"
attribute = "a"
},
{
id = "name2"
attribute = "a,b"
},
{
id = "name3"
attribute = "d"
}
... | You get the map with id="name2" with the following expression:
var.objects[index(var.objects.*.id, "name2")]
For a quick test, run the following one-liner in terraform console:
[{id = "name1", attribute = "a"}, {id = "name2", attribute = "a,b"}, {id = "name3", attribute = "d"}][index([{id = "name1", attribute = "a"}, ... | Terraform | 52,119,400 | 48 |
While using Terraform to deploy a fairly large infrastructure in AWS, our remote tfstate got corrupted and was deleted.
From the documentation, I gather that terraform refresh should query AWS to get the real state of the infrastructure and update the tfstate accordingly, but that does not happen: my tfstate is untouch... | terraform refresh attempts to find any resources held in the state file and update with any drift that has happened in the provider outside of Terraform since it was last ran.
For example, lets say your state file contains 3 EC2 instances with instance ids of i-abc123, i-abc124, i-abc125 and then you delete i-abc124 ou... | Terraform | 42,628,660 | 47 |
How do you check if a terraform string contains another string?
For example, I want to treat terraform workspaces with "tmp" in the name specially (e.g. allowing rds instances to be deleted without a snapshot), so something like this:
locals
{
is_tmp = "${"tmp" in terraform.workspace}"
}
As far as I can tell, the su... | For terraform 0.12.xx apparently you are suppose to use regexall to do this.
From the manual for terraform 0.12.XX:
regexall() documentation
regexall can also be used to test whether a particular string matches a given pattern, by testing whether the length of the resulting list of matches is greater than zero.
Examp... | Terraform | 47,243,474 | 47 |
Just today, whenever I run terraform apply, I see an error something like this: Can't configure a value for "lifecycle_rule": its value will be decided automatically based on the result of applying this configuration.
It was working yesterday.
Following is the command I run: terraform init && terraform apply
Following ... | Terraform AWS Provider is upgraded to version 4.0.0 which is published on 10 February 2022.
Major changes in the release include:
Version 4.0.0 of the AWS Provider introduces significant changes to the aws_s3_bucket resource.
Version 4.0.0 of the AWS Provider will be the last major version to support EC2-Classic resou... | Terraform | 71,078,462 | 47 |
What exactly does this AWS role do?
The most relevant bits seem to be:
"Action": "sts:AssumeRole", and
"Service": "ec2.amazonaws.com"
The full role is here:
resource "aws_iam_role" "test_role" {
name = "test_role"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts... | To understand the meaning of this it is necessary to understand some details of how IAM Roles work.
An IAM role is similar to a user in its structure, but rather than it being accessed by a fixed set of credentials it is instead used by assuming the role, which means to request and obtain temporary API credentials that... | Terraform | 44,623,056 | 46 |
I have some code in the general form:
variable "foo" {
type = "list"
default = [ 1,2,3 ]
}
resource "bar_type" "bar" {
bar_field = "${var.foo}"
}
I want to append an addition value to bar_field without modifying foo. How can I do this? I don't see any sort of contacting or appending functions in their docs.
Th... | You can use the concat function for this. Expanding upon the example in your question:
variable "foo" {
type = "list"
default = [ 1,2,3 ]
}
# assume a value of 4 of type number is the additional value to be appended
resource "bar_type" "bar" {
bar_field = "${concat(var.foo, [4])}"
}
which appends to the value a... | Terraform | 55,957,697 | 46 |
When running terraform plan or terraform apply with a list provided to for_each an error occurs saying
Error: Invalid for_each argument
on main.tf line 2, in resource "aws_ssm_parameter" "foo":
2: for_each = ["a", "b"]
The given "for_each" argument value is unsuitable: the "for_each" argument
must be a map, or ... | Explanation
This error is often caused by passing a list to for_each, but for_each only works with unordered data-types, i.e. with sets and maps.
Solution
The resolution depends on the situation.
List of strings
If the list is just a list of strings, the easiest fix is to add a toset()-call to transform the list to a s... | Terraform | 62,264,013 | 46 |
I want to identify the public IP of the terraform execution environment
and add it to aws security group inbound to prevent access from other environments.
Currently, I am manually editing the values in the variables.tf file.
variables.tf
variable public_ip_address {
default = "xx"
}
I would like to execute the ... | There's an easier way to do that without any scripts. The trick is having a website such as icanhazip.com which retrieve your IP, so set it in your terraform file as data:
data "http" "myip" {
url = "https://ipv4.icanhazip.com"
}
And whenever you want to place your IP just use data.http.myip.body, example:
ingress {... | Terraform | 46,763,287 | 45 |
I'm using the AWS VPC Terraform module to create a VPC. Additionally, I want to create and attach an Internet Gateway to this VPC using the aws_internet_gateway resource.
Here is my code:
module "vpc" "vpc_default" {
source = "terraform-aws-modules/vpc/aws"
name = "${var.env_name}-vpc-default"
cidr = "10.0.0.0/1... | Since you're using a module, you need to change the format of the reference slightly. Module Outputs use the form ${module.<module name>.<output name>}. It's also important to note, you can only reference values outputted from a module.
In your specific case, this would become ${module.vpc.vpc_id} based on the VPC Modu... | Terraform | 52,804,543 | 45 |
I upgraded to Terraform v0.12.16 and now I am getting a lot of messages that look like this:
Warning: Interpolation-only expressions are deprecated
on ../modules/test-notifier/test_notifier.tf line 27, in resource "aws_sns_topic_policy" "default":
27: arn = "${aws_sns_topic.default.arn}"
Terraform 0.11 and e... | Warning: Interpolation-only expressions are deprecated
on main.tf line 3, in provider "aws":
3: region = "${var.region}"
I also got the above warning, which is due to the changed syntax for declaring variables in terraform.
See the example below -:
Old syntax- region = "${var.region}" # you will get Int... | Terraform | 59,038,537 | 45 |
I have my s3 resource in terraform with configuration:
locals {
bucket_count = "${length(var.s3_config["bucket_names"])}"
}
resource "aws_s3_bucket" "s3_bucket" {
count = "${local.bucket_count}"
bucket = "${format("%s-%s", element(var.s3_config["bucket_names"], count.index), var.region)}"
acl = "privat... | Try this:
output "buckets" {
value = ["${aws_s3_bucket.s3_bucket.*.bucket}"]
}
output "buckets_arns" {
value = ["${aws_s3_bucket.s3_bucket.*.arn}"]
}
| Terraform | 52,040,798 | 44 |
I am using Terraform snowflake plugins. I want to use ${terraform.workspace} variable in terraform scope.
terraform {
required_providers {
snowflake = {
source = "chanzuckerberg/snowflake"
version = "0.20.0"
}
}
backend "s3" {
bucket = "data-pf-terraform-backend-${terraform.worksp... |
Set backend.tf
terraform {
backend "azurerm" {}
}
Create a file backend.conf
storage_account_name = "deploymanager"
container_name = "terraform"
key = "production.terraform.tfstate"
Run:
terraform init -backend-config=backend.conf
| Terraform | 65,838,989 | 43 |
We are looking into Terraform as a way of managing our infrastructure and it looks very interesting.
However, currently our corporate proxy/firewall is causing terraform apply to fail due to security restrictions.
While we wait for these network issues to be resolved, is there any way that I can experiment with Terrafo... | Terraform supports a bunch of providers, but the vast majority of them are public cloud based.
However, you could set up a local VMware vSphere cluster and use the vSphere provider to interact with that to get you going. There's also a provider for OpenStack if you want to set up an OpenStack cluster.
Alternatively you... | Terraform | 39,211,000 | 42 |
I'm looking at using the new conditionals in Terraform v0.11 to basically turn a config block on or off depending on the evnironment.
Here's the block that I'd like to make into a conditional, if, for example I have a variable to turn on for production.
access_logs {
bucket = "my-bucket"
prefix = "${var.environ... | One way to achieve this with TF 0.12 onwards is to use dynamic blocks:
dynamic "access_logs" {
for_each = var.environment_name == "production" ? [var.environment_name] : []
content {
bucket = "my-bucket"
prefix = "${var.environment_name}-alb"
}
}
This will create one or zero access_logs blocks dependin... | Terraform | 42,461,753 | 42 |
Is there a way of abstracting the provider for all the modules defined in a project.
for example, I have this project
├── modules
│ ├── RDS
│ └── VPC
└── stacks
├── production
│ └── main.tf
└── staging
└── main.tf
and it works fine...
the problem is with the definition of modules
├── RDS
│ ... | Right now it's not possible to achieve that.
There were previous discussions on github about the same topic in the following issues:
https://github.com/hashicorp/terraform/issues/5480
https://github.com/hashicorp/terraform/issues/4585
https://github.com/hashicorp/terraform/issues/2714
https://github.com/hashicorp/terr... | Terraform | 51,213,871 | 41 |
I need to ship my cloudwatch logs to a log analysis service.
I've followed along with these articles here and here and got it working by hand, no worries.
Now I'm trying to automate all this with Terraform (roles/policies, security groups, cloudwatch log group, lambda, and triggering the lambda from the log group).
B... | I had the aws_cloudwatch_log_subscription_filter resource defined incorrectly - you should not provide the role_arn argument in this situation.
You also need to add an aws_lambda_permission resource (with a depends_on relationship defined on the filter or TF may do it in the wrong order).
Note that the AWS lambda conso... | Terraform | 38,407,660 | 40 |
I'm using Terraform to create a few services in AWS. One of those services is an ECS task definition. I followed the docs and I keep getting the following error:
aws_ecs_task_definition.github-backup: ClientException: Fargate requires task definition to have execution role ARN to support ECR images.
status code: 400, r... | As mentioned in the AWS ECS User Guide Fargate tasks require the execution role to be specified as part of the task definition.
EC2 launch type tasks don't require this because the EC2 instances themselves should have an IAM role that allows them to pull the container image and optionally push logs to Cloudwatch.
Becau... | Terraform | 51,612,556 | 40 |
I'm new at terraform and I created a custom azure policies on module structure.
each policy represents a custom module.
One of the modules that I have created is enabling diagnostics logs for any new azure resource created.
but, I need a storage account for that. (before enabling the diagnostics settings how can I im... | In most cases, the necessary dependencies just occur automatically as a result of your references. If the configuration for one resource refers directly or indirectly to another, Terraform automatically infers the dependency between them without the need for explicit depends_on.
This works because module variables and ... | Terraform | 58,275,233 | 40 |
I am running Terraform using Terragrunt so I am not actually certain about the path that the terraform is invoked from.
So I am trying to get the current working directory as follows:
resource null_resource "pwd" {
triggers {
always_run = "${uuid()}"
}
provisioner "local-exec" {
command = "echo $pwd >> so... | Terraform has a built-in object path that contains attributes for various paths Terraform knows about:
path.module is the directory containing the module where the path.module expression is placed.
path.root is the directory containing the root module.
path.cwd is the current working directory.
When writing Terraform... | Terraform | 60,302,694 | 40 |
I am very new to GCP with terraform and I want to deploy all my modules using centralized tools.
Is there any way to remove the step of enabling google API's every time so that deployment is not interrupted?
| There is a Terraform resource definition called "google_project_service" that allows one to enable a service (API). This is documented at google_project_service.
An example of usage appears to be:
resource "google_project_service" "project" {
project = "your-project-id"
service = "iam.googleapis.com"
}
| Terraform | 59,055,395 | 39 |
I use a CI system to compile terraform providers and bundle them into an image, but every time I run terraform init, I am getting the following error/failure.
│ Error: Failed to install provider
│
│ Error while installing rancher/rancher2 v1.13.0: the current package for
│ registry.terraform.io/rancher/rancher2 1.13.0... | The issue is that my local workstation is a Mac which uses the darwin platform, so all of the providers are downloaded for darwin and the hashes stored in the lockfile for that platform. When the CI system, which is running on Linux runs, it attempts to retrieve the providers listed in the lockfile, but the checksums d... | Terraform | 67,204,811 | 38 |
I want to script terraform for CI/CD purpose and I don't like CDing in scripts, I rather have specific paths.
I tried terraform init c:\my\folder\containing\tf-file
But running that puts the .terraform folder in my cwd.
| I know this is an old thread but... The command you are looking for is:
terraform -chdir=environments/production apply
Please see this link for help with the global option -chdir=":
Quote from the actual Terraform site:
The usual way to run Terraform is to first switch to the
directory containing the .tf files for ... | Terraform | 47,274,254 | 37 |
Currently I am working on a infrastructure in azure that comprises of the following:
resource group
application gateway
app service
etc
everything I have is in one single main.tf file which I know was a mistake however I wanted to start from there. I am currently trying to move each section into its own sub folder in... | You are seeing this issue because terraform ignores subfolders, so those resources are not being included at all anymore. You would need to configure the subfolders to be Terraform Modules, and then include those modules in your root main.tf
| Terraform | 60,041,854 | 36 |
Terraform newbie here.
I'd like to iterate a list using for_each, but it seems like the key and value are the same:
provider "aws" {
profile = "default"
region = "us-east-1"
}
variable "vpc_cidrs" {
default = ["10.0.0.0/16", "10.1.0.0/16"]
}
resource "aws_vpc" "vpc" {
for_each = toset(var.vpc_cid... | Found an easy solution using the index function:
tags = { Name = "Company0${index(var.vpc_cidrs, each.value) + 1}" }
| Terraform | 61,343,796 | 36 |
In terraform, is there any way to conditionally use a data source? For example:
data "aws_ami" "application" {
most_recent = true
filter {
name = "tag:environment"
values = ["${var.environment}"]
}
owners = ["self"]
}
I'm hoping to be able to pass in an environment variable via t... | You can use a conditional on data sources the same as you can with resources and also from Terraform 0.13+ on modules as well:
variable "lookup_ami" {
default = true
}
data "aws_ami" "application" {
count = var.lookup_ami ? 1 : 0
most_recent = true
filter {
name = "tag:environment"
values... | Terraform | 41,858,630 | 35 |
I am configuring S3 backend through terraform for AWS.
terraform {
backend "s3" {}
}
On providing the values for (S3 backend) bucket name, key & region on running "terraform init" command, getting following error
"Error configuring the backend "s3": No valid credential sources found for AWS Provider. Please see htt... | When running the terraform init you have to add -backend-config options for your credentials (aws keys). So your command should look like:
terraform init -backend-config="access_key=<your access key>" -backend-config="secret_key=<your secret key>"
| Terraform | 55,449,909 | 35 |
So I have a terraform script that creates instances in Google Cloud Platform, I want to be able to have my terraform script also add my ssh key to the instances I create so that I can provision them through ssh. Here is my current terraform script.
#PROVIDER INFO
provider "google" {
credentials = "${file("account.js... | I think something like this should work:
metadata = {
ssh-keys = "${var.gce_ssh_user}:${file(var.gce_ssh_pub_key_file)}"
}
https://cloud.google.com/compute/docs/instances/adding-removing-ssh-keys describes the metadata mechanism, and I found this example at https://github.com/hashicorp/terraform/issues/6678
| Terraform | 38,645,002 | 34 |
I've been looking for a way to be able to deploy to multiple AWS accounts simultaneously in Terraform and coming up dry. AWS has the concept of doing this with Stacks but I'm not sure if there is a way to do this in Terraform? If so what would be some solutions?
You can read more about the Cloudformation solution here.... | You can define multiple provider aliases which can be used to run actions in different regions or even different AWS accounts.
So to perform some actions in your default region (or be prompted for it if not defined in environment variables or ~/.aws/config) and also in US East 1 you'd have something like this:
provider... | Terraform | 52,206,436 | 34 |
Every Terraform guide on the web provides a partial solution that is almost always not the real picture.
I get that, not everyone has the same infrastructure needs, but what worries me that the common scenario with:
multiple environments (dev, stage)
remote backend (s3)
some basic resources (bucket or ec2 instance)
i... | I work with terraform 5 years. I did a lot of mistakes with in my career with modules and environments.
Below text is just share of my knowledge and experience. They may be bad.
Real example project may is hard to find because terraform is not used to create opensource projects. It's often unsafe to share terraform fil... | Terraform | 66,024,950 | 34 |
(Please note: after receiving initial answers, this issue seems to not be just an issue with passing the variables, but with modularizing my configurations, note at the bottom where I hardcode the values yet the UI prompts me to provide the values)
Code example here
I've got a project I've broken into the following dir... | Your variables.tfvars file should be named terraform.tfvars.
Per the docs:
If a terraform.tfvars file is present in the current directory, Terraform automatically loads it to populate variables. If the file is named something else, you can use the -var-file flag directly to specify a file. These files are the same syn... | Terraform | 44,878,553 | 33 |
I want to create a new alb and a route53 record that points to it.
I see I have the DNS name: ${aws_lb.MYALB.dns_name}
Is it possible to create a cname to the public DNS name with aws_route53_record resource?
| See the Terraform Route53 Record docs
You can add a basic CNAME entry with the following:
resource "aws_route53_record" "cname_route53_record" {
zone_id = aws_route53_zone.primary.zone_id # Replace with your zone ID
name = "www.example.com" # Replace with your subdomain, Note: not valid with "apex" domains, e.g.... | Terraform | 48,919,317 | 33 |
I am trying to implement nested for loops using Terraform 0.12's new features in order to loop through AWS IAM users, each of which can have one or more policies attached. The variable used to represent this list is of type map(list(string)) and looks something like this:
{
"user 1" = [ "policy1", "policy2" ],
"use... | The for expression in your local value association-list is producing a list of list of lists of strings, but your references to it are treating it as a list of lists of strings.
To get the flattened representation you wanted, you can use the flatten function, but because it would otherwise group everything into a singl... | Terraform | 56,047,306 | 33 |
I have two subscriptions in Azure. Let's call them sub-dev and sub-prod. Under sub-dev I have resources for development (in a resource group rg-dev) and under sub-prod resources for production (in a resource group rg-prod).
Now, I would like to have only one state-file for both dev and prod. I can do this as I am using... | For better or worse (I haven't experimented much with other methods of organising terraform) we use terraform in the exact way you are describing. A state file, in a remote backend, in a different subscription to my resources. Workspaces are created to handle environments for the deployment.
Our state files are specifi... | Terraform | 57,289,924 | 33 |
join works BUT i want to keep the double quotes join gives me this
[ben,linda,john]
BUT i want this
["ben", "linda", "john"]
this is getting crazy, spent over 2 hours trying to fix this
i want to pass in a list as a string variable
why can't terraform just take in my list as a string? why is this so difficult?
so i ... | Conversion from list to string always requires an explicit decision about how the result will be formatted: which character (if any) will delimit the individual items, which delimiters (if any) will mark each item, which markers will be included at the start and end (if any) to explicitly mark the result as a list.
The... | Terraform | 59,381,410 | 33 |
I am using terraform version 0.11.13, and this afternoon I am getting the following error in terraform init step
Does it mean I've to upgrade the terraform version, is there a deprecation for this version for aws provider?
Full logs:
Successfully configured the backend "s3"! Terraform will automatically
use this backen... | HashiCorp has rotated its release signing key as a part of HCSEC-2021-12
For example, for terraform 0.11.x, you can set the aws version to v2.70.0
provider "aws" {
region = "us-east-1"
version = "v2.70.0"
}
For other versions, you can check: https://registry.terraform.io/providers/hashicorp/aws/latest/docs
| Terraform | 67,368,339 | 33 |
One team has already written a cloudformation template as a .yml file that provisions a stack of resources.
Is it possible to leverage this file by executing it from within Terraform? Or does it have to be rewritten?
I'm new to terraform and just getting started.
If I were using the AWS CLI I would execute a command li... | The aws_cloudformation_stack resource serves as a bridge from Terraform into CloudFormation, which can be used either as an aid for migration from CloudFormation to Terraform (as you're apparently doing here) or to make use of some of CloudFormation's features that Terraform doesn't currently handle, such as rolling de... | Terraform | 43,266,506 | 32 |
I'm a beginner in Terraform.
I have a directory which contains 2 .tf files.
Now I want to run Terraform Apply on a selected .tf file & neglect the other one.
Can I do that? If yes, how? If no, why & what is the best practice?
| You can't selectively apply one file and then the other. Two ways of (maybe) achieving what you're going for:
Use the -target flag to target resource(s) in one file and then the other.
Put each file (or more broadly, group of resources, which might be multiple files) in separate "modules" (folders). You can then apply... | Terraform | 47,708,338 | 32 |
I have a AWS CodePipeline configured in a terraform file, like this:
resource {
name = "Cool Pipeline"
...
stage {
name = "Source"
...
action {
name = "Source"
...
configuration {
Owner = "Me"
Repo = "<git-repo-ur... | This syntax, as hinted by terraform plan output, solved the problem:
ignore_changes = [
"stage.0.action.0.configuration.OAuthToken",
"stage.0.action.0.configuration.%"
]
Another way to solve it is to add the GITHUB_TOKEN system environment variable, with the token as the value. This way you do not need the ign... | Terraform | 48,243,968 | 32 |
I am launching an aws_launch_configuration instance using terraform.
I'm using a shell script for the user_data variable, like so:
resource "aws_launch_configuration" "launch_config" {
...
user_data = "${file("router-init.sh")}"
...
}
Within this router-init.sh, one of the things I would like to do is to... | You can do this using a template_file data source:
data "template_file" "init" {
template = "${file("router-init.sh.tpl")}"
vars = {
some_address = "${aws_instance.some.private_ip}"
}
}
Then reference it inside the template like:
#!/bin/bash
echo "SOME_ADDRESS = ${some_address}" > /tmp/
Then use that for ... | Terraform | 50,835,636 | 32 |
I've got a variable declared in my variables.tf like this:
variable "MyAmi" {
type = map(string)
}
but when I do:
terraform plan -var 'MyAmi=xxxx'
I get:
Error: Variables not allowed
on <value for var.MyAmi> line 1:
(source code not available)
Variables may not be used here.
Minimal code example:
test.tf
pr... | This error can also occurs when trying to setup a variable's value from a dynamic resource (e.g: an output from a child module):
variable "some_arn" {
description = "Some description"
default = module.some_module.some_output # <--- Error: Variables not allowed
}
Using locals block instead of the variable will... | Terraform | 58,712,999 | 32 |
I'm trying to create a module in Terraform that can be instantiated multiple times with different variable inputs. Within the module, how do I reference resources when their names depend on an input variable? I'm trying to do it via the bracket syntax ("${aws_ecs_task_definition[var.name].arn}") but I just guessed at t... | I was fundamentally misunderstanding how modules worked.
Terraform does not support interpolation in resource names (see the relevant issues), but that doesn't matter in my case, because the resources of each instance of a module are in the instance's namespace. I was worried about resource names colliding, but the mod... | Terraform | 38,619,691 | 31 |
I would like to use the same terraform template for several dev and production environments.
My approach:
As I understand it, the resource name needs to be unique, and terraform stores the state of the resource internally. I therefore tried to use variables for the resource names - but it seems to be not supported. I... | You can't interpolate inside the resource name. Instead what you should do is as @BMW have mentioned in the comments, you should make a terraform module that contains that SqsIntegrationOrderIn inside and takes env variable. Then you can use the module twice, and they simply won't clash. You can also have a look at a s... | Terraform | 46,353,686 | 31 |
I have an infrastructure I'm deploying using Terraform in AWS. This infrastructure can be deployed to different environments, for which I'm using workspaces.
Most of the components in the deployment should be created separately for each workspace, but I have several key components that I wish to be shared between them,... | For the shared resources, I create them in a separate template and then refer to them using terraform_remote_state in the template where I need information about them.
What follows is how I implement this, there are probably other ways to implement it. YMMV
In the shared services template (where you would put your IAM ... | Terraform | 52,606,011 | 31 |
My simple terraform file is:
provider "aws" {
region = "region"
access_key = "key"
secret_key = "secret_key"
}
terraform {
backend "s3" {
# Replace this with your bucket name!
bucket = "great-name-terraform-state-2"
key = "global/s3/terraform.tfstate"
region = "eu-ce... | I encountered this before.
Following are the steps that will help you overcome that error-
Delete the .terraform directory
Place the access_key and secret_key under the backend block. like below given code
Run terraform init
backend "s3" {
bucket = "great-name-terraform-state-2"
key = "global/s3/terrafor... | Terraform | 61,851,903 | 31 |
We have cronjob and shell script which we want to copy or upload to aws ec2 instance while creating instance using terraform.
we tried
file provisioner :
but its not wokring , and read this option does not work with all terraform version
provisioner "file" {
source = "abc.sh"
destination ... | When starting from an AMI that has cloud-init installed (which is common in many official Linux distri), we can use cloud-init's write_files module to place arbitrary files into the filesystem, as long as they are small enough to fit within the constraints of the user_data argument along with all of the other cloud-ini... | Terraform | 62,101,009 | 31 |
When I had a single hosted zone it was easy for me to create the zone and then create the NS records for the zone in the delegating account by referencing the hosted zone by name.
Edit To try to avoid confusion this is what I wanted to achieve but for multiple hosted zones and the owner of the domain is a management a... | Since your local.aws_zones is set ["dev", "test", "qa"], your aws_route53_zone.public_hosted_zone will be a map with keys "dev", "test", "qa".
Therefore, to use it in your aws_route53_record, you can try:
resource "aws_route53_record" "ns_records" {
for_each = local.aws_zones
# other attributes
records =... | Terraform | 63,641,187 | 31 |
I am trying to pass a variable from the root module to a child module with the following syntax:
main.tf:
provider "aws" {
version = "~> 1.11"
access_key = "${var.aws_access_key}"
secret_key = "${var.aws_secret_key}"
region = "${var.aws_region}"
}
module "iam" {
account_id = "${var.account_id}"
source ... | You need to declare any variables that a module uses at the module level itself:
variable "account_id" {
}
resource "aws_iam_policy_attachment" "myName" {
name = "myName"
policy_arn = "arn:aws:iam::${var.account_id}:policy/myName"
groups = []
users = []
roles = []
}
| Terraform | 49,535,315 | 30 |
I am having an issue using Terraform (v0.9.2) adding services to an ELB (I'm using: https://github.com/segmentio/stack/blob/master/s3-logs/main.tf).
When I run terraform apply I get this error:
* module.solr.module.elb.aws_elb.main: 1 error(s) occurred:
* aws_elb.main: Failure configuring ELB attributes:
InvalidC... | The docs for ELB access logs say that you want to allow a specific Amazon account to be able to write to S3, not your account.
As such you want something like:
{
"Id": "Policy1429136655940",
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1429136633762",
"Action": [
"s3:PutObject"
... | Terraform | 43,366,038 | 29 |
I have an AWS Lambda deployed successfully with Terraform:
resource "aws_lambda_function" "lambda" {
filename = "dist/subscriber-lambda.zip"
function_name = "test_get-code"
role = <my_role>
handler = "main.handler"
timeout... | This works for me and also doesn't trigger an update on the Lambda function when the code hasn't changed
data "archive_file" "lambda_zip" {
... | Terraform | 52,662,244 | 29 |
Can you create views in Amazon Athena? outlines how to create a view using the User Interface.
I'd like to create an AWS Athena View programatically, ideally using Terraform (which calls CloudFormation).
I followed the steps outlined here: https://ujjwalbhardwaj.me/post/create-virtual-views-with-aws-glue-and-query-them... | Creating views programmatically in Athena is not documented, and unsupported, but possible. What happens behind the scenes when you create a view using StartQueryExecution is that Athena lets Presto create the view and then extracts Presto's internal representation and puts it in the Glue catalog.
The staleness problem... | Terraform | 56,289,272 | 29 |
I am creating Secrets in AWS using Terraform code. My Jenkins pipeline will create the infrastructure every 2 hours and destroys it. Once Infrastructure re-creates after 2 hours, it happened that, AWS Secrets is not allowing me to re-create again and throwing me with below error. Please suggest.
Error: error creating S... | You need to set the recovery window to 0 for immediate deletion of secrets.
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/secretsmanager_secret#recovery_window_in_days
recovery_window_in_days - (Optional) Specifies the number of days that AWS Secrets Manager waits before it can delete the... | Terraform | 57,431,731 | 29 |
When attempting to run terraform init as a task in an Azure Pipeline, it errors stating
spawn C:\hostedtoolcache\windows\terraform\0.12.7\x64\terraform.exe ENOENT
The installation appears fine, as basic functionality is verified during the install step (terraform version)
Relevant Pipeline Tasks
...
- task: Terrafo... | Turns out the working directory path was incorrect, as the directory structure had been changed.
Changing all the named working directories from Terraform/terraform to just terraform corrected the issue.
Presumably both in this and cases where checkout was not performed, Terraform simply cannot locate main.tf, but the ... | Terraform | 59,794,909 | 29 |
I am declaring a google_logging_metric resource in Terraform (using version 0.11.14)
I have the following declaration
resource "google_logging_metric" "my_metric" {
description = "Check for logs of some cron job\t"
name = "mycj-logs"
filter = "resource.type=\"k8s_container\" AND resource.labels.cluste... | From the docs
String values are simple and represent a basic key to value mapping
where the key is the variable name. An example is:
variable "key" {
type = "string"
default = "value"
}
A multi-line string value can be provided using heredoc syntax.
variable "long_key" {
type = "string"
default = <<EOF
T... | Terraform | 60,722,012 | 29 |
After deleting kubernetes cluster with "terraform destroy" I can't create it again anymore.
"terraform apply" returns the following error message:
Error: Kubernetes cluster unreachable: invalid configuration: no
configuration has been provided, try setting KUBERNETES_MASTER
environment variable
Here is the terraform ... | Before doing something radical like manipulating the state directly, try setting the KUBE_CONFIG_PATH variable:
export KUBE_CONFIG_PATH=/path/to/.kube/config
After this rerun the plan or apply command.
This has fixed the issue for me.
| Terraform | 66,427,129 | 29 |
I need to execute a Terraform template to provision infrastructure for an AWS account which I can access by assuming a role.
The problem I have now is I do not have an IAM user in that AWS account so I do not have an aws_access_key_id or an aws_secret_access_key to set up another named profile in my ~/.aws/credentials.... | I have a bulletproof solution anytime you want to run commands as a specific role (including other accounts).
I assume you have the AWS CLI tools installed.
You will also have to install jq (easy tool to parse and extract data from json), although you can parse the data any way you wish.
aws_credentials=$(aws sts assum... | Terraform | 55,128,348 | 28 |
Can you conditionally apply lifecycle blocks to resources in Terraform 0.12.
For example if I wanted to add this block to an AWS ASG resource based of a parameter passed to the module.
lifecycle {
ignore_changes = [
target_group_arns,
]
}
| No, you can't.
From the The lifecycle Meta-Argument documentation:
The lifecycle settings all affect how Terraform constructs and traverses the dependency graph. As a result, only literal values can be used because the processing happens too early for arbitrary expression evaluation.
While that doesn't explicitly for... | Terraform | 62,427,931 | 28 |
When I run terraform init for my Google Cloud Platform project on my Apple Silicon macbook pro I get this error.
Provider registry.terraform.io/hashicorp/google v3.57.0 does not have a package available for your current platform, darwin_arm64.
How can I work around this? I thought that the Rosetta2 emulator would chec... | Build Terraform from scratch by using the tfenv package, which can build a specific version adapted to the platform architecture.
I ran the following to install a version that works under my M1 Macbook (version 1.3.3 in this case):
brew uninstall terraform
brew install tfenv
TFENV_ARCH=amd64 tfenv install 1.3.3
tfenv ... | Terraform | 66,281,882 | 28 |
I have a list in terraform that looks something like:
array = ["a","b","c"]
Within this terraform file there are two variables called age and gender, and I want to make it so that the list called array has an extra element called "d" if age is equal to 12 and gender is equal to male (i.e. if var.age == 12 && var.gende... | There is another way to do that using flatten:
variable = flatten(["a", "b", "c", var.age == 12 ? ["d"] : []])
| Terraform | 67,902,785 | 28 |
I'm a little confused about what I'm reading in the terraform documentation. Here's what it says about modules:
https://www.terraform.io/docs/language/modules/index.html
Modules are containers for multiple resources that are used together. A module consists of a collection of .tf and/or .tf.json files kept together i... | For backward compatibility with earlier versions of Terraform, Terraform v0.13 and later treat any use of a provider short name that isn't declared in required_providers as an implicit declaration of a requirement for a provider in the hashicorp namespace.
For example, we can consider a resource like this:
resource "aw... | Terraform | 68,216,074 | 28 |
How can I easily generate random numbers following a normal distribution in C or C++?
I don't want any use of Boost.
I know that Knuth talks about this at length but I don't have his books at hand right now.
| There are many methods to generate Gaussian-distributed numbers from a regular RNG.
The Box-Muller transform is commonly used. It correctly produces values with a normal distribution. The math is easy. You generate two (uniform) random numbers, and by applying an formula to them, you get two normally distributed ran... | Distribution | 2,325,472 | 130 |
I want to know if the JavaScript function Math.random uses a normal (vs. uniform) distribution or not.
If not, how can I get numbers which use a normal distribution? I haven't found a clear answer on the Internet, for an algorithm to create random normally-distributed numbers.
I want to rebuild a Schmidt-machine (Germa... | Since this is the first Google result for "js gaussian random" in my experience, I feel an obligation to give an actual answer to that query.
The Box-Muller transform converts two independent uniform variates on (0, 1) into two standard Gaussian variates (mean 0, variance 1). This probably isn't very performant because... | Distribution | 25,582,882 | 114 |
I can't figure out how to do a Two-sample KS test in Scipy.
After reading the documentation of scipy kstest, I can see how to test whether a distribution is identical to standard normal distribution
from scipy.stats import kstest
import numpy as np
x = np.random.normal(0,1,1000)
test_stat = kstest(x, 'norm')
#>>> test... | You are using the one-sample KS test. You probably want the two-sample test ks_2samp:
>>> from scipy.stats import ks_2samp
>>> import numpy as np
>>>
>>> np.random.seed(12345678)
>>> x = np.random.normal(0, 1, 1000)
>>> y = np.random.normal(0, 1, 1000)
>>> z = np.random.normal(1.1, 0.9, 1000)
>>>
>>> ks_2samp(x, y)... | Distribution | 10,884,668 | 110 |
I was wondering if there were statistics functions built into math libraries that are part of the standard C++ libraries like cmath. If not, can you guys recommend a good stats library that would have a cumulative normal distribution function?
More specifically, I am looking to use/create a cumulative distribution func... | Theres is no straight function. But since the gaussian error function and its complementary function is related to the normal cumulative distribution function (see here, or here) we can use the implemented c-function erfc (complementary error function):
double normalCDF(double value)
{
return 0.5 * erfc(-value * M_S... | Distribution | 2,328,258 | 62 |
Visualizing scipy.stats distributions
A histogram can be made of the scipy.stats normal random variable to see what the distribution looks like.
% matplotlib inline
import pandas as pd
import scipy.stats as stats
d = stats.norm()
rv = d.rvs(100000)
pd.Series(rv).hist(bins=32, normed=True)
What do the other distributi... | Visualizing all scipy.stats distributions
Based on the list of scipy.stats distributions, plotted below are the histograms and PDFs of each continuous random variable. The code used to generate each distribution is at the bottom. Note: The shape constants were taken from the examples on the scipy.stats distribution do... | Distribution | 37,559,470 | 55 |
I am trying to recreate maximum likelihood distribution fitting, I can already do this in Matlab and R, but now I want to use scipy. In particular, I would like to estimate the Weibull distribution parameters for my data set.
I have tried this:
import scipy.stats as s
import numpy as np
import matplotlib.pyplot as plt
... | My guess is that you want to estimate the shape parameter and the scale of the Weibull distribution while keeping the location fixed. Fixing loc assumes that the values of your data and of the distribution are positive with lower bound at zero.
floc=0 keeps the location fixed at zero, f0=1 keeps the first shape parame... | Distribution | 17,481,672 | 53 |
I have a dataset from sklearn and I plotted the distribution of the load_diabetes.target data (i.e. the values of the regression that the load_diabetes.data are used to predict).
I used this because it has the fewest number of variables/attributes of the regression sklearn.datasets.
Using Python 3, How can I get the d... | Use this approach
import scipy.stats as st
def get_best_distribution(data):
dist_names = ["norm", "exponweib", "weibull_max", "weibull_min", "pareto", "genextreme"]
dist_results = []
params = {}
for dist_name in dist_names:
dist = getattr(st, dist_name)
param = dist.fit(data)
pa... | Distribution | 37,487,830 | 52 |
I am plotting Cumulative Distribution Functions, with a large number of data points. I am plotting a few lines on the same plot, which are identified with markers as it will be printed in black and white. What I would like are markers evenly spaced in the x-dimension. What I am getting is one marker per data point (and... | You can do plot(x,y,marker='o',markevery=5) to mark every fifth point, but I don't think there is any built-in support for setting marks at even intervals. You could decide on the x locations where you want the marks, use e.g. numpy.searchsorted to find which data points the locations fall between, and then interpolate... | Distribution | 2,040,306 | 45 |
Can we say that a truncated md5 hash is still uniformly distributed?
To avoid misinterpretations: I'm aware the chance of collisions is much greater the moment you start to hack off parts from the md5 result; my use-case is actually interested in deliberate collisions. I'm also aware there are other hash methods that m... | Yes, not exhibiting any bias is a design requirement for a cryptographic hash. MD5 is broken from a cryptographic point of view however the distribution of the results was never in question.
If you still need to be convinced, it's not a huge undertaking to hash a bunch of files, truncate the output and use ent ( http:/... | Distribution | 8,184,941 | 39 |
So i have a Random object:
typedef unsigned int uint32;
class Random {
public:
Random() = default;
Random(std::mt19937::result_type seed) : eng(seed) {}
private:
uint32 DrawNumber();
std::mt19937 eng{std::random_device{}()};
std::uniform_int_distribution<uint32> uniform_dist{0, UINT32_MAX};
};
ui... | Distribution objects are lightweight. Simply construct a new distribution when you need a random number. I use this approach in a game engine, and, after benchmarking, it's comparable to using good old rand().
Also, I've asked how to vary the range of distribution on GoingNative 2013 live stream, and Stephen T. Lavavej... | Distribution | 19,036,141 | 33 |
I have a module that sits in a namespace. Should tests and data the tests rely on go in the namespace or in the top level where setup.py sites?
./company/__init__.py
./company/namespace/__init__.py
./company/namespace/useful.py
./company/namespace/test_useful.py
./company/namespace/test_data/useful_data.xml
./setup.py
... | The Sample Project stores the tests outside the module.
The directory structure looks like this:
├── data
│ └── data_file
├── MANIFEST.in
├── README.rst
├── sample
│ ├── __init__.py
│ └── package_data.dat
├── setup.cfg
├── setup.py
└── tests
├── __init__.py
└── test_simple.py
Related: The Packing Guide: ... | Distribution | 5,341,006 | 30 |
I'm working on a data mining algorithm where i want to pick a random direction from a particular point in the feature space.
If I pick a random number for each of the n dimensions from [-1,1] and then normalize the vector to a length of 1 will I get an even distribution across all possible directions?
I'm speaking ... | One simple trick is to select each dimension from a gaussian distribution, then normalize:
from random import gauss
def make_rand_vector(dims):
vec = [gauss(0, 1) for i in range(dims)]
mag = sum(x**2 for x in vec) ** .5
return [x/mag for x in vec]
For example, if you want a 7-dimensional random vector, se... | Distribution | 6,283,080 | 30 |
My requirement is to generate random bytes of data (not random numbers) aka uniformly distributed bits.
As such I was wondering what are the correct/efficient ways of doing this using C++11/14 random facilities. I've had a look around at the examples, but they all seem to focus on number generation (ints, floats etc)
C... | What you're looking for is the std::independent_bits_engine adaptor:
#include <vector>
#include <random>
#include <climits>
#include <algorithm>
#include <functional>
using random_bytes_engine = std::independent_bits_engine<
std::default_random_engine, CHAR_BIT, unsigned char>;
int main()
{
random_bytes_engin... | Distribution | 25,298,585 | 28 |
Does anyone know how to plot a skew normal distribution with scipy?
I supose that stats.norm class can be used but I just can't figure out how.
Furthermore, how can I estimate the parameters describing the skew normal distribution of a unidimensional dataset?
| From the Wikipedia description,
from scipy import linspace
from scipy import pi,sqrt,exp
from scipy.special import erf
from pylab import plot,show
def pdf(x):
return 1/sqrt(2*pi) * exp(-x**2/2)
def cdf(x):
return (1 + erf(x/sqrt(2))) / 2
def skew(x,e=0,w=1,a=0):
t = (x-e) / w
return 2 / w * pdf(t) *... | Distribution | 5,884,768 | 24 |
I'm developing a python framework that would have "addons" written as separate packages. I.e.:
import myframework
from myframework.addons import foo, bar
Now, what I'm trying to arrange is so that these addons can be distributed separately from core framework and injected into myframework.addons namespace.
Currently m... | See namespace packages:
http://www.python.org/dev/peps/pep-0382/
or in setuptools:
http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages
| Distribution | 454,691 | 23 |
Are there any R packages for the calculation of Kendall's tau-b and tau-c, and their associated standard errors? My searches on Google and Rseek have turned up nothing, but surely someone has implemented these in R.
| There are three Kendall tau statistics (tau-a, tau-b, and tau-c).
They are not interchangeable, and none of the answers posted so far deal with the last two, which is the subject of the OP's question.
I was unable to find functions to calculate tau-b or tau-c, either in the R Standard Library (stat et al.) or in any of... | Distribution | 2,557,863 | 23 |
I have a dataframe with a column that has numerical values. This column is not well-approximated by a normal distribution. Given another numerical value, not in this column, how can I calculate its percentile in the column? That is, if the value is greater than 80% of the values in the column but less than the other 20... | To find the percentile of a value relative to an array (or in your case a dataframe column), use the scipy function stats.percentileofscore().
For example, if we have a value x (the other numerical value not in the dataframe), and a reference array, arr (the column from the dataframe), we can find the percentile of x ... | Distribution | 44,824,927 | 23 |
I want to generate random numbers according some distributions. How can I do this?
| The standard random number generator you've got (rand() in C after a simple transformation, equivalents in many languages) is a fairly good approximation to a uniform distribution over the range [0,1]. If that's what you need, you're done. It's also trivial to convert that to a random number generated over a somewhat l... | Distribution | 3,510,475 | 22 |
I have the following code to generate bimodal distribution but when I graph the histogram. I don't see the 2 modes. I am wondering if there's something wrong with my code.
mu1 <- log(1)
mu2 <- log(10)
sig1 <- log(3)
sig2 <- log(3)
cpct <- 0.4
bimodalDistFunc <- function (n,cpct, mu1, mu2, sig1, sig2) {
y0 <- ... | The problem seems to be just too small n and too small difference between mu1 and mu2, taking mu1=log(1), mu2=log(50) and n=10000 gives this:
| Distribution | 11,530,010 | 22 |
On Stackoverflow there are many questions about generating uniformly distributed integers from a-priory unknown ranges. E.g.
C++11 Generating random numbers from frequently changing range
Vary range of uniform_int_distribution
The typical solution is something like:
inline std::mt19937 &engine()
{
thread_local std:... | Interesting question.
So I was wondering if interfering with how the distribution works by
constantly resetting it (i.e. recreating the distribution at every
call of get_int_from_range) I get properly distributed results.
I've written code to test this with uniform_int_distribution and poisson_distribution. It's ... | Distribution | 30,103,356 | 22 |
I have a bunch of keys that each have an unlikeliness variable. I want to randomly choose one of these keys, yet I want it to be more unlikely for unlikely (key, values) to be chosen than a less unlikely (a more likely) object. I am wondering if you would have any suggestions, preferably an existing python module that ... | This activestate recipe gives an easy-to-follow approach, specifically the version in the comments that doesn't require you to pre-normalize your weights:
import random
def weighted_choice(items):
"""items is a list of tuples in the form (item, weight)"""
weight_total = sum((item[1] for item in items))
n =... | Distribution | 526,255 | 21 |
I need to create a method to generate a unit vector in three dimensions that points in a random direction using a random number generator. The distribution of direction MUST be isotropic.
Here is how I am trying to generate a random unit vector:
v = randn(1,3);
v = v./sqrt(v*v');
But I don't know how to complete th... | You're doing it right. A random normal distribution of coordinates gives you a uniform distribution of directions.
To generate 10000 uniform points on the unit sphere, you run
v = randn(10000,3);
v = bsxfun(@rdivide,v,sqrt(sum(v.^2,2)));
plot3(v(:,1),v(:,2),v(:,3),'.')
axis equal
| Distribution | 9,750,908 | 21 |
People also often ask "How can I compile Perl?" while what they really want is to create an executable that can run on machines even if they don't have Perl installed.
There are several solutions, I know of:
perl2exe of IndigoStar
It is commercial. I never tried. Its web site says it can cross compile Win32, Linux, an... | In addition to the three tools listed in the question, there's another one called Cava Packager written by Mark Dootson, who has also contributed to PAR in the past. It only runs under Windows, has a nice Wx GUI and works differently from the typical three contenders in that it assembles all Perl dependencies in a sour... | Distribution | 77,278 | 20 |
My client has an iOS app with In-app purchase, Game-kit and Push notifications enabled, it is currently on the app store. I would like to resign the application using an in-house enterprise distribution certificate, to test internally, but still be able to test services tied to the original provisioning profile. Is thi... | I ended up doing this, which is a combination of :-
Very tricky question about iPhone/iPad resigned builds behaviors
and
Re-sign IPA (iPhone)
1) Create Entitlements plist, prevent issues with the Keychain etc
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.app... | Distribution | 15,634,188 | 20 |
I'm a newbie to distutils and I have a problem that really has me stuck. I am compiling a package that requires an extension, so I make the extension thus:
a_module = Extension(
"amodule",
["initmodule.cpp"],
library_dirs=libdirs,
extra_objects = [
"unix/x... | You can have the linker store paths to search in the output binary so LD_LIBRARY_PATH isn't necessary. Some examples:
# Will link fine but at run-time LD_LIBRARY_PATH would be required
gcc -o blah blah.o -lpcap -L/opt/csw/lib
# Without LD_LIBRARY_PATH=/opt/csw/lib it will fail to link, but
# it wouldn't be needed at ... | Distribution | 9,795,793 | 19 |
Given mean and variance of a Gaussian (normal) random variable, I would like to compute its probability density function (PDF).
I referred this post: Calculate probability in normal distribution given mean, std in Python,
Also the scipy docs: scipy.stats.norm
But when I plot a PDF of a curve, the probability exceeds ... | It's not a bug. It's not an incorrect result either. Probability density function's value at some specific point does not give you probability; it is a measure of how dense the distribution is around that value. For continuous random variables, the probability at a given point is equal to zero. Instead of p(X = x), we ... | Distribution | 38,141,951 | 19 |
I am developing cross-platform Qt application.
It is freeware though not open-source. Therefore I want to distribute it as a compiled binary.
On windows there is no problem, I pack my compiled exe along with MinGW's and Qt's DLLs and everything goes great.
But on Linux there is a problem because the user may have share... | Shared libraries is the way to go, but you can avoid using LD_LIBRARY_PATH (which involves running the application using a launcher shell script, etc) building your binary with the -rpath compiler flag, pointing to there you store your libraries.
For example, I store my libraries either next to my binary or in a direct... | Distribution | 934,950 | 18 |
This question relates to the Apple iOS Developer Enterprise Program
I am trying to determine the limits and relationships between the following 4 entities: Apple Enterprise Program distribution licenses, DUNS numbers, distribution certificates, and apps.
Here's the scenario: a client wants to develop iPad apps for in-h... | I posed these questions to Apple developer relations
Can an enterprise have more than one enterprise license? For example, could 2 departments each have their own enterprise license?
Can a single enterprise license have more than one distribution certificate?
Can a single enterprise distribution certificate apply to m... | Distribution | 6,034,495 | 18 |
heatmap.2 defaults to dist for calculating the distance matrix and hclust for clustering.
Does anyone now how I can set dist to use the euclidean method and hclust to use the centroid method?
I provided a compilable code sample bellow.
I tried: distfun = dist(method = "euclidean"),
but that doesn't work. Any ideas?
lib... | Glancing at the code for heatmap.2 I'm fairly sure that the default is to use dist, and it's default is in turn to use euclidean distances.
The reason your attempt at passing distfun = dist(method = 'euclidean') didn't work is that distfun (and hclustfun) are supposed to simply be name of functions. So if you want to a... | Distribution | 6,806,762 | 18 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.